mscan

    Native-first asynchronous network discovery CLI

    cli
    network
    scanner
    native
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    6 hours ago
    Downloads
    7

    No dependencies

    #mscan

    MoonBit native-first TCP scanner, independently implemented with inspiration from RustScan and fscan. See ROADMAP.md for stages.

    #Build and run

    Tested with MoonBit 0.1.20261126 (ccd306a) on Linux. Uses the bundled moonbitlang/core/async APIs; no external Mooncakes dependencies. Async APIs are evolving, so use this toolchain or verify compatibility with a newer one.

    CI installs the official latest archive channel and records actual tool versions. The local moon version build identifier is not used as a download archive tag: 0.1.20261126 returned HTTP 403 on all three runners. Historical local validation does not pin a remotely available SDK archive. New channel compatibility is established by the native check/test/build steps in each run. Verification, packaging, certificate helpers and Nmap handoff explicitly require successful child exit codes. The CI script has a separate regression test that proves a failing child command stops the gate rather than reporting success.

    moon run --target native cmd/mscan -- --help moon run --target native cmd/mscan -- 127.0.0.1 -p 1-1024 --all --format jsonl moon run --target native cmd/mscan -- -f targets.txt --scope authorized-scope.txt --rate 100 moon build --target native --release

    The release executable is _build/native/release/build/cmd/mscan/mscan.exe. Install the CLI from a local checkout with moon install ./cmd/mscan. After publishing the module to Mooncakes, install it with moon install OrisGo/mscan/cmd/mscan@0.1.0. The installed command is mscan (mscan.exe on Windows), placed in ~/.moon/bin by default; ensure that directory is on PATH. Use --output results.jsonl --format jsonl to also stream results to a new file. Existing files are refused. Only open ports are emitted by default; --all includes closed, timed_out, and failed. Summary is written to stderr.

    • Inputs: IPv4, IPv6 literals, hostnames, IPv4 CIDR, target files with one target per line and optional # comments. Repeated and overlapping IPv4 ranges merge.
    • Hostnames resolve to one address per scan. Numeric addresses bypass DNS. Explicit IPv4/IPv6 exclusions also apply after DNS resolution. Excluding a hostname excludes that name; it does not resolve the exclusion to every IP.
    • CIDRs include network and broadcast addresses, and are iterated lazily. IPv6 CIDR expansion is not implemented.
    • Fixed workers bound active connections and reporting. --concurrency and --rate independently control concurrency and starts per second. Rate is conservative at millisecond granularity (default 100; range 1..1000). Default concurrency is 32, with a maximum of 1024.
    • TCP refusal means closed; timeouts remain timed_out; DNS, routing, and resource errors are failed. A timeout does not prove a host is offline. On Windows the current async runtime can report a connection to a just-closed loopback port as timed_out; a timeout is never rewritten as closed.
    • SIGINT/SIGTERM cancel workers and close files/sockets. Partial results already written remain available; exit status is 130. Other statuses: 0 completed, 1 scan/IO error, 2 invalid arguments. Closed/timed-out ports alone return 0.

    JSONL records contain target, address, port, state, elapsed_ms, and error (a string or null), plus optional service and probe_error fields. Result order follows completion, not target order. Target file entries are stored in memory, but CIDRs and host × port jobs are not expanded into arrays. Numeric targets reached through multiple DNS names can be scanned more than once.

    #Service discovery

    Use --probe banner|http|https|auto to inspect open connections. Auto selects HTTPS on 443/8443/9443, HTTP on 80/8000/8008/8080/8081/8888, and passive banners elsewhere. Select http/https explicitly for custom ports. Ports guide probe selection; actual response evidence determines the reported service.

    --probe-timeout bounds each probe (default 1500 ms), and --max-probe-bytes bounds response collection (default 16 KiB; maximum 1 MiB). Probe failures do not change an open port to closed. Partial evidence survives probe timeouts. HTTP/1.x responses support Content-Length, chunked bodies (including extensions and trailers), close-delimited bodies, bounded informational responses, gzip and zlib-wrapped deflate. Wire bytes and decoded output are independently capped by --max-probe-bytes. Ambiguous lengths, unsupported encodings and malformed framing fail explicitly. Status/Server/Location evidence survives decode errors. Title matching accepts case variations and attributes, decodes numeric entities and common named entities (amp/lt/gt/quot/apos/nbsp), and preserves unknown names. Redirects are recorded, never followed. Response caps are reported with truncated. Terminal titles have control characters removed.

    TLS probes collect the leaf certificate as DER/base64 (up to 64 KiB). They permit self-signed certificates for inventory; tls_verified is false. Metadata extraction uses an OpenSSL 3+ executable (--openssl PATH) and reports subject, issuer, ISO-8601 validity dates, SAN DNS/IP names and SHA-256 fingerprint in service.certificate. Extraction errors are separate in certificate_error; the collected DER and open-port state are preserved if the executable is absent. Native TLS requires the system OpenSSL libraries on Linux.

    --cert-verify optionally performs an offline leaf-certificate trust, name and time check. --cert-ca-file PATH selects a PEM trust file instead of OpenSSL's default trust configuration. Results are not_checked, verified or failed with a verification scope and diagnostic. The runtime exports only the leaf, so missing intermediates can cause verification failure; this does not claim full server-chain validation. tls_verified remains false for the inventory TLS connection. No AIA, OCSP or CRL fetching is performed. Certificate helpers use private temporary files and are killed on cancellation within the probe budget. tests/tls_smoke.mbtx verifies metadata, self-signed rejection, explicit trust and preservation of DER when the helper is unavailable.

    #Validation commands

    Run moon run --target native tests/verify.mbtx for debug and release tests, release build, both CLI fixtures, generated interfaces and formatting. The GitHub Actions matrix is configured for Linux/macOS/Windows and runs this same verification, plus release packaging. Remote CI results are only available after pushing; Windows/macOS native are not yet locally verified. POSIX SIGINT audit smoke is automated; Windows console-control smoke still needs a dedicated console harness. Timer cancellation and cleanup tests run on every platform.

    moon run --target native tests/bench.mbtx records five 1024-port loopback scan timings including process startup, without enforcing hardware-dependent thresholds. Build in release mode first and compare samples on the same machine/toolchain.

    moon check --target native --deny-warn moon test --target native moon info --target native moon fmt moon build --target native --release moon run --target native tests/cli_smoke.mbtx moon run --target native tests/tls_smoke.mbtx

    Tests create ephemeral loopback listeners and do not scan external hosts. On systems where ccache's compiler directory has no ar, place /usr/bin before the ccache directory in PATH when running MoonBit build commands.

    #Workflow controls

    • --retries N --retry-delay MS: retries only failed/timed-out TCP connects; closed ports and probe failures are not retried. DNS failures are cached for the scan. Each attempt obeys the shared rate limit. attempts is 0 for DNS failures and otherwise counts TCP attempts; elapsed time includes retry waits.
    • --deadline MS: global wall-time budget including input/output and Nmap; cancels work and retains written results, returning 124.
    • --progress MS: writes completed/open counts and elapsed time to stderr on result completion, at most once per interval. Final summary always appears after a completed scan; stalled scans have no periodic completion updates.
    • --format csv: header plus quoted CSV rows, including service evidence as JSON.
    • --nmap PATH: invokes the chosen executable after scanning, using -sT -sV-Pn -n -p PORTS ADDRESS, with -6 for IPv6. Output goes to stderr. At most 1000 ports are passed per invocation. Only this option retains discovered open endpoints in memory. Both an argument fixture and real Nmap 7.993 were tested against ephemeral loopback services on Linux. Nmap is not bundled. The CI config also runs the real integration on macOS; Windows Nmap remains unverified.

    The CLI exits 1 if a Nmap subprocess fails. No shell interprets target arguments.

    #Fingerprints and detectors

    moon run --target native cmd/mscan -- 127.0.0.1 -p 8080 --probe http --checks --rules fingerprints/example.json --format jsonl

    --checks adds inventory observations (SSH banner, HTTP Server header and TLS certificate collection). --rules loads schema-v1 substring fingerprints, e.g.:

    {"version":1,"rules":[{"id":"nginx","name":"nginx server","field":"server","contains":"nginx"}]}

    Fields: protocol, banner, server, title, location, http_status. Matching is ASCII case insensitive. Files are capped at 1 MiB, rule counts at 256, and names/match strings at 256 characters; duplicate IDs/JSON keys and unknown schema versions are rejected. Evidence in rule findings is capped at 1024 UTF-16 units. Findings identify observed products/services, not confirmed vulnerabilities. Detectors require an explicit --probe mode; enabling rules does not implicitly enable protocol traffic.

    Library extensions implement the public Detector trait and use detect on a ScanResult. Each detector has a cooperative time budget (--detector-timeout, default 100 ms); endpoint findings have a result cap (--max-findings, default 32). Failures/timeouts are collected in detection.errors. Detectors inspect existing evidence and issue zero additional requests. Statically linked custom detectors are trusted code and must honor this contract and yield to cancellation; this is not a sandbox for arbitrary native code. Built-in detectors obey it.

    Active vulnerability/authentication checks are not implemented in this baseline.

    #Scope and operational safety

    --dry-run prints a schema-v1 JSON plan (compact targets, numeric scope, ports, host count, worst-case attempts including retries, and configured policy). It does not resolve names, connect, invoke Nmap, or create the result file. dns_pending identifies names that still require destination scope validation at execution time. A successful preview is not proof those names are in scope.

    --audit PATH creates a new JSONL file with restrictive permissions where supported. Schema-v1 events carry a random task ID, sequence, Unix/elapsed time, and plan/result/summary/termination data. Completed, rejected, deadline, error, and cancellation outcomes are recorded after argument parsing. Audit write errors stop execution; existing logs are never overwritten. Logs can contain sensitive asset information. Abrupt process termination or storage failures can leave a partial log; audit files are not tamper-proof.

    Only scan assets you own or have explicit permission to test. By default the CLI and library only permit loopback destinations (127.0.0.0/8 and ::1). For other destinations, provide --scope authorized-scope.txt, containing one numeric IPv4/CIDR or individual IPv6 address per line; # comments are accepted. The scope file replaces the default scope. Hostnames in scope files are rejected. The file declares the operator's scope; it is not proof of legal authorization.

    Numeric target ranges are checked before scanning. DNS results are checked against the numeric allowlist immediately before connecting, and the checked IP is used for the connection without resolving again. IPv4-mapped IPv6 addresses are canonicalized for scope and IPv4 exclusion checks.

    Defaults cap each scan at 256 planned hosts, 65536 worst-case TCP attempts (including retries), and a 60-second deadline. --max-hosts, --max-attempts and --deadline must be explicitly increased for larger approved tasks. Budget checks use compact CIDR arithmetic and run before any TCP connections. Target files are limited to 4096 entries; scope/rule files to 1 MiB. Connection starts remain rate limited; zero/unlimited rate is rejected. The CLI records configured limits to stderr, and result records retain the target and numeric destination.

    The attempt budget counts mscan TCP connection attempts. It does not count DNS queries, TCP retransmissions or packets within protocol exchanges. Nmap is an explicit external handoff: its port-scanning phase receives --max-rate, --max-retries 0 and --host-timeout, and version detection uses --version-light. Nmap's internal probes are outside mscan's attempt budget and its rate option does not cover every scan phase; the CLI's overall deadline also bounds the subprocess. See the Nmap timing reference.

    These controls reduce accidental scope expansion and excessive traffic in the distributed program. They cannot prevent a user changing the source, running multiple processes, or supplying an unrelated executable as --nmap. If exposed through a service, add authentication, per-user authorization/quotas, audit retention, and network egress enforcement outside the scanner process.

    Future detection modules should remain non-destructive, explicitly enabled, scoped and budgeted. Automatic exploitation, password guessing and concealment are outside the current project's feature scope.

    #Native resource checks and release artifacts

    moon run --target native --release tests/stress repeats connections and blocked probe cancellations (500 rounds by default). Set MSCAN_STRESS_ROUNDS up to 100000 for a longer run. It waits for peer EOF on every accepted connection; Linux additionally compares /proc/self/fd counts after IO warmup. Other platforms exercise cleanup without claiming a descriptor-counter measurement.

    moon run --target native tests/nmap_smoke.mbtx requires a real Nmap installation and touches only a temporary loopback fixture. The fixture serves HTTP through Python 3. MSCAN_NMAP can select the Nmap executable. NMAPDIR may select separately installed Nmap data files.

    After native release build and verification, run moon run --target native tests/package.mbtx. Archives in dist/ include the CLI, README, license/third-party notices, exact installed core NOTICE/LICENSE/ module metadata, and a manifest with revision, dirty status and toolchain. An adjacent SHA-256 file covers the archive. OpenSSL and Nmap are not bundled. Artifacts target the build machine's ABI and are not claimed to be static binaries. GitHub Actions uploads per-platform archives as workflow artifacts; it does not publish a GitHub release or push branches.

    #Library example

    ///|
    test {
    assert_eq(@mscan.parse_ports("443,80-81,80"), [80, 81, 443])
    let plan = @mscan.TargetPlan::parse(["192.0.2.0/30"], exclude=["192.0.2.1"])
    assert_eq(plan.hosts().collect(), ["192.0.2.0", "192.0.2.2", "192.0.2.3"])
    }

    Detector

    pub(open) trait Detector {
    fn id(Self) -> String
    async fn inspect(Self, ScanResult) -> Array[Finding]
    }

    Trusted, statically linked detectors inspect existing evidence. The interface supplies no network client: detectors must not issue additional requests. Implementations must yield during long computations to honor cancellation.

    InputError

    pub(all) suberror InputError {
    InputError(String)
    } derive(
    Debug
    )

    CertificateInfo

    pub struct CertificateInfo {
    subject : String
    issuer : String
    not_before : String
    not_after : String
    sha256_fingerprint : String
    dns_names : Array[String]
    ip_addresses : Array[String]
    verification : CertificateVerification
    } derive(
    Debug
    ,
    ToJson
    )

    CertificateVerification

    pub struct CertificateVerification {
    status : String
    verification_scope : String
    trust_source : String
    detail : String
    } derive(
    Debug
    ,
    ToJson
    )

    DetectionReport

    pub struct DetectionReport {
    findings : Array[Finding]
    errors : Array[String]
    truncated : Bool
    } derive(
    Debug
    ,
    ToJson
    )

    Finding

    pub(all) struct Finding {
    id : String
    name : String
    evidence : String
    } derive(
    Debug
    ,
    ToJson
    )

    InventoryDetector

    pub struct InventoryDetector {
    // private fields
    }

    Basic inventory observations. These findings are not vulnerability claims.

    InventoryDetector::new

    PortState

    pub(all) enum PortState {
    Open
    Closed
    TimedOut
    Failed
    } derive(Eq,
    Debug
    )

    PortState::to_string

    fn PortState::to_string(self : PortState) -> String

    ProbeMode

    pub(all) enum ProbeMode {
    Disabled
    Auto
    Banner
    Http
    Https
    } derive(Eq,
    Debug
    )

    RuleSet

    pub struct RuleSet {
    // private fields
    }

    impl Detector for RuleSet

    RuleSet::parse

    fn RuleSet::parse(text : String) -> RuleSet raise InputError

    Parse schema version 1: at most 256 substring rules against bounded service evidence. Matching is ASCII case insensitive; no scripts or regex are executed.

    test {
    let rules = @mscan.RuleSet::parse("{\"version\":1,\"rules\":[]}")
    assert_eq(@mscan.Detector::id(rules), "fingerprints.v1")
    }

    ScanPreview

    pub struct ScanPreview {
    hosts : Int64
    ports : Array[Int]
    worst_case_attempts : Int64
    targets : Array[String]
    dns_pending : Array[String]
    scope :
    Json

    } derive(
    Debug
    )

    A validated, compact plan. Hostnames remain unresolved until execution.

    ScanPreview::to_json

    ScanResult

    pub struct ScanResult {
    target : String
    address : String
    port : Int
    state : PortState
    elapsed_ms : Int64
    error : String?
    service : ServiceInfo?
    probe_error : String?
    attempts : Int
    detection : DetectionReport?
    } derive(
    Debug
    )

    ScanResult::to_csv

    fn ScanResult::to_csv(self : ScanResult) -> String

    ScanResult::to_json

    Stable JSONL record schema, with explicit state and optional error detail.

    ScanResult::to_text

    fn ScanResult::to_text(self : ScanResult) -> String

    ScanResult::with_detection

    fn ScanResult::with_detection(self : ScanResult, report : DetectionReport) -> ScanResult

    ScanSummary

    pub struct ScanSummary {
    completed : Int64
    open : Int64
    closed : Int64
    timed_out : Int64
    failed : Int64
    } derive(
    Debug
    )

    ScanSummary::new

    Scope

    pub struct Scope {
    // private fields
    }

    Numeric allowlist checked against the actual destination before connecting. Hostnames are deliberately not permitted as scope entries.

    Scope::contains

    fn Scope::contains(self : Scope, address : String) -> Bool raise InputError

    Scope::loopback

    fn Scope::loopback() -> Scope

    Scope::parse

    fn Scope::parse(entries : ArrayView[String]) -> Scope raise InputError

    Create scope from IPv4/CIDR or individual IPv6 addresses.

    test {
    let scope = @mscan.Scope::parse(["192.0.2.0/24", "::1"])
    assert_true(scope.contains("192.0.2.10"))
    assert_false(scope.contains("198.51.100.1"))
    }

    Scope::to_json

    ServiceInfo

    pub struct ServiceInfo {
    protocol : String
    banner : String?
    http_status : Int?
    title : String?
    server : String?
    location : String?
    certificate_der_base64 : String?
    certificate : CertificateInfo?
    certificate_error : String?
    truncated : Bool
    } derive(
    Debug
    )

    ServiceInfo::to_json

    TargetPlan

    pub struct TargetPlan {
    // private fields
    }

    A compact target plan. CIDRs are normalized, merged and excluded before iteration.

    TargetPlan::hosts

    fn TargetPlan::hosts(self : TargetPlan) -> Iter[String]

    Iterate normalized targets in bounded memory. Numeric IPv4 targets come first.

    TargetPlan::parse

    fn TargetPlan::parse(targets : ArrayView[String], exclude? : ArrayView[String]) -> TargetPlan raise InputError

    Build a reusable plan without expanding CIDR hosts into memory. IPv4 CIDRs include all addresses, including network and broadcast addresses.

    TargetPlan::preview

    fn TargetPlan::preview(self : TargetPlan, ports : ArrayView[Int], scope? : Scope, retries? : Int, max_hosts? : Int, max_attempts? : Int) -> ScanPreview raise InputError

    Validate numeric scope and resource budgets without DNS or TCP traffic.

    test {
    let plan = @mscan.TargetPlan::parse(["127.0.0.0/30"])
    assert_eq(plan.preview([80, 443]).worst_case_attempts, 8)
    }

    csv_header

    let csv_header : String

    detect

    async fn detect(result : ScanResult, detectors : ArrayView[&Detector], timeout_ms? : Int, max_findings? : Int) -> DetectionReport

    Evaluate each detector with a time budget. Ordinary detector failures are reported separately and never change the TCP port state. Findings are capped.

    inspect_certificate

    async fn inspect_certificate(der : Bytes, target : String, verify? : Bool, ca_file? : String, openssl? : String) -> CertificateInfo

    Parse a collected leaf certificate and optionally verify it offline with OpenSSL 3+. No chain fetching, OCSP, CRL downloads or additional TLS connections. The verification scope is leaf-only, not the server-supplied full chain.

    parse_ports

    fn parse_ports(text : String) -> Array[Int] raise InputError

    Parse comma-separated ports and inclusive ranges. Results are sorted and unique.

    test {
    assert_eq(@mscan.parse_ports("443,80,80-81"), [80, 81, 443])
    }

    scan

    async fn scan(targets : TargetPlan, ports : ArrayView[Int], concurrency? : Int, timeout_ms? : Int, rate? : Int, probe? : ProbeMode, probe_timeout_ms? : Int, max_probe_bytes? : Int, retries? : Int, retry_delay_ms? : Int, scope? : Scope, max_hosts? : Int, max_attempts? : Int, deadline_ms? : Int, cert_verify? : Bool, cert_ca_file? : String, openssl? : String, on_result~ : async (ScanResult) -> Unit) -> ScanSummary

    Scan targets with a fixed worker pool. The callback is serialized and backpressures workers. Callback errors cancel the scan; ordinary connection errors are results. Rate limits count connection attempts, not DNS lookups. DNS selects one address per hostname, cached for this scan; numeric IPv4/IPv6 targets bypass DNS.