///|
#derive(Debug, Eq)
pub(all) suberror ConfigError {
SyntaxError(line~ : Int32, message~ : String)
UnknownSection(line~ : Int32, section~ : String)
KeyOutsideSection(line~ : Int32, key~ : String)
UnknownKey(line~ : Int32, section~ : String, key~ : String)
MissingRequiredField(section~ : String, field~ : String)
InvalidKeyMaterial(line~ : Int32, field~ : String, reason~ : String)
InvalidPort(line~ : Int32, value~ : String)
InvalidKeepalive(line~ : Int32, value~ : String)
InvalidMtu(line~ : Int32, value~ : String)
InvalidCidr(line~ : Int32, value~ : String)
}
///|
/// Parsed `[Interface]` block of a `wg` / `wg-quick` configuration file.
#derive(Debug, Eq)
pub(all) struct InterfaceConfig {
private_key : Bytes
public_key : Bytes
addresses : Array[String]
listen_port : Int32?
mtu : Int32?
dns : Array[String]
hooks : Array[(String, String)]
}
///|
/// Parsed `[Peer]` block of a `wg` / `wg-quick` configuration file.
#derive(Debug, Eq)
pub(all) struct PeerConfig {
public_key : Bytes
preshared_key : Bytes?
allowed_ips : Array[@routing.Cidr]
raw_allowed_ips : Array[(String, Bool)]
endpoint : String?
persistent_keepalive : Int32?
}
///|
/// Complete parsed `wg` / `wg-quick` configuration document.
#derive(Debug, Eq)
pub(all) struct WgConfig {
iface : InterfaceConfig
peers : Array[PeerConfig]
}
///|
#derive(Debug, Eq)
pub(all) enum AuditSeverity {
Error
Warning
Info
}
///|
#derive(Debug, Eq)
pub(all) struct AuditFinding {
severity : AuditSeverity
code : String
message : String
}
///|
#derive(Debug, Eq)
pub(all) struct AuditReport {
interface_public_key_b64 : String
peer_count : Int32
findings : Array[AuditFinding]
}
///|
pub fn AuditReport::has_errors(self : AuditReport) -> Bool {
for f in self.findings {
if f.severity is Error {
return true
}
}
false
}
///|
pub fn AuditReport::format_text(self : AuditReport) -> String {
let sb = StringBuilder()
sb.write_string(
"Interface PublicKey: \{self.interface_public_key_b64} (peers: \{self.peer_count})\n",
)
if self.findings.length() == 0 {
sb.write_string("Status: OK (0 findings)\n")
} else {
for f in self.findings {
let tag = match f.severity {
Error => "ERROR"
Warning => "WARN"
Info => "INFO"
}
sb.write_string("[\{tag}] \{f.code}: \{f.message}\n")
}
}
sb.to_string()
}
///|
fn is_ws(c : UInt16) -> Bool {
c == ' ' || c == '\t' || c == '\r' || c == 0xfeff
}
///|
fn trim_ws(s : StringView) -> StringView {
let mut start = 0
let mut end = s.length()
while start < end && is_ws(s[start]) {
start = start + 1
}
while end > start && is_ws(s[end - 1]) {
end = end - 1
}
s[start:end]
}
///|
fn strip_comment(line : StringView) -> StringView {
for i in 0.. String {
let sb = StringBuilder()
for i in 0..= 'A' && ch <= 'Z' {
sb.write_char((ch.to_int() + 32).unsafe_to_char())
} else {
sb.write_char(ch.to_int().unsafe_to_char())
}
}
sb.to_string()
}
///|
fn split_csv(s : StringView) -> Array[StringView] {
let out : Array[StringView] = []
let mut start = 0
for i in 0..<=s.length() {
if i == s.length() || s[i] == ',' {
let item = trim_ws(s[start:i])
if item.length() > 0 {
out.push(item)
}
start = i + 1
}
}
out
}
///|
fn parse_uint_range(s : StringView, min_v : Int32, max_v : Int32) -> Int32? {
if s.length() == 0 || s.length() > 6 {
None
} else {
let mut acc = 0
for i in 0.. '9' {
return None
}
acc = acc * 10 + (ch.to_int() - '0'.to_int())
}
if acc < min_v || acc > max_v {
None
} else {
Some(acc)
}
}
}
///|
fn decode_key32(
line : Int32,
field : String,
val : StringView,
) -> Bytes raise ConfigError {
let raw = @crypto.from_base64(val) catch {
_ =>
raise ConfigError::InvalidKeyMaterial(
line~,
field~,
reason="invalid Base64 encoding",
)
}
if raw.length() != 32 {
raise ConfigError::InvalidKeyMaterial(
line~,
field~,
reason="expected 32-byte key, got \{raw.length()} bytes",
)
}
raw
}
///|
/// Parse a `wg` or `wg-quick` INI configuration text into a typed `WgConfig`.
pub fn parse_wg_config(content : StringView) -> WgConfig raise ConfigError {
let mut section = ""
let mut has_iface = false
let mut iface_priv : Bytes? = None
let iface_addrs : Array[String] = []
let mut iface_port : Int32? = None
let mut iface_mtu : Int32? = None
let iface_dns : Array[String] = []
let iface_hooks : Array[(String, String)] = []
let peers : Array[PeerConfig] = []
let mut in_peer = false
let mut peer_pub : Bytes? = None
let mut peer_psk : Bytes? = None
let mut peer_allowed : Array[@routing.Cidr] = []
let mut peer_raw_allowed : Array[(String, Bool)] = []
let mut peer_endpoint : String? = None
let mut peer_keepalive : Int32? = None
let mut line_no = 0
let mut pos = 0
let total = content.length()
while pos <= total {
let mut nl = pos
while nl < total && content[nl] != '\n' {
nl = nl + 1
}
line_no = line_no + 1
let raw_line = content[pos:nl]
let cleaned = trim_ws(strip_comment(raw_line))
if cleaned.length() > 0 {
if cleaned[0] == '[' {
if cleaned[cleaned.length() - 1] != ']' {
raise ConfigError::SyntaxError(
line=line_no,
message="unclosed section header",
)
}
if in_peer {
guard peer_pub is Some(pk) else {
raise ConfigError::MissingRequiredField(
section="Peer",
field="PublicKey",
)
}
peers.push({
public_key: pk,
preshared_key: peer_psk,
allowed_ips: peer_allowed,
raw_allowed_ips: peer_raw_allowed,
endpoint: peer_endpoint,
persistent_keepalive: peer_keepalive,
})
in_peer = false
}
let sec_name = ascii_lower(trim_ws(cleaned[1:cleaned.length() - 1]))
if sec_name == "interface" {
section = "interface"
has_iface = true
} else if sec_name == "peer" {
section = "peer"
in_peer = true
peer_pub = None
peer_psk = None
peer_allowed = []
peer_raw_allowed = []
peer_endpoint = None
peer_keepalive = None
} else {
raise ConfigError::UnknownSection(line=line_no, section=sec_name)
}
} else {
if section == "" {
raise ConfigError::KeyOutsideSection(
line=line_no,
key=cleaned.to_owned(),
)
}
let mut eq_idx = -1
for i in 0..
iface_priv = Some(decode_key32(line_no, "PrivateKey", val))
"address" =>
for item in split_csv(val) {
let _ = @routing.parse_cidr(item) catch {
_ =>
raise ConfigError::InvalidCidr(
line=line_no,
value=item.to_owned(),
)
}
iface_addrs.push(item.to_owned())
}
"listenport" =>
match parse_uint_range(val, 0, 65535) {
Some(p) => iface_port = Some(p)
None =>
raise ConfigError::InvalidPort(
line=line_no,
value=val.to_owned(),
)
}
"mtu" =>
match parse_uint_range(val, 576, 65535) {
Some(m) => iface_mtu = Some(m)
None =>
raise ConfigError::InvalidMtu(
line=line_no,
value=val.to_owned(),
)
}
"dns" =>
for item in split_csv(val) {
iface_dns.push(item.to_owned())
}
"table" | "fwmark" | "saveconfig" => ()
"preup" | "postup" | "predown" | "postdown" =>
iface_hooks.push((key_raw.to_owned(), val.to_owned()))
_ =>
raise ConfigError::UnknownKey(
line=line_no,
section="Interface",
key=key_raw.to_owned(),
)
}
} else {
match key {
"publickey" =>
peer_pub = Some(decode_key32(line_no, "PublicKey", val))
"presharedkey" =>
peer_psk = Some(decode_key32(line_no, "PresharedKey", val))
"allowedips" =>
for item in split_csv(val) {
let (cidr, had_host_bits) = @routing.parse_cidr_detailed(item) catch {
_ =>
raise ConfigError::InvalidCidr(
line=line_no,
value=item.to_owned(),
)
}
peer_allowed.push(cidr)
peer_raw_allowed.push((item.to_owned(), had_host_bits))
}
"endpoint" =>
if val.length() == 0 {
raise ConfigError::SyntaxError(
line=line_no,
message="empty Endpoint",
)
} else {
peer_endpoint = Some(val.to_owned())
}
"persistentkeepalive" =>
if ascii_lower(val) == "off" {
peer_keepalive = Some(0)
} else {
match parse_uint_range(val, 0, 65535) {
Some(ka) => peer_keepalive = Some(ka)
None =>
raise ConfigError::InvalidKeepalive(
line=line_no,
value=val.to_owned(),
)
}
}
_ =>
raise ConfigError::UnknownKey(
line=line_no,
section="Peer",
key=key_raw.to_owned(),
)
}
}
}
}
if nl >= total {
break
}
pos = nl + 1
}
if in_peer {
guard peer_pub is Some(pk) else {
raise ConfigError::MissingRequiredField(section="Peer", field="PublicKey")
}
peers.push({
public_key: pk,
preshared_key: peer_psk,
allowed_ips: peer_allowed,
raw_allowed_ips: peer_raw_allowed,
endpoint: peer_endpoint,
persistent_keepalive: peer_keepalive,
})
}
if !has_iface {
raise ConfigError::MissingRequiredField(
section="Interface",
field="[Interface]",
)
}
guard iface_priv is Some(priv_key) else {
raise ConfigError::MissingRequiredField(
section="Interface",
field="PrivateKey",
)
}
let pub_key = @crypto.x25519_public_key(priv_key) catch {
_ =>
raise ConfigError::InvalidKeyMaterial(
line=0,
field="PrivateKey",
reason="failed to derive public key",
)
}
{
iface: {
private_key: priv_key,
public_key: pub_key,
addresses: iface_addrs,
listen_port: iface_port,
mtu: iface_mtu,
dns: iface_dns,
hooks: iface_hooks,
},
peers,
}
}
///|
/// Run comprehensive static security & routing audits over a parsed `WgConfig`.
pub fn audit_wg_config(cfg : WgConfig) -> AuditReport {
let findings : Array[AuditFinding] = []
let iface_pub_b64 = @crypto.to_base64(cfg.iface.public_key)
if cfg.iface.hooks.length() > 0 {
findings.push({
severity: Warning,
code: "SHELL_HOOK_PRESENT",
message: "Interface defines \{cfg.iface.hooks.length()} wg-quick shell hook(s); MoonWire ignores host shell execution by design.",
})
}
let seen_peers : Array[String] = []
let route_inputs : Array[(String, Array[@routing.Cidr])] = []
for idx, p in cfg.peers {
let pk_b64 = @crypto.to_base64(p.public_key)
let short_id = "Peer#\{idx + 1}(\{pk_b64[:8]}...)"
// 1. Self-loop check
if @crypto.ct_eq(p.public_key, cfg.iface.public_key) {
findings.push({
severity: Error,
code: "SELF_PEER_PUBLIC_KEY",
message: "\{short_id} has PublicKey identical to local [Interface] PublicKey.",
})
}
// 2. Duplicate peer check
let mut dup = false
for prev in seen_peers {
if prev == pk_b64 {
dup = true
}
}
if dup {
findings.push({
severity: Error,
code: "DUPLICATE_PEER",
message: "\{short_id} duplicates an earlier [Peer] PublicKey.",
})
} else {
seen_peers.push(pk_b64)
}
// 3. Empty AllowedIPs
if p.allowed_ips.length() == 0 {
findings.push({
severity: Warning,
code: "EMPTY_ALLOWED_IPS",
message: "\{short_id} has no AllowedIPs; Cryptokey Routing will drop all traffic to and from this peer.",
})
}
// 4. Non-zero host bits in AllowedIPs
for raw_entry in p.raw_allowed_ips {
let (raw_str, had_host_bits) = raw_entry
if had_host_bits {
findings.push({
severity: Warning,
code: "NON_CANONICAL_ALLOWED_IP",
message: "\{short_id} AllowedIPs entry '\{raw_str}' has non-zero host bits (masked automatically).",
})
}
}
// 5. Neither ListenPort nor Endpoint
if cfg.iface.listen_port is None && p.endpoint is None {
findings.push({
severity: Warning,
code: "UNREACHABLE_PEER_NO_ENDPOINT",
message: "\{short_id} has no Endpoint while [Interface] has no ListenPort; neither side can initiate UDP contact.",
})
}
// 6. Post-quantum PSK hygiene info
if p.preshared_key is None {
findings.push({
severity: Info,
code: "NO_PRESHARED_KEY",
message: "\{short_id} omits PresharedKey (optional symmetric post-quantum resistance layer).",
})
}
route_inputs.push((short_id, p.allowed_ips))
}
// 7. Cross-peer & intra-peer Cryptokey Routing overlap checks
let overlaps = @routing.analyze_overlaps(route_inputs)
for ov in overlaps {
match ov.kind {
ExactDuplicateConflict =>
findings.push({
severity: Error,
code: "EXACT_ROUTE_CONFLICT",
message: "\{ov.wider_peer} and \{ov.narrower_peer} both claim identical AllowedIPs prefix \{ov.wider_cidr}; earlier route is overwritten.",
})
RedundantSelfSubset =>
findings.push({
severity: Warning,
code: "REDUNDANT_SELF_SUBNET",
message: "\{ov.wider_peer} lists \{ov.narrower_cidr} which is already covered by its own \{ov.wider_cidr}.",
})
CrossPeerSubnetCarve =>
findings.push({
severity: Warning,
code: "CROSS_PEER_SUBNET_SHADOW",
message: "\{ov.narrower_peer} prefix \{ov.narrower_cidr} is a more-specific subset inside \{ov.wider_peer} prefix \{ov.wider_cidr} (LPM carves traffic to \{ov.narrower_peer}).",
})
}
}
{
interface_public_key_b64: iface_pub_b64,
peer_count: cfg.peers.length(),
findings,
}
}