zmapgo

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2022 License: MIT Imports: 19 Imported by: 0

README

Go Reference Coverage Status

This library aims to provide to golang developers an idiomatic interface for zmap version 2.1.1.

Inspired by the nmap library.

What is Zmap

Zmap is a network tool for scanning the entire Internet (or large samples). ZMap is capable of scanning the entire Internet in around 45 minutes on a gigabit network connection, reaching ~98% theoretical line speed.

More Details

Supported Features

  • All of zmap 2.1.1 native options.
  • Cancellable contexts support
  • Validation for options
  • Async Scanner
  • Blocking Scanner

TODO

  • More examples

Installation

go get github.com/justmumu/zmapgo

Simple Example

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/justmumu/zmapgo"
)

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

    // Create Blocking Scanner with InitOptions
    scanner, err := zmapgo.NewBlockingScanner(
		zmapgo.WithContext(ctx),
	)
	if err != nil {
		log.Fatalf("unable to create zmap scanner: %v", err)
	}
    
    // Add Options to scanner
    // Equivalent to `zmap ---target-port 80 1.1.1.0/30 --rate 10000 --output-fields saddr,sport --log-file ./log-file.txt --output-file ./output-file.txt`
    err = scanner.AddOptions(
		zmapgo.WithTargets("1.1.1.0/30"),
		zmapgo.WithTargetPort("80"),
		zmapgo.WithRate("10000"),
        zmapgo.WithOutputFields([]string{"saddr", "sport"}),
		zmapgo.WithLogFile("./log-file.txt"),
		zmapgo.WithOutputFile("./output-file.txt"),
	)
	if err != nil {
		log.Fatalf("unable to add options: %v", err)
	}

    // Run the scan
    results, _, _, _, _, fatals, err := scanner.RunBlocking()
	if err != nil {
		log.Fatalf("unable to run zmap scan: %v", err)
	}

    // It's always good to check for fatals.
	if len(fatals) > 0 {
		// So zmap did not work as expected and waiting for results would be pointless.
		for _, fatal := range fatals {
			log.Printf("[FATAL]: %s", fatal.Message)
		}
		os.Exit(1)
	}

    // Print All Results
	for _, result := range results {
		fmt.Printf("%s\n", strings.Repeat("-", 20))
		for key, value := range result {
			fmt.Printf("%s: %s\n", key, value)
		}
	}

The program output:

--------------------
saddr: 1.1.1.3
sport: 80
--------------------
saddr: 1.1.1.1
sport: 80
--------------------
saddr: 1.1.1.0
sport: 80
--------------------
saddr: 1.1.1.2
sport: 80

LICENCE

This project is under MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNmapNotInstalled means that upon trying to manually locate zmap 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.
	ErrZmapNotInstalled = errors.New("zmap binary was not found")

	// ErrScanTimeout means that the provided context was done before the scanner finished its scan.
	ErrScanTimeout = errors.New("zmap scan timed out")
)

Functions

This section is empty.

Types

type AsyncScanner

type AsyncScanner interface {
	AddOptions(options ...Option) error
	RunAsync() error
	Wait() error
	GetTraceMessages() []LogLine
	GetDebugMessages() []LogLine
	GetWarningMessages() []LogLine
	GetInfoMessages() []LogLine
	GetFatalMessages() []LogLine
	GetResults() []map[string]interface{}
	ListProbeModules() ([]string, error)
	ListOutputModules() ([]string, error)
	ListOutputFields() ([]OutputField, error)
	GetVersion() (string, error)
}

func NewAsyncScanner

func NewAsyncScanner(initOptions ...InitOption) (AsyncScanner, error)

type BandwidthUnit

type BandwidthUnit string
var (
	UnitBandwidthBps  BandwidthUnit = "B"
	UnitBandwidthKbps BandwidthUnit = "K"
	UnitBandwidthMbps BandwidthUnit = "M"
	UnitBandwidthGbps BandwidthUnit = "G"
)

type BlockingScanner

type BlockingScanner interface {
	AddOptions(options ...Option) error
	RunBlocking() (results []map[string]interface{}, traces []LogLine, debugs []LogLine, warnings []LogLine, infos []LogLine, fatals []LogLine, err error)
	ListProbeModules() ([]string, error)
	ListOutputModules() ([]string, error)
	ListOutputFields() ([]OutputField, error)
	GetVersion() (string, error)
}

func NewBlockingScanner

func NewBlockingScanner(initOptions ...InitOption) (BlockingScanner, error)

