scan

package
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 20, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package scan is a generated GoMock package.

Index

Constants

This section is empty.

Variables

View Source
var (

	// IPv4/TCP parsing errors
	ErrShortIPv4Header     = errors.New("short IPv4 header")
	ErrNotIPv4             = errors.New("not IPv4")
	ErrBadIPv4HeaderLength = errors.New("bad IPv4 header length")
	ErrShortTCPHeader      = errors.New("short TCP header")
	ErrBadTCPHeaderLength  = errors.New("bad TCP header length")

	// Network errors
	ErrNonIPv4LocalIP     = errors.New("attachBPF: non-IPv4 local IP")
	ErrShortEthernet      = errors.New("short ethernet")
	ErrShortVLANHeader    = errors.New("short vlan header")
	ErrNonIPv4SourceIP    = errors.New("non-IPv4 source IP")
	ErrScanAlreadyRunning = errors.New("scan already running")
	ErrScanTimedOut       = errors.New("scan timed out")
	ErrPortClosed         = errors.New("port closed (RST)")

	// Interface errors
	ErrNoSuitableInterface = errors.New("no suitable local IP address and interface found")
	ErrInterfaceNotFound   = errors.New("could not find interface for local IP")
	ErrInterfaceNoIPv4     = errors.New("interface has no IPv4 address")
)
View Source
var (
	ErrNoPorts = errors.New("no ports available")
)

Functions

func ChecksumNew added in v1.0.55

func ChecksumNew(data []byte) uint16

func ExpandCIDR

func ExpandCIDR(cidr string) ([]string, error)

ExpandCIDR expands a CIDR notation into a slice of IP addresses. Skips network and broadcast addresses for non-/32 networks.

func TCPChecksumNew added in v1.0.55

func TCPChecksumNew(src, dst net.IP, tcpHdr, payload []byte) uint16

TCP checksum with IPv4 pseudo-header

func TargetFromIP

func TargetFromIP(ip string, mode models.SweepMode, port ...int) models.Target

TargetFromIP creates a models.Target from an IP string and mode, with optional port.

Types

type ICMPSweeper

type ICMPSweeper struct {
	// contains filtered or unexported fields
}

func NewICMPSweeper

func NewICMPSweeper(timeout time.Duration, rateLimit int, log logger.Logger, opts ...ICMPSweeperOption) (*ICMPSweeper, error)

NewICMPSweeper creates a new scanner for ICMP sweeping.

func (*ICMPSweeper) Scan

func (s *ICMPSweeper) Scan(ctx context.Context, targets []models.Target) (<-chan models.Result, error)

Scan performs the ICMP sweep and returns results.

func (*ICMPSweeper) SetResultCallback added in v1.0.55

func (s *ICMPSweeper) SetResultCallback(callback func(models.Result))

Stop stops the scanner and releases resources. SetResultCallback sets a callback function that will be called immediately when a result becomes available

func (*ICMPSweeper) Stop

func (s *ICMPSweeper) Stop() error

type ICMPSweeperOption added in v1.0.90

type ICMPSweeperOption func(*ICMPSweeper)

ICMPSweeperOption configures an ICMPSweeper instance.

func WithICMPCount added in v1.0.90

func WithICMPCount(count int) ICMPSweeperOption

WithICMPCount sets the number of ICMP packets to send per target.

type IPv4Hdr added in v1.0.55

type IPv4Hdr struct {
	IHL      uint8
	Protocol uint8
	SrcIP    net.IP
	DstIP    net.IP
}

IPv4

type Mmsghdr added in v1.0.55

type Mmsghdr struct {
	Hdr    unix.Msghdr
	MsgLen uint32
	// contains filtered or unexported fields
}

Mmsghdr represents the mmsghdr struct for amd64 architecture This matches the C struct mmsghdr layout on 64-bit systems

type MockResultProcessor

type MockResultProcessor struct {
	// contains filtered or unexported fields
}

MockResultProcessor is a mock of ResultProcessor interface.

func NewMockResultProcessor

