Documentation
¶
Overview ¶
Package gomap is a pure Go, cross-platform, library-importable port scanner inspired by nmap. It supports TCP connect scanning on all platforms and SYN (stealth) scanning on Linux where raw sockets are available.
Index ¶
- Constants
- Variables
- func ApplyTiming(opts *ScanOptions, template TimingTemplate)
- func ApplyTimingDiscovery(opts *DiscoveryOptions, template TimingTemplate)
- func CreateHostRange(cidr string) []string
- func DefaultOSDB() (*probedb.OSDB, error)
- func DefaultProbeDB() (*probedb.ServiceProbeDB, error)
- func DiscoverHostsStream(ctx context.Context, hosts []string, opts DiscoveryOptions) <-chan HostResult
- func ExcludePorts(ports []int, excludeSpec string) ([]int, error)
- func ExpandTargets(targets []string) ([]string, error)
- func FormatInterfaceList(ifaces []InterfaceInfo) string
- func GenerateRandomTargets(n int) []string
- func GetARPCache() map[string]ARPEntry
- func GetLocalAddr(target string) (string, error)
- func GetLocalIP() (string, error)
- func GetLocalIPv6() (string, error)
- func GetLocalRange() string
- func IsIPv6(addr string) bool
- func LoadARPTable() (map[string]ARPEntry, error)
- func LoadExcludesFromFile(path string) ([]string, error)
- func LoadTargetsFromFile(path string) ([]string, error)
- func LookupMACVendor(mac string) string
- func LookupMACVendorHW(mac net.HardwareAddr) string
- func LookupService(port int) string
- func LookupUDPService(port int) string
- func MACPrefixes() map[string]string
- func ParsePortRange(spec string) ([]int, error)
- func ParseScanFlags(spec string) (uint16, error)
- func PortsByRatio(ratio float64) []int
- func ResultsToXMLStyled(results []*ScanResult, scanType ScanType, startTime time.Time, version string, ...) ([]byte, error)
- func SaveResume(path string, state *ResumeState) error
- func ScanCIDRStream(ctx context.Context, cidr string, opts ScanOptions) <-chan ScanEvent
- func ScanHostStream(ctx context.Context, hostname string, opts ScanOptions) <-chan ScanEvent
- func SpoofMAC(iface, mac string) (restore func() error, err error)
- func ToScriptKiddie(normal string) string
- func TopUDPPorts(n int) []int
- type ARPEntry
- type DecoyConfig
- type DiscoveryMethod
- type DiscoveryOptions
- type FTPBounceConfig
- type HostResult
- type ICMPFingerprint
- type IdleScanConfig
- type InterfaceInfo
- type InvalidFlagError
- type JSONPort
- type JSONResult
- type ListTarget
- type NmapRun
- type OPSFingerprint
- type OSDetectResult
- type OSFingerprint
- type OSMatch
- type OutputConfig
- type PacketDirection
- type PortResult
- type PortState
- type ProbeFingerprint
- type ProtocolResult
- type RangeScanResult
- type RateLimiter
- type ResumeOptions
- type ResumeState
- type SEQFingerprint
- type ScanEvent
- type ScanOptions
- type ScanResult
- func (r *ScanResult) HasOpenPorts() bool
- func (r *ScanResult) JSON() (string, error)
- func (r *ScanResult) OpenPorts() []PortResult
- func (r *ScanResult) String() string
- func (r *ScanResult) ToGrepable() string
- func (r *ScanResult) ToXML(scanType ScanType, startTime time.Time, version string) ([]byte, error)
- type ScanType
- type Script
- type ScriptCategory
- type ScriptEngine
- func (e *ScriptEngine) GetScript(id string) (Script, bool)
- func (e *ScriptEngine) ListScripts() []string
- func (e *ScriptEngine) Register(s Script)
- func (e *ScriptEngine) RunScripts(ctx context.Context, scripts []Script, target ScriptTarget, workers int) []ScriptOutput
- func (e *ScriptEngine) SelectByCategory(categories ...ScriptCategory) []Script
- func (e *ScriptEngine) SelectByIDs(ids ...string) []Script
- type ScriptOutput
- type ScriptPhase
- type ScriptTarget
- type ServiceVersion
- func GrabBanner(ctx context.Context, host string, port int, timeout time.Duration, ...) (*ServiceVersion, error)
- func GrabBannerWithIntensity(ctx context.Context, host string, port int, timeout time.Duration, ...) (*ServiceVersion, error)
- func GrabBanners(ctx context.Context, host string, result *ScanResult, opts ScanOptions) []ServiceVersion
- type TimingTemplate
- type TracerouteHop
- type TracerouteOptions
- type TracerouteResult
- type UDPFingerprint
- type WINFingerprint
- type XMLAddress
- type XMLDebugging
- type XMLFinished
- type XMLHop
- type XMLHost
- type XMLHostStat
- type XMLHostname
- type XMLHostnames
- type XMLOS
- type XMLOSClass
- type XMLOSFingerprint
- type XMLOSMatch
- type XMLPort
- type XMLPorts
- type XMLRunStats
- type XMLScanInfo
- type XMLScript
- type XMLScriptElem
- type XMLService
- type XMLState
- type XMLStatus
- type XMLTimes
- type XMLTrace
- type XMLVerbose
Examples ¶
Constants ¶
const OSScanGuessAggressiveThreshold = 0.50
OSScanGuessAggressiveThreshold is used when --osscan-guess is enabled. Any match above this threshold is reported.
const OSScanGuessThreshold = 0.85
DetectOS attempts to identify the operating system of a target host by analyzing its TCP/IP stack behavior.
This requires: - At least one open port and one closed port on the target - Raw socket privileges (Linux: root or CAP_NET_RAW)
The function sends a series of carefully crafted probes and analyzes the responses to build a fingerprint, which is then compared against a database of known OS signatures. OSScanGuessThreshold is the default confidence threshold for OS match reporting. With --osscan-guess, this is lowered to report more aggressive guesses. Matches nmap's OSSCAN_GUESS_THRESHOLD (0.85).
Variables ¶
var ( // ErrRawSocketRequired is returned when a scan type needs raw sockets // but the process lacks sufficient privileges (root/CAP_NET_RAW on Linux). ErrRawSocketRequired = errors.New("raw socket required") // ErrLinuxRequired is returned when a feature is only available on Linux. ErrLinuxRequired = errors.New("feature requires Linux") // ErrResolveHost is returned when hostname resolution fails. ErrResolveHost = errors.New("host resolution failed") // ErrNoAddresses is returned when DNS resolves but yields no IP addresses. ErrNoAddresses = errors.New("no IP addresses for host") // ErrInvalidCIDR is returned when a CIDR string cannot be parsed. ErrInvalidCIDR = errors.New("invalid CIDR notation") // ErrInvalidPortSpec is returned when a port specification cannot be parsed. ErrInvalidPortSpec = errors.New("invalid port specification") // ErrScanCanceled is returned when a scan is canceled via context. ErrScanCanceled = errors.New("scan canceled") // ErrInvalidScanOptions is returned by Validate() when options are inconsistent. ErrInvalidScanOptions = errors.New("invalid scan options") )
Sentinel errors for common failure modes. Callers can use errors.Is() to distinguish error types programmatically.
var CommonPorts map[int]string
CommonPorts maps the top TCP ports to service names for fast scanning.
var DefaultEngine = NewScriptEngine()
DefaultEngine is the global script engine with built-in scripts.
var DetailedPorts map[int]string
DetailedPorts is the full TCP service map for comprehensive scans.
var ErrInvalidTimingTemplate = errors.New("invalid timing template (valid: T0-T5, paranoid, sneaky, polite, normal, aggressive, insane)")
ErrInvalidTimingTemplate is returned when an invalid timing template is specified.
var TCPPortFrequency = map[int]float64{}/* 4259 elements not displayed */
TCPPortFrequency maps TCP port numbers to their open frequency (0.0-1.0). Derived from nmap-services empirical scanning data.
var TCPServices = map[int]string{}/* 8385 elements not displayed */
TCPServices maps TCP port numbers to service names. Names are sourced from IANA where available, with nmap-services filling gaps.
var TopTCPPorts = []int{}/* 1000 elements not displayed */
TopTCPPorts contains the top 1000 most commonly open TCP ports, sorted by frequency (probability of being found open). Derived from empirical scanning data in nmap-services.
var UDPPortFrequency = map[int]float64{}/* 15617 elements not displayed */
UDPPortFrequency maps UDP port numbers to their open frequency (0.0-1.0).
var UDPServices = map[int]string{}/* 19204 elements not displayed */
UDPServices maps UDP port numbers to service names.
Functions ¶
func ApplyTiming ¶
func ApplyTiming(opts *ScanOptions, template TimingTemplate)
ApplyTiming configures ScanOptions based on a timing template.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
opts := gomap.ScanOptions{}
gomap.ApplyTiming(&opts, gomap.TimingAggressive)
fmt.Printf("Timeout: %s, Workers: %d\n", opts.Timeout, opts.Workers)
}
Output: Timeout: 1.25s, Workers: 1000
func ApplyTimingDiscovery ¶
func ApplyTimingDiscovery(opts *DiscoveryOptions, template TimingTemplate)
ApplyTimingDiscovery configures DiscoveryOptions based on a timing template.
func CreateHostRange ¶
CreateHostRange converts a CIDR notation string to a slice of host IP strings. Supports both IPv4 and IPv6 CIDR ranges.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
hosts := gomap.CreateHostRange("192.168.1.0/30")
fmt.Println(hosts)
}
Output: [192.168.1.1 192.168.1.2]
func DefaultOSDB ¶
DefaultOSDB returns the embedded nmap OS fingerprint database. Parsed lazily on first call and cached.
func DefaultProbeDB ¶
func DefaultProbeDB() (*probedb.ServiceProbeDB, error)
DefaultProbeDB returns the embedded nmap service probe database. Parsed lazily on first call and cached.
func DiscoverHostsStream ¶
func DiscoverHostsStream(ctx context.Context, hosts []string, opts DiscoveryOptions) <-chan HostResult
DiscoverHostsStream streams discovery results over a channel. The channel is closed when discovery completes.
func ExcludePorts ¶
ExcludePorts removes the specified ports from a port list. The exclude spec uses the same syntax as ParsePortRange: single ports, ranges, and protocol prefixes.
func ExpandTargets ¶
ExpandTargets takes a mixed list of IPs, hostnames, and CIDRs and expands CIDRs into individual IPs. Hostnames are resolved.
func FormatInterfaceList ¶
func FormatInterfaceList(ifaces []InterfaceInfo) string
FormatInterfaceList produces nmap-compatible --iflist output.
func GenerateRandomTargets ¶
GenerateRandomTargets generates n random public IPv4 addresses. Equivalent to nmap -iR.
func GetARPCache ¶
GetARPCache returns the most recently loaded ARP table. Call LoadARPTable first to populate the cache.
func GetLocalAddr ¶
GetLocalAddr returns the local IP matching the target's address family. If target is IPv6, returns a local IPv6 address; otherwise IPv4.
func GetLocalIP ¶
GetLocalIP returns the first non-loopback IPv4 address.
func GetLocalIPv6 ¶
GetLocalIPv6 returns the first non-loopback IPv6 address.
func GetLocalRange ¶
func GetLocalRange() string
GetLocalRange returns the local /24 CIDR range, or defaults to 192.168.1.0/24.
func IsIPv6 ¶
IsIPv6 returns true if the address string is an IPv6 address.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
fmt.Println(gomap.IsIPv6("192.168.1.1"))
fmt.Println(gomap.IsIPv6("::1"))
fmt.Println(gomap.IsIPv6("2001:db8::1"))
}
Output: false true true
func LoadARPTable ¶
LoadARPTable reads and parses the system ARP table from /proc/net/arp. This function is only available on Linux.
func LoadExcludesFromFile ¶
LoadExcludesFromFile reads a list of exclude targets from a file. Same format as LoadTargetsFromFile.
func LoadTargetsFromFile ¶
LoadTargetsFromFile reads a list of targets (IPs, hostnames, CIDRs) from a file. One target per line. Empty lines and lines starting with # are skipped.
func LookupMACVendor ¶
LookupMACVendor returns the vendor name for a given MAC address.
func LookupMACVendorHW ¶
func LookupMACVendorHW(mac net.HardwareAddr) string
LookupMACVendorHW returns the vendor name for a net.HardwareAddr.
func LookupService ¶
LookupService returns the service name for a given TCP port number. Returns "unknown" if no service is found.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
fmt.Println(gomap.LookupService(22))
fmt.Println(gomap.LookupService(80))
fmt.Println(gomap.LookupService(443))
}
Output: The Secure Shell (SSH) Protocol World Wide Web HTTP http protocol over TLS/SSL
func LookupUDPService ¶
LookupUDPService returns the service name for a given UDP port number.
func MACPrefixes ¶
MACPrefixes returns the full OUI-to-vendor map from the embedded database.
func ParsePortRange ¶
ParsePortRange parses an nmap-style port specification string. Supports:
- Single ports: "80"
- Ranges: "1-1024"
- Comma-separated: "80,443,8080"
- Mixed: "22,80-90,443,8000-9000"
- Protocol prefix: "T:80,U:53" (T=TCP, U=UDP)
- All ports: "-" (equivalent to "1-65535")
- Top ports: not handled here (use --top-ports flag)
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
ports, err := gomap.ParsePortRange("22,80,443")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(ports)
}
Output: [22 80 443]
Example (Range) ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
ports, err := gomap.ParsePortRange("80-82")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(ports)
}
Output: [80 81 82]
func ParseScanFlags ¶
ParseScanFlags parses a custom TCP flag specification. Accepts numeric values (e.g., "0x29") or flag characters: U=URG, A=ACK, P=PSH, R=RST, S=SYN, F=FIN. Matches nmap's --scanflags behavior.
func PortsByRatio ¶
PortsByRatio returns all TCP ports with an open frequency >= ratio. Ratio values typically range from 0.0 to 1.0. For example, PortsByRatio(0.01) returns ports open in >= 1% of scans.
Example ¶
ExamplePortsByRatio shows selecting ports by open-frequency ratio.
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
ports := gomap.PortsByRatio(0.01) // ports open >1% of the time
fmt.Printf("Ports with >1%% open ratio: %d\n", len(ports))
}
func ResultsToXMLStyled ¶
func ResultsToXMLStyled(results []*ScanResult, scanType ScanType, startTime time.Time, version string, stylesheet string) ([]byte, error)
resultsToXMLStyled produces XML output with an optional XSL stylesheet reference. If stylesheet is empty, no processing instruction is added. If stylesheet is "webxml", the nmap.org stylesheet URL is used. ResultsToXMLStyled produces XML output with an optional XSL stylesheet reference.
func SaveResume ¶
func SaveResume(path string, state *ResumeState) error
SaveResume writes the resume state to a file.
func ScanCIDRStream ¶
func ScanCIDRStream(ctx context.Context, cidr string, opts ScanOptions) <-chan ScanEvent
ScanCIDRStream scans a CIDR range and streams results over a channel. Results from different hosts are interleaved. Each host's completion is signaled by a ScanEvent with Done=true.
func ScanHostStream ¶
func ScanHostStream(ctx context.Context, hostname string, opts ScanOptions) <-chan ScanEvent
ScanHostStream scans a single host and streams results over a channel. The channel is closed when the scan completes. The caller must drain the channel to avoid goroutine leaks.
This is the preferred API for UIs and interactive applications that want to display results as they arrive.
func SpoofMAC ¶
SpoofMAC changes the MAC address of a network interface. mac can be: a specific MAC ("00:11:22:33:44:55"), a vendor prefix ("Dell", "Apple"), or "0" for a fully random MAC. Returns a restore function to set the original MAC back.
func ToScriptKiddie ¶
ToScriptKiddie converts normal output to "script kiddie" format (-oS). This is nmap's joke output mode that replaces characters with leet-speak.
func TopUDPPorts ¶
TopUDPPorts returns the top N most common UDP ports by frequency.
Types ¶
type ARPEntry ¶
ARPEntry represents a single entry in the system ARP table.
func ParseARPEntry ¶
ParseARPEntry parses a single line from /proc/net/arp.
type DecoyConfig ¶
type DecoyConfig struct {
// Decoys is a list of decoy IP addresses. Use "RND" to generate
// a random IP, or "ME" to insert the real IP at that position.
// Example: ["RND", "RND", "ME", "RND"]
Decoys []string
// contains filtered or unexported fields
}
DecoyConfig configures decoy scanning. Decoys send scan packets from spoofed source IPs to make it harder to determine the real scanning host.
func GenerateRandomDecoys ¶
func GenerateRandomDecoys(n int, realIP string, ipv6 bool) (*DecoyConfig, error)
GenerateRandomDecoys creates n random decoy IPs with the real IP inserted at a random position.
func ParseDecoys ¶
func ParseDecoys(spec string, realIP string) (*DecoyConfig, error)
ParseDecoys parses an nmap-style decoy string: "decoy1,decoy2,ME,RND"
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
dc, err := gomap.ParseDecoys("RND,ME,RND", "192.168.1.100")
if err != nil {
fmt.Println("error:", err)
return
}
ips := dc.ResolvedIPs()
fmt.Printf("Decoy count: %d\n", len(ips))
fmt.Printf("Real IP at index 1: %s\n", ips[1])
}
Output: Decoy count: 3 Real IP at index 1: 192.168.1.100
func (*DecoyConfig) ResolvedIPs ¶
func (dc *DecoyConfig) ResolvedIPs() []net.IP
ResolvedIPs returns the final list of IPs (decoys + real) in order.
type DiscoveryMethod ¶
type DiscoveryMethod int
DiscoveryMethod represents a host discovery technique.
const ( // DiscoveryTCPSYN sends a TCP SYN packet to detect hosts. // Default probe port is 80. DiscoveryTCPSYN DiscoveryMethod = iota // DiscoveryTCPACK sends a TCP ACK packet to detect hosts. // Default probe port is 80. DiscoveryTCPACK // DiscoveryUDP sends a UDP packet to detect hosts. // Default probe port is 40125. DiscoveryUDP // DiscoveryICMP sends an ICMP echo request (ping). DiscoveryICMP // DiscoveryConnect performs a TCP connect to detect hosts. // Works without privileges. DiscoveryConnect // DiscoveryARP uses ARP requests for local network discovery. // Only works on the local subnet. DiscoveryARP // DiscoveryICMPTimestamp sends an ICMP timestamp request. DiscoveryICMPTimestamp // DiscoveryICMPNetmask sends an ICMP address mask request. DiscoveryICMPNetmask // DiscoverySCTPInit sends an SCTP INIT chunk to detect hosts (-PY). DiscoverySCTPInit // DiscoveryIPProtocol sends raw IP packets with varying protocol numbers (-PO). DiscoveryIPProtocol )
func (DiscoveryMethod) String ¶
func (m DiscoveryMethod) String() string
String returns the human-readable name of a discovery method.
type DiscoveryOptions ¶
type DiscoveryOptions struct {
// Methods specifies which discovery techniques to use.
// If empty, defaults to [DiscoveryICMP, DiscoveryTCPSYN].
Methods []DiscoveryMethod
// Ports specifies TCP/UDP probe ports for non-ICMP methods.
// Default: [80, 443] for TCP, [40125] for UDP.
Ports []int
// Timeout is the per-probe timeout (default 2s).
Timeout time.Duration
// Workers is the number of concurrent discovery goroutines (default 100).
Workers int
}
DiscoveryOptions configures host discovery.
type FTPBounceConfig ¶
type FTPBounceConfig struct {
// Server is the FTP server host:port to use as relay.
Server string
// Username for FTP login (default "anonymous").
Username string
// Password for FTP login (default "gomap@").
Password string
}
FTPBounceConfig holds the FTP relay server configuration.
type HostResult ¶
type HostResult struct {
IP string
Hostname string
Alive bool
Method DiscoveryMethod
Latency time.Duration
}
HostResult represents the discovery result for a single host.
func DiscoverCIDR ¶
func DiscoverCIDR(ctx context.Context, cidr string, opts DiscoveryOptions) ([]HostResult, error)
DiscoverCIDR discovers all alive hosts in a CIDR range.
func DiscoverHosts ¶
func DiscoverHosts(ctx context.Context, hosts []string, opts DiscoveryOptions) ([]HostResult, error)
DiscoverHosts probes a list of IP addresses to determine which are alive.
func DiscoverLocal ¶
func DiscoverLocal(ctx context.Context, opts DiscoveryOptions) ([]HostResult, error)
DiscoverLocal discovers alive hosts on the local network.
func (HostResult) String ¶
func (r HostResult) String() string
String returns a human-readable representation of the host discovery result.
type ICMPFingerprint ¶
ICMPFingerprint contains characteristics from ICMP echo responses.
type IdleScanConfig ¶
type IdleScanConfig struct {
// ZombieHost is the IP or hostname of the zombie (idle) host.
ZombieHost string
// ZombiePort is the port on the zombie to probe (default 80).
ZombiePort int
}
IdleScanConfig holds the zombie host configuration for idle scanning.
type InterfaceInfo ¶
InterfaceInfo contains information about a network interface.
func ListInterfaces ¶
func ListInterfaces() ([]InterfaceInfo, error)
ListInterfaces returns information about all network interfaces, matching nmap's --iflist output.
type InvalidFlagError ¶
type InvalidFlagError struct {
Flag string
}
InvalidFlagError is returned when an unknown flag character is encountered.
func (*InvalidFlagError) Error ¶
func (e *InvalidFlagError) Error() string
type JSONPort ¶
type JSONPort struct {
Port int `json:"port"`
Protocol string `json:"protocol"`
State string `json:"state"`
Service string `json:"service"`
Reason string `json:"reason,omitempty"`
}
JSONPort is a structured representation of a port result for JSON output.
type JSONResult ¶
type JSONResult struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
Active bool `json:"active"`
StartTime string `json:"start_time,omitempty"`
EndTime string `json:"end_time,omitempty"`
Duration string `json:"duration,omitempty"`
Ports []JSONPort `json:"ports,omitempty"`
}
JSONResult is the JSON-serializable representation of a single host scan.
type ListTarget ¶
ListTargets resolves and lists targets without scanning (nmap -sL). Returns resolved hostnames and IPs.
type NmapRun ¶
type NmapRun struct {
XMLName xml.Name `xml:"nmaprun"`
Scanner string `xml:"scanner,attr"`
Args string `xml:"args,attr,omitempty"`
Start int64 `xml:"start,attr"`
StartStr string `xml:"startstr,attr"`
Version string `xml:"version,attr"`
XMLOutputVersion string `xml:"xmloutputversion,attr"`
ScanInfo *XMLScanInfo `xml:"scaninfo,omitempty"`
Verbose XMLVerbose `xml:"verbose"`
Debugging XMLDebugging `xml:"debugging"`
Hosts []XMLHost `xml:"host"`
RunStats XMLRunStats `xml:"runstats"`
}
NmapRun is the top-level XML element, compatible with nmap's -oX format.
type OPSFingerprint ¶
type OPSFingerprint struct {
// O1-O6: TCP options string from each of 6 SYN probes
Options [6]string
}
OPSFingerprint contains TCP options from SYN-ACK responses.
type OSDetectResult ¶
type OSDetectResult struct {
Host string
Fingerprint OSFingerprint
Matches []OSMatch
// Raw is the nmap-compatible fingerprint string
Raw string
}
OSDetectResult contains the results of OS detection for a host.
func DetectOS ¶
func DetectOS(ctx context.Context, host string, openPort, closedPort int, opts ScanOptions) (*OSDetectResult, error)
DetectOS performs OS fingerprinting against a host by sending TCP/IP probes to an open and a closed port, then matching the responses against the nmap OS fingerprint database. Both openPort and closedPort must be known in advance.
type OSFingerprint ¶
type OSFingerprint struct {
// SEQ: TCP ISN (Initial Sequence Number) analysis
SEQ SEQFingerprint
// OPS: TCP options in SYN-ACK responses
OPS OPSFingerprint
// WIN: TCP initial window sizes
WIN WINFingerprint
// T1-T7: Response characteristics to different probes
Probes [7]ProbeFingerprint
// U1: UDP probe response characteristics
U1 UDPFingerprint
// IE: ICMP echo response characteristics
IE ICMPFingerprint
}
OSFingerprint contains TCP/IP stack characteristics used for OS identification.
type OSMatch ¶
type OSMatch struct {
Name string
Family string
Generation string
DeviceType string
CPE []string
Accuracy float64
}
OSMatch represents a potential OS match with confidence score.
type OutputConfig ¶
type OutputConfig struct {
// NormalFile is the path for human-readable output (-oN).
NormalFile string
// XMLFile is the path for XML output (-oX).
XMLFile string
// GrepFile is the path for grepable output (-oG).
GrepFile string
// ScriptKiddieFile is the path for script kiddie output (-oS).
ScriptKiddieFile string
// Append appends to output files instead of overwriting.
Append bool
}
OutputConfig configures file output destinations.
func (*OutputConfig) HasFileOutput ¶
func (o *OutputConfig) HasFileOutput() bool
HasFileOutput returns true if any file output is configured.
func (*OutputConfig) WriteAll ¶
func (o *OutputConfig) WriteAll(normal string, xmlData []byte, grep string) error
WriteAll writes all configured output formats at once.
func (*OutputConfig) WriteGrep ¶
func (o *OutputConfig) WriteGrep(data string) error
WriteGrep writes grepable output to the configured file.
func (*OutputConfig) WriteNormal ¶
func (o *OutputConfig) WriteNormal(data string) error
WriteNormal writes human-readable output to the configured file.
func (*OutputConfig) WriteXML ¶
func (o *OutputConfig) WriteXML(data []byte) error
WriteXML writes XML output to the configured file.
type PacketDirection ¶
type PacketDirection string
PacketDirection indicates whether a packet was sent or received.
const ( PacketSent PacketDirection = "SENT" PacketReceived PacketDirection = "RCVD" )
type PortResult ¶
type PortResult struct {
Port int
Protocol string // "tcp", "udp", or "sctp" (default "tcp")
Open bool
State PortState
Service string
Reason string
}
PortResult describes the state of a single port.
type PortState ¶
type PortState int
PortState represents the state of a scanned port.
const ( // PortClosed indicates the port is closed (RST received). PortClosed PortState = iota // PortOpen indicates the port is open (connection accepted or SYN-ACK received). PortOpen // PortFiltered indicates the port is filtered (no response or ICMP unreachable). PortFiltered // PortUnfiltered indicates the port responded but open/closed is unknown (ACK scan). PortUnfiltered // PortOpenFiltered indicates the port is either open or filtered (no response in FIN/NULL/Xmas). PortOpenFiltered )
type ProbeFingerprint ¶
type ProbeFingerprint struct {
// R: Did we get a response? (Y/N)
Responded bool
// DF: Don't fragment bit set (Y/N)
DF bool
// T: IP TTL (time to live)
TTL int
// W: TCP window size
Window int
// S: TCP sequence number behavior
SeqBehavior string
// A: TCP acknowledgment behavior
AckBehavior string
// F: TCP flags
Flags string
// O: TCP options
Options string
// RD: RST data CRC
RD int
// Q: Quirks
Quirks string
}
ProbeFingerprint contains the response to a specific TCP probe.
type ProtocolResult ¶
ProtocolResult represents the result of an IP protocol scan for one protocol.
func IPProtocolScan ¶
func IPProtocolScan(ctx context.Context, host string, opts ScanOptions) ([]ProtocolResult, error)
IPProtocolScan sends raw IP packets for each protocol number (0-255) and determines which IP protocols are supported by the target. Matches nmap's -sO scan type.
type RangeScanResult ¶
type RangeScanResult []*ScanResult
RangeScanResult contains results for multiple hosts.
func ScanCIDR ¶
func ScanCIDR(ctx context.Context, cidr string, opts ScanOptions) (RangeScanResult, error)
ScanCIDR scans every address on a given CIDR for open ports.
func ScanRange ¶
func ScanRange(ctx context.Context, opts ScanOptions) (RangeScanResult, error)
ScanRange scans every address on the local CIDR for open ports.
func (RangeScanResult) JSON ¶
func (results RangeScanResult) JSON() (string, error)
JSON returns a JSON-encoded string of all scan results.
func (RangeScanResult) String ¶
func (results RangeScanResult) String() string
String returns a human-readable summary of all scan results.
func (RangeScanResult) ToGrepable ¶
func (results RangeScanResult) ToGrepable() string
ToGrepable converts a RangeScanResult to grepable format.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter controls the packet sending rate. It uses a token bucket algorithm to enforce min/max rates.
func NewRateLimiter ¶
func NewRateLimiter(minRate, maxRate int) *RateLimiter
NewRateLimiter creates a rate limiter with the given constraints. minRate is the minimum packets/second (0 = no minimum). maxRate is the maximum packets/second (0 = unlimited).
func (*RateLimiter) MinWorkers ¶
func (rl *RateLimiter) MinWorkers(timeoutPerProbe time.Duration) int
MinWorkers returns the minimum number of workers needed to sustain the minimum rate. Returns 0 if no minimum rate is set.
func (*RateLimiter) Wait ¶
func (rl *RateLimiter) Wait()
Wait blocks until it's safe to send the next packet according to the rate limit. It returns immediately if the context is canceled.
func (*RateLimiter) WaitCtx ¶
func (rl *RateLimiter) WaitCtx(ctx context.Context)
WaitCtx blocks until it's safe to send the next packet, or ctx is canceled.
type ResumeOptions ¶
type ResumeOptions struct {
ScanType string `json:"scanType"`
FastScan bool `json:"fastScan"`
TopPorts int `json:"topPorts,omitempty"`
PortSpec string `json:"portSpec,omitempty"`
Timing string `json:"timing,omitempty"`
}
ResumeOptions is a serializable subset of ScanOptions.
type ResumeState ¶
type ResumeState struct {
// Version identifies the resume file format.
Version int `json:"version"`
// StartTime is when the original scan began.
StartTime time.Time `json:"startTime"`
// Targets is the full list of targets.
Targets []string `json:"targets"`
// CompletedHosts tracks which hosts have been fully scanned.
CompletedHosts map[string]bool `json:"completedHosts"`
// Options stores the scan configuration.
Options ResumeOptions `json:"options"`
}
ResumeState contains the state needed to resume an interrupted scan.
func LoadResume ¶
func LoadResume(path string) (*ResumeState, error)
LoadResume reads a resume state from a file.
func (*ResumeState) MarkComplete ¶
func (s *ResumeState) MarkComplete(host, resumeFile string) error
MarkComplete marks a host as completed and saves state. Returns an error if the resume file cannot be written.
func (*ResumeState) RemainingTargets ¶
func (s *ResumeState) RemainingTargets() []string
RemainingTargets returns targets not yet completed.
type SEQFingerprint ¶
type SEQFingerprint struct {
// SP: TCP ISN sequence predictability (0=constant, >5=random)
SP int
// GCD: Greatest common divisor of ISN differences
GCD int
// ISR: ISN counter rate (ISNs per second)
ISR int
// TI: IPID sequence type (I=incremental, RI=random increment, etc.)
TI string
// CI: Closed-port IPID sequence
CI string
// II: ICMP IPID sequence
II string
// SS: Shared IP ID sequence (S=yes, O=no)
SS string
// TS: TCP timestamp option (U=unsupported, 0-F=Hz)
TS string
}
SEQFingerprint contains TCP sequence analysis data.
type ScanEvent ¶
type ScanEvent struct {
// Host identifies which host this result belongs to (for range/CIDR scans).
Host string
// Port is the scanned port result. Nil for host-level events.
Port *PortResult
// Done is true when all ports for this host have been scanned.
Done bool
// Error is non-nil if the scan encountered an error for this host.
Error error
}
ScanEvent represents a single result event from a streaming scan. Consumers receive these as they are produced, without waiting for the entire scan to complete.
type ScanOptions ¶
type ScanOptions struct {
// ScanType determines the scanning technique (default ConnectScan).
ScanType ScanType
// FastScan uses the common port list instead of the detailed list.
FastScan bool
// Stealth is a convenience alias that sets ScanType to SYNScan.
// Deprecated: use ScanType directly.
Stealth bool
// Timeout is the per-port connection timeout (default 3s).
Timeout time.Duration
// Workers is the number of concurrent scanning goroutines (default auto).
Workers int
// ProgressFunc is called after each port is scanned.
// It receives the number of ports scanned so far and the total.
// Set to nil to disable progress reporting.
ProgressFunc func(scanned, total int)
// Ports specifies custom ports to scan. If nil, the default port list is used.
Ports []int
// ProbeFile is an optional path to an nmap-service-probes file.
// If set, probes are loaded from this file instead of the embedded database.
// If empty, the embedded probe database is used.
ProbeFile string
// PreferIPv6 makes the scanner prefer IPv6 addresses when resolving hostnames.
PreferIPv6 bool
// Decoys configures decoy scanning. When set, additional packets are sent
// from spoofed source IPs to obscure the real scanner. Only works with
// raw socket scan types (SYN, FIN, Xmas, Null, ACK, Window).
Decoys *DecoyConfig
// OpenOnly filters results to only show open ports.
OpenOnly bool
// Reason includes the reason a port is in its state.
Reason bool
// ExcludeHosts is a list of hosts/CIDRs to skip during range scans.
ExcludeHosts []string
// ScanDelay is the minimum delay between probes to the same host.
ScanDelay time.Duration
// MaxRetries is the maximum number of port scan probe retransmissions.
MaxRetries int
// HostTimeout is the maximum time to spend on a single host.
HostTimeout time.Duration
// NoPing skips host discovery and treats all hosts as online (like nmap -Pn).
NoPing bool
// NoDNS disables reverse DNS resolution (like nmap -n).
NoDNS bool
// AlwaysDNS forces reverse DNS for all IPs (like nmap -R).
AlwaysDNS bool
// Verbose enables verbose output.
Verbose bool
// SourcePort forces scans to use this source port number.
SourcePort int
// MinRate is the minimum packets per second (0 = no minimum).
MinRate int
// MaxRate is the maximum packets per second (0 = unlimited).
MaxRate int
// VersionIntensity controls service probe depth (0-9, default 7).
// 0 = light (only NULL probe), 9 = try all probes.
VersionIntensity int
// PacketTrace logs every packet sent and received to TraceWriter.
// If TraceWriter is nil and PacketTrace is true, os.Stderr is used.
PacketTrace bool
// TraceWriter receives packet trace output. If nil and PacketTrace is true,
// defaults to os.Stderr. Library users should set this to avoid side effects.
TraceWriter io.Writer
// OSScanLimit skips OS detection on hosts without at least 1 open + 1 closed port.
OSScanLimit bool
// OSScanGuess lowers the OS match confidence threshold for more aggressive guessing.
OSScanGuess bool
// MinParallelism is the minimum number of parallel probe groups.
MinParallelism int
// MaxParallelism is the maximum number of parallel probe groups.
MaxParallelism int
// MinRTTTimeout is the minimum probe round-trip time timeout.
MinRTTTimeout time.Duration
// MaxRTTTimeout is the maximum probe round-trip time timeout.
MaxRTTTimeout time.Duration
// InitialRTTTimeout is the initial RTT timeout before adaptive adjustment.
InitialRTTTimeout time.Duration
// DNSServers overrides the system DNS resolvers.
DNSServers []string
// Fragment enables IP fragmentation of probe packets (-f).
Fragment bool
// MTU sets the fragment size when Fragment is enabled (default 8).
MTU int
// SpoofMAC sets a spoofed MAC address for outgoing packets.
SpoofMAC string
// IdleZombie configures the zombie host for idle scanning.
IdleZombie IdleScanConfig
// FTPBounce configures the FTP relay for bounce scanning.
FTPBounce FTPBounceConfig
// BadSum sends packets with an intentionally incorrect checksum.
// Useful for detecting firewalls/IDS that don't verify checksums.
BadSum bool
// TTL sets the IP time-to-live field on outgoing packets.
TTL int
// DataLength pads probe packets with random data to the specified length.
// Useful for evading IDS that trigger on specific packet sizes.
DataLength int
// ScanFlags sets custom TCP flags for raw scans (--scanflags).
// When set, overrides the flags implied by the scan type.
ScanFlags uint16
// ScanFlagsSet indicates whether ScanFlags was explicitly provided.
ScanFlagsSet bool
// SpoofSourceIP spoofs the source IP address (-S).
// Only effective with raw socket scan types on Linux.
SpoofSourceIP string
// Proxies is a list of HTTP/SOCKS4 proxy URLs to relay connect scans through.
Proxies []string
// Data is arbitrary hex data to append to sent packets (--data).
Data []byte
// DataString is an ASCII string to append to sent packets (--data-string).
DataString string
// IPOptions sets raw IP options on outgoing packets (--ip-options).
IPOptions []byte
// MaxOSTries limits the number of OS detection attempts per host.
MaxOSTries int
// VersionTrace enables detailed tracing of service version detection.
// Output goes to VersionTraceWriter (defaults to os.Stderr).
VersionTrace bool
// VersionTraceWriter receives version trace output. If nil and VersionTrace
// is true, defaults to os.Stderr. Library users should set this to avoid side effects.
VersionTraceWriter io.Writer
// ScriptArgs provides arguments to scripts as key=value pairs.
ScriptArgs map[string]string
// ScriptTrace enables tracing of all script data sent/received.
ScriptTrace bool
// ExcludePorts is a list of port numbers to exclude from scanning.
ExcludePorts []int
// MinHostgroup sets the minimum number of hosts to scan in parallel.
MinHostgroup int
// MaxHostgroup sets the maximum number of hosts to scan in parallel.
MaxHostgroup int
// Output configures file output destinations.
Output *OutputConfig
}
ScanOptions configures a scan.
func (*ScanOptions) Validate ¶
func (o *ScanOptions) Validate() error
Validate checks that the scan options are consistent and returns an error describing any problems. This is called automatically by Scan* functions, but callers may invoke it early for fast feedback.
Example ¶
ExampleScanOptions_Validate demonstrates early validation of scan options.
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
opts := gomap.ScanOptions{
VersionIntensity: 15, // invalid: must be 0-9
}
err := opts.Validate()
fmt.Println(err)
}
Output: invalid scan options: version-intensity must be 0-9, got 15
type ScanResult ¶
type ScanResult struct {
Hostname string
IP []net.IP
Ports []PortResult
StartTime time.Time // when scanning began for this host
EndTime time.Time // when scanning completed
Duration time.Duration // total scan time for this host
}
ScanResult contains the results of a scan on a single host.
func ScanHost ¶
func ScanHost(ctx context.Context, hostname string, opts ScanOptions) (*ScanResult, error)
ScanHost scans a single host for open ports.
func (*ScanResult) HasOpenPorts ¶
func (r *ScanResult) HasOpenPorts() bool
HasOpenPorts returns true if any ports are open.
func (*ScanResult) JSON ¶
func (r *ScanResult) JSON() (string, error)
JSON returns a JSON-encoded string of the scan result.
func (*ScanResult) OpenPorts ¶
func (r *ScanResult) OpenPorts() []PortResult
OpenPorts returns only the open ports from a scan result.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
result := &gomap.ScanResult{
Hostname: "example.com",
Ports: []gomap.PortResult{
{Port: 22, Open: true, Service: "ssh"},
{Port: 23, Open: false, Service: "telnet"},
{Port: 80, Open: true, Service: "http"},
},
}
for _, port := range result.OpenPorts() {
fmt.Printf("%d/%s\n", port.Port, port.Service)
}
}
Output: 22/ssh 80/http
func (*ScanResult) String ¶
func (r *ScanResult) String() string
String returns a human-readable summary of the scan result.
func (*ScanResult) ToGrepable ¶
func (r *ScanResult) ToGrepable() string
ToGrepable converts a ScanResult to nmap's grepable output format (-oG). Format: Host: <ip> (<hostname>) Ports: <port>/<state>/<proto>//<service>///
type ScanType ¶
type ScanType int
ScanType represents the type of port scan to perform.
const ( // ConnectScan performs a full TCP connect() scan. // Works on all platforms, no special privileges required. ConnectScan ScanType = iota // SYNScan performs a half-open SYN scan (stealth scan). // Linux only, requires raw socket privileges (root/CAP_NET_RAW). SYNScan // FINScan sends a TCP FIN packet. Open ports typically don't respond, // while closed ports respond with RST. Useful for evading firewalls. // Linux only, requires raw socket privileges. FINScan // XmasScan sends a TCP packet with FIN, PSH, and URG flags set. // Similar to FIN scan but with more flags lit up like a Christmas tree. // Linux only, requires raw socket privileges. XmasScan // NullScan sends a TCP packet with no flags set. // Closed ports respond with RST; open/filtered ports don't respond. // Linux only, requires raw socket privileges. NullScan // ACKScan sends a TCP ACK packet. Used to map firewall rules. // Doesn't determine open/closed, but filtered/unfiltered. // Linux only, requires raw socket privileges. ACKScan // WindowScan is like ACK scan but examines the TCP window field // of RST packets to differentiate open from closed ports. // Linux only, requires raw socket privileges. WindowScan // MaimonScan sends a TCP FIN/ACK packet. Similar to FIN scan but some // BSD-derived systems drop the packet for open ports instead of responding. // Linux only, requires raw socket privileges. MaimonScan // UDPScan sends UDP packets and interprets ICMP responses. // Works cross-platform but may require privileges for ICMP listening. UDPScan // SCTPInitScan sends an SCTP INIT chunk. An INIT-ACK indicates open, // ABORT indicates closed. Similar to TCP SYN scan. // Linux only, requires raw socket privileges. SCTPInitScan // SCTPCookieEchoScan sends an SCTP COOKIE-ECHO chunk. // Open ports silently drop the packet, closed ports respond with ABORT. // Linux only, requires raw socket privileges. SCTPCookieEchoScan // IdleScan uses a zombie host's IP ID sequence to infer port state // on the target without sending packets from the scanner's real IP. // Linux only, requires raw socket privileges. IdleScan // FTPBounceScan uses an FTP server's PORT command to scan ports // on a third-party host through the FTP server. FTPBounceScan )
func (ScanType) RequiresRawSocket ¶
RequiresRawSocket returns true if the scan type requires raw socket access.
type Script ¶
type Script interface {
// ID returns the unique script identifier (e.g., "http-title").
ID() string
// Description returns a human-readable description.
Description() string
// Categories returns the script's categories.
Categories() []ScriptCategory
// Phase returns when the script should run.
Phase() ScriptPhase
// Match returns true if this script should run against the given target.
// For port scripts, this typically checks service name or port number.
Match(target ScriptTarget) bool
// Run executes the script against the target.
Run(ctx context.Context, target ScriptTarget) (*ScriptOutput, error)
}
Script is the interface that all gomap scripts must implement.
type ScriptCategory ¶
type ScriptCategory string
ScriptCategory represents a script classification (matching nmap categories).
const ( CategoryAuth ScriptCategory = "auth" CategoryBroadcast ScriptCategory = "broadcast" CategoryDefault ScriptCategory = "default" CategoryDiscovery ScriptCategory = "discovery" CategoryDOS ScriptCategory = "dos" CategoryExploit ScriptCategory = "exploit" CategoryExternal ScriptCategory = "external" CategoryFuzzer ScriptCategory = "fuzzer" CategoryIntrusive ScriptCategory = "intrusive" CategoryMalware ScriptCategory = "malware" CategorySafe ScriptCategory = "safe" CategoryVersion ScriptCategory = "version" CategoryVuln ScriptCategory = "vuln" )
type ScriptEngine ¶
type ScriptEngine struct {
// contains filtered or unexported fields
}
ScriptEngine manages script registration, selection, and execution.
func NewScriptEngine ¶
func NewScriptEngine() *ScriptEngine
NewScriptEngine creates a new script engine.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
engine := gomap.NewScriptEngine()
fmt.Printf("Scripts: %d\n", len(engine.ListScripts()))
}
Output: Scripts: 0
func (*ScriptEngine) GetScript ¶
func (e *ScriptEngine) GetScript(id string) (Script, bool)
GetScript returns a script by ID.
func (*ScriptEngine) ListScripts ¶
func (e *ScriptEngine) ListScripts() []string
ListScripts returns all registered script IDs.
func (*ScriptEngine) Register ¶
func (e *ScriptEngine) Register(s Script)
Register adds a script to the engine.
func (*ScriptEngine) RunScripts ¶
func (e *ScriptEngine) RunScripts(ctx context.Context, scripts []Script, target ScriptTarget, workers int) []ScriptOutput
RunScripts executes the given scripts against a target with concurrency control.
func (*ScriptEngine) SelectByCategory ¶
func (e *ScriptEngine) SelectByCategory(categories ...ScriptCategory) []Script
SelectByCategory returns all scripts matching any of the given categories.
func (*ScriptEngine) SelectByIDs ¶
func (e *ScriptEngine) SelectByIDs(ids ...string) []Script
SelectByIDs returns scripts matching the given IDs. Supports glob patterns with "*" (e.g., "http-*").
type ScriptOutput ¶
ScriptOutput contains the results of a script execution.
func (*ScriptOutput) String ¶
func (so *ScriptOutput) String() string
String returns a formatted script output.
type ScriptPhase ¶
type ScriptPhase int
ScriptPhase determines when a script runs.
const ( // PhasePreScan runs before any scanning begins. PhasePreScan ScriptPhase = iota // PhasePort runs against each open port. PhasePort // PhaseHost runs once per host after port scanning. PhaseHost // PhasePostScan runs after all scanning is complete. PhasePostScan )
type ScriptTarget ¶
type ScriptTarget struct {
Host string
IP string
Port int
Service string
Banner string
Result *ScanResult
// Args provides script arguments from --script-args.
Args map[string]string
// Trace enables verbose tracing of script data (--script-trace).
Trace bool
}
ScriptTarget provides context to a running script.
type ServiceVersion ¶
type ServiceVersion struct {
Port int
Service string
Banner string
Version string
ProductName string
Info string
OS string
DeviceType string
CPE []string
}
ServiceVersion contains the result of service version detection.
func GrabBanner ¶
func GrabBanner(ctx context.Context, host string, port int, timeout time.Duration, probeDB *probedb.ServiceProbeDB) (*ServiceVersion, error)
GrabBanner connects to a port and attempts service identification using the nmap-compatible probe database. It sends protocol-specific probes and matches responses against known service signatures.
If probeDB is nil, the embedded probe database is used.
func GrabBannerWithIntensity ¶
func GrabBannerWithIntensity(ctx context.Context, host string, port int, timeout time.Duration, probeDB *probedb.ServiceProbeDB, intensity int) (*ServiceVersion, error)
GrabBannerWithIntensity is like GrabBanner but with configurable probe intensity.
func GrabBanners ¶
func GrabBanners(ctx context.Context, host string, result *ScanResult, opts ScanOptions) []ServiceVersion
GrabBanners performs service version detection on all open ports in a scan result. If opts.ProbeFile is set, probes are loaded from that file; otherwise the embedded database is used.
type TimingTemplate ¶
type TimingTemplate int
TimingTemplate represents nmap-compatible timing presets (T0-T5).
const ( // TimingParanoid is T0: very slow, IDS evasion. // 5 min timeout, serial scan, 5 sec between probes. TimingParanoid TimingTemplate = iota // TimingSneaky is T1: slow, IDS evasion. // 15 sec timeout, serial scan, 1 sec between probes. TimingSneaky // TimingPolite is T2: conservative, reduces network load. // 10 sec timeout, serial scan, 400ms between probes. TimingPolite // TimingNormal is T3: default balanced timing. // 3 sec timeout, parallel scan. TimingNormal // TimingAggressive is T4: fast, assumes reliable network. // 1.25 sec timeout, high parallelism. TimingAggressive // TimingInsane is T5: maximum speed, may miss ports. // 300ms timeout, maximum parallelism. TimingInsane )
func ParseTimingTemplate ¶
func ParseTimingTemplate(s string) (TimingTemplate, error)
ParseTimingTemplate converts a string (T0-T5 or name) to a TimingTemplate.
Example ¶
package main
import (
"fmt"
"github.com/taigrr/gomap"
)
func main() {
tmpl, err := gomap.ParseTimingTemplate("T4")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(tmpl)
}
Output: aggressive
func (TimingTemplate) String ¶
func (t TimingTemplate) String() string
String returns the timing template name.
type TracerouteHop ¶
type TracerouteHop struct {
// TTL is the time-to-live value for this hop.
TTL int
// IP is the IP address of the responding host.
IP string
// Hostname is the reverse DNS name (if resolved).
Hostname string
// RTT is the round-trip time for this hop.
RTT time.Duration
// TimedOut indicates the hop did not respond.
TimedOut bool
}
TracerouteHop represents a single hop in a traceroute.
type TracerouteOptions ¶
type TracerouteOptions struct {
// MaxHops is the maximum TTL (default 30).
MaxHops int
// Timeout per hop (default 2s).
Timeout time.Duration
// Port to send TCP SYN to (default 80). Used for TCP traceroute.
Port int
// Retries per hop (default 2).
Retries int
}
TracerouteOptions configures traceroute behavior.
type TracerouteResult ¶
type TracerouteResult struct {
Host string
Hops []TracerouteHop
}
TracerouteResult contains the full traceroute output.
func Traceroute ¶
func Traceroute(ctx context.Context, host string, opts TracerouteOptions) (*TracerouteResult, error)
Traceroute performs a UDP-based traceroute to the target host. It sends UDP packets with increasing TTL values and listens for ICMP Time Exceeded responses.
func (*TracerouteResult) String ¶
func (r *TracerouteResult) String() string
String returns a human-readable traceroute output.
type UDPFingerprint ¶
type UDPFingerprint struct {
Responded bool
DF bool
TTL int
IPLen int
UnusedField int
RIPL string
RID string
RIPCK string
RUCK string
RUD string
}
UDPFingerprint contains characteristics from the UDP probe response.
type WINFingerprint ¶
type WINFingerprint struct {
// W1-W6: Window sizes from each of 6 SYN probes
Windows [6]int
}
WINFingerprint contains TCP initial window sizes.
type XMLAddress ¶
XMLAddress is an IP or MAC address.
type XMLDebugging ¶
type XMLDebugging struct {
Level int `xml:"level,attr"`
}
XMLDebugging is the debug level element.
type XMLFinished ¶
type XMLFinished struct {
Time int64 `xml:"time,attr"`
TimeStr string `xml:"timestr,attr"`
Elapsed string `xml:"elapsed,attr"`
Summary string `xml:"summary,attr,omitempty"`
}
XMLFinished contains scan completion info.
type XMLHop ¶
type XMLHop struct {
TTL int `xml:"ttl,attr"`
IPAddr string `xml:"ipaddr,attr,omitempty"`
RTT string `xml:"rtt,attr,omitempty"`
Host string `xml:"host,attr,omitempty"`
}
XMLHop is a single traceroute hop.
type XMLHost ¶
type XMLHost struct {
StartTime int64 `xml:"starttime,attr,omitempty"`
EndTime int64 `xml:"endtime,attr,omitempty"`
Status XMLStatus `xml:"status"`
Address XMLAddress `xml:"address"`
Hostnames XMLHostnames `xml:"hostnames"`
Ports *XMLPorts `xml:"ports,omitempty"`
OS *XMLOS `xml:"os,omitempty"`
Trace *XMLTrace `xml:"trace,omitempty"`
Scripts []XMLScript `xml:"hostscript>script,omitempty"`
Times *XMLTimes `xml:"times,omitempty"`
}
XMLHost represents a scanned host.
type XMLHostStat ¶
type XMLHostStat struct {
Up int `xml:"up,attr"`
Down int `xml:"down,attr"`
Total int `xml:"total,attr"`
}
XMLHostStat summarizes host counts.
type XMLHostname ¶
XMLHostname is a single hostname entry.
type XMLHostnames ¶
type XMLHostnames struct {
Hostnames []XMLHostname `xml:"hostname,omitempty"`
}
XMLHostnames contains hostname entries.
type XMLOS ¶
type XMLOS struct {
OSMatch []XMLOSMatch `xml:"osmatch,omitempty"`
OSFingerprint []XMLOSFingerprint `xml:"osfingerprint,omitempty"`
}
XMLOS contains OS detection results.
type XMLOSClass ¶
type XMLOSClass struct {
Vendor string `xml:"vendor,attr,omitempty"`
Family string `xml:"osfamily,attr,omitempty"`
Generation string `xml:"osgen,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Accuracy string `xml:"accuracy,attr,omitempty"`
CPE []string `xml:"cpe,omitempty"`
}
XMLOSClass is an OS classification within a match.
type XMLOSFingerprint ¶
type XMLOSFingerprint struct {
Fingerprint string `xml:"fingerprint,attr"`
}
XMLOSFingerprint contains a raw OS fingerprint.
type XMLOSMatch ¶
type XMLOSMatch struct {
Name string `xml:"name,attr"`
Accuracy string `xml:"accuracy,attr"`
Line int `xml:"line,attr,omitempty"`
Classes []XMLOSClass `xml:"osclass,omitempty"`
}
XMLOSMatch represents a matched OS.
type XMLPort ¶
type XMLPort struct {
Protocol string `xml:"protocol,attr"`
PortID int `xml:"portid,attr"`
State XMLState `xml:"state"`
Service XMLService `xml:"service"`
Scripts []XMLScript `xml:"script,omitempty"`
}
XMLPort represents a single port result.
type XMLPorts ¶
type XMLPorts struct {
Ports []XMLPort `xml:"port"`
}
XMLPorts contains port scan results.
type XMLRunStats ¶
type XMLRunStats struct {
Finished XMLFinished `xml:"finished"`
Hosts XMLHostStat `xml:"hosts"`
}
XMLRunStats contains scan statistics.
type XMLScanInfo ¶
type XMLScanInfo struct {
Type string `xml:"type,attr"`
Protocol string `xml:"protocol,attr"`
NumServices int `xml:"numservices,attr"`
Services string `xml:"services,attr"`
}
XMLScanInfo describes the scan parameters.
type XMLScript ¶
type XMLScript struct {
ID string `xml:"id,attr"`
Output string `xml:"output,attr"`
Elements []XMLScriptElem `xml:"elem,omitempty"`
}
XMLScript contains script output for a port or host.
type XMLScriptElem ¶
XMLScriptElem is a key-value element within script output.
type XMLService ¶
type XMLService struct {
Name string `xml:"name,attr"`
}
XMLService describes the service running on a port.
type XMLTimes ¶
type XMLTimes struct {
SRTT string `xml:"srtt,attr"`
RTT string `xml:"rttvar,attr"`
To string `xml:"to,attr"`
}
XMLTimes contains timing information.
type XMLTrace ¶
type XMLTrace struct {
Port int `xml:"port,attr,omitempty"`
Proto string `xml:"proto,attr,omitempty"`
Hops []XMLHop `xml:"hop"`
}
XMLTrace represents traceroute data.
type XMLVerbose ¶
type XMLVerbose struct {
Level int `xml:"level,attr"`
}
XMLVerbose is the verbose level element.
Source Files
¶
- arp_linux.go
- banner.go
- constants.go
- decoy.go
- discovery.go
- discovery_icmp.go
- discovery_linux.go
- discovery_proto_linux.go
- discovery_sctp_linux.go
- errors.go
- fragment_linux.go
- ftpbounce.go
- gomap.go
- idle_linux.go
- iflist.go
- net.go
- nmap_default.go
- osdetect.go
- osdetect_linux.go
- output_file.go
- output_grep.go
- output_scriptkiddie.go
- output_xml.go
- portrange.go
- ports.go
- portselect.go
- protocol.go
- protocol_linux.go
- proxy.go
- ratelimit.go
- rawpacket_linux.go
- rawscan_linux.go
- resume.go
- scan.go
- scantype.go
- script.go
- scripts_builtin.go
- scripts_extra.go
- sctp_linux.go
- services_generated.go
- spoofmac_linux.go
- stream.go
- syn_linux.go
- targets.go
- timing.go
- trace.go
- traceroute.go
- traceroute_linux.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
generate-services
command
Command generate-services builds a Go source file containing port-to-service mappings from two sources:
|
Command generate-services builds a Go source file containing port-to-service mappings from two sources: |
|
gomap
command
|
|
|
Package probedb parses and provides access to nmap-compatible service probe and OS fingerprint databases.
|
Package probedb parses and provides access to nmap-compatible service probe and OS fingerprint databases. |