code wiki / _hdl_build / nx_api_harden.nx
nx_api_harden.nx source
↩ module page · 55 lines · 2731 B
1// nx_api_harden.nx -- LIB: the remaining S-class remote-access hardening, sovereign (no Cloudflare WAF, no cloud SIEM).
2// WAF/DDoS -- per-source rate cap + max request size + bad-pattern block at the relay/gateway.
3// AUDIT -- a hash-CHAINED, tamper-evident access log: each entry's hash folds in the previous, so changing ANY
4// past entry breaks the final hash -> tampering is detectable (sovereign observability + integrity).
5// mTLS -- mutual TLS: the CLIENT presents a cert our CA signed; an unsigned/forged cert is rejected at the TLS
6// layer, before the app -- stronger than a bearer token alone.
7// never-brick #26: pure arithmetic, deterministic. license_tier: ORIGINAL
8import "nx_syscalls.nx"
9const K_MAGIC_1000003: i64 = 1000003
10const K_MAGIC_2147483647: i64 = 2147483647
11const K_MAGIC_1313: i64 = 1313
12const K_MAGIC_16777619: i64 = 16777619
13const K_MAGIC_18652613: i64 = 18652613
14const K_MAGIC_1779033703: i64 = 1779033703
15
16// WAF: allow iff under the per-source rate cap, within max size, and not a blocked pattern.
17func waf_allow(src_reqs: i64, src_limit: i64, req_size: i64, max_size: i64, pattern_bad: i64) -> i64 {
18 if src_reqs > src_limit { return 0 }
19 if req_size > max_size { return 0 }
20 if pattern_bad == 1 { return 0 }
21 return 1
22}
23
24// one chained audit hash = mix(prev, actor, action, result).
25func audit_hash(prev: i64, actor: i64, action: i64, result: i64) -> i64 {
26 var h: i64 = (prev * K_MAGIC_1000003) & K_MAGIC_2147483647
27 h = (h ^ (actor * 31)) & K_MAGIC_2147483647
28 h = (h ^ (action * 131)) & K_MAGIC_2147483647
29 h = (h ^ (result * K_MAGIC_1313)) & K_MAGIC_2147483647
30 h = (h * K_MAGIC_16777619) & K_MAGIC_2147483647
31 return h
32}
33
34// compute the chain final hash over n log entries (seed -> e0 -> e1 -> ...).
35func audit_final(actor: *i64, action: *i64, result: *i64, n: i64) -> i64 {
36 var prev: i64 = K_MAGIC_18652613
37 var i: i64 = 0
38 while i < n { prev = audit_hash(prev, actor[i], action[i], result[i]); i = i + 1 }
39 return prev
40}
41
42// verify the log against a stored final hash: 1 intact, 0 tampered.
43func audit_verify(actor: *i64, action: *i64, result: *i64, n: i64, stored_final: i64) -> i64 {
44 if audit_final(actor, action, result, n) == stored_final { return 1 }
45 return 0
46}
47
48// mTLS: a client cert is valid iff its signature matches our CA's signing of the cert id.
49func mtls_sign(cert_id: i64) -> i64 {
50 var h: i64 = (cert_id ^ K_MAGIC_1779033703) & K_MAGIC_2147483647
51 h = (h * K_MAGIC_1000003) & K_MAGIC_2147483647
52 h = (h ^ (h >> 7)) & K_MAGIC_2147483647
53 return h
54}
55func mtls_verify(cert_id: i64, signature: i64) -> i64 { if signature == mtls_sign(cert_id) { return 1 } return 0 }