Creates new Scanner Interface

type InitOption

type InitOption func(*scanner) error

InitOptions is initialization option for the Scanner. Ex: WithBinaryPath, WithContext..

func WithBinaryPath

func WithBinaryPath(binaryPath string) InitOption

WithBinaryPath sets the zmap binary path for a scanner

func WithContext

func WithContext(ctx context.Context) InitOption

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

type LogLine

type LogLine struct {
	LogTime time.Time
	LogType string
	Message string
}

type Option

type Option func(*scanner) error

Options is a function that is used for grouping of Scanner options. Option adds or remove zmap command line arguments.

func WithBandwidth

func WithBandwidth(bandwidth string, unit BandwidthUnit) Option

WithBandwidth sets the bandwidth to give to zmap binary. It supports B, K, M and G suffixes. This option overrides --rate flag.

func WithBlacklistFile

func WithBlacklistFile(blacklistFile string) Option

WithBlacklistFile sets the blacklist file name to give to the zmap binary. If you are not passing this option, Zmap will use default blacklist file in "/usr/local/etc/zmap/blacklist.conf".

func WithConfigFile

func WithConfigFile(configFile string) Option

WithConfigFile sets the config file to give to zmap binary. Read a configuration file, which can specify any of these options (default=`/usr/local/etc/zmap/zmap.conf')

func WithCooldownTime

func WithCooldownTime(cooldown string) Option

WithCooldownTime sets the cooldown to give to zmap binary. How long to continue receiving after sending last probe (default=`8')

func WithCores

func WithCores(cores []string) Option

WithCores sets the cores to give to zmap binary. Comma-separated list of cores to pin to

func WithCustomArguments

func WithCustomArguments(args ...string) Option

WithCustomArguments sets custom arguments to give to the zmap binary. There should be no reason to use this, unless you are using a custom build of zmap or that this repository isn't up to date with the latest options of the official zmap release.

func WithDisableSyslog

func WithDisableSyslog() Option

WithDisableSyslog sets the disable syslog to give to zmap binary. Disables logging messages to syslog

func WithDryrun

func WithDryrun() Option

WithDryrun sets the dryrun to give to zmap binary. Don't actually send packets

func WithGatewayMAC

func WithGatewayMAC(gatewayMAC string) Option

WithGatewayMAC sets the gateway mac to give to zmap binary. Specify gateway MAC address

func WithIgnoreInvalidHosts

func WithIgnoreInvalidHosts() Option

WithIgnoreInvalidHosts sets the ignore invalid hosts to give to zmap binary. Ignore invalid hosts in whitelist/blacklist file

func WithInterface

func WithInterface(ifa string) Option

WithInterface sets the interface to give to zmap binary. Specify network interface to use

func WithLogDirectory

func WithLogDirectory(logDirectory string) Option

WithLogDirectory sets the log directory to give to zmap binary. Write log entries to a timestamped file in this directory

func WithLogFile

func WithLogFile(logFile string) Option

WithLogFile sets the log file to give to zmap binary. Write log entries to file

func WithMaxResults

func WithMaxResults(maxResults string) Option

WithMaxResults set the max results to give to zmap binary.

func WithMaxRetries

func WithMaxRetries(maxRetries string) Option

WithMaxRetries sets the retries to give to zmap binary. Max number of times to try to send packet if send fails (default=`10')

func WithMaxRuntime

func WithMaxRuntime(maxRuntime string) Option

WithMaxRuntime sets the max runtime to give to zmap binary.

func WithMaxSendtoFailures

func WithMaxSendtoFailures(maxSendtoFailures string) Option

WithMaxSendtoFailures sets the max sendto failures to give to zmap binary. Maximum NIC sendto failures before scan is aborted (default=`-1')

func WithMaxTargets

func WithMaxTargets(maxTarget string, isPercentage bool) Option

WithMaxTargets sets the max targets to give to zmap binary.

func WithMetadataFile

func WithMetadataFile(metadataFile string) Option

WithMetadataFile sets the metadata file to give to zmap binary. Output file for scan metadata (JSON)

func WithMinHitrate

func WithMinHitrate(minHitrate string) Option

WithMinHitrate sets the min hitrate to give to zmap binary. Minimum hitrate that scan can hit before scan is aborted (default=`0.0')

func WithNotes

func WithNotes(notes string) Option

WithNotes sets the notes to give to zmap binary. Inject user-specified notes into scan metadata

func WithNumberOfProbesPerIP

func WithNumberOfProbesPerIP(numberOfProbes string) Option

WithNumberOfProbesPerIP set the probes to give to zmap binary.

func WithOutputArgs

func WithOutputArgs(outputArgs string) Option

WithOutputArgs sets the output args to give to zmap binary. Arguments to pass to output module

func WithOutputFields

func WithOutputFields(fields []string) Option

WithOutputFields sets the output fields to give to zmap binary. Fields that should be output in result set

func WithOutputFile

func WithOutputFile(outputFile string) Option

WithOutputFile sets the output file name to give to the zmap binary. If you are not passing this option, We will use "-" as value to read from stdout by default.

func WithOutputFilter

func WithOutputFilter(outputFilter string) Option

WithOutputFilter sets the output filter to give to zmap binary. Specify a filter over the response fields to limit what responses get sent to the output module

func WithOutputModule

func WithOutputModule(outputModule string) Option

WithOutputModule sets the output module to give to zmap binary. Select output module (default=`default')

func WithProbeArgs

func WithProbeArgs(probeArgs string) Option

WithProbeArgs sets the probe args to give to zmap binary. Arguments to pass to probe module

func WithProbeModule

func WithProbeModule(probeModule string) Option

WithProbeModule sets the probe module to give to zmap binary. Select probe module (default=`tcp_synscan')

func WithQuiet

func WithQuiet() Option

WithQuiet sets the quiet to give to zmap binary. Do not print status updates

func WithRate

func WithRate(rate string) Option

WithRate sets the rate to give to the zmap binary. Rate in packet/second (pps)

func WithSeed

func WithSeed(seed string) Option

WithSeed sets the seed to give to zmap binary. Seed used to select address permutation

func WithSenderThreads

func WithSenderThreads(senderThreads string) Option

WithSenderThreads sets the sender threads to give to zmap binary. Threads used to send packets (default=`1')

func WithShardID

func WithShardID(shardID string) Option

WithShardID sets the shard to give to zmap binary. Set which shard this scan is (0 indexed) (default=`0')

func WithSourceIP

func WithSourceIP(sourceIP string) Option

WithSourceIP sets the source ip to give to zmap binary. Source address(es) for scan packets Can be one ip (192.168.1.1) or ip range (Ex: 192.168.1.1-192.168.1.5)

func WithSourceMAC

func WithSourceMAC(sourceMAC string) Option

WithSourceMAC sets the source mac to give to zmap binary. Source MAC address

func WithSourcePort

func WithSourcePort(sourcePort string) Option

WithSourcePort sets the source port to give to zmap binary. Source port(s) for scan packets Can be one port (50000) or port range (Ex: 50000-50010)

func WithStatusUpdatesFile

func WithStatusUpdatesFile(statusUpdateFile string) Option

WithStatusUpdatesFile sets the status updates file to give to zmap binary. Write scan progress updates to CSV file

func WithTargetPort

func WithTargetPort(targetPort string) Option

WithTargetPort sets the target port to give to the zmap binary. This is required option. And should be used for ones. Zmap does not support multiple ports

func WithTargets

func WithTargets(targets ...string) Option

WithTargets sets the target informations to give to the zmap binary. Targets can be ip address or cidr notation

func WithTotalShards

func WithTotalShards(shards string) Option

WithTotalShards sets the shards to give to zmap binary. Set the total number of shards (default=`1')

func WithUserMetadata

func WithUserMetadata(userMetadata string) Option

WithUserMetadata sets the user metadata to give to zmap binary. Inject user-specified JSON metadata into scan metadata

func WithVPN

func WithVPN() Option

WithVPN sets the vpn to give to zmap binary. Sends IP packets instead of Ethernet (for VPNs)

func WithVerbosity

func WithVerbosity(verbosityLevel VerbosityLevel) Option

WithVerbosity sets the verbosity to give to zmap binary. Level of log detail (0-5) (default=`3')

func WithWhitelistFile

func WithWhitelistFile(whitelistFile string) Option

WithWhitelistFile sets the whitelist file name to give to the zmap binary.

type OutputField

type OutputField struct {
	Name        string
	Type        string
	Explanation string
}

type VerbosityLevel

type VerbosityLevel string
var (
	VerbosityLevel1 VerbosityLevel = "1"
	VerbosityLevel2 VerbosityLevel = "2"
	VerbosityLevel3 VerbosityLevel = "3"
	VerbosityLevel4 VerbosityLevel = "4"
	VerbosityLevel5 VerbosityLevel = "5"
)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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