Documentation ¶
Overview ¶
Package nmap provides idiomatic `nmap` bindings for go developers.
Index ¶
- Variables
- func Parse(content []byte, result *Run) error
- type Address
- type CPE
- type Debugging
- type Distance
- type Element
- type ExtraPort
- type Finished
- type Hop
- type Host
- type HostStats
- type Hostname
- type IPIDSequence
- type Interface
- type InterfaceList
- type OS
- type OSClass
- type OSFingerprint
- type OSMatch
- type Option
- func WithACKDiscovery(ports ...string) Option
- func WithACKScan() Option
- func WithASCIIData(data string) Option
- func WithAggressiveScan() Option
- func WithAppendOutput() Option
- func WithBadSum() Option
- func WithBinaryPath(binaryPath string) Option
- func WithConnectScan() Option
- func WithConsecutivePortScanning() Option
- func WithCustomArguments(args ...string) Optiondeprecated
- func WithCustomDNSServers(dnsServers ...string) Option
- func WithCustomSysProcAttr(f func(*syscall.SysProcAttr)) Option
- func WithDataDir(directoryPath string) Option
- func WithDataLength(length int) Option
- func WithDebugging(level int) Option
- func WithDecoys(decoys ...string) Option
- func WithDefaultScript() Option
- func WithDisabledDNSResolution() Option
- func WithFTPBounceScan(FTPRelayHost string) Option
- func WithFastMode() Option
- func WithFilterHost(hostFilter func(Host) bool) Option
- func WithFilterPort(portFilter func(Port) bool) Option
- func WithForcedDNSResolution() Option
- func WithFragmentPackets() Option
- func WithGrepOutput(outputFileName string) Option
- func WithHexData(data string) Option
- func WithHostTimeout(timeout time.Duration) Option
- func WithICMPEchoDiscovery() Option
- func WithICMPNetMaskDiscovery() Option
- func WithICMPTimestampDiscovery() Option
- func WithIPOptions(options string) Option
- func WithIPProtocolPingDiscovery(protocols ...string) Option
- func WithIPProtocolScan() Option
- func WithIPTimeToLive(ttl int16) Option
- func WithIPv6Scanning() Option
- func WithIdleScan(zombieHost string, probePort int) Option
- func WithInitialRTTTimeout(roundTripTime time.Duration) Option
- func WithInterface(iface string) Option
- func WithListScan() Option
- func WithMTU(offset int) Option
- func WithMaimonScan() Option
- func WithMaxHostgroup(size int) Option
- func WithMaxParallelism(probes int) Option
- func WithMaxRTTTimeout(roundTripTime time.Duration) Option
- func WithMaxRate(packetsPerSecond int) Option
- func WithMaxRetries(tries int) Option
- func WithMaxScanDelay(timeout time.Duration) Option
- func WithMinHostgroup(size int) Option
- func WithMinParallelism(probes int) Option
- func WithMinRTTTimeout(roundTripTime time.Duration) Option
- func WithMinRate(packetsPerSecond int) Option
- func WithMostCommonPorts(number int) Option
- func WithNmapOutput(outputFileName string) Option
- func WithNoStylesheet() Option
- func WithNonInteractive() Option
- func WithOSDetection() Option
- func WithOSScanGuess() Option
- func WithOSScanLimit() Option
- func WithOpenOnly() Option
- func WithPacketTrace() Option
- func WithPingScan() Option
- func WithPortExclusions(ports ...string) Option
- func WithPortRatio(ratio float32) Option
- func WithPorts(ports ...string) Option
- func WithPrivileged() Option
- func WithProxies(proxies ...string) Option
- func WithRandomTargets(randomTargets int) Option
- func WithReason() Option
- func WithResumePreviousScan(filePath string) Option
- func WithSCTPCookieEchoScan() Option
- func WithSCTPDiscovery(ports ...string) Option
- func WithSCTPInitScan() Option
- func WithSYNDiscovery(ports ...string) Option
- func WithSYNScan() Option
- func WithScanDelay(timeout time.Duration) Option
- func WithScriptArguments(arguments map[string]string) Option
- func WithScriptArgumentsFile(inputFilePath string) Option
- func WithScriptTimeout(timeout time.Duration) Option
- func WithScriptTrace() Option
- func WithScriptUpdateDB() Option
- func WithScripts(scripts ...string) Option
- func WithSendEthernet() Option
- func WithSendIP() Option
- func WithServiceInfo() Option
- func WithSkipHostDiscovery() Option
- func WithSourcePort(port uint16) Option
- func WithSpoofIPAddress(ip string) Option
- func WithSpoofMAC(argument string) Option
- func WithStatsEvery(interval string) Option
- func WithStylesheet(stylesheetPath string) Option
- func WithSystemDNS() Option
- func WithTCPFINScan() Option
- func WithTCPNullScan() Option
- func WithTCPScanFlags(flags ...TCPFlag) Option
- func WithTCPXmasScan() Option
- func WithTargetExclusionInput(inputFileName string) Option
- func WithTargetExclusions(targets ...string) Option
- func WithTargetInput(inputFileName string) Option
- func WithTargets(targets ...string) Option
- func WithTimingTemplate(timing Timing) Option
- func WithTraceRoute() Option
- func WithUDPDiscovery(ports ...string) Option
- func WithUDPScan() Option
- func WithUnique() Option
- func WithUnprivileged() Option
- func WithVerbosity(level int) Option
- func WithVersionAll() Option
- func WithVersionIntensity(intensity int16) Option
- func WithVersionLight() Option
- func WithVersionTrace() Option
- func WithWebXML() Option
- func WithWindowScan() Option
- type Owner
- type Port
- type PortStatus
- type PortUsed
- type Reason
- type Route
- type Run
- type ScanInfo
- type ScanRunner
- type Scanner
- func (s *Scanner) AddOptions(options ...Option) *Scanner
- func (s *Scanner) Args() []string
- func (s *Scanner) Async(doneAsync chan error) *Scanner
- func (s *Scanner) GetInterfaceList() (result *InterfaceList, err error)
- func (s *Scanner) Progress(liveProgress chan float32) *Scanner
- func (s *Scanner) Run() (result *Run, warnings *[]string, err error)
- func (s *Scanner) Streamer(stream io.Writer) *Scanner
- func (s *Scanner) ToFile(file string) *Scanner
- type Script
- type Sequence
- type Service
- type Smurf
- type State
- type Stats
- type Status
- type TCPFlag
- type TCPSequence
- type TCPTSSequence
- type Table
- type Target
- type Task
- type TaskProgress
- type Times
- type Timestamp
- func (t Timestamp) FormatTime() string
- func (t Timestamp) MarshalJSON() ([]byte, error)
- func (t Timestamp) MarshalXMLAttr(name xml.Name) (xml.Attr, error)
- func (t *Timestamp) ParseTime(s string) error
- func (t *Timestamp) UnmarshalJSON(b []byte) error
- func (t *Timestamp) UnmarshalXMLAttr(attr xml.Attr) (err error)
- type Timing
- type Trace
- type Uptime
- type Verbose
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNmapNotInstalled means that upon trying to manually locate nmap in the user's path, // it was not found. Either use the WithBinaryPath method to set it manually, or make sure that // the nmap binary is present in the user's $PATH. ErrNmapNotInstalled = errors.New("nmap binary was not found") // ErrScanTimeout means that the provided context was done before the scanner finished its scan. ErrScanTimeout = errors.New("nmap scan timed out") // ErrMallocFailed means that nmap crashed due to insufficient memory, which may happen on large target networks. ErrMallocFailed = errors.New("malloc failed, probably out of space") // ErrParseOutput means that nmap's output was not parsed successfully. ErrParseOutput = errors.New("unable to parse nmap output, see warnings for details") // ErrResolveName means that Nmap could not resolve a name. ErrResolveName = errors.New("nmap could not resolve a name") )
Functions ¶
Types ¶
type Address ¶
type Address struct { Addr string `xml:"addr,attr" json:"addr"` AddrType string `xml:"addrtype,attr" json:"addr_type"` Vendor string `xml:"vendor,attr" json:"vendor"` }
Address contains a IPv4 or IPv6 address for a host.
type CPE ¶
type CPE string
CPE (Common Platform Enumeration) is a standardized way to name software applications, operating systems and hardware platforms.
type Debugging ¶
type Debugging struct {
Level int `xml:"level,attr" json:"level"`
}
Debugging contains the debugging level of the scan.
type Distance ¶
type Distance struct {
Value int `xml:"value,attr" json:"value"`
}
Distance is the amount of hops to a particular host.
type Element ¶
type Element struct { Key string `xml:"key,attr,omitempty" json:"key,omitempty"` Value string `xml:",innerxml" json:"value"` }
Element is the smallest building block for scripts/tables. It can optionally(!) have a key.
type ExtraPort ¶
type ExtraPort struct { State string `xml:"state,attr" json:"state"` Count int `xml:"count,attr" json:"count"` Reasons []Reason `xml:"extrareasons" json:"reasons"` }
ExtraPort contains the information about the closed and filtered ports.
type Finished ¶
type Finished struct { Time Timestamp `xml:"time,attr" json:"time"` TimeStr string `xml:"timestr,attr" json:"time_str"` Elapsed float32 `xml:"elapsed,attr" json:"elapsed"` Summary string `xml:"summary,attr" json:"summary"` Exit string `xml:"exit,attr" json:"exit"` ErrorMsg string `xml:"errormsg,attr" json:"error_msg"` }
Finished contains detailed statistics regarding a finished scan.
type Hop ¶
type Hop struct { TTL float32 `xml:"ttl,attr" json:"ttl"` RTT string `xml:"rtt,attr" json:"rtt"` IPAddr string `xml:"ipaddr,attr" json:"ip_addr"` Host string `xml:"host,attr" json:"host"` }
Hop is an IP hop to a host.
type Host ¶
type Host struct { Distance Distance `xml:"distance" json:"distance"` EndTime Timestamp `xml:"endtime,attr,omitempty" json:"end_time"` IPIDSequence IPIDSequence `xml:"ipidsequence" json:"ip_id_sequence"` OS OS `xml:"os" json:"os"` StartTime Timestamp `xml:"starttime,attr,omitempty" json:"start_time"` TimedOut bool `xml:"timedout,attr,omitempty" json:"timed_out"` Status Status `xml:"status" json:"status"` TCPSequence TCPSequence `xml:"tcpsequence" json:"tcp_sequence"` TCPTSSequence TCPTSSequence `xml:"tcptssequence" json:"tcp_ts_sequence"` Times Times `xml:"times" json:"times"` Trace Trace `xml:"trace" json:"trace"` Uptime Uptime `xml:"uptime" json:"uptime"` Comment string `xml:"comment,attr" json:"comment"` Addresses []Address `xml:"address" json:"addresses"` ExtraPorts []ExtraPort `xml:"ports>extraports" json:"extra_ports"` Hostnames []Hostname `xml:"hostnames>hostname" json:"hostnames"` HostScripts []Script `xml:"hostscript>script" json:"host_scripts"` Ports []Port `xml:"ports>port" json:"ports"` Smurfs []Smurf `xml:"smurf" json:"smurfs"` }
Host represents a host that was scanned.
type HostStats ¶
type HostStats struct { Up int `xml:"up,attr" json:"up"` Down int `xml:"down,attr" json:"down"` Total int `xml:"total,attr" json:"total"` }
HostStats contains the amount of up and down hosts and the total count.
type Hostname ¶
type Hostname struct { Name string `xml:"name,attr" json:"name"` Type string `xml:"type,attr" json:"type"` }
Hostname is a name for a host.
type Interface ¶
type Interface struct { Device string `json:"device"` Short string `json:"short"` IP net.IP `json:"ip"` IPMask net.IP `json:"ip_mask"` Type string `json:"type"` Up bool `json:"up"` MTU int `json:"mtu"` Mac net.HardwareAddr `json:"mac"` }
Interface is a interface object.
type InterfaceList ¶
type InterfaceList struct { Interfaces []*Interface `json:"interfaces"` Routes []*Route `json:"routes"` }
InterfaceList contains interfaces and routes.
type OS ¶
type OS struct { PortsUsed []PortUsed `xml:"portused" json:"ports_used"` Matches []OSMatch `xml:"osmatch" json:"os_matches"` Fingerprints []OSFingerprint `xml:"osfingerprint" json:"os_fingerprints"` }
OS contains the fingerprinted operating system for a host.
type OSClass ¶
type OSClass struct { Vendor string `xml:"vendor,attr" json:"vendor"` OSGeneration string `xml:"osgen,attr" json:"os_generation"` Type string `xml:"type,attr" json:"type"` Accuracy int `xml:"accuracy,attr" json:"accuracy"` Family string `xml:"osfamily,attr" json:"os_family"` CPEs []CPE `xml:"cpe" json:"cpes"` }
OSClass contains vendor information about an operating system.
type OSFingerprint ¶
type OSFingerprint struct {
Fingerprint string `xml:"fingerprint,attr" json:"fingerprint"`
}
OSFingerprint is the actual fingerprint string of an operating system.
type OSMatch ¶
type OSMatch struct { Name string `xml:"name,attr" json:"name"` Accuracy int `xml:"accuracy,attr" json:"accuracy"` Line int `xml:"line,attr" json:"line"` Classes []OSClass `xml:"osclass" json:"os_classes"` }
OSMatch contains detailed information regarding an operating system fingerprint.
type Option ¶
type Option func(*Scanner)
Option is a function that is used for grouping of Scanner options. Option adds or removes nmap command line arguments.
func WithACKDiscovery ¶
WithACKDiscovery sets the discovery mode to use ACK packets. If the portList argument is empty, this will enable ACK discovery for all ports. Otherwise, it will be only for the specified ports.
func WithACKScan ¶
func WithACKScan() Option
WithACKScan sets the scan technique to use ACK packets over TCP. This scan is unable to determine if a port is open. When scanning unfiltered systems, open and closed ports will both return a RST packet. Nmap then labels them as unfiltered, meaning that they are reachable by the ACK packet, but whether they are open or closed is undetermined.
func WithASCIIData ¶
WithASCIIData appends a custom ascii-encoded payload to sent packets.
func WithAggressiveScan ¶
func WithAggressiveScan() Option
WithAggressiveScan enables the use of aggressive scan options. This has the same effect as using WithOSDetection, WithServiceInfo, WithDefaultScript and WithTraceRoute at the same time. Because script scanning with the default set is considered intrusive, you should not use this method against target networks without permission.
func WithAppendOutput ¶
func WithAppendOutput() Option
WithAppendOutput makes nmap append to files instead of overwriting them. Currently does nothing, since this library doesn't write in files.
func WithBadSum ¶
func WithBadSum() Option
WithBadSum makes nmap send an invalid TCP, UDP or SCTP checksum for packets sent to target hosts. Since virtually all host IP stacks properly drop these packets, any responses received are likely coming from a firewall or IDS that didn't bother to verify the checksum.
func WithBinaryPath ¶
WithBinaryPath sets the nmap binary path for a scanner.
func WithConnectScan ¶
func WithConnectScan() Option
WithConnectScan sets the scan technique to use TCP connections. This is the default method used when a user does not have raw packet privileges. Target machines are likely to log these connections.
func WithConsecutivePortScanning ¶
func WithConsecutivePortScanning() Option
WithConsecutivePortScanning makes the scan go through ports consecutively instead of picking them out randomly.
func WithCustomArguments
deprecated
WithCustomArguments sets custom arguments to give to the nmap binary. There should be no reason to use this, unless you are using a custom build of nmap or that this repository isn't up to date with the latest options of the official nmap release.
Deprecated: You can use this as a quick way to paste an nmap command into your go code, but remember that the whole purpose of this repository is to be idiomatic, provide type checking, enums for the values that can be passed, etc.
func WithCustomDNSServers ¶
WithCustomDNSServers sets custom DNS servers for the scan. List format: dns1[,dns2],...
func WithCustomSysProcAttr ¶
func WithCustomSysProcAttr(f func(*syscall.SysProcAttr)) Option
WithCustomSysProcAttr allows customizing the *syscall.SysProcAttr on the *exec.Cmd instance
func WithDataDir ¶
WithDataDir specifies a custom data directory for nmap to get its nmap-service-probes, nmap-services, nmap-protocols, nmap-rpc, nmap-mac-prefixes, and nmap-os-db.
func WithDataLength ¶
WithDataLength appends a random payload of the given length to sent packets.
func WithDebugging ¶
WithDebugging sets and increases the debugging level of nmap.
func WithDecoys ¶
WithDecoys causes a decoy scan to be performed, which makes it appear to the remote host that the host(s) you specify as decoys are scanning the target network too. Thus their IDS might report 5–10 port scans from unique IP addresses, but they won't know which IP was scanning them and which were innocent decoys. While this can be defeated through router path tracing, response-dropping, and other active mechanisms, it is generally an effective technique for hiding your IP address. You can optionally use ME as one of the decoys to represent the position for your real IP address. If you put ME in the sixth position or later, some common port scan detectors are unlikely to show your IP address at all.
func WithDefaultScript ¶
func WithDefaultScript() Option
WithDefaultScript sets the scanner to perform a script scan using the default set of scripts. It is equivalent to --script=default. Some of the scripts in this category are considered intrusive and should not be run against a target network without permission.
func WithDisabledDNSResolution ¶
func WithDisabledDNSResolution() Option
WithDisabledDNSResolution disables DNS resolution in the discovery step of the nmap scan.
func WithFTPBounceScan ¶
WithFTPBounceScan sets the scan technique to use the an FTP relay host. It takes an argument of the form "<username>:<password>@<server>:<port>. <Server>". You may omit <username>:<password>, in which case anonymous login credentials (user: anonymous password:-wwwuser@) are used. The port number (and preceding colon) may be omitted as well, in which case the default FTP port (21) on <server> is used.
func WithFastMode ¶
func WithFastMode() Option
WithFastMode makes the scan faster by scanning fewer ports than the default scan.
func WithFilterHost ¶
WithFilterHost allows to set a custom function to filter out hosts that don't fulfill a given condition. When the given function returns true, the host is kept, otherwise it is removed from the result. Can be used along with WithFilterPort.
func WithFilterPort ¶
WithFilterPort allows to set a custom function to filter out ports that don't fulfill a given condition. When the given function returns true, the port is kept, otherwise it is removed from the result. Can be used along with WithFilterHost.
func WithForcedDNSResolution ¶
func WithForcedDNSResolution() Option
WithForcedDNSResolution enforces DNS resolution in the discovery step of the nmap scan.
func WithFragmentPackets ¶
func WithFragmentPackets() Option
WithFragmentPackets enables the use of tiny fragmented IP packets in order to split up the TCP header over several packets to make it harder for packet filters, intrusion detection systems, and other annoyances to detect what you are doing. Some programs have trouble handling these tiny packets.
func WithGrepOutput ¶
WithGrepOutput makes nmap output greppable output to the filename specified.
func WithHexData ¶
WithHexData appends a custom hex-encoded payload to sent packets.
func WithHostTimeout ¶
WithHostTimeout sets the time after which nmap should give up on a target host.
func WithICMPEchoDiscovery ¶
func WithICMPEchoDiscovery() Option
WithICMPEchoDiscovery sets the discovery mode to use an ICMP type 8 packet (an echo request), like the standard packets sent by the ping command. Many hosts and firewalls block these packets, so this is usually not the best for exploring networks.
func WithICMPNetMaskDiscovery ¶
func WithICMPNetMaskDiscovery() Option
WithICMPNetMaskDiscovery sets the discovery mode to use an ICMP type 17 packet (an address mask request). This query can be valuable when administrators specifically block echo request packets while forgetting that other ICMP queries can be used for the same purpose.
func WithICMPTimestampDiscovery ¶
func WithICMPTimestampDiscovery() Option
WithICMPTimestampDiscovery sets the discovery mode to use an ICMP type 13 packet (a timestamp request). This query can be valuable when administrators specifically block echo request packets while forgetting that other ICMP queries can be used for the same purpose.
func WithIPOptions ¶
WithIPOptions uses the specified IP options to send packets. You may be able to use the record route option to determine a path to a target even when more traditional traceroute-style approaches fail. See http://seclists.org/nmap-dev/2006/q3/52 for examples of use.
func WithIPProtocolPingDiscovery ¶
WithIPProtocolPingDiscovery sets the discovery mode to use the IP protocol ping. If no protocols are specified, the default is to send multiple IP packets for ICMP (protocol 1), IGMP (protocol 2), and IP-in-IP (protocol 4).
func WithIPProtocolScan ¶
func WithIPProtocolScan() Option
WithIPProtocolScan sets the scan technique to use the IP protocol. IP protocol scan allows you to determine which IP protocols (TCP, ICMP, IGMP, etc.) are supported by target machines. This isn't technically a port scan, since it cycles through IP protocol numbers rather than TCP or UDP port numbers.
func WithIPTimeToLive ¶
WithIPTimeToLive sets the IP time-to-live field of IP packets.
func WithIPv6Scanning ¶
func WithIPv6Scanning() Option
WithIPv6Scanning enables the use of IPv6 scanning.
func WithIdleScan ¶
WithIdleScan sets the scan technique to use a zombie host to allow for a truly blind TCP port scan of the target. Besides being extraordinarily stealthy (due to its blind nature), this scan type permits mapping out IP-based trust relationships between machines.
func WithInitialRTTTimeout ¶
WithInitialRTTTimeout sets the initial probe round trip time.
func WithInterface ¶
WithInterface specifies which network interface to use for scanning.
func WithListScan ¶
func WithListScan() Option
WithListScan sets the discovery mode to simply list the targets to scan and not scan them.
func WithMTU ¶
WithMTU allows you to specify your own offset size for fragmenting IP packets. Using fragmented packets allows to split up the TCP header over several packets to make it harder for packet filters, intrusion detection systems, and other annoyances to detect what you are doing. Some programs have trouble handling these tiny packets.
func WithMaimonScan ¶
func WithMaimonScan() Option
WithMaimonScan sends the same packets as NULL, FIN, and Xmas scans, except that the probe is FIN/ACK. Many BSD-derived systems will drop these packets if the port is open.
func WithMaxHostgroup ¶
WithMaxHostgroup sets the maximal parallel host scan group size.
func WithMaxParallelism ¶
WithMaxParallelism sets the maximal number of parallel probes.
func WithMaxRTTTimeout ¶
WithMaxRTTTimeout sets the maximal probe round trip time.
func WithMaxRate ¶
WithMaxRate sets the maximal number of packets sent per second.
func WithMaxRetries ¶
WithMaxRetries sets the maximal number of port scan probe retransmissions.
func WithMaxScanDelay ¶
WithMaxScanDelay sets the maximum time to wait between each probe sent to a host.
func WithMinHostgroup ¶
WithMinHostgroup sets the minimal parallel host scan group size.
func WithMinParallelism ¶
WithMinParallelism sets the minimal number of parallel probes.
func WithMinRTTTimeout ¶
WithMinRTTTimeout sets the minimal probe round trip time.
func WithMinRate ¶
WithMinRate sets the minimal number of packets sent per second.
func WithMostCommonPorts ¶
WithMostCommonPorts sets the scanner to go through the provided number of most common ports.
func WithNmapOutput ¶
WithNmapOutput makes nmap output standard output to the filename specified.
func WithNoStylesheet ¶
func WithNoStylesheet() Option
WithNoStylesheet prevents the use of XSL stylesheets with the XML output.
func WithNonInteractive ¶ added in v3.0.2
func WithNonInteractive() Option
WithNonInteractive disable runtime interactions via keyboard
func WithOSScanGuess ¶
func WithOSScanGuess() Option
WithOSScanGuess makes nmap attempt to guess the OS more aggressively.
func WithOSScanLimit ¶
func WithOSScanLimit() Option
WithOSScanLimit sets the scanner to not even try OS detection against hosts that do have at least one open TCP port, as it is unlikely to be effective. This can save substantial time, particularly on -Pn scans against many hosts. It only matters when OS detection is requested with -O or -A.
func WithPacketTrace ¶
func WithPacketTrace() Option
WithPacketTrace makes nmap show all packets sent and received.
func WithPingScan ¶
func WithPingScan() Option
WithPingScan sets the discovery mode to simply ping the targets to scan and not scan them.
func WithPortExclusions ¶
WithPortExclusions sets the ports that the scanner should not scan on each host.
func WithPortRatio ¶
WithPortRatio sets the scanner to go the ports more common than the given ratio. Ratio must be a float between 0 and 1.
func WithPrivileged ¶
func WithPrivileged() Option
WithPrivileged makes nmap assume that the user is fully privileged.
func WithProxies ¶
WithProxies allows to relay connection through HTTP/SOCKS4 proxies.
func WithRandomTargets ¶
WithRandomTargets sets the amount of targets to randomly choose from the targets.
func WithReason ¶
func WithReason() Option
WithReason makes nmap specify why a port is in a particular state.
func WithResumePreviousScan ¶
WithResumePreviousScan makes nmap continue a scan that was aborted, from an output file.
func WithSCTPCookieEchoScan ¶
func WithSCTPCookieEchoScan() Option
WithSCTPCookieEchoScan sets the scan technique to use SCTP packets containing a COOKIE-ECHO chunk. The advantage of this scan type is that it is not as obvious a port scan than an INIT scan. Also, there may be non-stateful firewall rulesets blocking INIT chunks, but not COOKIE ECHO chunks.
func WithSCTPDiscovery ¶
WithSCTPDiscovery sets the discovery mode to use SCTP packets containing a minimal INIT chunk. If the portList argument is empty, this will enable SCTP discovery for all ports. Otherwise, it will be only for the specified ports. Warning: on Unix, only the privileged user root is generally able to send and receive raw SCTP packets.
func WithSCTPInitScan ¶
func WithSCTPInitScan() Option
WithSCTPInitScan sets the scan technique to use SCTP packets containing an INIT chunk. It can be performed quickly, scanning thousands of ports per second on a fast network not hampered by restrictive firewalls. Like SYN scan, INIT scan is relatively unobtrusive and stealthy, since it never completes SCTP associations.
func WithSYNDiscovery ¶
WithSYNDiscovery sets the discovery mode to use SYN packets. If the portList argument is empty, this will enable SYN discovery for all ports. Otherwise, it will be only for the specified ports.
func WithSYNScan ¶
func WithSYNScan() Option
WithSYNScan sets the scan technique to use SYN packets over TCP. This is the default method, as it is fast, stealthy and not hampered by restrictive firewalls.
func WithScanDelay ¶
WithScanDelay sets the minimum time to wait between each probe sent to a host.
func WithScriptArguments ¶
WithScriptArguments provides arguments for scripts. If a value is the empty string, the key will be used as a flag.
func WithScriptArgumentsFile ¶
WithScriptArgumentsFile provides arguments for scripts from a file.
func WithScriptTimeout ¶
WithScriptTimeout sets the script timeout.
func WithScriptTrace ¶
func WithScriptTrace() Option
WithScriptTrace makes the scripts show all data sent and received.
func WithScriptUpdateDB ¶
func WithScriptUpdateDB() Option
WithScriptUpdateDB updates the script database.
func WithScripts ¶
WithScripts sets the scanner to perform a script scan using the enumerated scripts, script directories and script categories.
func WithSendEthernet ¶
func WithSendEthernet() Option
WithSendEthernet makes nmap send packets at the raw ethernet (data link) layer rather than the higher IP (network) layer. By default, nmap chooses the one which is generally best for the platform it is running on.
func WithSendIP ¶
func WithSendIP() Option
WithSendIP makes nmap send packets via raw IP sockets rather than sending lower level ethernet frames.
func WithServiceInfo ¶
func WithServiceInfo() Option
WithServiceInfo enables the probing of open ports to determine service and version info.
func WithSkipHostDiscovery ¶
func WithSkipHostDiscovery() Option
WithSkipHostDiscovery disables host discovery and considers all hosts as online.
func WithSourcePort ¶
WithSourcePort specifies from which port to scan.
func WithSpoofIPAddress ¶
WithSpoofIPAddress spoofs the IP address of the machine which is running nmap. This can be used if nmap is unable to determine your source address. Another possible use of this flag is to spoof the scan to make the targets think that someone else is scanning them. The WithInterface option and WithSkipHostDiscovery are generally required for this sort of usage. Note that you usually won't receive reply packets back (they will be addressed to the IP you are spoofing), so Nmap won't produce useful reports.
func WithSpoofMAC ¶
WithSpoofMAC uses the given MAC address for all of the raw ethernet frames the scanner sends. This option implies WithSendEthernet to ensure that Nmap actually sends ethernet-level packets. Valid argument examples are Apple, 0, 01:02:03:04:05:06, deadbeefcafe, 0020F2, and Cisco.
func WithStatsEvery ¶
WithStatsEvery periodically prints a timing status message after each interval of time.
func WithStylesheet ¶
WithStylesheet makes nmap apply an XSL stylesheet to transform its XML output to HTML.
func WithSystemDNS ¶
func WithSystemDNS() Option
WithSystemDNS sets the scanner's DNS to the system's DNS.
func WithTCPFINScan ¶
func WithTCPFINScan() Option
WithTCPFINScan sets the scan technique to use TCP packets with the FIN flag set. This scan method can be used to exploit a loophole in the TCP RFC. If an RST packet is received, the port is considered closed, while no response means it is open|filtered.
func WithTCPNullScan ¶
func WithTCPNullScan() Option
WithTCPNullScan sets the scan technique to use TCP null packets. (TCP flag header is 0). This scan method can be used to exploit a loophole in the TCP RFC. If an RST packet is received, the port is considered closed, while no response means it is open|filtered.
func WithTCPScanFlags ¶
WithTCPScanFlags sets the scan technique to use custom TCP flags.
func WithTCPXmasScan ¶
func WithTCPXmasScan() Option
WithTCPXmasScan sets the scan technique to use TCP packets with the FIN, PSH and URG flags set. This scan method can be used to exploit a loophole in the TCP RFC. If an RST packet is received, the port is considered closed, while no response means it is open|filtered.
func WithTargetExclusionInput ¶
WithTargetExclusionInput sets the input file name to set the target exclusions.
func WithTargetExclusions ¶ added in v3.0.4
WithTargetExclusions sets the excluded targets of a scanner.
func WithTargetInput ¶
WithTargetInput sets the input file name to set the targets.
func WithTargets ¶
WithTargets sets the target of a scanner.
func WithTimingTemplate ¶
WithTimingTemplate sets the timing template for nmap.
func WithTraceRoute ¶
func WithTraceRoute() Option
WithTraceRoute enables the tracing of the hop path to each host.
func WithUDPDiscovery ¶
WithUDPDiscovery sets the discovery mode to use UDP packets. If the portList argument is empty, this will enable UDP discovery for all ports. Otherwise, it will be only for the specified ports.
func WithUDPScan ¶
func WithUDPScan() Option
WithUDPScan sets the scan technique to use UDP packets. It can be combined with a TCP scan type such as SYN scan to check both protocols during the same run. UDP scanning is generally slower than TCP, but should not be ignored.
func WithUnique ¶
func WithUnique() Option
WithUnique makes each address be scanned only once. The default behavior is to scan each address as many times as it is specified in the target list, such as when network ranges overlap or different hostnames resolve to the same address.
func WithUnprivileged ¶
func WithUnprivileged() Option
WithUnprivileged makes nmap assume that the user lacks raw socket privileges.
func WithVerbosity ¶
WithVerbosity sets and increases the verbosity level of nmap.
func WithVersionAll ¶
func WithVersionAll() Option
WithVersionAll sets the level of intensity with which nmap should probe the open ports to get version information to 9. This will ensure that every single probe is attempted against each port.
func WithVersionIntensity ¶
WithVersionIntensity sets the level of intensity with which nmap should probe the open ports to get version information. Intensity should be a value between 0 (light) and 9 (try all probes). The default value is 7.
func WithVersionLight ¶
func WithVersionLight() Option
WithVersionLight sets the level of intensity with which nmap should probe the open ports to get version information to 2. This will make version scanning much faster, but slightly less likely to identify services.
func WithVersionTrace ¶
func WithVersionTrace() Option
WithVersionTrace causes Nmap to print out extensive debugging info about what version scanning is doing. TODO: See how this works along with XML output.
func WithWebXML ¶
func WithWebXML() Option
WithWebXML makes nmap apply the default nmap.org stylesheet to transform XML output to HTML. The stylesheet can be found at https://nmap.org/svn/docs/nmap.xsl
func WithWindowScan ¶
func WithWindowScan() Option
WithWindowScan sets the scan technique to use ACK packets over TCP and examining the TCP window field of the RST packets returned. Window scan is exactly the same as ACK scan except that it exploits an implementation detail of certain systems to differentiate open ports from closed ones, rather than always printing unfiltered when a RST is returned.
type Owner ¶
type Owner struct {
Name string `xml:"name,attr" json:"name"`
}
Owner contains the name of a port's owner.
type Port ¶
type Port struct { ID uint16 `xml:"portid,attr" json:"id"` Protocol string `xml:"protocol,attr" json:"protocol"` Owner Owner `xml:"owner" json:"owner"` Service Service `xml:"service" json:"service"` State State `xml:"state" json:"state"` Scripts []Script `xml:"script" json:"scripts"` }
Port contains all the information about a scanned port.
type PortStatus ¶
type PortStatus string
PortStatus represents a port's state.
const ( Open PortStatus = "open" Closed PortStatus = "closed" Filtered PortStatus = "filtered" Unfiltered PortStatus = "unfiltered" )
Enumerates the different possible state values.
type PortUsed ¶
type PortUsed struct { State string `xml:"state,attr" json:"state"` Proto string `xml:"proto,attr" json:"proto"` ID int `xml:"portid,attr" json:"port_id"` }
PortUsed is the port used to fingerprint an operating system.
type Reason ¶
type Reason struct { Reason string `xml:"reason,attr" json:"reason"` Count int `xml:"count,attr" json:"count"` }
Reason represents a reason why a port is closed or filtered. This won't be in the scan results unless WithReason is used.
type Route ¶
type Route struct { DestinationIP net.IP `json:"destination_ip"` DestinationIPMask net.IP `json:"destination_ip_mask"` Device string `json:"device"` Metric int `json:"metric"` Gateway net.IP `json:"gateway"` }
Route is a route object.
type Run ¶
type Run struct { XMLName xml.Name `xml:"nmaprun"` Args string `xml:"args,attr" json:"args"` ProfileName string `xml:"profile_name,attr" json:"profile_name"` Scanner string `xml:"scanner,attr" json:"scanner"` StartStr string `xml:"startstr,attr" json:"start_str"` Version string `xml:"version,attr" json:"version"` XMLOutputVersion string `xml:"xmloutputversion,attr" json:"xml_output_version"` Debugging Debugging `xml:"debugging" json:"debugging"` Stats Stats `xml:"runstats" json:"run_stats"` ScanInfo ScanInfo `xml:"scaninfo" json:"scan_info"` Start Timestamp `xml:"start,attr" json:"start"` Verbose Verbose `xml:"verbose" json:"verbose"` Hosts []Host `xml:"host" json:"hosts"` PostScripts []Script `xml:"postscript>script" json:"post_scripts"` PreScripts []Script `xml:"prescript>script" json:"pre_scripts"` Targets []Target `xml:"target" json:"targets"` TaskBegin []Task `xml:"taskbegin" json:"task_begin"` TaskProgress []TaskProgress `xml:"taskprogress" json:"task_progress"` TaskEnd []Task `xml:"taskend" json:"task_end"` NmapErrors []string // contains filtered or unexported fields }
Run represents an nmap scanning run.
type ScanInfo ¶
type ScanInfo struct { NumServices int `xml:"numservices,attr" json:"num_services"` Protocol string `xml:"protocol,attr" json:"protocol"` ScanFlags string `xml:"scanflags,attr" json:"scan_flags"` Services string `xml:"services,attr" json:"services"` Type string `xml:"type,attr" json:"type"` }
ScanInfo represents the scan information.
type ScanRunner ¶
ScanRunner represents something that can run a scan.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner represents n Nmap scanner.
Example (Simple) ¶
A scanner can be instantiated with options to set the arguments that are given to nmap.
s, err := NewScanner( context.Background(), WithTargets("google.com", "facebook.com", "youtube.com"), WithCustomDNSServers("8.8.8.8", "8.8.4.4"), WithTimingTemplate(TimingFastest), WithTCPScanFlags(FlagACK, FlagNULL, FlagRST), ) if err != nil { log.Fatalf("unable to create nmap scanner: %v", err) } scanResult, _, err := s.Run() if err != nil { log.Fatalf("nmap encountered an error: %v", err) } fmt.Printf( "Scan successful: %d hosts up\n", scanResult.Stats.Hosts.Up, )
Output: Scan successful: 3 hosts up
func NewScanner ¶
NewScanner creates a new Scanner, and can take options to apply to the scanner.
func (*Scanner) AddOptions ¶
AddOptions sets more scan options after the scan is created.
func (*Scanner) Async ¶
Async will run the nmap scan asynchronously. You need to provide a channel with error type. When the scan is finished an error or nil will be piped through this channel.
func (*Scanner) GetInterfaceList ¶
func (s *Scanner) GetInterfaceList() (result *InterfaceList, err error)
GetInterfaceList runs nmap with the --iflist option. The output will be parsed. The return value is a struct containing all host interfaces and routes.
func (*Scanner) Progress ¶
Progress pipes the progress of nmap every 100ms. It needs a channel of type float.
func (*Scanner) Run ¶
Run will run the Scanner with the enabled options. You need to create a Run struct and warnings array first so the function can parse it.
type Script ¶
type Script struct { ID string `xml:"id,attr" json:"id"` Output string `xml:"output,attr" json:"output"` Elements []Element `xml:"elem,omitempty" json:"elements,omitempty"` Tables []Table `xml:"table,omitempty" json:"tables,omitempty"` }
Script represents an Nmap Scripting Engine script. The inner elements can be an arbitrary collection of Tables and Elements. Both of them can also be empty.
type Sequence ¶
type Sequence struct { Class string `xml:"class,attr" json:"class"` Values string `xml:"values,attr" json:"values"` }
Sequence represents a detected sequence.
type Service ¶
type Service struct { DeviceType string `xml:"devicetype,attr" json:"device_type"` ExtraInfo string `xml:"extrainfo,attr" json:"extra_info"` HighVersion string `xml:"highver,attr" json:"high_version"` Hostname string `xml:"hostname,attr" json:"hostname"` LowVersion string `xml:"lowver,attr" json:"low_version"` Method string `xml:"method,attr" json:"method"` Name string `xml:"name,attr" json:"name"` OSType string `xml:"ostype,attr" json:"os_type"` Product string `xml:"product,attr" json:"product"` Proto string `xml:"proto,attr" json:"proto"` RPCNum string `xml:"rpcnum,attr" json:"rpc_num"` ServiceFP string `xml:"servicefp,attr" json:"service_fp"` Tunnel string `xml:"tunnel,attr" json:"tunnel"` Version string `xml:"version,attr" json:"version"` Confidence int `xml:"conf,attr" json:"confidence"` CPEs []CPE `xml:"cpe" json:"cpes"` }
Service contains detailed information about a service on an open port.
type Smurf ¶
type Smurf struct {
Responses string `xml:"responses,attr" json:"responses"`
}
Smurf contains responses from a smurf attack.
type State ¶
type State struct { State string `xml:"state,attr" json:"state"` Reason string `xml:"reason,attr" json:"reason"` ReasonIP string `xml:"reason_ip,attr" json:"reason_ip"` ReasonTTL float32 `xml:"reason_ttl,attr" json:"reason_ttl"` }
State contains information about a given port's status. State will be open, closed, etc.
type Stats ¶
type Stats struct { Finished Finished `xml:"finished" json:"finished"` Hosts HostStats `xml:"hosts" json:"hosts"` }
Stats contains statistics for an nmap scan.
type Status ¶
type Status struct { State string `xml:"state,attr" json:"state"` Reason string `xml:"reason,attr" json:"reason"` ReasonTTL float32 `xml:"reason_ttl,attr" json:"reason_ttl"` }
Status represents a host's status.
type TCPSequence ¶
type TCPSequence struct { Index int `xml:"index,attr" json:"index"` Difficulty string `xml:"difficulty,attr" json:"difficulty"` Values string `xml:"values,attr" json:"values"` }
TCPSequence represents a detected TCP sequence.
type TCPTSSequence ¶
type TCPTSSequence Sequence
TCPTSSequence represents a detected TCP TS sequence.
type Table ¶
type Table struct { Key string `xml:"key,attr,omitempty" json:"key,omitempty"` Tables []Table `xml:"table,omitempty" json:"tables,omitempty"` Elements []Element `xml:"elem,omitempty" json:"elements,omitempty"` }
Table is an arbitrary collection of (sub-)Tables and Elements. All its fields can be empty.
type Target ¶
type Target struct { Specification string `xml:"specification,attr" json:"specification"` Status string `xml:"status,attr" json:"status"` Reason string `xml:"reason,attr" json:"reason"` }
Target represents a target, how it was specified when passed to nmap, its status and the reason for its status. Example: <target specification="domain.does.not.exist" status="skipped" reason="invalid"/>
type Task ¶
type Task struct { Time Timestamp `xml:"time,attr" json:"time"` Task string `xml:"task,attr" json:"task"` ExtraInfo string `xml:"extrainfo,attr" json:"extra_info"` }
Task contains information about a task.
type TaskProgress ¶
type TaskProgress struct { Percent float32 `xml:"percent,attr" json:"percent"` Remaining int `xml:"remaining,attr" json:"remaining"` Task string `xml:"task,attr" json:"task"` Etc Timestamp `xml:"etc,attr" json:"etc"` Time Timestamp `xml:"time,attr" json:"time"` }
TaskProgress contains information about the progression of a task.
type Times ¶
type Times struct { SRTT string `xml:"srtt,attr" json:"srtt"` RTT string `xml:"rttvar,attr" json:"rttv"` To string `xml:"to,attr" json:"to"` }
Times contains time statistics for an nmap scan.
type Timestamp ¶
Timestamp represents time as a UNIX timestamp in seconds.
func (Timestamp) FormatTime ¶
FormatTime formats the time.Time value as a UNIX timestamp string.
func (Timestamp) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (Timestamp) MarshalXMLAttr ¶
MarshalXMLAttr implements the xml.MarshalerAttr interface.
func (*Timestamp) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
type Timing ¶
type Timing int16
Timing represents a timing template for nmap. These are meant to be used with the WithTimingTemplate method.
const ( // TimingSlowest also called paranoiac NO PARALLELISM | 5min timeout | 100ms to 10s round-trip time timeout | 5mn scan delay TimingSlowest Timing = 0 // TimingSneaky NO PARALLELISM | 15sec timeout | 100ms to 10s round-trip time timeout | 15s scan delay TimingSneaky Timing = 1 // TimingPolite NO PARALLELISM | 1sec timeout | 100ms to 10s round-trip time timeout | 400ms scan delay TimingPolite Timing = 2 // TimingNormal PARALLELISM | 1sec timeout | 100ms to 10s round-trip time timeout | 0s scan delay TimingNormal Timing = 3 // TimingAggressive PARALLELISM | 500ms timeout | 100ms to 1250ms round-trip time timeout | 0s scan delay TimingAggressive Timing = 4 // TimingFastest also called insane PARALLELISM | 250ms timeout | 50ms to 300ms round-trip time timeout | 0s scan delay TimingFastest Timing = 5 )
type Trace ¶
type Trace struct { Proto string `xml:"proto,attr" json:"proto"` Port int `xml:"port,attr" json:"port"` Hops []Hop `xml:"hop" json:"hops"` }
Trace represents the trace to a host, including the hops.