Documentation
¶
Overview ¶
Package sensoractive is the sensor-active module: active device discovery with nmap and read-only SNMP, only inside the customer's confirmed LAN scope, time window and speed limit (S-INV-1, S-SCAN-4). Its only endpoints are the SNMP credentials (/inventory/snmp*). It imports no other module but leaf packages: the inventory is reached through the Inventory port and core/observe, adapted in cmd/vedette. nmap is the customer's own OS package, started only through core/exec.
Index ¶
- Constants
- Variables
- func ExportProbes(ctx context.Context, db *store.DB, from, to time.Time, w io.Writer) error
- func NmapBinary(path string) exec.Binary
- func PendingRunsAboutGoneDevices(ctx context.Context, db *sql.DB, devices []string) (int64, error)
- func ValidateNmapArgs(args []string) error
- type Asset
- type BlockedEvent
- type Config
- type Current
- type Decision
- type DeepGate
- type DeviceFound
- type Dispatcher
- func (d *Dispatcher) ActiveHeartbeat(_ context.Context, hb *sensorlink.ActiveHeartbeat) (string, error)
- func (d *Dispatcher) JobProgress(_ context.Context, id string, p *sensorlink.JobProgress) error
- func (d *Dispatcher) JobResult(_ context.Context, id string, res *sensorlink.JobResult) error
- func (d *Dispatcher) JobResultRejected(id string, e *sensorlink.Error)
- func (d *Dispatcher) JobRunning(id string) bool
- func (d *Dispatcher) Jobs(ctx context.Context, wait time.Duration, running []string) (sensorlink.JobsReply, error)
- func (d *Dispatcher) NmapHealth() string
- func (d *Dispatcher) NmapMissing() bool
- func (d *Dispatcher) NucleiHealth() string
- func (d *Dispatcher) OnReport(fn func())
- func (d *Dispatcher) Probe(ctx context.Context, argv []string) (Output, error)
- func (d *Dispatcher) ProbeDomain(ctx context.Context, argv []string, scope sensorlink.DomainScope) (Output, error)
- func (d *Dispatcher) Ready(context.Context) error
- func (d *Dispatcher) RunNuclei(ctx context.Context, r NucleiRequest) (nucleiout.Outcome, error)
- func (d *Dispatcher) RunSNMP(ctx context.Context, job sensorlink.SNMPJob) ([]sensorlink.SNMPAnswer, error)
- func (d *Dispatcher) SNMPHealth() string
- func (d *Dispatcher) WorkerAbsent() bool
- type DispatcherOptions
- type DomainIP
- type DomainProber
- type DomainRefusedError
- type EngineView
- type Event
- type External
- type ExternalScript
- type ExternalService
- type FinishedEvent
- type FoundPort
- type Health
- type Identification
- type Inventory
- type JobHead
- type JobProbe
- type JobRow
- type ManualRun
- type NucleiRequest
- type Output
- type OwnEgress
- type PendingGentle
- type Probe
- type Prober
- type Publisher
- type PublisherFunc
- type Result
- type SNMPBlocked
- type SNMPCheckResult
- type SNMPDevice
- type SNMPFacts
- type SNMPHandlers
- func (h *SNMPHandlers) InventoryDeleteInventorySnmpDevicesID(ctx context.Context, params oas.InventoryDeleteInventorySnmpDevicesIDParams) error
- func (h *SNMPHandlers) InventoryGetInventorySnmp(ctx context.Context) (*oas.InventoryGetInventorySnmpOK, error)
- func (h *SNMPHandlers) InventoryGetInventorySnmpDevicesID(ctx context.Context, params oas.InventoryGetInventorySnmpDevicesIDParams) (*oas.InventoryGetInventorySnmpDevicesIDOK, error)
- func (h *SNMPHandlers) InventoryPostInventorySnmpDevicesIDCheck(ctx context.Context, params oas.InventoryPostInventorySnmpDevicesIDCheckParams) (*oas.InventoryPostInventorySnmpDevicesIDCheckOK, error)
- func (h *SNMPHandlers) InventoryPostInventorySnmpNoticesDismiss(ctx context.Context) (*oas.InventoryPostInventorySnmpNoticesDismissOK, error)
- func (h *SNMPHandlers) InventoryPutInventorySnmpDevicesID(ctx context.Context, req *oas.InventoryPutInventorySnmpDevicesIDReq, ...) (*oas.InventoryPutInventorySnmpDevicesIDOK, error)
- type SNMPInput
- type SNMPNotice
- type SNMPReader
- type Scanner
- type ScriptFinding
- type Service
- func (s *Service) AssetChanged(ctx context.Context, assetID string) error
- func (s *Service) CheckSNMP(ctx context.Context, actor, id string) (SNMPCheckResult, error)
- func (s *Service) Close()
- func (s *Service) DeleteCommitted(_ context.Context, d lifecycle.Delete)
- func (s *Service) DeleteSNMP(ctx context.Context, actor, id string) error
- func (s *Service) DeviceDeleted(ctx context.Context, tx *sql.Tx, d lifecycle.Delete) error
- func (s *Service) DeviceMerged(ctx context.Context, tx *sql.Tx, m lifecycle.Merge) error
- func (s *Service) DiscoverRanges(ctx context.Context) (Result, error)
- func (s *Service) DismissSNMPNotices(ctx context.Context) error
- func (s *Service) Engine(ctx context.Context) (EngineView, error)
- func (s *Service) Enqueue(ctx context.Context, assetID, reason string) error
- func (s *Service) Health(ctx context.Context) Health
- func (s *Service) IdentifyDevice(ctx context.Context, assetID string) (Identification, error)
- func (s *Service) Jobs(ctx context.Context, limit int) ([]JobRow, error)
- func (s *Service) JobsOf(ctx context.Context, id string, _ netip.Addr, limit int) ([]JobRow, error)
- func (s *Service) Manual(ctx context.Context) *ManualRun
- func (s *Service) MergeCommitted(_ context.Context, m lifecycle.Merge)
- func (s *Service) Persons(ctx context.Context) []ManualRun
- func (s *Service) Probes(ctx context.Context, since time.Time, limit int) ([]Probe, error)
- func (s *Service) Prune(ctx context.Context) (int, error)
- func (s *Service) QueueLen(ctx context.Context) (int, error)
- func (s *Service) ReadAddresses(ctx context.Context) (map[string]netip.Addr, error)
- func (s *Service) Resume()
- func (s *Service) Runs() *run.Manager
- func (s *Service) SNMPDeviceOf(ctx context.Context, id string) (SNMPDevice, error)
- func (s *Service) SNMPDevices(ctx context.Context) ([]SNMPDevice, error)
- func (s *Service) SNMPNotices(ctx context.Context) ([]SNMPNotice, error)
- func (s *Service) SNMPStatus() (ready bool, message string)
- func (s *Service) ScanDevice(ctx context.Context, assetID, reason string) error
- func (s *Service) ScanDomainIP(ctx context.Context, ip netip.Addr, kind nmapargv.Kind, d DomainIP, ...) (External, error)
- func (s *Service) ScanExternal(ctx context.Context, ip netip.Addr, kind nmapargv.Kind, own OwnEgress) (External, error)
- func (s *Service) ScheduleOwner() schedule.Owner
- func (s *Service) SetSNMP(ctx context.Context, actor, id string, in SNMPInput) (SNMPDevice, error)
- func (s *Service) SettingsChanged(ctx context.Context) error
- func (s *Service) StartManual(ctx context.Context, by string, targets []string, ...) (ManualRun, error)
- func (s *Service) Stop()
- func (s *Service) Tick(ctx context.Context) error
- func (s *Service) WaitManual(ctx context.Context) error
- type Services
- type Settings
- type StartedEvent
- type SweepCost
- type TargetError
- type TooSoonError
Constants ¶
const ( WhyHostDown = "host_down" // no answer at all: off, asleep, gone, or a firewall drops even the ARP/ping WhyNoOpenPorts = "no_open_ports" // answered, but every port tried was closed // WhyFiltered: answered, but no port it was asked about did (every port "filtered": no response, or an ICMP error). nmap cannot // tell a firewall that drops from a device or link that rate-limits or loses the probes, so the customer reads "scan incomplete // (the device or a firewall dropped or slowed the probes)", never "filtered" as what the device does (kf-scan item 3). WhyFiltered = "filtered" WhyNoVersion = "no_version" // open ports, but no service named its product and version, and no usable OS guess WhyOSGuess = "os_unconfirmed" // only nmap's OS guess: recorded and shown, never matched until a person adds it WhyOSUnsure = "os_low_confidence" // as no_version, and nmap's OS guess was below minOSAccuracy WhyOSNoPatch = "os_no_patch_level" // the device named its Windows release (NTLM), not its monthly update level WhyGentleOnly = "gentle_only" // fragile: only the gentle scan ran (no -sV, no -O), which never records software WhyTimedOut = "timed_out" // nmap's host timeout ended the scan before it printed ports WhyBusy = "busy" // discovery, or an exposure scan of the public IP (up to an hour when deep), was running nmap; one nmap at a time, so nothing ran )
Why a device scan recorded no software with a version (Identification.Why), in nmap's terms. Without it the vulnerability scan has nothing to compare with the KEV list. IdentifyDevice also passes the inventory's refusal reasons (box, declared_by_hand, no_ip, out_of_scope, scope_not_confirmed, regular_scan_never, scanning_off) and its own WhyBusy and WhyUnavailable.
const ( RefuseUnknown = "unknown_device" // no device has this address or id RefuseOutOfScope = "out_of_scope" // outside lan_ranges, excluded, or the box itself RefuseNotAllowed = "not_scannable" // the device's own safety rules refuse a check (never scan, declared by hand, no address) )
Reasons of TargetError.
const ( // ModuleID is the module's id: the module of its runs. ModuleID = "sensor-active" RunSweep = "lan_sweep" // one pass over the confirmed ranges, across windows: a step per range, its done count the cursor RunCheck = "device_check" // the nmap check of one device: the window's queue, a person's check, Scan now's identification RunSNMP = "snmp_read" // the window's SNMP round, or the read of one device a person asked for RunAllPorts = "all_ports" // the weekly scan of every port of one device RunService = "service_scan" // the nmap -sV of one public address for an exposure scan )
Every piece of work of the module is a run of core/run (DB-DESIGN core_run): the run is its record (the Runs tab, the run page, every "Open the run"), its queue (the queued and waiting rows survive a restart) and its lane (one live run per lane, held by the database). The nmap work shares the lane nmap, so a person's check that meets a sweep is a queued run that says what it waits for; the SNMP reads have their own lane.
const ( SNMPOK = "ok" SNMPNotSetUp = "not_set_up" SNMPNotApproved = "not_approved" SNMPBusy = "busy" SNMPMoved = "moved" SNMPSecretLost = "secret_lost" SNMPNoIP = "no_ip" )
SNMP reasons a Check now answers with (SnmpReason in contract.ts), beside the read statuses of sensorlink and the inventory's refusals it passes on.
const ( SNMPWorking = "working" SNMPNotAnswering = "not_answering" SNMPWaiting = "waiting" )
The states of a device's SNMP (SnmpState in contract.ts).
const ( EventScanStarted = "sensor.scan.started" EventScanFinished = "sensor.scan.finished" EventScanBlocked = "sensor.scan.blocked" )
Event names (CONTRACT "Events").
const ( KindSweep = "sweep" KindDevice = "device" KindSNMP = "snmp" // a Test or the window's round of SNMP reads StatusRunning = "running" StatusDone = "done" StatusStopped = "stopped" StatusFailed = "failed" )
Job kinds and statuses of the history rows (JobRow) and the scan events.
const KindExternal = "external"
KindExternal is the kind of the scan events of a service scan for exposure.
const MaxBatch = nmapargv.MaxBatch
MaxBatch is the most addresses one nmap run gets, so its XML stays small.
const MaxManualTargets = 64
MaxManualTargets bounds the devices of one Check now.
const ( // ProbeRetention is how long sa_probe rows are kept (INV-9 asks for at least 90 days). ProbeRetention = 365 * 24 * time.Hour )
const ScheduleKey = "inventory.sweep"
ScheduleKey is the owner key of the LAN sweep in core/schedule.
const SweepGap = 10 * time.Minute
SweepGap is the least time between two sweeps a person starts, or a person's and the window's (INV-21, review #857 L4): the window stays the rule, a sweep on demand the exception.
Variables ¶
var ( ErrNmapMissing = fmt.Errorf("%w: nmap_missing", ErrUnavailable) ErrWorkerLost = errors.New("sensoractive: worker_lost") ErrWorkerRefused = errors.New("sensoractive: the worker refused the job") ErrResultRejected = errors.New("sensoractive: the worker's result was rejected") )
Errors of the remote Prober. ErrWorkerUnavailable and ErrNmapMissing wrap ErrUnavailable (INV-6): the queue keeps the device and tries again later. ErrWorkerLost, ErrWorkerRefused and ErrResultRejected fail the probe.
var ( // ErrDomainUnsupported is returned when the worker's latest heartbeat does not say domain_ip (it holds no fence key: a remote sensor, a container-only // install, or an older worker). A domain_ip job is never sent to it. Nothing was sent. ErrDomainUnsupported = errors.New("sensoractive: the scan container's worker runs no domain_ip job (it has no fence key, or it is older)") // ErrTypedUnsupported is returned when the worker's heartbeat does not say typed_ip (an older worker): a job for a typed public IP is not sent. ErrTypedUnsupported = errors.New("sensoractive: the scan container's worker does not check the proof of a typed public IP (it is older)") // ErrDomainRefused is the refusal of the worker's own domain fence (DomainRefusedError says why), also when it stopped a job while // it ran (then the error is ErrStoppedMidRun too). ErrDomainRefused = errors.New("sensoractive: the scan container's domain fence refused the job") )
var ( ErrBusy = errors.New("sensoractive: the scan container's nmap is busy with another scan") ErrNoTime = errors.New("sensoractive: too little time was left for service identification") ErrNotOwnIP = errors.New("sensoractive: the address is not the box's own public IP now") ErrEgressUnverified = errors.New("sensoractive: the public IP services could not be reached to check the address") ErrHostTimedOut = errors.New("sensoractive: nmap gave up on the address before it finished") ErrAnswersEverywhere = errors.New("sensoractive: the address answers on almost every port") // ErrNotDeep: a full shape was asked, and right before the job is handed out the target's testing terms no longer // allow a deep scan (withdrawn, or of an older version), or the fence cannot tell (no DeepGate). Nothing was sent: the run was // asked as deep, so it never falls back to the External shape by itself. ErrNotDeep = errors.New("sensoractive: the target's testing terms no longer allow a deep scan") // ErrFullUnsupported: the worker's latest heartbeat does not say it runs the full shapes (an older worker, while an // update runs). Nothing was sent. ErrFullUnsupported = errors.New("sensoractive: the scan container's worker is older and runs no deep nmap scan") // ErrPortsUnsupported: the worker is older and takes no port list, so the -sV follow-up of the weekly scan of every // port is not sent (its open ports are recorded without versions). ErrPortsUnsupported = errors.New("sensoractive: the scan container's worker is older and runs no port_versions job") // ErrStoppedMidRun (review r1 H1, r2 LOW-5): the worker's re-check during a full run found the address no longer the box's own // (also ErrNotOwnIP) or could not check it (also ErrEgressUnverified), killed nmap and discarded its output. Unlike a refusal // at the start, nmap had already probed the address. ErrStoppedMidRun = errors.New("sensoractive: the scan worker stopped the deep scan while it ran and discarded its output") )
Errors of ScanExternal. No packet went to ip with ErrBusy (another nmap run kept the slot), ErrNoTime (too little of the caller's time was left for the run, #723 review L5), ErrNotOwnIP (the fence in core or in the worker saw the box leave through another address) or ErrEgressUnverified (the worker could not reach the public IP services to check). ErrHostTimedOut: nmap ran and gave up on the host at its --host-timeout, so it printed no port table and nothing can be said of the services. ErrAnswersEverywhere: nmap saw more than commonports.MaxBelievableOpen ports open, the shape of a router or firewall that answers for every port: its rows describe that device, not services, so they are discarded. Only the full shapes return it: the External shape still reads the fixed list with -sV and keeps the ports that named a service (External.AnswersEverywhere).
var ( ErrNucleiMissing = fmt.Errorf("%w: nuclei_missing", ErrScannerUnavailable) // ErrPackMismatch: the template pack in the scan image is not the one the request was planned against. Nothing was sent, and // asking again with the same request cannot succeed: it is not ErrScannerUnavailable (core's pack and the image's pack come // from different releases; an update or a new plan fixes it). ErrPackMismatch = errors.New("sensoractive: pack_mismatch") // ErrPackInvalid: the worker found the image's template pack damaged (a file whose hash is not the index's, a link or a // special file in the tree): an integrity signal, never retried, logged at ERROR; not ErrScannerUnavailable. ErrPackInvalid = errors.New("sensoractive: pack_invalid: the template pack in the scan image failed its integrity check") ErrOutputTruncated = errors.New("sensoractive: nuclei printed more than the limit; its output is discarded") // ErrOwnIPUnsupported: the worker's latest heartbeat does not say own_ip (an older worker, while an update runs): an own_ip // job is never sent to it. Nothing was sent. ErrOwnIPUnsupported = errors.New("sensoractive: the scan container's worker is older and runs no own-IP nuclei job") // ErrNucleiBusy: an own_ip job found the nuclei slot holding another job (a Scan now of the LAN may run up to an hour), and // exposure's 5-minute step does not queue behind it. Nothing was sent. ErrNucleiBusy = errors.New("sensoractive: the scan container's nuclei is busy with another scan") // ErrNucleiFullUnsupported: the worker's latest heartbeat does not say nuclei.full: a job of depth full is never sent to it. // Nothing was sent. ErrNucleiFullUnsupported = errors.New("sensoractive: the scan container's worker is older and runs no deep nuclei job") )
Errors of the nuclei path. ErrScannerUnavailable (and what wraps it) is "keep the targets, try again later, tell the user the scanner is down" (503 scanner_unavailable); the others fail the run.
var ( ErrNotFound = errors.New("sensoractive: device not found") ErrBlocked = errors.New("sensoractive: scan blocked by the inventory's policy") ErrOutsideWindow = errors.New("sensoractive: outside the scan window") ErrScanningOff = errors.New("sensoractive: active scanning is off") // INV-2 ErrScopeNotConfirmed = errors.New("sensoractive: the scan scope is not confirmed") // INV-2 ErrNoRanges = errors.New("sensoractive: no network range to scan") // INV-2 ErrStopped = errors.New("sensoractive: the run was stopped") // PRE-3 )
Errors of the entry points. ErrBlocked, ErrOutsideWindow and the ErrNot* errors mean no packet was sent.
ErrSNMPUnavailable says nothing was sent: the worker cannot take an snmp job now (no heartbeat, or a worker of protocol 4).
var ErrSlotBusy = errors.New("sensoractive: discovery is running nmap now")
ErrSlotBusy says a sweep is going now, or gave way to other work and goes on by itself once that work is done: a second sweep is refused (the one going is the person's answer); a person's check is queued behind it instead and says so.
var Migrations = mustSub(migrationFiles, "migrations/sqlite")
Migrations holds the SQLite migrations of the module, rooted at the directory that contains the NNNN_*.sql files. Pass it to store.Migrate(ctx, db, "sensor-active", sensoractive.Migrations).
Functions ¶
func ExportProbes ¶
ExportProbes is the "scan_probes" source of GET /core/logs/export (core INV-13): the probe log from through to, oldest first, as JSON lines, the columns of the table (argv is the stored flag part, targets the merged ranges). A zero time is open. It takes the database, not the Service, so it works on a box where nmap is missing and the service cannot be built.
func NmapBinary ¶
NmapBinary is the allowlist entry for nmap: an absolute path to the OS package's binary, the validator above, and the output cap. Register it with core/exec.NewRunner.
func PendingRunsAboutGoneDevices ¶
PendingRunsAboutGoneDevices counts the module's runs about a device that have not started or wait (queued, waiting) while the device is not in devices, the ids of every device that exists: deleting a device stops them in the same transaction (DeviceDeleted), and a merge gives them to the device that stays (DeviceMerged). A running one is not counted: it holds its lane until its work ends, and a restart stops it. It only reads, so the selfcheck runs it on its read-only handle with the inventory's list of devices.
func ValidateNmapArgs ¶
ValidateNmapArgs re-checks a whole nmap argv; the rules live in the leaf package nmapargv, which the sensor binary links too.
Types ¶
type Asset ¶
type Asset struct {
ID string
IP netip.Addr // invalid when the inventory knows no IP
// Approved: a person approved the device (or its osquery enrolment did). SNMP credentials go only to approved devices:
// a device nobody vouched for may be a rogue one that collects communities.
Approved bool
// Name is how a person knows the device (its host name, else its model, else its vendor; "" when none): for plain words only.
Name string
}
Asset is a device as the scanner needs it.
type BlockedEvent ¶
BlockedEvent is the data of sensor.scan.blocked: a device was not scanned and no packet was sent.
type Config ¶
type Config struct {
DB *store.DB
Inventory Inventory
Observe observe.Sink // the inventory, through core/observe
Software observe.SoftwareSink // the inventory, through core/observe
Services Services // the inventory's open ports; nil: the open ports are not recorded
Events Publisher
NmapPath string // absolute path of the OS package's nmap; Health reads it, and the local Prober runs it
// Prober runs the nmap command the module has already checked. Nil means the local one, core/exec around
// NmapPath (NewLocalProber). The Dispatcher hands the job to the worker in the scan container; then
// NmapPath is not used and Health comes from the worker's heartbeat.
Prober Prober
Clock func() time.Time
Log *slog.Logger
// Location is the organization's time zone, the one the windows are read in (INV-3). Nil, or a nil result,
// means the box's own zone (time.Local).
Location func() *time.Location
// SNMP reads. Secrets seals the credentials' secrets (nil: the credential calls answer 501); Audit records who changed
// or tested a credential; SNMP sends the reads (nil: the Prober when it is one, the Dispatcher, else none).
Secrets *secrets.Store
Audit *audit.Log
SNMP SNMPReader
// Runs is the box's run manager (core/run): every sweep, device check, SNMP read and scan of every port is a run of it. The kinds
// are registered by New, before the manager starts. Nil (tests): the service builds and starts its own over DB.
Runs *run.Manager
// LocalPrefixes is the IPv4 networks the box has a card on: a sweep reaches them with one ARP request an address,
// everything else through a router with SweepProbes packets. Only the sweep-time estimate reads it; nil: every range counts
// as routed.
LocalPrefixes func(context.Context) []netip.Prefix
}
Config is what New needs. Everything except Events and Log is required.
type Current ¶
type Current struct {
JobID string // its run
Kind string // sweep or device
Asset string
Targets []netip.Addr
Manual bool // part of the manual run
StartedAt time.Time
}
Current is the LAN job holding the nmap slot now: a sweep (Asset "") or the scan of one device. External runs (exposure) are not listed: their own module shows them.
type Decision ¶
type Decision struct {
Allowed bool
Rate int // packets per second the scan may use
Reason string // the inventory's reason, passed through in sensor.scan.blocked
FirstGentle bool // the one gentle scan of a fragile device
// Fragile and Unclassified describe the device (fragile, kind still unknown): IdentifyDevice picks its scan shape from them.
// Never is regular_scan=never: IdentifyDevice refuses it outright.
Fragile, Unclassified, Never bool
}
Decision is the answer of the inventory's ScanPolicy (PRE-2).
type DeepGate ¶
type DeepGate interface {
ShapeNow(ctx context.Context, asked nmapargv.Kind) (nmapargv.Kind, error)
}
DeepGate is the second half of core's fence of a full run, asked right after OwnEgress, right before the job is handed out: which external shape the target's testing terms allow now, given the one asked. A full run is sent only through an OwnEgress that implements it (fail closed). An answer that is not a full shape is ErrNotDeep; ExternalFull for an asked ExternalDisruptive (the disruptive tick taken back) runs the full shape without the disruptive scripts; the run never gets more than it asked for.
type DeviceFound ¶
type DeviceFound struct {
// Reach is how far the check looked: "top100" (the gentle scan), "top1000" (a normal or versions scan with the extra ports),
// "extra" (only the extra ports answered), "all" (the weekly scan of every port). Ports are compared only within one reach.
Reach string `json:"reach"`
TimedOut bool `json:"timed_out,omitempty"` // nmap reached its host timeout: no port table, what was known is kept
// ExtraFailed: a top1000 check whose run over the extra ports (nmapargv.ExtraPorts) did not finish, so it covered nmap's top
// 1000 only. Its ports are compared, and compared with, only outside the extra ports, and its OS guess (an NTLM answer may come
// from that run) is never compared.
ExtraFailed bool `json:"extra_failed,omitempty"`
Open int `json:"open"` // open ports it found (Ports holds the first maxFoundPorts)
Ports []FoundPort `json:"ports,omitempty"`
OS string `json:"os,omitempty"` // the OS it recorded (nmap's guess of 85 % or more, or the device's NTLM answer); "" when none
// Compared: a previous check of the device with the same reach was there to compare the ports with (New, Gone).
Compared bool `json:"compared,omitempty"`
// ComparedPart: one of the two checks had ExtraFailed, so the extra ports were left out of the comparison.
ComparedPart bool `json:"compared_part,omitempty"`
New []int `json:"new,omitempty"` // TCP ports open now that the previous check of the same reach did not find
// Gone are the TCP ports that check found open and that refused the connection this time (host.answer): closed.
Gone []int `json:"gone,omitempty"`
// NoAnswer are the TCP ports that check found open and that sent nothing back this time: a firewall that drops probes and a device
// or link that rate-limits them look the same, so the check is incomplete for them and what was known about them is kept.
NoAnswer []int `json:"no_answer,omitempty"`
// Dropped are the TCP ports the previous check already kept as NoAnswer and that sent nothing back again: two misses in a row
// take a port off the device's list (the public scan's rule too).
Dropped []int `json:"dropped,omitempty"`
// NoPortAnswered: the device was up but no port it was asked about answered (host.noPortAnswered): the check is incomplete.
NoPortAnswered bool `json:"no_port_answered,omitempty"`
// OSWas is the previous OS guess when this check recorded another one; "" when it is the same, or when there is nothing to compare.
OSWas string `json:"os_was,omitempty"`
}
DeviceFound is what one device check found, as stored with its run (items: foundItems): the words of its History row and of the device page's Last checks come from it. Only nmap's own result is kept (port numbers, nmap's service names, its OS guess), never a banner or a page title.
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher is the Prober that hands a job to the worker, and the sensorlink.Backend of the active role: the listener of core serves Jobs, JobRunning, JobResult and ActiveHeartbeat to it. Create it with NewDispatcher. It has three slots, nmap, nuclei and snmp: one job of each kind may run at once, so a "Scan now" or an SNMP Test does not wait for a two-hour sweep. The rules of a slot (lease, pickup, grace, cancel) are those of SP-3 for all.
func NewDispatcher ¶
func NewDispatcher(o DispatcherOptions) *Dispatcher
NewDispatcher returns a Dispatcher with a fresh instance nonce, the one the worker's lease is tied to.
func (*Dispatcher) ActiveHeartbeat ¶
func (d *Dispatcher) ActiveHeartbeat(_ context.Context, hb *sensorlink.ActiveHeartbeat) (string, error)
ActiveHeartbeat implements sensorlink.Backend and feeds Health. The OnReport hook hears of it after mu is released.
func (*Dispatcher) JobProgress ¶
func (d *Dispatcher) JobProgress(_ context.Context, id string, p *sensorlink.JobProgress) error
JobProgress implements sensorlink.ProgressReceiver (#830): the worker's report of how far a running job is goes to the Sink the probe's context carried (the scan run or the exposure scan that waits for it). Nothing is stored here; a report of a job that is being cancelled, or whose probe has no Sink, is accepted and dropped, and so is one that comes sooner than progressMin after the last one of the job (the worker sends one every sensorlink.ProgressEvery; review r1 #2). The Sink is called under mu, so a report can never land after the job's result (JobResult takes mu too and the job is then no longer running; review r1 #1). A Sink is a progress.Tracker or the job's part of a progress.Series: a short lock of its own, never a call back into the Dispatcher. The Tracker checks every field again. The first report of a job opens a new pass of its phase (a second nmap run of a device starts from 0 again, whatever the previous run's last word was); the jobs of a Series are one pass, which the Series keeps.
func (*Dispatcher) JobResult ¶
func (d *Dispatcher) JobResult(_ context.Context, id string, res *sensorlink.JobResult) error
JobResult implements sensorlink.Backend. A result of any job but a running one is unknown, which is also what a second copy of a result gets.
func (*Dispatcher) JobResultRejected ¶
func (d *Dispatcher) JobResultRejected(id string, e *sensorlink.Error)
JobResultRejected implements sensorlink.ResultRejector: the server refused the body of the result (413 or 400). The worker does not send it again, so the probe fails now.
func (*Dispatcher) JobRunning ¶
func (d *Dispatcher) JobRunning(id string) bool
JobRunning implements sensorlink.Backend: id is a job handed to the worker and not finished.
func (*Dispatcher) Jobs ¶
func (d *Dispatcher) Jobs(ctx context.Context, wait time.Duration, running []string) (sensorlink.JobsReply, error)
Jobs implements sensorlink.Backend: one long poll of the worker. running holds the jobs the worker says it runs.
func (*Dispatcher) NmapHealth ¶
func (d *Dispatcher) NmapHealth() string
NmapHealth is "" when the worker can run nmap, otherwise what the status page says (INV-6): no heartbeat for 90 s, or the heartbeat says nmap is missing.
func (*Dispatcher) NmapMissing ¶
func (d *Dispatcher) NmapMissing() bool
NmapMissing says the scan worker reports, and says it has no nmap: work that waits for nmap will not get it by waiting.
func (*Dispatcher) NucleiHealth ¶
func (d *Dispatcher) NucleiHealth() string
NucleiHealth is "" when the worker can run nuclei with a template pack, otherwise what the status page says: no heartbeat for 90 s, nuclei missing, or no pack in the image.
func (*Dispatcher) OnReport ¶
func (d *Dispatcher) OnReport(fn func())
OnReport sets the hook told after every heartbeat of the scan worker: work that waits for the worker starts when it reports, not at the next tick. The hook must not block (the worker's request waits for it). Set it before the worker can report.
func (*Dispatcher) Probe ¶
Probe implements Prober. argv is what nmapargv.Build made; the job on the wire carries its shape, rate and targets and no argv. It returns when the result is in, when the worker is gone, or when ctx ended and the worker had 30 seconds to confirm the stop.
func (*Dispatcher) ProbeDomain ¶
func (d *Dispatcher) ProbeDomain(ctx context.Context, argv []string, scope sensorlink.DomainScope) (Output, error)
ProbeDomain implements DomainProber: Probe of a full shape with one target as a domain_ip job, sent only to a worker whose heartbeat says domain_ip (else ErrDomainUnsupported, nothing sent); the worker checks the domain fence itself before nmap.
func (*Dispatcher) Ready ¶
func (d *Dispatcher) Ready(context.Context) error
Ready implements Scanner (and scan.Engine). The error says which of the reasons it is: ErrScanWorkerUnavailable, ErrNucleiMissing, or ErrScannerUnavailable alone (an overrun not yet stopped, no pack); all of them wrap ErrScannerUnavailable.
func (*Dispatcher) RunNuclei ¶
func (d *Dispatcher) RunNuclei(ctx context.Context, r NucleiRequest) (nucleiout.Outcome, error)
RunNuclei implements Scanner.
func (*Dispatcher) RunSNMP ¶
func (d *Dispatcher) RunSNMP(ctx context.Context, job sensorlink.SNMPJob) ([]sensorlink.SNMPAnswer, error)
RunSNMP implements SNMPReader.
func (*Dispatcher) SNMPHealth ¶
func (d *Dispatcher) SNMPHealth() string
SNMPHealth implements SNMPReader.
func (*Dispatcher) WorkerAbsent ¶
func (d *Dispatcher) WorkerAbsent() bool
WorkerAbsent says the scan worker has not reported since core started, or not for 90 seconds (a restart of the scan container): a person's check waits for it instead of being refused.
type DispatcherOptions ¶
type DispatcherOptions struct {
// Now is the clock of the heartbeat, pickup and grace timeouts. nil means time.Now.
Now func() time.Time
// Tick is how often a waiting probe looks at those timeouts. 0 means one second.
Tick time.Duration
Log *slog.Logger
// ContainerOnly is the install kind (modreg.Registry.ContainerOnly): the health texts then give the advice that fits a
// customer who runs the compose files, not the appliance's "rebuilt".
ContainerOnly bool
}
DispatcherOptions configures a Dispatcher. Both fields are for tests.
type DomainIP ¶
type DomainIP struct {
Scope sensorlink.DomainScope
Chain string
}
DomainIP is a domain_ip run of ScanDomainIP: the fence fields the worker checks and the CNAME chain core saw for the name (for the probe log row; "" when core did not look it up).
type DomainProber ¶
type DomainProber interface {
ProbeDomain(ctx context.Context, argv []string, scope sensorlink.DomainScope) (Output, error)
}
DomainProber is implemented by a Prober that can send a domain_ip nmap job (*Dispatcher). A Prober without it never runs one.
type DomainRefusedError ¶
DomainRefusedError is ErrDomainRefused with the fence's reason (core/domainfence.Reasons). MidRun: the re-check during a deep nmap stopped it and its output was discarded.
func (*DomainRefusedError) Error ¶
func (e *DomainRefusedError) Error() string
func (*DomainRefusedError) Is ¶
func (e *DomainRefusedError) Is(target error) bool
Is makes it ErrDomainRefused, and ErrStoppedMidRun when it ended a running job.
type EngineView ¶
type EngineView struct {
Health Health
NextWindow *time.Time // the next time a window opens; nil when the settings have none
Open bool // a window is open now
Last map[string]JobHead // the newest job that ended, by kind (sweep, device, snmp)
Current *Current
SNMP *JobHead // the SNMP read running now, nil when none
Manual *ManualRun
Persons []ManualRun // every run a person started that is queued or going, oldest first (Persons)
}
EngineView is what Settings › Scanning shows of active discovery, the version scans and the SNMP rounds.
type Event ¶
Event is what Service publishes after a transaction commits; cmd/vedette adapts it to core/events.
type External ¶
type External struct {
Services []ExternalService
Ports int
Probed []int
Scripts []ExternalScript
DiscoveryCut bool
AnswersEverywhere bool
Unfinished []int
}
External is the result of ScanExternal: the open ports with what -sV read, how many TCP ports were probed, which ones, and the script results of a full run (nil for the External shape). Probed are the TCP ports the run probed, ascending: for the External shape the ports nmap's discovery says it probed (its <scaninfo>, nmap's own top ports) and those of the finished -sV batches; nil for a full shape, which probed every port 1..65535. Ports is their count (65535 for a full shape). DiscoveryCut: the External shape's discovery hit its host timeout or its output was not usable, so only the fixed list's -sV batches were read. AnswersEverywhere: the address answers on almost every port (a router or SYN proxy), so the -sV batches read the fixed list only and Services keeps only the ports where -sV named a real service.
Unfinished are the ports of the -sV batches that hit their host timeout, printed nothing usable or were not started for want of time, ascending: they are not in Probed (a scan that did not read them never calls them closed), and the next scan of the address reads them first (rotation from this run's probe rows).
type ExternalScript ¶
type ExternalScript struct {
Port int
ID string
Output string
Findings []ScriptFinding
}
ExternalScript is one NSE script result of a full run: Port is the open TCP port it ran on, 0 for a host script (<hostscript>, such as smb-vuln-ms17-010); ID nmap's script name; Output its text, printable runes and line breaks only, at most 2000 runes (scriptText), or "Output not stored: it can hold credentials." for a script nmapargv.StoresOutput names (review r1 M4); Findings the vulns library's findings, read only from the structured output (review r1 M1, L3). Everything came from the network: exposure limits it again before it is stored.
type ExternalService ¶
type ExternalService struct {
Port int
Name string
Product string
Version string
CPE string
Extra string
Method string
Conf int
}
ExternalService is what -sV read on one open TCP port. The strings come from the network: printable, at most 200 runes (text, INV-7); CPE is the first application CPE ("cpe:/a:…") nmap printed, "" when none. exposure limits them further. Method is how nmap named the service (M2-7): "probed" (a probe's answer matched), "table" (only the usual service of the port number, nothing confirmed), "" when nmap did not say; Conf nmap's confidence 1..10 (0 when absent; a table name is 3).
type FinishedEvent ¶
type FinishedEvent struct {
JobID string `json:"job_id"`
Targets int `json:"targets"`
NewDevices int `json:"new_devices"`
Status string `json:"status"` // done, stopped or failed
}
FinishedEvent is the data of sensor.scan.finished.
type FoundPort ¶
type FoundPort struct {
Port int `json:"port"`
Proto string `json:"proto"`
Name string `json:"name,omitempty"`
}
FoundPort is one open port of a check, with nmap's service name ("" when nmap named none).
type Health ¶
type Health struct {
Status string `json:"status"`
Message string `json:"message"`
Zone string `json:"zone"`
Warning string `json:"warning,omitempty"`
}
Health is the module's state for the status page (INV-6): "ok", or "unavailable" with a message. Zone is the time zone the windows are read in (INV-3). Warning is set while a full sweep cannot fit in one window at the configured rate (an estimate: one packet an address on the box's own networks, nmapargv.SweepProbes or more behind a router); the sweep then takes several days.
type Identification ¶
type Identification struct {
Found []string
Why string // a Why* code, or the inventory's refusal reason
}
Identification is what IdentifyDevice found: Found says in words what was recorded (type, operating system, software), Why says why no software was recorded ("" when some was). Without software a vulnerability scan has nothing to compare with the KEV list.
type Inventory ¶
type Inventory interface {
Settings(ctx context.Context) (Settings, error)
// InScope reports whether ip is inside lan_ranges and outside the exclusions (SYS-7).
InScope(ctx context.Context, ip netip.Addr) (bool, error)
ScanPolicy(ctx context.Context, assetID string) (Decision, error)
// SNMPPolicy is ScanPolicy for SNMP reads: the device's own SNMP setting in place of its network scan setting (snmp_off
// when a person turned SNMP off for it; a device added by hand only once a person turned its SNMP on).
SNMPPolicy(ctx context.Context, assetID string) (Decision, error)
MarkFirstScan(ctx context.Context, assetID string) error
Asset(ctx context.Context, assetID string) (Asset, error) // ErrNotFound when unknown
Addresses(ctx context.Context) (map[netip.Addr]string, error) // IP -> device id of every known device
KnownMACs(ctx context.Context) ([]string, error) // MAC of every known device (uncapped): a sweep charges only MACs not in it
// ProtectedIPs lists the addresses a sweep must not probe: devices declared by hand, devices set to
// regular_scan=never, fragile or unclassified devices after their one gentle scan, and the box itself. It
// is by IP, so a new MAC at a protected address does not make it fair game.
ProtectedIPs(ctx context.Context) ([]netip.Addr, error)
// BoxIPs lists only the addresses that are the box (its own device, its cards, the decoys): never probed, not even by an SNMP read
// of a fragile device.
BoxIPs(ctx context.Context) ([]netip.Addr, error)
// SNMPKnown lists the devices an SNMP read described (an snmp observation) and those whose SNMP switch a person stored on: the
// devices the old SNMP credentials are moved to (snmp_move.go).
SNMPKnown(ctx context.Context) (read, on []string, err error)
// TurnSNMPOn stores a device's SNMP switch on as the person (audited by the inventory): saving SNMP settings on a device is
// the person's consent to read it. The inventory's refusals (box_device, device_ignored) are API errors, passed on as they are.
TurnSNMPOn(ctx context.Context, actor, assetID string) error
}
Inventory is what this module asks of the inventory (INV-1, INV-2, INV-5). The real implementation is an adapter over inventory.Service in cmd/vedette.
type JobHead ¶
type JobHead struct {
ID, Kind, Status string
Reason string // "" when none (a window's run); scan_now for an identification a person asked for
StartedAt string
FinishedAt *string
Targets int
NewDevices int
Error string
}
JobHead is a run of the module as Settings › Scanning and the history list it (core_run).
type JobProbe ¶
type JobProbe struct{ Targets, Result string }
JobProbe is one probe of a job: its targets (an address, or the ranges of a sweep batch) and its result as recorded ("ok: 3 hosts up", "ok: 2 of 3 answered", "failed: …"; "" while it runs).
type JobRow ¶
type JobRow struct {
JobHead
Probes []JobProbe // in the order they were sent; empty when it sent none
// Found is what a device check found (its items): nil for the other kinds, a check that found nothing it could record (the
// device did not answer, nmap failed or was stopped) and the checks stored before it was kept.
Found *DeviceFound
// AssetID is the device a device check was for (the run's subject); "" for the other kinds.
AssetID string
// Own is, in JobsOf only, how the device's own read went in this SNMP read (sa_snmp_device.last_status of the read that
// stored it: ok, no_answer, auth_failed, unknown_user, error); "" when it is not known (an older read of the device).
Own string
}
JobRow is a run of the module for a list of past runs, with every probe it sent (read only): a sweep runs in batches, an SNMP read records "ok: n of m answered", so what the run found is in its probes, never only in the row's target count.
type ManualRun ¶
type ManualRun struct {
ID string
Runs []string // every run it queued: the sweep, or one check per device in the order of Assets
Assets []string // the device ids checked, in order; empty for a sweep
IP netip.Addr // the address of the device when there is one; invalid otherwise
Ranges []string // the scope a sweep covers
StartedAt time.Time
Until time.Time // a sweep's end outside the window at the latest: manualFor after its start
Progress *progress.View
// Queued is true while the run waits: for the run in its way, for the scan worker, or after it gave way (Progress says what
// for); see waits.
Queued bool
}
ManualRun is a run a person started (#850, INV-21): a sweep of the whole scope now (Assets empty), or the checks of the chosen devices now, one device_check run each (ID is the first). Its record is core_run.
type NucleiRequest ¶
type NucleiRequest struct {
PackVersion, PackSHA256 string
Templates []string // template ids, 1..nucleiargv.MaxTemplates
Targets []nucleiargv.Target
Rate int // requests per second, 1..nucleiargv.MaxRate (own_ip: nucleiargv.OwnIPRate)
MaxHostErrors int // nucleiargv.MinHostErrors..MaxHostErrors
Scope string // "" (LAN) or nucleiargv.ScopeOwnIP
// An own_ip run of depth nucleiargv.DepthFull (1..nucleiargv.MaxFullTemplates at nucleiargv.FullRate), and
// with Disruptive the disruptive set too. Sent only to a worker whose heartbeat said nuclei.full.
Depth string
Disruptive bool
// Domain: a job of Scope sensorlink.ScopeDomainIP (depth full, one public target that is not the box's own egress) and
// its fence fields; sent only to a worker whose heartbeat says domain_ip, which checks the domain fence itself.
Domain *sensorlink.DomainScope
}
NucleiRequest is one nuclei run: template ids from the pack index, never paths; targets that are canonical private IPv4 literals with a port, or for Scope nucleiargv.ScopeOwnIP exactly one public one, the box's own IP (the caller has checked that, and the worker checks it again). The grammar is nucleiargv's; Dispatcher.RunNuclei checks it again before the job leaves, and the worker checks it a third time.
type Output ¶
type Output struct {
XML []byte
Truncated bool // the run printed more than the cap; XML is incomplete and must be discarded (INV-7)
}
Output is what a finished nmap run hands back: the XML it printed on stdout.
type OwnEgress ¶
OwnEgress says whether ip is the box's own verified public egress now: exposure's gate (verified, committed, seen by the public-IP check within the last 5 minutes, else a fresh full check; exposure INV-13). cmd/vedette implements it.
type PendingGentle ¶
PendingGentle is an optional part of Inventory (#714): the devices whose one gentle scan is still to come (discovered, kind unknown, not fragile, not set to never, not the box, not declared by hand, no first scan yet). Devices reach the queue only through inventory.asset.discovered, which fires for new devices; inventory migration 0004 cleared the first scan of devices seen before, so Tick queues these once per start (INSERT OR IGNORE, idempotent).
type Probe ¶
type Probe struct {
Time string `json:"time"`
Shape string `json:"shape"`
Rate int `json:"rate"`
Target string `json:"target"`
Argv []string `json:"argv"`
Result string `json:"result"`
JobID string `json:"job_id"`
}
Probe is one row of the probe log (INV-9). Argv is the flag part of the command line that was approved, up to and including "-oX -", as stored with the row (a later change of the templates does not rewrite it); the addresses it was run on are in Target as merged ranges ("a.b.c.d-e.f.g.h,i.j.k.l"). Shape is the template (sweep, normal or gentle) and Rate the --max-rate of it.
type Prober ¶
Prober runs one nmap command that sensoractive has already checked against the scope, the window and the settings (INV-1..INV-3), and whose probe row is already written (INV-9). argv is the whole nmapargv.Build line; ctx carries the deadline (the window's end or maxRun) and cancelling it kills the run. A non-zero exit is an error that errors.As finds an *exec.ExitError in. The local implementation runs nmap through core/exec; SP-3 adds one that hands the job to a worker in the scan container.
type PublisherFunc ¶
PublisherFunc adapts a function to Publisher.
type SNMPBlocked ¶
type SNMPBlocked struct{ Reason, Message string }
SNMPBlocked says why nothing is sent to a device now (SnmpBlocked in contract.ts).
type SNMPCheckResult ¶
type SNMPCheckResult struct {
OK bool
Reason string
Message string
Answer *SNMPFacts
Device SNMPDevice
}
SNMPCheckResult is what a Check now answers (SnmpCheckResult in contract.ts). Answer is set when the device answered.
type SNMPDevice ¶
type SNMPDevice struct {
DeviceID, Name string
IP netip.Addr // the device's own address; invalid when none
State string // working, not_answering, waiting, not_set_up
ReadFrom netip.Addr // invalid when not set up
ReadFromDefault bool
Version, Username, Auth, Priv string // Priv "aes128" or "none" for v3, "" for v2c
Port int // 0 when not set up
SecretLast4, PrivLast4 string
SecretLost bool
LastCheckedAt, LastAnswerAt time.Time // zero: never
UpdatedAt time.Time
LastReason string // the status of the last read; "" when never read
Error string // plain words for a last read without an answer
Answer *SNMPFacts
Blocked *SNMPBlocked
}
SNMPDevice is the SNMP of one device without its secrets (DeviceSnmp in contract.ts). IP and Name are the inventory's.
type SNMPFacts ¶
type SNMPFacts struct {
SysDescr, SysObjectID, SysName string // cleaned, as the device said them
Vendor, Product, Model, OS, Kind, Hostname, Serial, Firmware string
}
SNMPFacts is what one answer says. Product is the family of the sysObjectID ("FortiGate"); Serial and Firmware are shown in the answer of a Test and not stored (the inventory has no field for them).
type SNMPHandlers ¶
type SNMPHandlers struct {
// contains filtered or unexported fields
}
SNMPHandlers implement the SNMP operations (CONTRACT "Endpoints owned"): the list and notices, and one device's SNMP: read, set up or edit, remove, Check now. The route table requires the admin role; the server answers 404 for all of them while the module is off (SYS-5).
func NewSNMPHandlers ¶
func NewSNMPHandlers(s *Service) *SNMPHandlers
NewSNMPHandlers wraps the service; nil gives 501 for every operation, like a module that is not wired.
func (*SNMPHandlers) InventoryDeleteInventorySnmpDevicesID ¶
func (h *SNMPHandlers) InventoryDeleteInventorySnmpDevicesID(ctx context.Context, params oas.InventoryDeleteInventorySnmpDevicesIDParams) error
InventoryDeleteInventorySnmpDevicesID implements DELETE /inventory/snmp/devices/{id}.
func (*SNMPHandlers) InventoryGetInventorySnmp ¶
func (h *SNMPHandlers) InventoryGetInventorySnmp(ctx context.Context) (*oas.InventoryGetInventorySnmpOK, error)
InventoryGetInventorySnmp implements GET /inventory/snmp.
func (*SNMPHandlers) InventoryGetInventorySnmpDevicesID ¶
func (h *SNMPHandlers) InventoryGetInventorySnmpDevicesID(ctx context.Context, params oas.InventoryGetInventorySnmpDevicesIDParams) (*oas.InventoryGetInventorySnmpDevicesIDOK, error)
InventoryGetInventorySnmpDevicesID implements GET /inventory/snmp/devices/{id}.
func (*SNMPHandlers) InventoryPostInventorySnmpDevicesIDCheck ¶
func (h *SNMPHandlers) InventoryPostInventorySnmpDevicesIDCheck(ctx context.Context, params oas.InventoryPostInventorySnmpDevicesIDCheckParams) (*oas.InventoryPostInventorySnmpDevicesIDCheckOK, error)
InventoryPostInventorySnmpDevicesIDCheck implements POST /inventory/snmp/devices/{id}/check (Check now).
func (*SNMPHandlers) InventoryPostInventorySnmpNoticesDismiss ¶
func (h *SNMPHandlers) InventoryPostInventorySnmpNoticesDismiss(ctx context.Context) (*oas.InventoryPostInventorySnmpNoticesDismissOK, error)
InventoryPostInventorySnmpNoticesDismiss implements POST /inventory/snmp/notices/dismiss.
func (*SNMPHandlers) InventoryPutInventorySnmpDevicesID ¶
func (h *SNMPHandlers) InventoryPutInventorySnmpDevicesID(ctx context.Context, req *oas.InventoryPutInventorySnmpDevicesIDReq, params oas.InventoryPutInventorySnmpDevicesIDParams) (*oas.InventoryPutInventorySnmpDevicesIDOK, error)
InventoryPutInventorySnmpDevicesID implements PUT /inventory/snmp/devices/{id}.
type SNMPInput ¶
type SNMPInput struct {
CopyFrom, ReadFrom string
Version, Username, Auth, Priv string
Community, AuthPassword, PrivPassword secrets.Value
Port int
}
SNMPInput is the form of a device's SNMP (DeviceSnmpInput in contract.ts). A blank secret on an edit keeps the saved one, unless the read address changes. Port 0 is none given: 161. ReadFrom "" is the device's IP. CopyFrom names another device whose settings and secrets are copied on the box; then only ReadFrom is read besides it.
type SNMPNotice ¶
SNMPNotice is a change the box made to SNMP settings by itself (SnmpNotice in contract.ts).
type SNMPReader ¶
type SNMPReader interface {
// SNMPHealth is "" when an snmp job can be sent now, else what the person is told.
SNMPHealth() string
// RunSNMP sends the job and returns one answer per target the worker got to, each checked against the job.
RunSNMP(ctx context.Context, job sensorlink.SNMPJob) ([]sensorlink.SNMPAnswer, error)
}
SNMPReader is how the Service sends SNMP reads; *Dispatcher implements it, tests put a fake in Config.SNMP.
type Scanner ¶
type Scanner interface {
// Ready returns nil when a job can be sent now: the worker has a fresh heartbeat and says nuclei runs and its image holds a
// template pack; otherwise it says why (NucleiHealth).
Ready(ctx context.Context) error
// RunNuclei sends the job and returns one Result per line nuclei printed, after the output was parsed fail closed: one line
// that is not what the job asked for makes the whole run an error. It also returns the host errors the worker counted
// (targets that stopped answering, INV-6), each checked against the request: a target the job did not name, or an
// Unreachable that does not follow from the count and the job's MaxHostErrors, makes the run an error too. ctx carries
// the deadline (at most one hour reaches the worker) and cancelling it stops the run: the worker kills nuclei within seconds.
RunNuclei(ctx context.Context, r NucleiRequest) (nucleiout.Outcome, error)
}
Scanner is the seam the scan module calls (the smallest one: scan's own Engine asks only Ready, and the run is what S5 adds). *Dispatcher implements it. A nil Scanner in scan means the scanner is unavailable and nothing is ever sent.
type ScriptFinding ¶
ScriptFinding is one finding of the vulns library: State "vulnerable" (VULNERABLE, also "(Exploitable)" or "(DoS)"), "likely" (LIKELY VULNERABLE) or "not_vulnerable"; Title the script's name for it (printable, at most 120 runes); CVEs its CVE ids (unique, at most 20).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service runs active discovery. Create it with New. It is the only writer of the sa_* tables.
func (*Service) AssetChanged ¶
AssetChanged reacts to inventory.asset.updated and .deleted: if the device being scanned now left the address the run probes (it moved, or another device took the address: #874) or no longer passes the inventory's policy (marked fragile, regular scan never, declared by hand, deleted, out of scope), or the run is heavier than the policy now allows, the run is stopped; that is not an attempt (the queue keeps it only if the policy still lets it be scanned later). Other devices are not the run's business.
func (*Service) CheckSNMP ¶
CheckSNMP reads one device now at its read address (POST /inventory/snmp/devices/{id}/check): every rule of the window's round but the window. It answers what the device said, recorded on the device, or a plain reason; one audit row says who checked which device. 409 not_set_up, and secret_lost when its saved secret this box cannot open: nothing is sent.
func (*Service) Close ¶
func (s *Service) Close()
Close stops the run manager the service made itself (Config.Runs nil); a shared one is the box's to close.
func (*Service) DeleteCommitted ¶
DeleteCommitted stops an SNMP batch that holds the deleted device.
func (*Service) DeleteSNMP ¶
DeleteSNMP removes the SNMP settings of device id and their secrets in one transaction (DELETE /inventory/snmp/devices/{id}). What the device said stays in the inventory; its SNMP switch is left as it is. 404 when it has none.
func (*Service) DeviceDeleted ¶
DeviceDeleted is sensor-active's part of deleting a device (core/lifecycle, inside the inventory's write): its queued or waiting checks are stopped, its SNMP settings with their secrets and its weekly port record go with it. Its finished runs stay: they are a log, with the device id and name they ran on.
func (*Service) DeviceMerged ¶
DeviceMerged is sensor-active's part of a merge (core/lifecycle, inside the inventory's write): device m.From was the same machine as m.Into. Its runs become Into's (the runs' subject, INV-23: Into's Last checks lists them and its next check compares with them); its weekly port record becomes Into's unless Into has its own. A device has one SNMP setting: when only From has one it becomes Into's (a read address that was From's IP stays the address it was: if Into is elsewhere, nothing is sent until a person sets it, INV-10 (i)); when both have one, the one that works is kept (snmpBetter) and the other goes with its secrets, and a notice says which was kept and which removed (sa_snmp_notice, until a person dismisses it).
func (*Service) DiscoverRanges ¶
DiscoverRanges goes on with the pass of the confirmed ranges now (PRE-1): the pass that waits is resumed, else a new one is queued, and it is waited for. It returns how far the pass got; ErrStopped when it stopped or waits with work left.
func (*Service) DismissSNMPNotices ¶
DismissSNMPNotices removes every notice (POST /inventory/snmp/notices/dismiss).
func (*Service) Engine ¶
func (s *Service) Engine(ctx context.Context) (EngineView, error)
Engine reads EngineView.
func (*Service) Enqueue ¶
Enqueue queues a device for its check inside the window (a device another sensor saw first, a device whose scan was turned on): a device_check run waiting for its turn, which survives a restart. A device that already has a check queued or waiting keeps that one. A device found by a person's sweep is checked right after it, as a step of it.
func (*Service) Health ¶
Health reports INV-6: nmap is the OS package, and without it the module has no way to work. It also names the time zone of the windows, and warns while a full sweep cannot fit in one window.
func (*Service) IdentifyDevice ¶
IdentifyDevice identifies one device for the vulnerability check a person started with Scan now: a device check run (a step of the vulnerability check's run), queued in the nmap lane, with the scan shape of pickedPlan and at once (the window does not apply, as for Scan now itself). Every other rule of a device scan holds: scanning on, scope confirmed, the device's address in scope right before the command line is built (INV-1), the probe log (INV-9), one nmap at a time, the stop on a change of settings or of the device. A sweep gives way to it between two batches; when the lane does not come free within busyWait the check is stopped and the result says busy. The result says what was recorded, or why nothing was; err is ErrStopped when the run was stopped, or a failure of nmap, the worker or storage.
func (*Service) Jobs ¶
Jobs lists the newest runs of the LAN (sweeps, device checks, SNMP reads, scans of every port), newest first, at most limit (1..500), each with its probes. Read only: the history of Settings › Scanning.
func (*Service) JobsOf ¶
JobsOf lists the LAN runs of device id (the device page's Last checks), newest first, at most limit (1..500) of each kind: its checks (the window's, a person's, Scan now's identification, the weekly scan of every port: the runs whose subject it is), and the SNMP reads that asked the read address of its SNMP settings, among the newest snmpReadsScanned reads. A device without SNMP set up has no SNMP read. No sweep: it reaches every address of the scope and identifies nothing. addr is kept for the callers; the runs name their device.
func (*Service) Manual ¶
Manual is the newest run a person started that is queued or going now, nil when none.
func (*Service) MergeCommitted ¶
MergeCommitted stops an SNMP batch that holds either device: their settings changed.
func (*Service) Persons ¶
Persons is every run a person started that is queued or going now, oldest first (the order they run in): each one says what it waits for. A pass a person asked to go on now counts while it goes on within their hour.
func (*Service) Probes ¶
Probes returns the probe log from since on, oldest first, at most limit rows (INV-9). Argv is the flag part stored with the row, so history stays true when the templates change; Target is the merged ranges of the addresses probed.
func (*Service) Prune ¶
Prune deletes probe rows older than ProbeRetention and returns how many went (core/run prunes the runs).
func (*Service) QueueLen ¶
QueueLen is the number of device checks waiting for their turn in the window.
func (*Service) ReadAddresses ¶
ReadAddresses returns, by device id, the address a person typed as the device's SNMP read address. A read address left to the device's own IP is not here (it is only the IP the device had when saved, and says nothing once the device moves). Nothing else of the settings is read: no secret is opened and no policy is checked, so a caller that only matches addresses to devices (logs) costs the device nothing. A device the inventory no longer has may still be listed until inventory.asset.deleted is handled; the caller matches against its own device list.
func (*Service) Resume ¶
func (s *Service) Resume()
Resume is the module turned on again: SNMP reads may be sent again (Stop's off flag is cleared).
func (*Service) SNMPDeviceOf ¶
SNMPDeviceOf is the SNMP of device id (GET /inventory/snmp/devices/{id}); a device without SNMP is State not_set_up. 404 when the inventory has no such device.
func (*Service) SNMPDevices ¶
func (s *Service) SNMPDevices(ctx context.Context) ([]SNMPDevice, error)
SNMPDevices lists every device with SNMP set up, by name (GET /inventory/snmp: the Copy from list and the Scanning card). A device the inventory no longer has is left out (its settings go with inventory.asset.deleted).
func (*Service) SNMPNotices ¶
func (s *Service) SNMPNotices(ctx context.Context) ([]SNMPNotice, error)
SNMPNotices lists what the box changed by itself, oldest first (GET /inventory/snmp notices).
func (*Service) SNMPStatus ¶
SNMPStatus says whether an SNMP read can be sent now, and if not, why (GET /inventory/snmp).
func (*Service) ScanDevice ¶
ScanDevice identifies one device with nmap (PRE-2): the inventory's ScanPolicy must allow it, the window must be open (even the one gentle scan of a device that is fragile or not yet classified waits for it), and the device's address must be in scope immediately before the command line is built (INV-1). The run is registered before the checks and its address published as soon as it is known, so a SettingsChanged that arrives while it is still checking reaches it. A refusal by policy or scope publishes sensor.scan.blocked and sends nothing. reason says why it was asked ("discovered", ...). Outside a run (a caller of its own) the check is a device_check run made for it, which it waits for.
func (*Service) ScanDomainIP ¶
func (s *Service) ScanDomainIP(ctx context.Context, ip netip.Addr, kind nmapargv.Kind, d DomainIP, gate DeepGate) (External, error)
ScanDomainIP is ScanExternal of a full shape on a public address that is not the box's own egress, reached because a name under a verified domain resolves to it: a domain_ip job. Core's half of the fence is exposure's deepGate (just before the step) and gate's DeepGate (the terms, right before the job leaves, like a full run of the box's own IP); own-egress is not asked, the worker's domain fence is: its key, the TXT record, the name's address now, again every 3 minutes while nmap runs. The probe row names the domain, the name and its CNAME chain. A worker that does not say domain_ip gets nothing (ErrDomainUnsupported); a refusal of the worker's fence is a *DomainRefusedError.
func (*Service) ScanExternal ¶
func (s *Service) ScanExternal(ctx context.Context, ip netip.Addr, kind nmapargv.Kind, own OwnEgress) (External, error)
ScanExternal identifies the services on the open TCP ports of ip, the box's own verified public IP, for exposure, with the shape kind: External, or one of the full shapes of a target whose testing terms are accepted. Order: wait for the nmap slot at most busyWait, and never so long that less than the run's need plus coreFenceTime would be left (else ErrBusy, or ErrNoTime when no wait at all fits); a Stop that came during the wait ends it (ErrStopped); the worker must be there (ErrUnavailable); a job row; then, right before the job is handed out, own says whether ip is still the box's own egress (else ErrNotOwnIP, nothing sent) and, for a full shape, own's DeepGate which shape the terms allow now (else ErrNotDeep); less than the need left → ErrNoTime; the probe row; then the job. A nil own refuses (fail closed). The stop of the module (Stop) or of ctx ends it with ErrStopped.
func (*Service) ScheduleOwner ¶
ScheduleOwner is what the LAN sweep registers with core/schedule: the person's rule decides when a pass of the confirmed ranges is queued (by default every day at 22:00, held until the scan window is open); the window stays the safety limit of the pass, which waits for the next window when one closes on it and goes on from its cursor.
func (*Service) SetSNMP ¶
SetSNMP sets up or edits the SNMP of device id (PUT /inventory/snmp/devices/{id}): the form, or a copy of another device's settings and secrets made on the box. Saving is the person's consent to read this device: its SNMP source switch is turned on first (audited by the inventory; an ignored device is refused there). A blank secret keeps the saved one, unless the read address changes: a person who can edit the form but never knew the secret cannot send it to an address of their own (as the scopes of before did). One audit row says who set what, never the secret.
func (*Service) SettingsChanged ¶
SettingsChanged reacts to inventory.settings.changed: it bumps the settings version (a run that has not started nmap yet sees it and stops), and if a run is registered and the settings no longer allow it (scanning off, scope unconfirmed, outside the window, a lower rate, an address of the run out of scope), it is stopped now. The next batch reads the new settings by itself.
func (*Service) StartManual ¶
func (s *Service) StartManual(ctx context.Context, by string, targets []string, record func(tx *sql.Tx, m ManualRun) error) (ManualRun, error)
StartManual checks a person's run and queues it (INV-21): no targets sweeps the whole scope now, with the window counted open for manualFor, and then checks the devices the sweep found ("Scan the LAN now"); targets (IPv4 addresses of devices or device ids, at most MaxManualTargets) queue one check per device, run at once whatever the window ("Check this device now"). Every rule but the window holds and is checked before anything is queued: the module on (ErrStopped once Stop ran), active scanning on (ErrScanningOff), the scope confirmed (ErrScopeNotConfirmed, ErrNoRanges), nmap present (ErrUnavailable), no sweep going now for a sweep (ErrSlotBusy), no sweep started in the last SweepGap (a *TooSoonError), and per target the device exists, is inside the scope and outside the exclusions and the box, and its policy lets a person check it (a *TargetError). Whatever else holds the scanner, a person's run is queued behind it and says so (INV-28): another person's run, the window's checks, the weekly scan of every port (which gives the lane up at once); a sweep gives way to it between two batches. A device that already has a person's check queued or going keeps that one (its run is answered, nothing new is queued or recorded). record writes the person's consent (the audit row) in the transaction that queues the runs: its error refuses the run and nothing is queued. by is the person.
func (*Service) Stop ¶
func (s *Service) Stop()
Stop cancels the run in progress, whatever it is: the module was turned off (SYS-5). The scheduler stops the jobs it runs; an identification for Scan now runs on the scan module's goroutine, so only this reaches it.
func (*Service) Tick ¶
Tick is the window job, run every minute. While a window is open it checks first the devices no check has reached yet (at most firstBeforeSweep of them, within a share of the window), then goes on with the pass of the ranges (resuming the one that waits, or following the pass the schedule started), then checks the rest of the waiting devices, reads SNMP and runs the weekly scans of every port. Every piece is a run: Tick queues or resumes it and waits for it. Outside a window it runs the first pass of a new box, else nothing.
type Services ¶
type Services interface {
observe.ServiceSink
PortReadTimes(ctx context.Context, assetID string, source observe.Source) (map[int]time.Time, error)
}
Services is the inventory's open ports: the scans write them through observe.ServiceSink, and the weekly scan of every port reads back when the nmap source last read each TCP port of a device with version detection (inventory INV-23, inv_service.read_at) to pick the ports its follow-up reads: never read first, then read longest ago. A port only found open is not in the map.
type Settings ¶
type Settings struct {
Enabled bool
ScopeConfirmed bool
LANRanges []string // CIDR
Exclusions []string // IPv4 or CIDR
Days []int // 1 = Monday ... 7 = Sunday
From, To string // HH:MM in the organization's time zone; To before From crosses midnight
Rate int // packets per second
}
Settings is the part of the inventory's scan settings this module obeys (S-INV-1). The adapter in cmd/vedette fills it from inventory.Settings; strings are in the inventory's own notation.
type StartedEvent ¶
type StartedEvent struct {
JobID string `json:"job_id"`
Kind string `json:"kind"` // "sweep" or "device"
Targets int `json:"targets"`
}
StartedEvent is the data of sensor.scan.started.
type SweepCost ¶
type SweepCost struct {
Addresses int // in the ranges, outside the exclusions
Pass time.Duration // one pass at the rate
Window time.Duration // one window (0: no window is set)
Windows int // windows one pass needs (1 when it fits one; 0 without a window)
}
SweepCost is what one pass over a scope costs at a rate: the addresses it walks, the time one pass takes (a floor: an address behind a router costs nmapargv.SweepProbes packets, one on the box's own networks one ARP request), and the windows it needs.
type TargetError ¶
type TargetError struct {
Target string
Reason string
Detail string // the inventory's reason (regular_scan_never, declared_by_hand, no_ip, box, ...) behind Reason
}
TargetError is why one target of a manual run may not be checked; nothing was started. Reason is one of the Refuse* values.
func (*TargetError) Error ¶
func (e *TargetError) Error() string
type TooSoonError ¶
TooSoonError refuses a sweep that would start within SweepGap of the last one; RetryAfter is how long until it may.
func (*TooSoonError) Error ¶
func (e *TooSoonError) Error() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
snmptest
Package snmptest is a fake SNMP agent on loopback for the tests of the worker and of core's SNMP round: no test sends a packet to a real device.
|
Package snmptest is a fake SNMP agent on loopback for the tests of the worker and of core's SNMP round: no test sends a packet to a real device. |
|
Package nmapargv builds and checks the only eleven nmap command lines Vedette ever runs.
|
Package nmapargv builds and checks the only eleven nmap command lines Vedette ever runs. |
|
Package worker is the worker of the scan container (`vedette-sensor active`, sensor-protocol.md section 6.4).
|
Package worker is the worker of the scan container (`vedette-sensor active`, sensor-protocol.md section 6.4). |
|
workertest
Package workertest holds what tests of the worker and of the Dispatcher share for the nuclei job: a template pack on disk with its index, and a fake nuclei (a shell script run through the real core/exec).
|
Package workertest holds what tests of the worker and of the Dispatcher share for the nuclei job: a template pack on disk with its index, and a fake nuclei (a shell script run through the real core/exec). |