moonwire

    Userspace Sans-IO WireGuard protocol engine, configuration auditor, and PCAP packet decryptor in pure MoonBit.

    wireguard
    vpn
    sans-io
    noise-protocol
    cryptography
    networking
    pcap
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    4 days ago
    Downloads
    16

    #MoonWire

    MoonWire is a clean-room, userspace Sans-IO WireGuard protocol engine, wg-quick static topology auditor, and offline PCAP / Wireshark keylog packet decryptor implemented in pure MoonBit.

    • Zero-FFI Cross-Backend Core: All protocol, cryptographic, routing, configuration, and PCAP packages compile identically across wasm-gc, wasm, js, and native targets using only moonbitlang/core.
    • Full WireGuard Cryptographic & State Suite:
      • Self-contained RFC-verified X25519 (RFC 7748), ChaCha20-Poly1305 & XChaCha20-Poly1305 (RFC 8439 / XChaCha), BLAKE2s & HKDF-BLAKE2s (RFC 7693), and SipHash-2-4.
      • Complete Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s handshake, TAI64N monotonic anti-replay timestamps, mac1/mac2 authentication, and Cookie Reply (Type 3) under-load DoS challenges.
      • 3-slot session key ring (previous / current / next with responder key confirmation), RFC 6479 2048-packet anti-replay window, and §6 session timers (120s rekey, 180s hard expiration, 5s retry, 10s passive keepalive, persistent keepalive).
      • IPv4 (32-bit) & IPv6 (128-bit) Cryptokey Routing longest-prefix-match radix trie with inbound reverse-path source IP anti-spoofing.
    • Native CLI (cmd/moonwire): Key generation, static wg-quick configuration auditing, offline .pcap + Wireshark wg.keylog_file decryption, and unprivileged localhost/remote UDP tunnel interoperability.


    #Package Architecture

    PackageTargetsResponsibility
    TZH-nh/moonwirewasm-gc, wasm, js, nativePublic facade re-exporting core types and high-level helpers
    TZH-nh/moonwire/cryptoAll targetsX25519, ChaCha20-Poly1305, XChaCha20-Poly1305, BLAKE2s, HKDF, SipHash-2-4, Hex/Base64
    TZH-nh/moonwire/packetAll targetsWireGuard Type 1–4 codecs, 16-byte block padding, IPv4/IPv6 header trimming, ICMPv4 Echo builder
    TZH-nh/moonwire/replayAll targetsTwo-phase RFC 6479 2048-packet sliding anti-replay window
    TZH-nh/moonwire/routingAll targetsIPv4/IPv6 CIDR radix trie (LPM, reverse-path source check, route overlap/shadow detector)
    TZH-nh/moonwire/configAll targetswg / wg-quick INI parser and multi-peer static security/routing auditor
    TZH-nh/moonwire/protocolAll targetsNoise_IKpsk2 handshake, TAI64N, Cookie Reply DoS challenge, 3-slot session timers, multi-peer Device
    TZH-nh/moonwire/pcapAll targetsLibpcap reader/writer and Wireshark wg.keylog_file / session-key trace decryptor
    TZH-nh/moonwire/cmd/moonwirenativeCLI tool (genkey, pubkey, check-config, inspect-pcap, udp-demo, udp-client)

    Scope & Platform Boundary: MoonWire intentionally decouples the WireGuard protocol state machine from OS kernel virtual NIC drivers (wintun.dll on Windows or /dev/net/tun on Linux) and does not execute wg-quick shell hooks (PostUp/PostDown).


    #Quick Start (Embeddable Sans-IO Tunnel)

    ///|
    test "end-to-end sans-io WireGuard tunnel over in-memory datagrams" {
    let alice_priv = @moonwire.from_hex(
    "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
    )
    let bob_priv = @moonwire.from_hex(
    "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
    )
    let alice_pub = @moonwire.x25519_public_key(alice_priv)
    let bob_pub = @moonwire.x25519_public_key(bob_priv)

    let alice = @moonwire.Device::new(
    alice_priv,
    Bytes::from_array(FixedArray::make(32, b'\x01')),
    0UL,
    )
    let _ = alice.add_peer(bob_pub, [@moonwire.parse_cidr("10.10.0.2/32")])

    let bob = @moonwire.Device::new(
    bob_priv,
    Bytes::from_array(FixedArray::make(32, b'\x02')),
    0UL,
    )
    let _ = bob.add_peer(alice_pub, [@moonwire.parse_cidr("10.10.0.1/32")])

    // 1. Alice encapsulates an inner IPv4 ICMP Echo Request (10.10.0.1 -> 10.10.0.2)
    let icmp_req = @moonwire.build_ipv4_icmp_echo(
    0x0a0a0001U, 0x0a0a0002U, 0x1234, 1, b"hello-wireguard",
    )
    let (_, init_wire) = alice.route_and_encapsulate(icmp_req, 100UL)

    // 2. Bob processes HandshakeInitiation and emits 92-byte HandshakeResponse
    let (_, bob_hs_act, _) = bob.receive_wire(init_wire[0], 110UL)
    guard bob_hs_act is HandshakeCompleted(response_wire=Some(resp_wire)) else {
    fail("expected HandshakeResponse")
    }

    // 3. Alice processes HandshakeResponse -> automatically flushes queued encrypted ICMP packet
    let (_, _, flushed_data) = alice.receive_wire(resp_wire, 120UL)

    // 4. Bob authenticates, checks Cryptokey Routing source IP, and delivers plaintext IPv4 packet
    let (_, bob_data_act, _) = bob.receive_wire(flushed_data[0], 130UL)
    guard bob_data_act is DeliverInnerPacket(inner_ip=decrypted_ip, ..) else {
    fail("expected DeliverInnerPacket")
    }
    inspect(
    @moonwire.describe_inner_ip(decrypted_ip),
    content="IPv4 10.10.0.1 -> 10.10.0.2 (ICMPv4 Echo Request seq=1, 43B)",
    )
    }


    #CLI Usage (3-Minute Walkthrough)

    Build or run on the native backend:

    # 1. Generate keypair & audit a wg-quick configuration (clean vs misconfigured) moon run cmd/moonwire --target native -- genkey moon run cmd/moonwire --target native -- check-config fixtures/sample-hub.conf moon run cmd/moonwire --target native -- check-config fixtures/sample-audit-issues.conf # 2. Decrypt an OpenSSL-generated WireGuard PCAP capture using a Wireshark wg.keylog_file moon run cmd/moonwire --target native -- inspect-pcap fixtures/openssl-wg-session.pcap --keylog fixtures/openssl-wg-session.keys # 3. Run a live Windows localhost UDP tunnel (with DoS CookieReply challenge + 3 ICMP roundtrips) moon run cmd/moonwire --target native -- udp-demo --export-pcap _build/demo.pcap --export-keys _build/demo.keys # 4. Cross-verify live UDP interoperability against an independent OpenSSL 3.0.x WireGuard responder node scripts/verify_with_openssl.mjs interop _build/native/debug/build/cmd/moonwire/moonwire.exe


    #Testing & Verification

    moon check --deny-warn moon test --target wasm-gc moon test --target wasm moon test --target js moon test --target native

    See docs/test-evidence/verification-report.md for toolchain details, cross-backend test counts, OpenSSL 3.0.x live UDP interop logs, and real Linux kernel capture decryption evidence, and THIRD_PARTY_NOTICES.md for standards attribution.

    #License

    Licensed under the Apache License, Version 2.0.

    AuditReport

    CaptureAuditSummary

    Summary of an inspected WireGuard PCAP capture.

    Cidr

    Canonical masked IPv4 (0..=32) or IPv6 (0..=128) CIDR network prefix.

    CookieReply

    Type 3: WireGuard Cookie Reply message (64 bytes, §5.4.7).

    CookieValidator

    Stateful responder-side cookie generator and mac2 validator (§5.4.7).

    Device

    Multi-peer Sans-IO WireGuard interface engine uniting per-peer Noise tunnels, CookieValidator DoS mitigation, and §4 Cryptokey Routing (outbound LPM + inbound source anti-spoofing).

    HandshakeInitiation

    Type 1: WireGuard Handshake Initiation message (148 bytes, §5.4.2).

    HandshakeResponse

    Type 2: WireGuard Handshake Response message (92 bytes, §5.4.3).

    IpAddr

    Canonical IPv4 or IPv6 network address.

    KeyLog

    Parsed WireGuard key material supporting both:
    1. Standard Wireshark wg.keylog_file (LOCAL_STATIC_PRIVATE_KEY = ..., LOCAL_EPHEMERAL_PRIVATE_KEY = ..., etc.)
    2. Kernel probe session keylogs (STAT/TIME/EMPT + 0x<receiver_idx> <base64_traffic_key>).

    PeerTunnel

    Sans-IO WireGuard single-peer state machine managing handshakes, 3-slot key rotation (previous / current / next), RFC 6479 anti-replay, TAI64N monotonic timestamps, Cookie Reply caching, and §6 timers.

    ReplayWindow

    RFC 6479 2048-packet anti-replay window without bit-shifting across words. Separates read-only pre-decryption check(counter) from post-AEAD-authentication accept(counter) so unauthenticated packets can never advance or poison the window.

    RoutingTable

    WireGuard Cryptokey Routing longest-prefix-match binary radix trie (§4) supporting both IPv4 and IPv6.

    Tai64n

    TAI64N 12-byte External TAI64 format timestamp (WireGuard §5.4.2). First 8 bytes: big-endian seconds (0x4000000000000000 + unix_seconds + leap_offset). Last 4 bytes: big-endian nanoseconds (0..999_999_999), masked to 0xffffff00 or exact per sender policy (WireGuard Linux kernel masks the lowest 24 bits / ~16ms granularity or full ns; comparison is lexicographical over 12 bytes).

    TransportData

    Type 4: WireGuard Transport Data message (>= 32 bytes, §5.4.6).

    TunnelAction

    Result emitted by PeerTunnel when processing inbound UDP packets or timer ticks.

    WgConfig

    Complete parsed wg / wg-quick configuration document.

    WirePacket

    Parsed WireGuard outer UDP frame.

    WG_CONSTRUCTION

    let WG_CONSTRUCTION : String

    Protocol identification prologue defined by WireGuard specification §5.4.

    WG_IDENTIFIER

    let WG_IDENTIFIER : String

    WireGuard protocol identifier mixed into the initial Noise hash state.

    audit_wg_config

    Run comprehensive static security & routing audits over a parsed WgConfig.

    blake2s

    fn blake2s(data : BytesView, out_len? : Int, key? : BytesView) -> Bytes raise
    CryptoError

    Compute a single-shot BLAKE2s digest (default 32 bytes, unkeyed).

    blake2s_256

    fn blake2s_256(data : BytesView) -> Bytes

    Unkeyed 32-byte BLAKE2s hash (Hash(input) in WireGuard §5.4).

    build_ipv4_icmp_echo

    fn build_ipv4_icmp_echo(src_v4 : UInt, dst_v4 : UInt, identifier : Int, sequence : Int, payload : BytesView, is_reply? : Bool) -> Bytes

    Build a standards-compliant IPv4 ICMP Echo Request (icmp_type = 8) or Reply (icmp_type = 0) packet with valid IPv4 header and ICMP checksums for userspace tunnel testing.

    build_ipv4_udp_pcap

    fn build_ipv4_udp_pcap(datagrams : Array[(UInt, Int, UInt, Int, UInt, UInt, Bytes)]) -> Bytes

    Build a standards-compliant Little-Endian LINKTYPE_ETHERNET (.pcap) capture containing IPv4 UDP datagrams, directly readable by Wireshark, tshark, and parse_pcap_udp_frames.

    chacha20_poly1305_open

    fn chacha20_poly1305_open(key : BytesView, nonce12 : BytesView, ciphertext_and_tag : BytesView, aad : BytesView) -> Bytes raise
    CryptoError

    IETF ChaCha20-Poly1305 AEAD open (RFC 8439 §2.8): verifies 16-byte tag in constant time before decrypting.

    chacha20_poly1305_seal

    fn chacha20_poly1305_seal(key : BytesView, nonce12 : BytesView, plaintext : BytesView, aad : BytesView) -> Bytes raise
    CryptoError

    IETF ChaCha20-Poly1305 AEAD seal (RFC 8439 §2.8): returns ciphertext || tag16.

    describe_inner_ip

    fn describe_inner_ip(decrypted : BytesView) -> String

    Summarize an inner IP packet into a concise human-readable diagnostic string (e.g., for PCAP inspection).

    format_wireshark_keylog

    fn format_wireshark_keylog(local_static_private : BytesView, remote_static_public : BytesView, ephemeral_privates : Array[Bytes], preshared_key? : BytesView) -> String

    Format key material in standard Wireshark wg.keylog_file syntax.

    from_base64

    fn from_base64(input : StringView) -> Bytes raise
    CryptoError

    Decode standard RFC 4648 Base64 string into Bytes.

    from_hex

    fn from_hex(hex : StringView) -> Bytes raise
    CryptoError

    Decode hexadecimal string (whitespace ignored) into Bytes.

    inspect_and_trim_inner_ip

    fn inspect_and_trim_inner_ip(decrypted : BytesView) ->
    InnerIpInfo
    raise
    PacketError

    Inspect a decrypted inner WireGuard payload, validate its IPv4/IPv6 header length, strip WireGuard 16-byte block padding, and extract (src, dst, next_proto).

    inspect_wireguard_pcap

    Inspect all UDP frames in pcap_bytes, dissect WireGuard frames, validate mac1 when keys are available, derive session keys from keylog (if provided), and decrypt inner IPv4/IPv6 payloads.

    parse_cidr

    Parse "<ip>/<prefix>" and canonicalize host bits to zero.

    parse_ip_addr

    Parse an IPv4 (a.b.c.d) or IPv6 (:: compressed or full 8-group hex) address string.

    parse_keylog

    Parse a WireGuard keylog text (Wireshark KEY = BASE64 format or 0xINDEX BASE64 session trace format).

    parse_wg_config

    Parse a wg or wg-quick INI configuration text into a typed WgConfig.

    parse_wire_packet

    fn parse_wire_packet(raw : BytesView, strict_reserved? : Bool) ->
    WirePacket
    raise
    PacketError

    Parse raw UDP datagram bytes into a typed WirePacket. When strict_reserved is true, non-zero reserved bytes [1..4) raise NonZeroReservedBytes.

    to_base64

    fn to_base64(data : BytesView) -> String

    Encode bytes using standard RFC 4648 Base64 with = padding (WireGuard key format).

    to_hex

    fn to_hex(data : BytesView) -> String

    Encode bytes as lowercase hexadecimal string.

    version

    fn version() -> String

    Library semantic version string.

    x25519_dh

    fn x25519_dh(private_key32 : BytesView, peer_public_key32 : BytesView) -> Bytes raise
    CryptoError

    WireGuard X25519 Diffie-Hellman shared secret derivation (rejects low-order/all-zero shared secrets per RFC 7748 §6.1).

    x25519_public_key

    fn x25519_public_key(private_key32 : BytesView) -> Bytes raise
    CryptoError

    Derive a 32-byte X25519 public key from a 32-byte private key using the basepoint u = 9.

    xchacha20_poly1305_open

    fn xchacha20_poly1305_open(key : BytesView, nonce24 : BytesView, ciphertext_and_tag : BytesView, aad : BytesView) -> Bytes raise
    CryptoError

    XChaCha20-Poly1305 AEAD open (XAEAD^-1 in WireGuard §5.4.7, 24-byte nonce).

    xchacha20_poly1305_seal

    fn xchacha20_poly1305_seal(key : BytesView, nonce24 : BytesView, plaintext : BytesView, aad : BytesView) -> Bytes raise
    CryptoError

    XChaCha20-Poly1305 AEAD seal (XAEAD in WireGuard §5.4.7, 24-byte nonce).

    Source Files