Documentation
¶
Overview ¶
Package scanning provides core network scanning functionality for Scanorama.
This package contains the essential scanning engine that powers Scanorama's network discovery and port scanning capabilities. It handles scan execution, result processing, XML parsing, and provides the core data structures used throughout the application.
Overview ¶
The scanning package is built around the ScanConfig structure which defines scan parameters, and the ScanResult structure which contains scan outcomes. The main entry points are RunScanWithContext and RunScanWithDB functions that execute scans with different database integration levels.
Main Components ¶
## Scan Execution
The core scanning functionality is provided through:
- ScanConfig: Configuration structure defining scan parameters
- RunScanWithContext: Execute scans with context and optional database
- RunScanWithDB: Execute scans with database integration
- PrintResults: Display scan results in human-readable format
## Result Processing
Scan results are processed and structured through:
- ScanResult: Main result structure containing discovered hosts and services
- Host: Individual host information including open ports and services
- Port: Port-specific information including state and service details
- Service: Service identification and version information
## XML Processing
Nmap XML output parsing is handled by:
- NmapRun: Root structure for parsing nmap XML output
- NmapHost: Host-specific data from nmap scans
- NmapPort: Port-specific data from nmap scans
- ParseNmapXML: Parse nmap XML output into structured data
Usage Examples ¶
## Basic Scan
config := &scanning.ScanConfig{ Targets: []string{"192.168.1.1/24"}, Ports: "80,443,22", ScanType: "syn", Timeout: 300, Concurrency: 10, } ctx := context.Background() result, err := scanning.RunScanWithContext(ctx, config, nil) if err != nil { log.Fatal(err) } scanning.PrintResults(result)
## Database-Integrated Scan
db, err := db.NewDB(dbConfig) if err != nil { log.Fatal(err) } config := &scanning.ScanConfig{ Targets: []string{"10.0.0.0/8"}, Ports: "1-1000", ScanType: "connect", Timeout: 600, Concurrency: 50, } result, err := scanning.RunScanWithDB(config, db) if err != nil { log.Fatal(err) } // Results are automatically stored in the database
## XML Parsing
xmlData, err := os.ReadFile("scan_results.xml") if err != nil { log.Fatal(err) } nmapResult, err := scanning.ParseNmapXML(xmlData) if err != nil { log.Fatal(err) } // Process structured nmap data for _, host := range nmapResult.Hosts { fmt.Printf("Host: %s\n", host.Address.Addr) for _, port := range host.Ports.Ports { if port.State.State == "open" { fmt.Printf(" Port %d/%s: %s\n", port.PortID, port.Protocol, port.State.State) } } }
Configuration Options ¶
ScanConfig supports various scanning modes and options:
- Targets: IP addresses, ranges, or hostnames to scan
- Ports: Port specifications (ranges, lists, or named services)
- ScanType: Scan technique (syn, connect, udp, etc.)
- Timeout: Maximum scan duration in seconds
- Concurrency: Number of parallel scanning threads
- Rate: Packets per second limit
- HostTimeout: Per-host timeout in seconds
Scan Types ¶
Supported scan types include:
- "syn": TCP SYN scan (default, requires privileges)
- "connect": TCP connect scan (no privileges required)
- "udp": UDP scan
- "ping": Host discovery only
- "ack": TCP ACK scan
- "window": TCP Window scan
- "maimon": TCP Maimon scan
Error Handling ¶
All functions return descriptive errors that can be used for:
- User feedback in CLI applications
- API error responses in web services
- Logging and monitoring in daemon processes
Common error scenarios include:
- Invalid target specifications
- Network connectivity issues
- Permission errors (for privileged scans)
- Timeout errors for long-running scans
- Database connection failures (for DB-integrated scans)
Thread Safety ¶
The scanning package is designed to be thread-safe:
- Multiple scans can run concurrently
- ScanConfig and result structures are immutable after creation
- Database operations use connection pooling
- Context cancellation is properly handled
Performance Considerations ¶
For optimal performance:
- Use appropriate concurrency levels based on target network capacity
- Set reasonable timeouts to avoid hanging scans
- Consider rate limiting for large networks
- Use database integration for persistent storage of large result sets
- Monitor memory usage for very large scans
Integration ¶
This package integrates with other Scanorama components:
- internal/db: Database storage and retrieval of scan results
- internal/discovery: Network discovery and host enumeration
- internal/daemon: Background scanning services
- internal/api: REST API endpoints for scan management
- internal/scheduler: Automated scanning workflows
Package scanning provides core scanning functionality and shared types for scanorama. It contains scan execution logic, result processing, XML handling, and common data structures used throughout the application.
Index ¶
- func PrintResults(result *ScanResult)
- func SaveResults(result *ScanResult, filePath string) error
- type Host
- type HostStats
- type HostXML
- type Port
- type PortXML
- type ScanConfig
- type ScanError
- type ScanResult
- func LoadResults(filePath string) (*ScanResult, error)
- func NewScanResult() *ScanResult
- func RunScan(config *ScanConfig) (*ScanResult, error)
- func RunScanWithContext(ctx context.Context, config *ScanConfig, database *db.DB) (*ScanResult, error)
- func RunScanWithDB(config *ScanConfig, database *db.DB) (*ScanResult, error)
- type ScanXML
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func PrintResults ¶
func PrintResults(result *ScanResult)
PrintResults displays scan results in a human-readable format on stdout. The output includes host status, open ports, and detected services.
func SaveResults ¶
func SaveResults(result *ScanResult, filePath string) error
SaveResults writes scan results to an XML file at the specified path. The output is formatted with proper indentation for readability.
Types ¶
type Host ¶
type Host struct { // Address is the IP address or hostname of the scanned host Address string // Status indicates whether the host is "up" or "down" Status string // Ports contains information about all scanned ports Ports []Port }
Host represents a scanned host and its findings.
type HostStats ¶
type HostStats struct { // Up is the number of hosts that were up Up int // Down is the number of hosts that were down Down int // Total is the total number of hosts scanned Total int }
HostStats contains summary statistics about a network scan.
type HostXML ¶
type HostXML struct { Address string `xml:"Address"` Status string `xml:"Status"` Ports []PortXML `xml:"Ports,omitempty"` }
HostXML represents a scanned host for XML serialization. It contains the host's address, status, and discovered ports.
type Port ¶
type Port struct { // Number is the port number (1-65535) Number uint16 // Protocol is the transport protocol ("tcp" or "udp") Protocol string // State indicates whether the port is "open", "closed", or "filtered" State string // Service is the name of the detected service, if any Service string // Version is the version of the detected service, if available Version string // ServiceInfo contains additional service details, if available ServiceInfo string }
Port represents the scan results for a single port.
type PortXML ¶
type PortXML struct { Number uint16 `xml:"Number"` Protocol string `xml:"Protocol"` State string `xml:"State"` Service string `xml:"Service"` Version string `xml:"Version,omitempty"` ServiceInfo string `xml:"ServiceInfo,omitempty"` }
PortXML represents a scanned port for XML serialization. It includes the port number, protocol, state, and service information.
type ScanConfig ¶
type ScanConfig struct { // Targets is a list of targets to scan (IPs, hostnames, CIDR ranges) Targets []string // Ports specifies which ports to scan (e.g., "80,443" or "1-1000") Ports string // ScanType determines the type of scan: "connect", "syn", or "version" ScanType string // TimeoutSec specifies scan timeout in seconds (0 = default timeout) TimeoutSec int // Concurrency specifies the number of concurrent scans (0 = auto) Concurrency int // RetryCount specifies the number of retry attempts for failed scans RetryCount int // RetryDelay specifies the delay between retries RetryDelay time.Duration }
ScanConfig represents the configuration for a network scan.
func (*ScanConfig) Validate ¶
func (c *ScanConfig) Validate() error
Validate checks if the scan configuration is valid.
type ScanError ¶
type ScanError struct { Op string // Operation that failed Err error // Original error Host string // Host where the error occurred, if applicable Port uint16 // Port where the error occurred, if applicable }
ScanError represents error types for scan operations.
type ScanResult ¶
type ScanResult struct { // Hosts contains all scanned hosts and their findings Hosts []Host // Stats contains summary statistics about the scan Stats HostStats // StartTime is when the scan started StartTime time.Time // EndTime is when the scan completed EndTime time.Time // Duration is how long the scan took Duration time.Duration // Error is any error that occurred during the scan Error error }
ScanResult contains the complete results of a network scan.
func LoadResults ¶
func LoadResults(filePath string) (*ScanResult, error)
LoadResults reads and parses scan results from an XML file. It returns the parsed results or an error if the file cannot be read or parsed.
func NewScanResult ¶
func NewScanResult() *ScanResult
NewScanResult creates a new scan result with the current time as start time.
func RunScan ¶
func RunScan(config *ScanConfig) (*ScanResult, error)
RunScan is a convenience wrapper around RunScanWithContext that uses a background context.
func RunScanWithContext ¶
func RunScanWithContext(ctx context.Context, config *ScanConfig, database *db.DB) (*ScanResult, error)
RunScanWithContext performs a network scan based on the provided configuration and context. It uses nmap to scan the specified targets and ports, returning detailed results about discovered hosts and services. If database is provided, results are stored.
func RunScanWithDB ¶
func RunScanWithDB(config *ScanConfig, database *db.DB) (*ScanResult, error)
RunScanWithDB is a convenience wrapper that includes database storage.
func (*ScanResult) Complete ¶
func (r *ScanResult) Complete()
Complete marks the scan as complete and calculates duration.