func NewMockResultProcessor(ctrl *gomock.Controller) *MockResultProcessor

NewMockResultProcessor creates a new mock instance.

func (*MockResultProcessor) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockResultProcessor) GetSummary

func (m *MockResultProcessor) GetSummary() (*models.SweepSummary, error)

GetSummary mocks base method.

func (*MockResultProcessor) Process

func (m *MockResultProcessor) Process(result *models.Result) error

Process mocks base method.

func (*MockResultProcessor) Reset

func (m *MockResultProcessor) Reset()

Reset mocks base method.

type MockResultProcessorMockRecorder

type MockResultProcessorMockRecorder struct {
	// contains filtered or unexported fields
}

MockResultProcessorMockRecorder is the mock recorder for MockResultProcessor.

func (*MockResultProcessorMockRecorder) GetSummary

func (mr *MockResultProcessorMockRecorder) GetSummary() *gomock.Call

GetSummary indicates an expected call of GetSummary.

func (*MockResultProcessorMockRecorder) Process

func (mr *MockResultProcessorMockRecorder) Process(result any) *gomock.Call

Process indicates an expected call of Process.

func (*MockResultProcessorMockRecorder) Reset

Reset indicates an expected call of Reset.

type MockScanner

type MockScanner struct {
	// contains filtered or unexported fields
}

MockScanner is a mock of Scanner interface.

func NewMockScanner

func NewMockScanner(ctrl *gomock.Controller) *MockScanner

NewMockScanner creates a new mock instance.

func (*MockScanner) EXPECT

func (m *MockScanner) EXPECT() *MockScannerMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockScanner) Scan

func (m *MockScanner) Scan(arg0 context.Context, arg1 []models.Target) (<-chan models.Result, error)

Scan mocks base method.

func (*MockScanner) Stop

func (m *MockScanner) Stop() error

Stop mocks base method.

type MockScannerMockRecorder

type MockScannerMockRecorder struct {
	// contains filtered or unexported fields
}

MockScannerMockRecorder is the mock recorder for MockScanner.

func (*MockScannerMockRecorder) Scan

func (mr *MockScannerMockRecorder) Scan(arg0, arg1 any) *gomock.Call

Scan indicates an expected call of Scan.

func (*MockScannerMockRecorder) Stop

func (mr *MockScannerMockRecorder) Stop() *gomock.Call

Stop indicates an expected call of Stop.

type PortAllocator added in v1.0.55

type PortAllocator struct {
	// contains filtered or unexported fields
}

PortAllocator hands out ephemeral TCP source ports without reuse until Release. It is MPMC and lock-free: selection uses a round-robin cursor and each slot has an atomic state flag (0=free, 1=reserved).

func NewPortAllocator added in v1.0.55

func NewPortAllocator(start, end uint16) *PortAllocator

NewPortAllocator builds an allocator for [start, end] inclusive. Panics if start > end or range size is 0.

func (*PortAllocator) Available added in v1.0.55

func (a *PortAllocator) Available() int

Available is a heuristic count of currently free ports (O(n)).

func (*PortAllocator) Free added in v1.0.55

func (a *PortAllocator) Free() int

Free returns a fast, approximate count of free ports using the atomic counter. It does not scan the slots and is safe for concurrent use.

func (*PortAllocator) Release added in v1.0.55

func (a *PortAllocator) Release(port uint16)

Release marks a port free again. It’s safe to call multiple times.

func (*PortAllocator) Reserve added in v1.0.55

func (a *PortAllocator) Reserve(ctx context.Context) (uint16, error)

Reserve attempts to obtain one free port. It spins up to cnt fast attempts, then backs off briefly; repeats until success or ctx is done.

type ResultProcessor

type ResultProcessor interface {
	// Process takes a Result and updates internal state
	Process(result *models.Result) error
	// GetSummary returns the current summary of all processed results
	GetSummary() (*models.SweepSummary, error)
	// Reset clears the processor's state
	Reset()
}

ResultProcessor defines how to process and aggregate sweep results.

