### Naabu Port Usage Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/port.md A comprehensive example demonstrating the creation and usage of Port and Service structures within Naabu. Shows how to initialize ports, add service details, and print string representations. ```go package main import ( "fmt" "github.com/projectdiscovery/naabu/v2/pkg/port" "github.com/projectdiscovery/naabu/v2/pkg/protocol" ) func main() { // Create a basic port p := &port.Port{ Port: 80, Protocol: protocol.TCP, } fmt.Println(p.String()) // "80" // Create port with service information p2 := &port.Port{ Port: 443, Protocol: protocol.TCP, TLS: true, Service: &port.Service{ Name: "https", Product: "Apache httpd", Version: "2.4.41", Confidence: 95, Banner: "Apache/2.4.41 (Ubuntu)", Method: "probes", }, } fmt.Println(p2.StringWithDetails()) // "443[tcp/tls]" if p2.Service != nil { fmt.Printf("%s %s/%s\n", p2.Service.Name, p2.Service.Product, p2.Service.Version) } } ``` -------------------------------- ### Prediction Model Usage Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/prediction.md Demonstrates how to create, train, and use the prediction model. It shows how to train the model with host-port data, get model statistics, predict likely open ports based on a known open port, and prioritize candidate ports. ```go package main import ( "fmt" "github.com/projectdiscovery/naabu/v2/pkg/prediction" "github.com/projectdiscovery/naabu/v2/pkg/result" ) func main() { // Create and train model model := prediction.NewModel() // Training data from previous scans hostPorts := map[string][]int{ "192.168.1.1": {22, 80, 443, 3306}, "192.168.1.2": {80, 443, 8000}, "192.168.1.3": {22, 80, 443}, "192.168.1.4": {80, 443, 8080}, "192.168.1.5": {22, 3306}, } model.Train(hostPorts) sources, total := model.Stats() fmt.Printf("Trained model: %d sources, %d entries\n", sources, total) // Use trained model for predictions known := []int{80} predictions := model.Predict(known, 0.20) fmt.Println("Predicted ports if 80 is open:") for _, p := range predictions { fmt.Printf(" %d (confidence: %.1f%%)\n", p.Port, p.Confidence*100) } // Rank specific candidates candidates := []int{22, 443, 8080, 9000} ranked := model.Prioritize(candidates, known) fmt.Println("\nRanked candidates:") for _, p := range ranked { fmt.Printf(" %d: %.1f%%\n", p.Port, p.Confidence*100) } } ``` -------------------------------- ### Naabu Usage Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/scan.md Demonstrates how to use the Naabu library to perform a network scan. This example shows how to create a scanner, configure options, and perform a connect scan on a specific port. ```go package main import ( "context" "fmt" "log" "time" "github.com/projectdiscovery/naabu/v2/pkg/port" "github.com/projectdiscovery/naabu/v2/pkg/protocol" "github.com/projectdiscovery/naabu/v2/pkg/scan" ) func main() { // Create scanner opts := &scan.Options{ Timeout: 1000 * time.Millisecond, Retries: 3, Rate: 1000, ScanType: "c", // CONNECT scan (no root required) } scanner, err := scan.NewScanner(opts) if err != nil { log.Fatal(err) } defer scanner.Close() // Scan a port ctx, cancel := context.WithTimeout( context.Background(), 5*time.Second, ) defer cancel() p := &port.Port{Port: 80, Protocol: protocol.TCP} isOpen, err := scanner.ConnectScan(ctx, "scanme.sh", p) if err != nil { log.Fatal(err) } if isOpen { fmt.Println("Port 80 is open") } else { fmt.Println("Port 80 is closed") } } ``` -------------------------------- ### Install Naabu using Go Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Installs the Naabu port scanner globally using the Go toolchain. Ensure Go is installed and configured. ```sh go install -v github.com/projectdiscovery/naabu/v2/cmd/naabu@latest ``` -------------------------------- ### Port String Method Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/port.md Demonstrates how to get the port number as a string using the String() method. Requires a Port struct instance. ```go p := &port.Port{Port: 80, Protocol: protocol.TCP} fmt.Println(p.String()) // "80" ``` -------------------------------- ### Port StringWithDetails Method Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/port.md Shows how to obtain a detailed string representation of a port, including protocol and TLS information. Useful for logging or display. ```go p := &port.Port{Port: 443, Protocol: protocol.TCP, TLS: true} fmt.Println(p.StringWithDetails()) // "443[tcp/tls]" ``` -------------------------------- ### Naabu Scan Output Example Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Example output from a Naabu scan against hackerone.com, showing discovered open ports. ```console naabu -host hackerone.com __ ___ ___ ___ _/ / __ __ / _ \/ _ \/ _ \/ _ \/ // / /_//_/\_,_/",_/_.__/\_,_/ v2.0.3 projectdiscovery.io [WRN] Use with caution. You are responsible for your actions [WRN] Developers assume no liability and are not responsible for any misuse or damage. [INF] Running SYN scan with root privileges [INF] Found 4 ports on host hackerone.com (104.16.100.52) hackerone.com:80 hackerone.com:443 hackerone.com:8443 hackerone.com:8080 ``` -------------------------------- ### Example Naabu Configuration File Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md A sample YAML configuration file for Naabu, demonstrating various settings for input, rate limiting, scanning, service detection, host discovery, output, and optimization. ```yaml # Input host: - example.com - 192.168.1.0/24 ports: "80,443,8080-8090" top-ports: "1000" # Rate limiting rate: 2000 threads: 50 timeout: 1500ms retries: 3 # Scanning scan-type: s source-ip: 192.168.1.100 interface: eth0 # Service detection service-version: true service-version-workers: 25 service-version-timeout: 5s udp-probes: true # Host discovery with-host-discovery: true probe-tcp-syn: - "80" - "443" icmp-echo-request: true # Output output: results.json json: true verbose: true # Optimization smart-scan: true prediction-threshold: 30 verify: true # Other exclude-cdn: true display-cdn: true nmap-cli: "nmap -sV -sC" ``` -------------------------------- ### Service String Method Example Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/port.md Illustrates retrieving the service name as a string using the String() method. Useful for identifying the detected service. ```go svc := &port.Service{Name: "http"} fmt.Println(svc.String()) // "http" ``` -------------------------------- ### Scan ASN Output Example Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Example output when scanning an ASN, showing discovered open ports on the associated IP addresses. ```console echo AS14421 | naabu -p 80,443 216.101.17.249:80 216.101.17.249:443 216.101.17.248:443 216.101.17.252:443 216.101.17.251:80 216.101.17.251:443 216.101.17.250:443 216.101.17.250:80 ``` -------------------------------- ### Naabu Service Version Detection Output Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Example output showing discovered ports and identified services with their versions. ```console scanme.sh:22 [ssh OpenSSH/6.6.1p1] scanme.sh:80 [http Apache httpd/2.4.7] scanme.sh:9929 [nping-echo Nping echo] [INF] Found 3 ports on host scanme.sh (45.33.32.156) with 3 services identified ``` -------------------------------- ### Standard Output Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Example of standard output format, typically showing scanned ports. ```text scanme.sh:22 scanme.sh:80 scanme.sh:9929 ``` -------------------------------- ### Get Protocol as String Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/protocol.md Returns the protocol as a lowercase string. Useful for display or logging. ```go p := protocol.TCP fmt.Println(p.String()) // "tcp" ``` -------------------------------- ### Port Scan with Host Discovery Enabled Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/runner.md Enables host discovery before port scanning. This example shows how to use ICMP echo requests and TCP SYN pings for probing, and how to display dead hosts. ```go options := &runner.Options{ Host: goflags.StringSlice{"192.168.1.0/24"}, Ports: "80,443", WithHostDiscovery: true, IcmpEchoRequestProbe: true, TcpSynPingProbes: goflags.StringSlice{"80", "443"}, ShowDeadHosts: true, } runner, err := runner.NewRunner(options) if err != nil { log.Fatal(err) } deferrunner.Close() runner.RunEnumeration(context.Background()) ``` -------------------------------- ### Run Naabu Enumeration Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/runner.md Executes the main enumeration process, including host discovery, port scanning, and service detection. Use this to start a scan with a given context. ```go ctx := context.Background() err := naabuRunner.RunEnumeration(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Check Naabu Version via CLI and Programmatically Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Check the installed naabu version. This can be done directly from the command line or programmatically by setting the Version option. ```bash // From CLI naabu -version ``` ```go // Programmatically via runner options.Version = true ``` -------------------------------- ### Port String Method Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/types.md Returns the port number as a string, for example, "80". ```go func (p *Port) String() string ``` -------------------------------- ### Protocol String Conversion Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/protocol.md Demonstrates how to get the string representation of a Protocol type. ```APIDOC ## Protocol.String() ### Description Returns the protocol as a lowercase string. ### Method `String()` ### Returns `string` - "tcp", "udp", or "arp" ### Example ```go p := protocol.TCP fmt.Println(p.String()) // "tcp" ``` ``` -------------------------------- ### Integration with Runner for SmartScan Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/prediction.md Shows how to enable and configure the prediction model within the naabu runner for SmartScan mode. This example sets a custom prediction threshold. ```go options := &runner.Options{ Host: goflags.StringSlice{"example.com"}, Ports: "80,443", SmartScan: true, PredictionThreshold: 30, // Min 30% confidence } naabuRunner, _ := runner.NewRunner(options) def NaabuRunner.Close() naabuRunner.Close() naabuRunner.RunEnumeration(context.Background()) ``` -------------------------------- ### NewRunner Constructor Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/runner.md Initializes a new Runner instance with specified configuration options for port enumeration. It handles the setup required for scanning and returns a Runner object or an error if initialization fails. ```APIDOC ## NewRunner Creates a new Runner instance with the provided options. ### Signature ```go func NewRunner(options *Options) (*Runner, error) ``` ### Parameters #### Path Parameters * **options** (*Options) - Required - Configuration for port enumeration ### Returns - `(*Runner, error)`: Runner instance if successful, or an error if initialization fails (e.g., invalid options, port parsing issues, DNS setup problems). ### Throws - Port parsing errors - Network policy setup errors - DNS client initialization errors ### Example ```go package main import ( "context" "log" "github.com": "/projectdiscovery/goflags" "github.com": "/projectdiscovery/naabu/v2/pkg/result" "github.com": "/projectdiscovery/naabu/v2/pkg/runner" ) func main() { options := &runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, ScanType: "s", Ports: "80,443", Rate: 1000, Threads: 25, OnResult: func(hr *result.HostResult) { for _, p := range hr.Ports { log.Printf("%s:%d\n", hr.Host, p.Port) } }, } naabuRunner, err := runner.NewRunner(options) if err != nil { log.Fatal(err) } defer naabuRunner.Close() naabuRunner.RunEnumeration(context.Background()) } ``` ``` -------------------------------- ### Create Naabu Runner Instance Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/runner.md Initializes a new Naabu runner with specified configuration options. Ensure all required fields in Options are populated correctly. Handles potential errors during initialization, such as invalid port formats or network setup issues. ```go package main import ( "context" "log" "github.com/projectdiscovery/goflags" "github.com/projectdiscovery/naabu/v2/pkg/result" "github.com/projectdiscovery/naabu/v2/pkg/runner" ) func main() { options := &runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, ScanType: "s", Ports: "80,443", Rate: 1000, Threads: 25, OnResult: func(hr *result.HostResult) { for _, p := range hr.Ports { log.Printf("%s:%d\n", hr.Host, p.Port) } }, } naabuRunner, err := runner.NewRunner(options) if err != nil { log.Fatal(err) } defer naabuRunner.Close() naabuRunner.RunEnumeration(context.Background()) } ``` -------------------------------- ### Run Nmap CLI with Naabu Input Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Pipe hostnames to Naabu and use the `-nmap-cli` flag to execute Nmap commands on discovered ports. Ensure Nmap is installed. ```console echo hackerone.com | naabu -nmap-cli 'nmap -sV -oX nmap-output' ``` -------------------------------- ### CSV Result Output Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Example of results formatted as CSV, including headers and data rows. ```csv ip,port,host,protocol,service,version 104.16.99.52,80,,tcp,http, 104.16.99.52,443,,tcp,https, ``` -------------------------------- ### JSON Lines Result Output Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Example of results formatted as JSON Lines, with and without service detection details. ```json {"ip":"104.16.99.52","port":80,"protocol":"tcp"} {"ip":"104.16.99.52","port":443,"protocol":"tcp","service":{"name":"https","product":"Apache"}} ``` -------------------------------- ### Get Map of IP to Open Ports (2+ Ports) Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetHostPortsMap` to retrieve a map where keys are IP addresses and values are lists of open ports. This method specifically returns entries only for hosts that have two or more ports open. ```go hostPorts := results.GetHostPortsMap() for ip, ports := range hostPorts { fmt.Printf("%s: %v\n", ip, ports) } ``` -------------------------------- ### Fingerprint Targets and Get Services Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Probes a list of targets and returns a map of detected services. The map is keyed by 'ip:port', and the value is the detected service object or nil if no service was identified. ```go targets := []fingerprint.Target{ {Host: "scanme.sh", IP: "45.33.32.156", Port: 80}, {Host: "scanme.sh", IP: "45.33.32.156", Port: 443}, } services := engine.Fingerprint(ctx, targets) for key, svc := range services { if svc != nil { fmt.Printf("%s: %s\n", key, svc.Name) } } ``` -------------------------------- ### Handle Runner and Enumeration Errors in Go Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Handle potential errors during runner creation and the enumeration process. Invalid options or network setup issues will be caught by NewRunner, while enumeration failures are caught by RunEnumeration. ```go runner, err := runner.NewRunner(options) if err != nil { // Invalid options, network setup failed log.Fatal(err) } err = runner.RunEnumeration(ctx) if err != nil { // Enumeration failed (network, timeout, etc.) log.Fatal(err) } ``` -------------------------------- ### Enable Service Version Detection with Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Use the `-sV` flag to enable Naabu's built-in service version detection. This requires the nmap-service-probes database, which Naabu attempts to find in local Nmap installations. ```sh naabu -host scanme.sh -sV ``` -------------------------------- ### Create Ports with Protocol Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/protocol.md Demonstrates creating port structures with different protocols (TCP and UDP). ```go package main import ( "fmt" "github.com/projectdiscovery/naabu/v2/pkg/port" "github.com/projectdiscovery/naabu/v2/pkg/protocol" ) func main() { // TCP port tcpPort := &port.Port{ Port: 80, Protocol: protocol.TCP, } fmt.Println(tcpPort.Protocol.String()) // "tcp" // UDP port udpPort := &port.Port{ Port: 53, Protocol: protocol.UDP, } fmt.Println(udpPort.Protocol.String()) // "udp" } ``` -------------------------------- ### Configure Host Discovery Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Enable host discovery, specify TCP SYN ping ports, use ICMP echo requests, and report dead hosts. ```go options := &runner.Options{ WithHostDiscovery: true, TcpSynPingProbes: goflags.StringSlice{"80", "443"}, IcmpEchoRequestProbe: true, ShowDeadHosts: true, } ``` -------------------------------- ### Handle Runner Initialization and Execution Errors Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/00_START_HERE.md Demonstrates how to properly initialize the Naabu runner and handle potential errors during both configuration and runtime execution. ```go runner, err := runner.NewRunner(options) if err != nil { // Configuration error (invalid options, network setup failed) return err } err = runner.RunEnumeration(ctx) if err != nil { // Runtime error (network, timeout, interrupted) return err } ``` -------------------------------- ### Configure Cloud/Dashboard Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Set up authentication, asset uploading, and specify team and asset details for cloud dashboard integration. ```go options := &runner.Options{ PdcpAuth: "YOUR_API_KEY", AssetUpload: true, TeamID: "team-uuid", AssetName: "Production Servers", } ``` -------------------------------- ### Configure Callback Functions for Results Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Set up callbacks for real-time port discovery and final scan results. ```go options := &runner.Options{ OnReceive: func(hr *result.HostResult) { log.Printf("Found port: %s:%d", hr.IP, hr.Ports[0].Port) }, OnResult: func(hr *result.HostResult) { log.Printf("Final: %s has %d ports", hr.Host, len(hr.Ports)) }, } ``` -------------------------------- ### Configure Optimization Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Enable smart scanning with a prediction threshold and verify ports using TCP. ```go options := &runner.Options{ SmartScan: true, PredictionThreshold: 30, Verify: true, } ``` -------------------------------- ### Configure CDN/WAF Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Skip full scans for CDN IPs and display CDN information. ```go options := &runner.Options{ ExcludeCDN: true, // Only scan 80,443 for CDN IPs OutputCDN: true, // Show CDN names } ``` -------------------------------- ### Runner.BackgroundWorkers Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/EXPORTED-API.md Starts background worker goroutines to perform scanning tasks. This method takes a context for managing the lifecycle of these workers. ```APIDOC ## Runner.BackgroundWorkers ### Description Starts background worker goroutines to perform scanning tasks. This method takes a context for managing the lifecycle of these workers. ### Signature `func(ctx context.Context)` ### Parameters - **ctx** (context.Context) - Required - Context for managing the worker goroutines. ``` -------------------------------- ### Configure Resume/Stream Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Enable stream mode for real-time scanning without resume, and enable passive scanning. ```go options := &runner.Options{ Stream: true, // Real-time scanning without resume Passive: true, // Passive scanning } ``` -------------------------------- ### Go: Batch and Stream Fingerprinting Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Demonstrates how to use the fingerprinting engine for both batch and stream processing of targets. Includes loading the probe database, creating the engine with custom workers and timeouts, and processing results. ```go package main import ( "context" "fmt" "log" "time" "github.com/projectdiscovery/naabu/v2/pkg/fingerprint" ) func main() { // Auto-locate probe database probePath, err := fingerprint.LocateProbeDB() if err != nil { log.Fatal(err) } // Load probes db, err := fingerprint.LoadProbeDB(probePath) if err != nil { log.Fatal(err) } // Create engine engine := fingerprint.New( db, fingerprint.WithWorkers(25), fingerprint.WithTimeout(5*time.Second), ) // Batch fingerprinting ctx := context.Background() targets := []fingerprint.Target{ {Host: "scanme.sh", IP: "45.33.32.156", Port: 22}, {Host: "scanme.sh", IP: "45.33.32.156", Port: 80}, {Host: "scanme.sh", IP: "45.33.32.156", Port: 443}, } services := engine.Fingerprint(ctx, targets) for key, svc := range services { if svc != nil { fmt.Printf("%s: %s %s\n", key, svc.Product, svc.Version) } } // Stream fingerprinting targetChan := make(chan fingerprint.Target, 10) go func() { targetChan <- fingerprint.Target{IP: "1.1.1.1", Port: 443} targetChan <- fingerprint.Target{IP: "1.1.1.1", Port: 80} close(targetChan) }() results := engine.FingerprintStream(ctx, targetChan) for result := range results { if result.Service != nil { fmt.Printf("%s:%d -> %s\n", result.IP, result.Port, result.Service.Name) } } } ``` -------------------------------- ### Get All Results at Once Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/00_START_HERE.md Use this pattern to collect all scan results after the scan is complete. The `OnResult` callback is used to aggregate results into a single structure. ```go results := result.NewResult() options := &runner.Options{ Host: goflags.StringSlice{"target.com"}, Ports: "1-65535", OnResult: func(hr *result.HostResult) { results.SetPorts(hr.IP, hr.Ports) }, } ``` -------------------------------- ### Configure Input Options for Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Set hosts to scan, specify a file for hosts, and define IPs/CIDRs to exclude. ```go options := &runner.Options{ Host: goflags.StringSlice{"example.com", "192.168.1.0/24"}, HostsFile: "targets.txt", ExcludeIps: "10.0.0.1,10.0.0.2", } ``` -------------------------------- ### Get Model Statistics Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/prediction.md Returns statistics about the prediction model, including the number of distinct source ports and the total number of probability entries stored. ```go sources, total := model.Stats() fmt.Printf("Model has %d source ports, %d total entries\n", sources, total) ``` -------------------------------- ### Configure Service Detection Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Enable service version detection with custom workers, timeouts, probe files, and UDP probe support. ```go options := &runner.Options{ ServiceVersion: true, ServiceVersionWorkers: 50, ServiceVersionTimeout: 10 * time.Second, ServiceProbesFile: "/usr/share/nmap/nmap-service-probes", UDPProbes: true, } ``` -------------------------------- ### Initialize Naabu Scanner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/scan.md Create a new Naabu scanner instance with custom options. Ensure to close the scanner when done to release resources. ```go opts := &scan.Options{ Timeout: 1000 * time.Millisecond, Retries: 3, Rate: 1000, ScanType: "s", // SYN scan } scanner, err := scan.NewScanner(opts) if err != nil { log.Fatal(err) } defer scanner.Close() ``` -------------------------------- ### Configure Fingerprint Engine Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Initializes a new fingerprint engine with custom worker count, timeout, and fast mode settings. Ensure the probe database is loaded before creating the engine. ```go engine := fingerprint.New(db, fingerprint.WithWorkers(50), fingerprint.WithTimeout(10*time.Second), fingerprint.WithFastMode(true), ) ``` -------------------------------- ### Retrieve the List of Dead Hosts Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetDeadHosts` to get a slice containing all IP addresses that were recorded as dead hosts. This provides a definitive list of unreachable IPs. ```go deadHosts := results.GetDeadHosts() ``` -------------------------------- ### Protocol Parsing and String Conversion Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/protocol.md Demonstrates parsing protocol strings into constants and converting them back to strings. ```go import ( "github.com/projectdiscovery/naabu/v2/pkg/protocol" ) func main() { // Parse protocol from string tcp := protocol.ParseProtocol("tcp") udp := protocol.ParseProtocol("udp") arp := protocol.ParseProtocol("arp") // Convert back to string fmt.Println(tcp.String()) // "tcp" fmt.Println(udp.String()) // "udp" fmt.Println(arp.String()) // "arp" } ``` -------------------------------- ### Get Correlations for a Given Port Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/prediction.md Retrieves all stored conditional probabilities P(target | givenPort) for a specific known open port. Returns a map of candidate ports to their confidences. ```go corrs := model.GetCorrelations(80) for port, prob := range corrs { if prob > 0.5 { fmt.Printf("Port %d has %.1f%% chance if 80 is open\n", port, prob*100) } } ``` -------------------------------- ### Display Help for Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md Run this command to display the help message and view all supported command-line switches for the naabu tool. ```sh naabu -h ``` -------------------------------- ### Iterate Through Host Results with Ports Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetIPsPorts` to get a channel that yields `HostResult` objects, each containing an IP and its associated open ports. This is useful for processing detailed results for each host. ```go for hostResult := range results.GetIPsPorts() { fmt.Printf("%s: %d ports\n", hostResult.IP, len(hostResult.Ports)) } ``` -------------------------------- ### Basic Port Scan with Naabu Runner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/runner.md Demonstrates a basic port scan using the Naabu runner. Specify hosts, ports, and scan type. Ensure to handle potential errors and close the runner when done. ```go options := &runner.Options{ Host: goflags.StringSlice{"example.com"}, Ports: "80,443,8080", ScanType: "c", // CONNECT scan } runner, err := runner.NewRunner(options) if err != nil { log.Fatal(err) } deferrunner.Close() err = runner.RunEnumeration(context.Background()) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Deduplicated List of Open Port Numbers Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetOpenPortNumbers` to obtain a sorted list of all unique port numbers discovered across all hosts. This is useful for understanding the overall port landscape. ```go ports := results.GetOpenPortNumbers() ``` -------------------------------- ### Get Port Count for a Specific Host Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetPortCount` to retrieve the number of open ports discovered for a particular IP address. This provides a quick summary of the host's open ports. ```go count := results.GetPortCount("192.168.1.1") ``` -------------------------------- ### Go Library Usage for Naabu Port Scanner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Demonstrates basic library usage for naabu port scanning. Configure scan options like hosts, ports, and scan type, and provide a callback function for handling scan results. ```go package main import ( "context" "log" "github.com/projectdiscovery/goflags" "github.com/projectdiscovery/naabu/v2/pkg/result" "github.com/projectdiscovery/naabu/v2/pkg/runner" ) func main() { options := &runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, Ports: "80,443", ScanType: "c", // CONNECT scan OnResult: func(hr *result.HostResult) { log.Printf("Host: %s, Ports: %d\n", hr.Host, len(hr.Ports)) }, } naabuRunner, err := runner.NewRunner(options) if err != nil { log.Fatal(err) } defer naabuRunner.Close() err = naabuRunner.RunEnumeration(context.Background()) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Configure DNS Resolution Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Set custom DNS resolvers, define resolution order, and control IP version usage. Enable scanning all resolved IPs or using the system resolver as a fallback. ```go options := &runner.Options{ Resolvers: "8.8.8.8,1.1.1.1", DnsOrder: "pl", // proxy first, then local IPVersion: goflags.StringSlice{"4"}, // IPv4 only ScanAllIPS: true, // scan all resolved IPs } ``` -------------------------------- ### Load Probe Database from Path Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Loads and parses the nmap-service-probes file from a specified path. Handles file not found and parse errors. ```go db, err := fingerprint.LoadProbeDB("/usr/share/nmap/nmap-service-probes") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Count of Hosts with a Specific Port Open Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `GetHostCountForPort` to find out how many different hosts have a particular port number open. This helps in identifying commonly open ports across a network. ```go hostCount := results.GetHostCountForPort(80) ``` -------------------------------- ### Configure Scan Type and Network Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Select scan type (SYN or CONNECT), specify source IP, port, and network interface. A CONNECT scan payload can also be defined. ```go options := &runner.Options{ ScanType: "s", // SYN scan (requires root) SourceIP: "192.168.1.100", SourcePort: "53", Interface: "eth0", ConnectPayload: "GET / HTTP/1.0\r\n\r\n", } ``` -------------------------------- ### Set Environment Variables for Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Set environment variables to configure Naabu's behavior, such as team ID and disabling stdout output. This example shows how to export variables and pipe the output to jq for JSON processing. ```bash export PDCP_TEAM_ID="team-uuid" export DISABLE_STDOUT=1 naabu -host example.com -json | jq ``` -------------------------------- ### NewRunner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/EXPORTED-API.md Initializes a new Runner instance with the provided options. It returns the Runner and an error if initialization fails. ```APIDOC ## NewRunner ### Description Initializes a new Runner instance with the provided options. It returns the Runner and an error if initialization fails. ### Signature `func(options *Options) (*Runner, error)` ### Returns - Runner: An initialized Runner object. - error: An error if the Runner could not be initialized. ``` -------------------------------- ### Create New Fingerprint Engine Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Initializes a new fingerprint engine with a probe database and optional configurations like worker count and timeout. Ensure the probe database is loaded correctly before creating the engine. ```go db, err := fingerprint.LoadProbeDB("/usr/share/nmap/nmap-service-probes") if err != nil { log.Fatal(err) } engine := fingerprint.New(db, fingerprint.WithWorkers(25), fingerprint.WithTimeout(5*time.Second), ) ``` -------------------------------- ### JSON Output with OnReceive Callback Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Configures JSON output and registers an `OnReceive` callback for real-time port discovery notifications. Specify the output file using the `Output` field. ```go options := &runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, Ports: "80,443", JSON: true, Output: "results.jsonl", OnReceive: func(hr *result.HostResult) { log.Printf("Found: %s:%d", hr.IP, hr.Ports[0].Port) }, } ``` -------------------------------- ### Set Debug and Metrics Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Configure debug and metrics settings for the runner. Set MetricsPort to specify the port for the metrics endpoint. ```go options := &runner.Options{ MetricsPort: 9090, Verbose: true, Debug: true, } ``` -------------------------------- ### Configure Proxy Settings for Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Specify a SOCKS5 proxy and its authentication credentials if required. ```go options := &runner.Options{ Proxy: "127.0.0.1:1080", ProxyAuth: "user:password", } ``` -------------------------------- ### Port StringWithDetails Method Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/types.md Returns a detailed string representation of a port, including its protocol, such as "80[tcp]" or "443[tcp/tls]". ```go func (p *Port) StringWithDetails() string ``` -------------------------------- ### Runner Configuration Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/INDEX.md Outlines the various configuration options available for the Naabu runner, covering input, ports, scanning, services, and output. ```Go Options (runner config) ├─ Input: Host, HostsFile, ExcludeIps ├─ Ports: Ports, PortsFile, TopPorts, ExcludePorts ├─ Scanning: ScanType, Rate, Timeout, Retries ├─ Service: ServiceVersion, ServiceVersionTimeout ├─ HostDiscovery: WithHostDiscovery, Probes ├─ Output: JSON, CSV, Output file ├─ Callbacks: OnResult, OnReceive, OnClose └─ Cloud: PdcpAuth, AssetUpload, TeamID ``` -------------------------------- ### Go: Runner Options for Service Fingerprinting Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/fingerprint.md Configuration options for enabling and customizing service fingerprinting when using the naabu runner. The `ServiceProbesFile` can be left empty to auto-detect the probe database. ```go options := &runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, Ports: "22,80,443", ServiceVersion: true, ServiceVersionWorkers: 25, ServiceVersionTimeout: 5 * time.Second, ServiceProbesFile: "", // auto-detect if empty } ``` -------------------------------- ### Create Naabu Scanner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/scan.md Initializes a new Naabu scanner instance. This is typically done by the runner during initialization. ```go scanner, err := scan.NewScanner(&scan.Options{ Timeout: options.GetTimeout(), Retries: options.Retries, Rate: options.Rate, ScanType: options.ScanType, OnReceive: options.OnReceive, }) ``` -------------------------------- ### Service String Method Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/types.md Returns the service name field from a port.Service structure. ```go func (s *Service) String() string ``` -------------------------------- ### Configure Output Options for Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Define output file, format (JSON, CSV), and logging verbosity. Control output fields and disable specific output streams. ```go options := &runner.Options{ Output: "results.json", JSON: true, Verbose: true, ExcludeOutputFields: goflags.StringSlice{"timestamp"}, } ``` -------------------------------- ### Port Scan with Host Discovery Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Includes host discovery mechanisms alongside port scanning. Enable `WithHostDiscovery` and specify probe types like ICMP Echo or TCP SYN. ```go options := &runner.Options{ Host: goflags.StringSlice{"192.168.1.0/24"}, Ports: "80,443", WithHostDiscovery: true, IcmpEchoRequestProbe: true, TcpSynPingProbes: goflags.StringSlice{"80", "443"}, } ``` -------------------------------- ### IsEmpty Method Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Checks if the Result object contains any host information. Returns true if no hosts are present, false otherwise. ```go func (r *Result) IsEmpty() bool ``` -------------------------------- ### JSON Marshaling of Port with Protocol Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/protocol.md Shows how a Port structure, including its protocol field, is marshaled into JSON. ```go import ( "encoding/json" "github.com/projectdiscovery/naabu/v2/pkg/port" "github.com/projectdiscovery/naabu/v2/pkg/protocol" ) func main() { p := &port.Port{ Port: 443, Protocol: protocol.TCP, } data, _ := json.MarshalIndent(p, "", " ") fmt.Println(string(data)) // Output: // { // "port": 443, // "protocol": "tcp", // "tls": false, // "service": null // } ``` -------------------------------- ### Basic Network Scan with Naabu Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/00_START_HERE.md Performs a basic network scan on specified hosts and ports. Ensure you have the necessary imports and initialize the runner correctly. Results are printed to standard output. ```go package main import ( "context" "fmt" "github.com/projectdiscovery/goflags" "github.com/projectdiscovery/naabu/v2/pkg/runner" ) func main() { options := &runner.Options{ Host: goflags.StringSlice{"example.com"}, Ports: "80,443", } r, err := runner.NewRunner(options) if err != nil { panic(err) } defer r.Close() r.RunEnumeration(context.Background()) // Results printed to stdout } ``` -------------------------------- ### Options Type Definition Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/EXPORTED-API.md Illustrates the Options struct used for configuring naabu scanning parameters. ```go type Options struct { // Input Host string HostsFile string ExcludeIps []string ExcludeIpsFile string // Ports Ports []string PortsFile string TopPorts int ExcludePorts []string PortThreshold int // Rate Rate int Threads int Timeout time.Duration Retries int WarmUpTime time.Duration // Scanning ScanType string SourceIP string SourcePort string Interface string ConnectPayload string // DNS Resolvers []string DnsOrder string SystemResolver bool ScanAllIPS bool IPVersion string // Proxy Proxy string ProxyAuth string // Output Output string JSON bool CSV bool Silent bool Verbose bool Debug bool NoColor bool DisableStdout bool // Host Discovery OnlyHostDiscovery bool WithHostDiscovery bool ShowDeadHosts bool TcpSynPingProbes []string TcpAckPingProbes []string IcmpEchoRequestProbe bool IcmpTimestampRequestProbe bool IcmpAddressMaskRequestProbe bool ArpPing bool IPv6NeighborDiscoveryPing bool // Service ServiceDiscovery bool ServiceVersion bool ServiceVersionFast bool ServiceVersionTimeout time.Duration ServiceVersionWorkers int ServiceProbesFile string UDPProbes []string // Optimization Verify bool Ping bool SmartScan bool PredictionThreshold int // CDN ExcludeCDN bool OutputCDN bool // Resume/Stream Resume bool Stream bool Passive bool InputReadTimeout time.Duration // nmap Nmap bool NmapCLI string // Callbacks OnResult ResultFn OnReceive func(*HostResult) OnClose func() // Cloud PdcpAuth string PdcpAuthCredFile string AssetUpload bool TeamID string AssetID string AssetName string AssetFileUpload string // Debug HealthCheck bool MetricsPort int DisableUpdateCheck bool } ``` -------------------------------- ### Balanced Performance Tuning Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/00_START_HERE.md Use balanced performance settings for a default scanning configuration, offering a moderate rate, thread count, and timeout. ```go Rate: 1000, Threads: 25, Timeout: 1 * time.Second, Retries: 3, ``` -------------------------------- ### scan.NewScanner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/scan.md Initializes a new Naabu scanner instance with the specified options. This is the primary method for setting up the scanner for network scanning operations. ```APIDOC ## scan.NewScanner ### Description Creates a new scanner instance with the provided options. ### Method Signature ```go func NewScanner(options *Options) (*Scanner, error) ``` ### Parameters #### Request Body - **options** (*Options) - Required - Configuration options for the scanner, including timeout, retries, rate, scan type, and receive callback. - **Timeout** (time.Duration) - Required - The timeout for scan operations. - **Retries** (int) - Required - The number of retries for failed scan attempts. - **Rate** (int) - Required - The rate at which to send packets. - **ScanType** (string) - Required - The type of scan to perform (e.g., "c" for CONNECT scan). - **OnReceive** (func(*Result)) - Required - A callback function to be executed when a result is received. ``` -------------------------------- ### Record a Dead Host Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/result.md Use `AddDeadHost` to log an IP address that did not respond to any host discovery probes. This is useful for identifying hosts that are likely offline or unreachable. ```go results.AddDeadHost("192.168.1.1") ``` -------------------------------- ### Service.String Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/port.md Returns the name of the discovered service. ```APIDOC ## Service.String ### Description Returns the service name. ### Method func (s *Service) String() string ### Returns `string` - Service name ### Example ```go svc := &port.Service{Name: "http"} fmt.Println(svc.String()) // "http" ``` ``` -------------------------------- ### Scan Ports Using Naabu Library Source: https://github.com/projectdiscovery/naabu/blob/dev/README.md This Go program scans port 80 on 'scanme.sh' using the Naabu library. Results are processed via the `OnResult` callback after the scan completes. Ensure necessary imports are included. ```go package main import ( "log" "context" "github.com/projectdiscovery/goflags" "github.com/projectdiscovery/naabu/v2/pkg/result" "github.com/projectdiscovery/naabu/v2/pkg/runner" ) func main() { options := runner.Options{ Host: goflags.StringSlice{"scanme.sh"}, ScanType: "s", OnResult: func(hr *result.HostResult) { log.Println(hr.Host, hr.Ports) }, Ports: "80", } naabuRunner, err := runner.NewRunner(&options) if err != nil { log.Fatal(err) } defer naabuRunner.Close() naabuRunner.RunEnumeration(context.Background()) } ``` -------------------------------- ### Configure Nmap Integration Options Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/configuration.md Specify a custom nmap command to run on results. ```go options := &runner.Options{ NmapCLI: "nmap -sV -sC", } ``` -------------------------------- ### NewScanner Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/scan.md Creates a new Scanner instance with the specified configuration options. This is the entry point for using the Naabu scanner. ```APIDOC ## NewScanner ### Description Creates a new Scanner with specified options. ### Signature ```go func NewScanner(options *Options) (*Scanner, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (*Options) - Yes - Scanner configuration ### Request Example ```go opts := &scan.Options{ Timeout: 1000 * time.Millisecond, Retries: 3, Rate: 1000, ScanType: "s", // SYN scan } scanner, err := scan.NewScanner(opts) if err != nil { log.Fatal(err) } defer scanner.Close() ``` ### Response #### Success Response (200) - **Scanner** (*Scanner) - Scanner instance - **error** (error) - nil if setup is successful #### Response Example - None explicitly provided for success, but an error can be returned. ### Throws - Raw socket access errors (requires root/admin) - Network interface errors - CDN client initialization errors ``` -------------------------------- ### Naabu Real-Time Port Discovery Callback Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/README.md Implement the OnReceive callback to process individual ports as they are discovered during the scan. This is useful for real-time monitoring and aggregation of results. ```go OnReceive: func(hr *result.HostResult) { // Process individual ports as they arrive for _, p := range hr.Ports { fmt.Printf("Discovered: %s:%d\n", hr.IP, p.Port) } } ``` -------------------------------- ### Train Model from Scan Results Source: https://github.com/projectdiscovery/naabu/blob/dev/_autodocs/api-reference/prediction.md Builds the probability model from a map of host IP addresses to their lists of open ports. It computes P(PortA | PortB) based on co-occurrence. ```go data := map[string][]int{ "192.168.1.1": {80, 443, 8080}, "192.168.1.2": {80, 443}, "192.168.1.3": {80, 22}, } model.Train(data) // Learned probabilities: // P(443 | 80) = 2/3 = 0.667 (2 hosts have both 443,80 out of 3 with 80) // P(8080 | 80) = 1/3 = 0.333 // P(22 | 80) = 1/3 = 0.333 ```