nmap

package module
v2.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2022 License: MIT Imports: 18 Imported by: 36

README

nmap

PkgGoDev github.com/Ullaakut/nmap/v2 Coverage Status

This library aims at providing idiomatic nmap bindings for go developers, in order to make it easier to write security audit tools using golang.

What is nmap

Nmap (Network Mapper) is a free and open-source network scanner created by Gordon Lyon. Nmap is used to discover hosts and services on a computer network by sending packets and analyzing the responses.

Nmap provides a number of features for probing computer networks, including host discovery and service and operating system detection. These features are extensible by scripts that provide more advanced service detection, vulnerability detection, and other features. Nmap can adapt to network conditions including latency and congestion during a scan.

Why use go for penetration testing

Most pentest tools are currently written using Python and not Go, because it is easy to quickly write scripts, lots of libraries are available, and it's a simple language to use. However, for writing robust and reliable applications, Go is the better tool. It is statically compiled, has a static type system, much better performance, it is also a very simple language to use and goroutines are awesome... But I might be slighly biased, so feel free to disagree.

Supported features

  • All of nmap's native options.
  • Additional idiomatic go filters for filtering hosts and ports.
  • Cancellable contexts support.
  • Helpful enums for nmap commands. (time templates, os families, port states, etc.)
  • Complete documentation of each option, mostly insipred from nmap's documentation.

TODO

  • Add asynchronous scan, send scan progress percentage and time estimation through channel

Simple example

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/Ullaakut/nmap/v2"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
    defer cancel()

    // Equivalent to `/usr/local/bin/nmap -p 80,443,843 google.com facebook.com youtube.com`,
    // with a 5 minute timeout.
    scanner, err := nmap.NewScanner(
        nmap.WithTargets("google.com", "facebook.com", "youtube.com"),
        nmap.WithPorts("80,443,843"),
        nmap.WithContext(ctx),
    )
    if err != nil {
        log.Fatalf("unable to create nmap scanner: %v", err)
    }

    result, warnings, err := scanner.Run()
    if err != nil {
        log.Fatalf("unable to run nmap scan: %v", err)
    }

    if warnings != nil {
        log.Printf("Warnings: \n %v", warnings)
    }

    // Use the results to print an example output
    for _, host := range result.Hosts {
        if len(host.Ports) == 0 || len(host.Addresses) == 0 {
            continue
        }

        fmt.Printf("Host %q:\n", host.Addresses[0])

        for _, port := range host.Ports {
            fmt.Printf("\tPort %d/%s %s %s\n", port.ID, port.Protocol, port.State, port.Service.Name)
        }
    }

    fmt.Printf("Nmap done: %d hosts up scanned in %3f seconds\n", len(result.Hosts), result.Stats.Finished.Elapsed)
}

The program above outputs:

Host "172.217.16.46":
    Port 80/tcp open http
    Port 443/tcp open https
    Port 843/tcp filtered unknown
Host "31.13.81.36":
    Port 80/tcp open http
    Port 443/tcp open https
    Port 843/tcp open unknown
Host "216.58.215.110":
    Port 80/tcp open http
    Port 443/tcp open https
    Port 843/tcp filtered unknown
Nmap done: 3 hosts up scanned in 1.29 seconds

Advanced example

Cameradar already uses this library at its core to communicate with nmap, discover RTSP streams and access them remotely.

More examples:

External resources

Documentation

Overview

Package nmap provides idiomatic `nmap` bindings for go developers.

Index

Examples

Constants

This section is empty.

Variables

View Source
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

This section is empty.

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.

func (Address) String

func (a Address) String() string

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"`
	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.

func (Hostname) String

func (h Hostname) String() string

type IPIDSequence

type IPIDSequence Sequence

IPIDSequence represents a detected IP ID sequence.

type Interface added in v2.2.0

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 added in v2.2.0

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.

func (OSClass) OSFamily

func (o OSClass) OSFamily() family.OSFamily

OSFamily returns the OS family in an enumerated format.

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 added in v2.1.1

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

func WithACKDiscovery(ports ...string) Option

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

func WithASCIIData(data string) Option

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

func WithBinaryPath(binaryPath string) Option

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 WithContext

func WithContext(ctx context.Context) Option

WithContext adds a context to a scanner, to make it cancellable and able to timeout.

func WithCustomArguments

func WithCustomArguments(args ...string) Option

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. 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

func WithCustomDNSServers(dnsServers ...string) Option

WithCustomDNSServers sets custom DNS servers for the scan. List format: dns1[,dns2],...

func WithCustomSysProcAttr added in v2.2.2

func WithCustomSysProcAttr(f func(*syscall.SysProcAttr)) Option

WithCustomSysProcAttr allows customizing the *syscall.SysProcAttr on the *exec.Cmd instance

func WithDataDir

func WithDataDir(directoryPath string) Option

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

func WithDataLength(length int) Option

WithDataLength appends a random payload of the given length to sent packets.

func WithDebugging

func WithDebugging(level int) Option

WithDebugging sets and increases the debugging level of nmap.

func WithDecoys

func WithDecoys(decoys ...string) Option

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

func WithFTPBounceScan(FTPRelayHost string) Option

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

func WithFilterHost(hostFilter func(Host) bool) Option

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

func WithFilterPort(portFilter func(Port) bool) Option

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 added in v2.1.1

func WithGrepOutput(outputFileName string) Option

WithGrepOutput makes nmap output greppable output to the filename specified.

func WithHexData

func WithHexData(data string) Option

WithHexData appends a custom hex-encoded payload to sent packets.

func WithHostTimeout

func WithHostTimeout(timeout time.Duration) Option

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

func WithIPOptions(options string) Option

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

func WithIPProtocolPingDiscovery(protocols ...string) Option

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

func WithIPTimeToLive(ttl int16) Option

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

func WithIdleScan(zombieHost string, probePort int) Option

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

func WithInitialRTTTimeout(roundTripTime time.Duration) Option

WithInitialRTTTimeout sets the initial probe round trip time.

func WithInterface

func WithInterface(iface string) Option

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

func WithMTU(offset int) Option

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

func WithMaxHostgroup(size int) Option

WithMaxHostgroup sets the maximal parallel host scan group size.

func WithMaxParallelism

func WithMaxParallelism(probes int) Option

WithMaxParallelism sets the maximal number of parallel probes.

func WithMaxRTTTimeout

func WithMaxRTTTimeout(roundTripTime time.Duration) Option

WithMaxRTTTimeout sets the maximal probe round trip time.

func WithMaxRate

func WithMaxRate(packetsPerSecond int) Option

WithMaxRate sets the maximal number of packets sent per second.

func WithMaxRetries

func WithMaxRetries(tries int) Option

WithMaxRetries sets the maximal number of port scan probe retransmissions.

func WithMaxScanDelay

func WithMaxScanDelay(timeout time.Duration) Option

WithMaxScanDelay sets the maximum time to wait between each probe sent to a host.

func WithMinHostgroup

func WithMinHostgroup(size int) Option

WithMinHostgroup sets the minimal parallel host scan group size.

func WithMinParallelism

func WithMinParallelism(probes int) Option

WithMinParallelism sets the minimal number of parallel probes.

func WithMinRTTTimeout

func WithMinRTTTimeout(roundTripTime time.Duration) Option

WithMinRTTTimeout sets the minimal probe round trip time.

func WithMinRate

func WithMinRate(packetsPerSecond int) Option

WithMinRate sets the minimal number of packets sent per second.

func WithMostCommonPorts

func WithMostCommonPorts(number int) Option

WithMostCommonPorts sets the scanner to go through the provided number of most common ports.

func WithNmapOutput added in v2.1.1

func WithNmapOutput(outputFileName string) Option

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 WithOSDetection

func WithOSDetection() Option

WithOSDetection enables OS detection.

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 WithOpenOnly

func WithOpenOnly() Option

WithOpenOnly makes nmap only show open ports.

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

func WithPortExclusions(ports ...string) Option

WithPortExclusions sets the ports that the scanner should not scan on each host.

func WithPortRatio

func WithPortRatio(ratio float32) Option

WithPortRatio sets the scanner to go the ports more common than the given ratio. Ratio must be a float between 0 and 1.

func WithPorts

func WithPorts(ports ...string) Option

WithPorts sets the ports which the scanner should scan on each host.

func WithPrivileged

func WithPrivileged() Option

WithPrivileged makes nmap assume that the user is fully privileged.

func WithProxies

func WithProxies(proxies ...string) Option

WithProxies allows to relay connection through HTTP/SOCKS4 proxies.

func WithRandomTargets

func WithRandomTargets(randomTargets int) Option

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

func WithResumePreviousScan(filePath string) Option

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

func WithSCTPDiscovery(ports ...string) Option

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

func WithSYNDiscovery(ports ...string) Option

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

func WithScanDelay(timeout time.Duration) Option

WithScanDelay sets the minimum time to wait between each probe sent to a host.

func WithScriptArguments

func WithScriptArguments(arguments map[string]string) Option

WithScriptArguments provides arguments for scripts. If a value is the empty string, the key will be used as a flag.

func WithScriptArgumentsFile

func WithScriptArgumentsFile(inputFilePath string) Option

WithScriptArgumentsFile provides arguments for scripts from a file.

func WithScriptTimeout added in v2.2.1

func WithScriptTimeout(timeout time.Duration) Option

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

func WithScripts(scripts ...string) Option

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 diables host discovery and considers all hosts as online.

func WithSourcePort

func WithSourcePort(port uint16) Option

WithSourcePort specifies from which port to scan.

func WithSpoofIPAddress

func WithSpoofIPAddress(ip string) Option

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

func WithSpoofMAC(argument string) Option

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

func WithStatsEvery(interval string) Option

WithStatsEvery periodically prints a timing status message after each interval of time.

func WithStylesheet

func WithStylesheet(stylesheetPath string) Option

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

func WithTCPScanFlags(flags ...TCPFlag) Option

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 WithTargetExclusion

func WithTargetExclusion(target string) Option

WithTargetExclusion sets the excluded targets of a scanner.

func WithTargetExclusionInput

func WithTargetExclusionInput(inputFileName string) Option

WithTargetExclusionInput sets the input file name to set the target exclusions.

func WithTargetInput

func WithTargetInput(inputFileName string) Option

WithTargetInput sets the input file name to set the targets.

func WithTargets

func WithTargets(targets ...string) Option

WithTargets sets the target of a scanner.

func WithTimingTemplate

func WithTimingTemplate(timing Timing) Option

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

func WithUDPDiscovery(ports ...string) Option

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 added in v2.2.1

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

func WithVerbosity(level int) Option

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

func WithVersionIntensity(intensity int16) Option

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.

func (Owner) String

func (o Owner) String() string

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.

func (Port) Status

func (p Port) Status() PortStatus

Status returns the status of a 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 added in v2.2.0

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.

func Parse

func Parse(content []byte) (*Run, error)

Parse takes a byte array of nmap xml data and unmarshals it into a Run struct.

func (Run) ToFile

func (r Run) ToFile(filePath string) error

ToFile writes a Run as XML into the specified file path.

func (Run) ToReader

func (r Run) ToReader() io.Reader

ToReader writes the raw XML into an streamable buffer.

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

type ScanRunner interface {
	Run() (result *Run, warnings []string, err error)
}

ScanRunner represents something that can run a scan.

type Scanner

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

Scanner represents an Nmap scanner.

Example (Filters)

A scanner can be given custom idiomatic filters for both hosts and ports.

s, err := NewScanner(
	WithTargets("google.com", "facebook.com"),
	WithPorts("843"),
	WithFilterHost(func(h Host) bool {
		// Filter out hosts with no open ports.
		for idx := range h.Ports {
			if h.Ports[idx].Status() == "closed" {
				return true
			}
		}
		return false
	}),
)
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(
	"Filtered out hosts %d / Original number of hosts: %d\n",
	len(scanResult.Hosts),
	scanResult.Stats.Hosts.Total,
)
Output:

Filtered out hosts 1 / Original number of hosts: 2
Example (Simple)

A scanner can be instantiated with options to set the arguments that are given to nmap.

s, err := NewScanner(
	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

func NewScanner(options ...Option) (*Scanner, error)

NewScanner creates a new Scanner, and can take options to apply to the scanner.

func (*Scanner) AddOptions

func (s *Scanner) AddOptions(options ...Option)

AddOptions sets more scan options after the scan is created.

func (*Scanner) Args added in v2.2.0

func (s *Scanner) Args() []string

ReturnArgs return the list of nmap args

func (*Scanner) GetInterfaceList added in v2.2.0

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) GetStderr

func (s *Scanner) GetStderr() bufio.Scanner

GetStderr returns stderr variable for scanner.

func (*Scanner) GetStdout

func (s *Scanner) GetStdout() bufio.Scanner

GetStdout returns stdout variable for scanner.

func (*Scanner) Run

func (s *Scanner) Run() (result *Run, warnings []string, err error)

Run runs nmap synchronously and returns the result of the scan.

func (*Scanner) RunAsync

func (s *Scanner) RunAsync() error

RunAsync runs nmap asynchronously and returns error. TODO: RunAsync should return warnings as well.

func (*Scanner) RunWithProgress added in v2.0.3

func (s *Scanner) RunWithProgress(liveProgress chan<- float32) (result *Run, warnings []string, err error)

RunWithProgress runs nmap synchronously and returns the result of the scan. It needs a channel to constantly stream the progress.

func (*Scanner) RunWithStreamer added in v2.1.0

func (s *Scanner) RunWithStreamer(stream Streamer, file string) (warnings []string, err error)

RunWithStreamer runs nmap synchronously. The XML output is written directly to a file. It uses a streamer interface to constantly stream the stdout.

func (*Scanner) Wait

func (s *Scanner) Wait() error

Wait waits for the cmd to finish and returns error.

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.

func (Service) String

func (s Service) String() string

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.

func (State) String

func (s State) String() string

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.

func (Status) String

func (s Status) String() string

type Streamer added in v2.1.0

type Streamer interface {
	Write(d []byte) (int, error)
	Bytes() []byte
}

Streamer constantly streams the stdout.

type TCPFlag

type TCPFlag int

TCPFlag represents a TCP flag.

const (
	FlagNULL TCPFlag = 0
	FlagFIN  TCPFlag = 1
	FlagSYN  TCPFlag = 2
	FlagRST  TCPFlag = 4
	FlagPSH  TCPFlag = 8
	FlagACK  TCPFlag = 16
	FlagURG  TCPFlag = 32
	FlagECE  TCPFlag = 64
	FlagCWR  TCPFlag = 128
	FlagNS   TCPFlag = 256
)

Flag enumerations.

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

type Timestamp time.Time

Timestamp represents time as a UNIX timestamp in seconds.

func (Timestamp) FormatTime

func (t Timestamp) FormatTime() string

FormatTime formats the time.Time value as a UNIX timestamp string.

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Timestamp) MarshalXMLAttr

func (t Timestamp) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

MarshalXMLAttr implements the xml.MarshalerAttr interface.

func (*Timestamp) ParseTime

func (t *Timestamp) ParseTime(s string) error

ParseTime converts a UNIX timestamp string to a time.Time.

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Timestamp) UnmarshalXMLAttr

func (t *Timestamp) UnmarshalXMLAttr(attr xml.Attr) (err error)

UnmarshalXMLAttr implements the xml.UnmarshalXMLAttr 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.

type Uptime

type Uptime struct {
	Seconds  int    `xml:"seconds,attr" json:"seconds"`
	Lastboot string `xml:"lastboot,attr" json:"last_boot"`
}

Uptime is the amount of time the host has been up.

type Verbose

type Verbose struct {
	Level int `xml:"level,attr" json:"level"`
}

Verbose contains the verbosity level of the scan.

Jump to

Keyboard shortcuts

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