type SYNScanner added in v1.0.55

type SYNScanner struct {
	// contains filtered or unexported fields
}

SYNScanner performs SYN scanning (half-open scanning) for faster TCP port detection.

For maximum accuracy, consider setting iptables rules to drop outbound RSTs from your ephemeral port range to prevent kernel interference:

iptables -A OUTPUT -p tcp --tcp-flags RST RST --sport 32768:61000 -j DROP

or with nftables:

nft add rule inet filter output tcp flags rst tcp sport 32768-61000 drop

This implementation sniffs replies via AF_PACKET + TPACKET_V3 ring (zero-copy), uses classic BPF to reduce userland traffic, and PACKET_FANOUT to scale across cores. Packet crafting uses raw IPv4+TCP with IP_HDRINCL (unsafe only for ring setup, not packet crafting).

Linux-only. https://www.kernel.org/doc/Documentation/networking/packet_mmap.txt

func NewSYNScanner added in v1.0.55

func NewSYNScanner(timeout time.Duration, concurrency int, log logger.Logger, opts *SYNScannerOptions) (*SYNScanner, error)

NewSYNScanner creates a new SYN scanner with custom options

The scanner automatically detects a safe port range that doesn't conflict with the system's ephemeral ports or other local applications by reading: - /proc/sys/net/ipv4/ip_local_port_range (system ephemeral range) - /proc/sys/net/ipv4/ip_local_reserved_ports (reserved ports)

Rate limiting guidance: Set rate limit to avoid source-port exhaustion. The available window depends on the detected safe range. Each port is in-flight for ~timeout+grace. Safe starting rate: pps ≈ window/(timeout+grace)

Configure rate limit before starting a scan for best results, though SetRateLimit uses atomic.Value and is safe to call anytime, including during active scans.

Example: scanner.SetRateLimit(20000, 5000) // 20k pps, 5k burst

func (*SYNScanner) GetStats added in v1.0.55

func (s *SYNScanner) GetStats() ScannerStats

GetStats returns a snapshot of scanner performance statistics Safe to call concurrently during scans

func (*SYNScanner) ResetStats added in v1.0.55

func (s *SYNScanner) ResetStats()

ResetStats clears all performance counters and updates the reset timestamp

func (*SYNScanner) Scan added in v1.0.55

func (s *SYNScanner) Scan(ctx context.Context, targets []models.Target) (<-chan models.Result, error)

Scan performs SYN scanning on the given targets

func (*SYNScanner) SetRateLimit added in v1.0.55

func (s *SYNScanner) SetRateLimit(pps, burst int)

SetRateLimit installs a global rate limit (packets/sec) with a burst. Pass pps<=0 to disable. If burst<=0, burst defaults to pps. Safe to call anytime, including during active scans.

func (*SYNScanner) SetResultCallback added in v1.0.55

func (s *SYNScanner) SetResultCallback(callback func(models.Result))

SetResultCallback sets a callback function that will be called immediately when a result becomes available

func (*SYNScanner) Stop added in v1.0.55

func (s *SYNScanner) Stop() error

Stop gracefully stops the scanner

type SYNScannerOptions added in v1.0.55

type SYNScannerOptions struct {
	// SendBatchSize is the number of packets to send per sendmmsg call
	// If 0, defaults to defaultSendBatchSize or SENDMMSG_BATCH_SIZE env var
	SendBatchSize int
	// RateLimit is the packets per second limit
	// If 0, a safe default will be calculated based on port window and timeout
	RateLimit int
	// RateLimitBurst is the burst size for rate limiting
	// If 0, defaults to RateLimit
	RateLimitBurst int
	// RouteDiscoveryHost is the target address for local IP discovery
	// If empty, defaults to "8.8.8.8:80"
	RouteDiscoveryHost string

	// Ring buffer tuning options for memory vs latency tradeoffs
	// RingBlockSize is the size of each ring buffer block in bytes
	// If 0, defaults to defaultBlockSize (1 MiB)
	RingBlockSize uint32
	// RingBlockCount is the number of blocks in the ring buffer
	// If 0, defaults to defaultBlockCount (8 blocks = 8 MiB total)
	RingBlockCount uint32
	// RingFrameSize is the frame size hint for packet alignment
	// If 0, defaults to defaultFrameSize (2048 bytes)
	RingFrameSize uint32

	// Interface specifies which network interface to use for scanning
	// If empty, the interface will be auto-detected based on routing table
	// Examples: "eth0", "wlan0", "enp0s3"
	// Useful for multi-homed hosts or container environments
	Interface string

	// NAT/Firewall options for advanced environments
	// SuppressRSTReply can be set to true to avoid generating RST packets
	// This helps in environments where firewall rules might interfere
	// Note: This is optional and most environments don't need it
	SuppressRSTReply bool

	// GlobalRingMemoryMB is the total memory cap (in MB) for all ring buffers
	// across all CPU cores. If 0, defaults to 64MB total. This prevents
	// excessive memory usage on high-CPU systems by distributing the cap.
	GlobalRingMemoryMB int

	// RingReaders limits the number of AF_PACKET ring readers (and rings).
	// If 0, defaults to min(4, runtime.NumCPU()). More readers can increase
	// wakeups on low-reply scans without benefit.
	RingReaders int

	// RingPollTimeoutMs sets the poll() timeout in milliseconds for ring readers.
	// If 0, defaults to max(TPACKET_RETIRE_TOV_MS, 50). Raising this reduces
	// wakeups when traffic is sparse, cutting CPU in listenForReplies.
	RingPollTimeoutMs int
}

SYNScannerOptions contains optional configuration for the SYN scanner

type Scanner

type Scanner interface {
	// Scan performs the sweep and returns results through the channel
	Scan(context.Context, []models.Target) (<-chan models.Result, error)
	// Stop gracefully stops any ongoing scans
	Stop() error
}

Scanner defines how to perform network sweeps.

type ScannerStats added in v1.0.55

type ScannerStats struct {
	// Packet statistics
	PacketsSent    uint64 // Total SYN packets sent
	PacketsRecv    uint64 // Total packets received (SYN-ACK, RST, etc.)
	PacketsDropped uint64 // Packets dropped by kernel (ring buffer full)

	// Ring buffer statistics
	RingBlocksProcessed uint64 // TPACKET_V3 blocks processed
	RingBlocksDropped   uint64 // TPACKET_V3 blocks lost due to buffer overruns (TP_STATUS_LOSING)

	// Retry statistics
	RetriesAttempted  uint64 // Number of retry attempts made
	RetriesSuccessful uint64 // Number of successful retries

	// Port allocation statistics
	PortsAllocated uint64 // Total port allocations
	PortsReleased  uint64 // Total port releases
	PortExhaustion uint64 // Number of times port allocator was exhausted

	// Rate limiting statistics
	RateLimitDeferrals uint64 // Packet send operations deferred due to rate limiting

	// Timing statistics (in nanoseconds, for precision)
	LastStatsReset int64 // Timestamp of last stats reset (UnixNano)
}

ScannerStats holds performance and diagnostic counters

type StatsProvider added in v1.0.79

type StatsProvider interface {
	// GetStats returns a snapshot of scanner performance statistics
	GetStats() ScannerStats
}

StatsProvider is an optional interface for scanners that can provide statistics.

type TCPHdr added in v1.0.55

type TCPHdr struct {
	SrcPort uint16
	DstPort uint16
	Seq     uint32
	Ack     uint32
	Flags   uint8
}

TCP

type TCPSweeper

type TCPSweeper struct {
	// contains filtered or unexported fields
}

func NewTCPSweeper

func NewTCPSweeper(timeout time.Duration, concurrency int, log logger.Logger) *TCPSweeper

func (*TCPSweeper) Scan

func (s *TCPSweeper) Scan(ctx context.Context, targets []models.Target) (<-chan models.Result, error)

func (*TCPSweeper) Stop

func (s *TCPSweeper) Stop() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL