681 lines
36 KiB
Markdown
681 lines
36 KiB
Markdown
# NSC Routing Specification
|
|
|
|
| Field | Value |
|
|
| --- | --- |
|
|
| Version | 0.1 |
|
|
| Status | Normative architecture and behavioral specification |
|
|
| Platform | Linux; local applications; IPv4 TCP and UDP |
|
|
| Related documents | [Routing overview](HOW_WORKS_ROUTING.md), [project README](../README.md) |
|
|
|
|
The key words **MUST**, **MUST NOT**, **SHOULD**, **SHOULD NOT**, and **MAY** express
|
|
requirements on a conforming implementation. This specification defines the
|
|
routing contract and configuration semantics; it does not assert that the current
|
|
code implements every requirement. Release-specific BPF layouts and deployment
|
|
settings MUST satisfy this contract.
|
|
|
|
## 1. Scope and terminology
|
|
|
|
NSC provides transparent routing by destination domain, geosite membership,
|
|
destination IP/geoip, and overlay namespace. Its routing outcomes are `DIRECT`,
|
|
`BLOCK`, and `PROXY(proxy_id)`.
|
|
|
|
| Term | Meaning |
|
|
| --- | --- |
|
|
| FakeDNS | The NSC DNS service; it can return real answers, allocate synthetic addresses, or block a query |
|
|
| REAL | Resolve through an authorized source without substituting a fake address |
|
|
| FAKE | Return a synthetic address associated with the original domain |
|
|
| Clearnet | An application destination outside a recognized overlay namespace or supported native overlay address space |
|
|
| Network class | Destination classification, such as `CLEARNET`, `I2P`, or `TOR` |
|
|
| Mapping | The runtime association between a fake IP, original domain, and classification |
|
|
| Flow | A TCP connection or a tracked UDP conversation with a specific original destination |
|
|
| Generation | An immutable version of the active routing policy |
|
|
| Runtime epoch | One daemon process lifetime; retained across SIGHUP and discarded at system reboot |
|
|
| Trusted service traffic | Narrowly authorized DNS upstream, proxy transport, or overlay peer traffic |
|
|
|
|
The mandatory profile supports local IPv4 TCP and UDP, DNS over UDP and TCP,
|
|
SOCKS5 CONNECT and UDP ASSOCIATE, and HTTP proxies. The eBPF attachment point is
|
|
**TC**. Transparent listeners and payload forwarding run in userspace.
|
|
|
|
IPv6 interception, gateway operation, and kernel payload relay are extension
|
|
profiles. An implementation MUST NOT advertise one of these profiles without
|
|
covering its entire packet path. In a protected profile, unsupported traffic MUST
|
|
be blocked; IPv6 or QUIC MUST NOT become an implicit bypass. Supported QUIC uses
|
|
the same UDP routing and killswitch checks as other UDP traffic.
|
|
|
|
Privileged administrators and root-controlled changes to the host are outside
|
|
the enforcement threat model. The base profile assumes local client processes;
|
|
client DNS caches persisted across a reboot are outside its mapping guarantees.
|
|
|
|
## 2. Architecture
|
|
|
|
### 2.1. Component responsibilities
|
|
|
|
| Component | Responsibilities |
|
|
| --- | --- |
|
|
| Policy engine | Configuration validation, rule evaluation, geosite/geoip lookup, proxy selection, policy publication |
|
|
| FakeDNS | DNS policy, authorized resolution, domain mappings, address allocation, DNS lifetime management |
|
|
| TC eBPF | Bounded header parsing, compact policy and flow lookups, classification, packet admission or drop |
|
|
| nftables and policy routing | OUTPUT interception, local delivery, TPROXY, independent egress guard |
|
|
| Transparent listeners | TCP acceptance and UDP reception with the original destination preserved |
|
|
| Dialers and relay | Proxy handshakes, direct dialing where allowed, TCP byte relay and UDP encapsulation |
|
|
| Init integration | Boot startup, SIGHUP reload, restart restrictions, readiness reporting |
|
|
|
|
A userspace `HashMap` is not shared with TC. The daemon MUST publish kernel-visible
|
|
state through BPF maps. Domain strings, geosite data, MMDB lookup, and complex
|
|
matching remain in userspace. The kernel receives compact decisions and indexes.
|
|
|
|
### 2.2. Architecture diagram
|
|
|
|
Solid arrows show logical traffic paths; dashed arrows show state publication or
|
|
lookup. Repeated kernel traversal is abbreviated: DNS and proxy upstream sockets
|
|
still pass through the same egress enforcement. Section 3 defines packet-hook order.
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
APP["Local application"]
|
|
|
|
subgraph USER["Userspace: NSC daemon"]
|
|
DNS["FakeDNS: REAL / FAKE / BLOCK"]
|
|
POLICY["Policy engine: TOML and geodata"]
|
|
JOURNAL["Domain mappings and network classes"]
|
|
RELAY["Transparent listeners, dialers and relay"]
|
|
end
|
|
|
|
subgraph KERNEL["Kernelspace"]
|
|
BPF["BPF maps: runtime, policy, mappings, flows"]
|
|
PATH["Interception and egress enforcement<br/>OUTPUT, TC, TPROXY and firewall"]
|
|
end
|
|
|
|
UPSTREAM["Configured DNS upstream"]
|
|
PROXY["Configured SOCKS5 / HTTP proxy"]
|
|
OVERLAY["Overlay destination"]
|
|
CLEAR["Clearnet destination"]
|
|
|
|
APP <-->|"DNS"| DNS
|
|
APP <-->|"TCP / UDP"| PATH
|
|
POLICY -.-> DNS
|
|
DNS -.-> JOURNAL
|
|
JOURNAL -.-> BPF
|
|
POLICY -.-> BPF
|
|
BPF -.-> PATH
|
|
JOURNAL -.-> RELAY
|
|
POLICY -.-> RELAY
|
|
PATH <-->|"Transparent socket"| RELAY
|
|
DNS <-->|"DNS service exception"| UPSTREAM
|
|
RELAY <-->|"Admitted proxy socket"| PROXY
|
|
PROXY <--> OVERLAY
|
|
PROXY <-->|"allow-proxy"| CLEAR
|
|
PATH <-->|"DIRECT when permitted"| CLEAR
|
|
```
|
|
|
|
Trusted overlay peer transports use narrow service exceptions. Denied traffic is
|
|
dropped at enforcement; no denied edge creates a DIRECT fallback. Overlay daemon
|
|
internals and optional kernel payload relay are outside this diagram.
|
|
|
|
TPROXY delivers traffic to a transparent local socket; it does not join the
|
|
application stream to a SOCKS connection. After a successful handshake, the
|
|
userspace relay MUST forward payload between the two sockets, preserving
|
|
backpressure and half-close behavior. SOCKMAP/SOCKHASH offload MAY be provided by
|
|
a separate extension; it MUST NOT be assumed by the base profile.
|
|
|
|
## 3. Interception and packet delivery
|
|
|
|
The local intercepted path is:
|
|
|
|
```text
|
|
application -> OUTPUT classification/mark -> policy route to lo
|
|
-> TC ingress -> PREROUTING/TPROXY -> transparent listener
|
|
```
|
|
|
|
The backend MUST establish this path for both TCP and UDP before accepting
|
|
application traffic. Loopback ingress coverage and delivery to the listener MUST
|
|
be verified on every supported kernel/deployment profile. TC ingress on an
|
|
external interface is not a substitute for intercepting local OUTPUT traffic.
|
|
|
|
TC egress on a physical interface occurs after the initial route selection. A
|
|
backend MUST NOT rely on setting a mark there to repeat policy routing or enter
|
|
PREROUTING automatically. TC egress supplies an egress guard. OUTPUT routing and
|
|
the loopback ingress path supply transparent interception.
|
|
|
|
The backend MUST preserve the original destination without requiring DNAT to the
|
|
listener. Listeners MUST enable `IP_TRANSPARENT`; UDP reception MUST expose
|
|
original-destination metadata. Return traffic MUST retain the application's
|
|
expected peer identity.
|
|
|
|
Marks, masks, routing tables, hook priorities, interface selection, and exemptions
|
|
MUST be declared by the deployment profile and checked for conflicts with the
|
|
host firewall and VPN configuration. Every application egress path MUST be covered
|
|
by enforcement, including paths that do not require userspace relay. A standalone
|
|
firewall guard MUST retain a protected default if TC is detached or the daemon dies.
|
|
|
|
## 4. Policy evaluation and killswitch
|
|
|
|
### 4.1. Rule evaluation
|
|
|
|
A new flow MUST be evaluated in this order:
|
|
|
|
1. Check runtime admission, mandatory backend constraints, and trusted service identity.
|
|
2. Recover the original domain from a fake mapping when available.
|
|
3. Evaluate transport rules in declaration order; the first matching rule wins.
|
|
4. If no rule matches, apply an explicitly configured overlay namespace route.
|
|
5. Otherwise, apply the default clearnet policy; a missing permitted route is `BLOCK`.
|
|
6. Apply killswitch restrictions and dialer capabilities before establishing an upstream flow.
|
|
|
|
Ordinary A/AAAA queries do not specify the future destination port or TCP/UDP
|
|
transport. DNS resolution therefore publishes classification and an optional
|
|
route hint, not a completed SOCKS connection. TCP acceptance or the first UDP
|
|
datagram triggers the final per-flow decision.
|
|
|
|
For mixed domain/IP rules, the engine MUST preserve rule order. A geosite rule
|
|
cannot match without reliable domain identity. If an earlier geoip rule requires
|
|
a real address, the engine resolves it through an authorized source before
|
|
continuing. Synthetic pool addresses MUST NOT be treated as real geoip input.
|
|
For proxy-only overlay names, geoip has no meaning unless an extension defines
|
|
an actual overlay address space.
|
|
|
|
For an address-dependent decision, the upstream connection MUST use the real
|
|
address that was evaluated. If resolution yields multiple candidates, each
|
|
candidate MUST be evaluated before use. A clearnet proxy request whose admission
|
|
depends on geoip MUST carry the admitted numeric address rather than allow the
|
|
proxy to resolve the domain to an unchecked address. Overlay proxy requests
|
|
continue to carry their original overlay domain.
|
|
|
|
### 4.2. Killswitch settings
|
|
|
|
| Setting | Required behavior |
|
|
| --- | --- |
|
|
| `clearnet = "allowed"` | Unmatched ordinary traffic MAY use DIRECT; explicit routing rules still apply |
|
|
| `clearnet = "killswitched"` | Application egress is restricted by `killswitch_mode` and explicit rule exceptions |
|
|
| `killswitch_mode = "allow-proxy"` | Overlay destinations are permitted; clearnet applications MUST use a proxy explicitly configured in NSC |
|
|
| `killswitch_mode = "full"` | Only overlay application destinations are permitted; clearnet destinations are blocked even through an exit, outproxy, or other configured proxy |
|
|
|
|
`killswitch_mode` selects the restrictions when `clearnet = "killswitched"`;
|
|
it does not activate a killswitch when `clearnet = "allowed"`. Defaults are
|
|
`clearnet = "allowed"` and `killswitch_mode = "allow-proxy"`. A protected deployment
|
|
MUST select `clearnet = "killswitched"` explicitly.
|
|
|
|
Killswitch restrictions take precedence over a rule's `DIRECT` action unless the
|
|
selected rule explicitly contains `killswitch_exception = true`. Such an
|
|
exception MUST be reported as a direct exception. A full profile with a clearnet
|
|
direct exception no longer guarantees overlay-only application traffic. The
|
|
exception MUST NOT bypass invalid mappings, expired runtime admission, or
|
|
unsupported backend paths.
|
|
|
|
### 4.3. Overlay identity
|
|
|
|
FakeDNS is the source of classification for synthetic domain routes. For example,
|
|
`example.i2p` has class `I2P`; its mapping and kernel index carry that class.
|
|
Namespace matching MUST respect DNS label boundaries. Proxy aliases and URL
|
|
schemes MUST NOT confer an overlay class on an ordinary clearnet domain.
|
|
|
|
The namespace registry MUST recognize `.i2p` as I2P and `.onion` as Tor. Enabling
|
|
an overlay route does not silently change DNS mode: its rule or enabled preset
|
|
MUST explicitly request FAKE when no real address source exists. In full mode,
|
|
a clearnet name routed to i2pd or Tor remains clearnet and MUST be blocked before
|
|
the proxy request.
|
|
|
|
Proxy-only overlay names MUST NOT be sent to a public DNS upstream or assigned a
|
|
physical DIRECT route. A configuration requesting such a route MUST be rejected.
|
|
Native overlay addressing MAY use DIRECT only on a declared overlay interface
|
|
in a profile that supports that address family. Native IPv6 overlay support is
|
|
outside the mandatory IPv4 profile.
|
|
|
|
### 4.4. Trusted service exceptions
|
|
|
|
The following service traffic MAY be authorized separately from application egress:
|
|
|
|
- NSC dialer sockets to configured proxy endpoints, including a negotiated SOCKS UDP relay.
|
|
- Overlay daemon sockets to the peer transports needed to operate the overlay.
|
|
- FakeDNS sockets to explicitly configured DNS upstream endpoints, including in full mode.
|
|
|
|
An exception MUST be bound to a trusted service/socket identity and the required
|
|
remote address, port, and transport. Destination IP alone is insufficient. An
|
|
application connecting to the same endpoint MUST NOT inherit the service exception.
|
|
Proxy and DNS service sockets MUST avoid recursive interception without creating
|
|
a general bypass for daemon-originated traffic.
|
|
|
|
Full mode consequently restricts application destinations while allowing the
|
|
explicitly configured DNS service exception. Overlay names MUST remain local to
|
|
the overlay resolution path even when a clearnet upstream is authorized.
|
|
|
|
## 5. Configuration contract
|
|
|
|
### 5.1. Policy and rule fields
|
|
|
|
The existing TOML structure is extended by the following contract. These fields
|
|
are normative for implementations of version 0.1; the current parser may require
|
|
changes before it accepts them.
|
|
|
|
| Field | Values | Default or constraint |
|
|
| --- | --- | --- |
|
|
| `[policy].clearnet` | `allowed`, `killswitched` | `allowed` |
|
|
| `[policy].killswitch_mode` | `allow-proxy`, `full` | `allow-proxy` |
|
|
| `[policy].dns_mode` | `real`, `fake`, `block` | `real` |
|
|
| `[[rule]].target` | A selector from Section 5.2 | Required |
|
|
| `[[rule]].action` | `direct`, `block`, `proxy` | Required |
|
|
| `[[rule]].proxy_name` | A configured proxy alias | Required only for `action = "proxy"` |
|
|
| `[[rule]].dns_mode` | `real`, `fake`, `block` | Optional; omission does not select a mode |
|
|
| `[[rule]].killswitch_exception` | Boolean | `false`; valid only for `action = "direct"` |
|
|
| `[[proxy]].alias` | Unique nonempty name | Required |
|
|
| `[[proxy]].url` | `socks5://` or `http://` endpoint | Required |
|
|
| `[[proxy]].http_mode` | `connect`, `forward` | `connect` for HTTP; invalid for SOCKS5 |
|
|
| `[dns].upstreams` | Ordered list of `udp://IPv4:port` or `tcp://IPv4:port` endpoints | Empty unless explicitly configured |
|
|
|
|
A proxy endpoint MAY be a loopback service. No additional proxy protocol is
|
|
required by this version. An endpoint hostname MUST be resolved through an
|
|
authorized, nonrecursive bootstrap source before admission rules are installed.
|
|
The baseline DNS upstream list uses literal IPv4 addresses to avoid bootstrap
|
|
recursion. An implementation MAY provide additional resolver protocols as an
|
|
extension; it MUST NOT silently enable an unconfigured upstream.
|
|
|
|
Unknown enum values, malformed targets, duplicate aliases, missing aliases,
|
|
invalid field combinations, and unsupported mandatory capabilities MUST fail
|
|
configuration validation before the active generation changes. A proxy route
|
|
MUST NOT become DIRECT because an alias or capability is unavailable.
|
|
|
|
### 5.2. Selectors
|
|
|
|
| Selector | Matches |
|
|
| --- | --- |
|
|
| `domain:<name>` | Exactly one normalized DNS name |
|
|
| `suffix:<name>` | The normalized name and its subdomains, at DNS label boundaries |
|
|
| `geosite:<set>` | A domain in the configured geosite dataset |
|
|
| `geoip:<country>` | A real destination address classified by the configured geoip dataset |
|
|
| `clearnet` | A destination not classified as a recognized overlay |
|
|
|
|
Names MUST use the same lowercase, trailing-dot removal, and IDNA normalization
|
|
in configuration matching and mapping lookup. `suffix:i2p` MUST NOT match
|
|
`noti2p` or `example.i2p.example.com`. Empty selector values MUST be rejected.
|
|
|
|
### 5.3. Independent DNS and transport selection
|
|
|
|
Transport routing and DNS mode are evaluated independently over the same ordered
|
|
rules. Transport selection stops at the first matching rule. DNS selection stops
|
|
at the first matching rule that explicitly declares `dns_mode`; a matching rule
|
|
without that field does not stop the DNS search. If none supplies a mode,
|
|
`[policy].dns_mode` applies.
|
|
|
|
DNS-mode selection uses information available before address resolution:
|
|
`domain`, `suffix`, `geosite`, and the known namespace/clearnet classification.
|
|
A rule combining `geoip` with `dns_mode` MUST be rejected to avoid circular
|
|
resolution. A rule's killswitch exception belongs only to its selected transport
|
|
action and MUST NOT be inherited from a different rule.
|
|
|
|
`dns_mode = "block"` denies DNS resolution; `action = "block"` denies matching
|
|
flows. Neither field implicitly sets the other. DNS denial alone MUST NOT be
|
|
reported as enforcement against connections made with cached or literal addresses.
|
|
|
|
### 5.4. Example: overlay-only applications with real DNS by default
|
|
|
|
```toml
|
|
[policy]
|
|
clearnet = "killswitched"
|
|
killswitch_mode = "full"
|
|
dns_mode = "real"
|
|
|
|
[dns]
|
|
# Documentation address: replace it with the resolver authorized for this host.
|
|
upstreams = ["udp://192.0.2.53:53"]
|
|
|
|
[[proxy]]
|
|
alias = "i2pd"
|
|
url = "socks5://127.0.0.1:1080" # Use the port configured in i2pd.
|
|
|
|
[[rule]]
|
|
target = "suffix:i2p"
|
|
action = "proxy"
|
|
proxy_name = "i2pd"
|
|
dns_mode = "fake"
|
|
```
|
|
|
|
This configuration selects FAKE and i2pd for `.i2p`, retaining REAL elsewhere.
|
|
Ordinary clearnet DNS answers do not authorize application connections in full
|
|
mode. FakeDNS alone receives the narrow upstream DNS exception.
|
|
|
|
## 6. DNS and mapping lifecycle
|
|
|
|
### 6.1. Resolution modes
|
|
|
|
REAL is the global default for compatibility with software that rejects synthetic
|
|
DNS answers. REAL MUST use an authorized resolver or local authoritative data;
|
|
it MUST NOT fall back to FAKE without a matching explicit DNS policy. If no real
|
|
address exists, resolution fails. Overlay names without address-based resolution
|
|
therefore require an explicit FAKE rule or an overlay resolver.
|
|
|
|
The REAL observation journal MAY associate multiple domains with an IP and record
|
|
TTL information. It MUST NOT be treated as proof of which name a particular flow
|
|
uses. A domain rule MUST NOT be applied to every connection to a shared CDN IP
|
|
merely because that domain appeared in a DNS answer. Without reliable domain
|
|
identity, domain rules do not match; IP/default rules and killswitch restrictions
|
|
remain in force. Precise domain routing uses FAKE.
|
|
|
|
FakeDNS MUST serve client DNS over both UDP and TCP. UDP upstream resolution MUST
|
|
support TCP retry to the same configured address and port when required by a
|
|
truncated reply. That retry is part of the same service exception. If no upstream
|
|
is configured, queries requiring one MUST fail rather than use an implicit public
|
|
resolver. Clearnet names may be resolved through the configured upstream even in
|
|
full mode; proxy-only overlay names MUST NOT be forwarded there.
|
|
|
|
Integration with `/etc/resolv.conf` MUST respect its owner, including
|
|
systemd-resolved or NetworkManager. The daemon MUST avoid recursion through its
|
|
own resolver and MUST restore only resolver state that it owns. This integration
|
|
does not capture arbitrary application DoH/DoT; those connections remain subject
|
|
to transport routing. The IPv4 profile MUST NOT publish synthetic AAAA records
|
|
or permit an unprotected IPv6 egress path.
|
|
|
|
### 6.2. FAKE publication
|
|
|
|
For a synthetic address response, FakeDNS MUST complete the following sequence:
|
|
|
|
1. Normalize the original name and evaluate its DNS policy and network class.
|
|
2. Find or allocate an address from the reserved `198.18.0.0/15` pool.
|
|
3. Commit the userspace mapping and kernel index, including mapping identity,
|
|
runtime epoch, network class, generation, and any available route hint.
|
|
4. Check publication success before returning the DNS answer.
|
|
|
|
If publication fails or the pool is exhausted, the DNS query MUST fail without a
|
|
REAL or DIRECT fallback. The pool MUST be checked for local LAN/VPN conflicts and
|
|
MUST be blocked from physical egress. An unknown fake IP MUST be blocked rather
|
|
than treated as a real address. DIRECT for a known fake IP still requires relay
|
|
to a resolved real destination.
|
|
|
|
The mapping does not assert that a proxy connection exists. Multiple flows to the
|
|
same fake IP, including different ports and transports, have separate upstream
|
|
state. DNS TTL does not bound an active flow's lifetime. An active flow pins its
|
|
mapping, and a fake address MUST NOT be reassigned to another name within the
|
|
runtime epoch even after its DNS TTL expires.
|
|
|
|
### 6.3. SIGHUP, reboot, and restart restrictions
|
|
|
|
Mappings and the REAL observation journal are in-memory runtime state. SIGHUP MUST
|
|
preserve them while validating and publishing a new policy generation. Preserving
|
|
a mapping does not preserve old access permissions: new flows use the new policy.
|
|
|
|
The supported lifecycle is boot, one daemon lifetime with SIGHUP reloads, then
|
|
system reboot. The journal and allocator start empty after reboot. Persistent
|
|
mapping storage is not required. Daemon stop/start or restart within a live client
|
|
session is unsupported; Section 10 defines init integration.
|
|
|
|
Blocking unknown fake IPs cannot detect a stale client answer if an unsupported
|
|
restart has already assigned that address to another domain. This is an explicit
|
|
lifecycle limitation, not a claim that resetting the allocator repairs client
|
|
caches. Gateway clients with independent lifetimes require an extension profile.
|
|
|
|
## 7. Kernel/userspace control contract
|
|
|
|
### 7.1. Logical state
|
|
|
|
| State | Key and value | Ownership and retention |
|
|
| --- | --- | --- |
|
|
| `RuntimeState` | Singleton: ABI version, host boot ID, runtime ID, active generation, lifecycle state, lease deadline | Daemon writes; no eviction |
|
|
| `PolicySnapshot` | Generation and selector/prefix to action, proxy ID, rule ID | Daemon publishes immutable snapshots |
|
|
| `FakeIndex` | Fake IP to mapping ID, runtime epoch, network class, route hint, generation | Daemon writes; no correctness-changing eviction |
|
|
| `FlowDecision` | Network namespace, address family, protocol, tuple, incarnation to action, generation, expiry | Backend declares one owner for each mutable field; cache entries MAY expire |
|
|
| `ProxyRegistry` | Proxy ID to dialer settings and capabilities | Userspace owns configuration |
|
|
| `Events` and `Counters` | Diagnostic reason, flow identity, generation; per-CPU statistics | Kernel produces; events MAY be lost |
|
|
|
|
The host boot ID and runtime ID are distinct: SIGHUP changes neither, while a new
|
|
process has a new runtime ID even on the same boot. Kernel state from a different
|
|
runtime MUST NOT restore old permissions. Unrecognized or mismatched ABI versions
|
|
MUST prevent readiness.
|
|
|
|
The backend MUST declare map types, capacities, key/value layouts, eviction
|
|
behavior, and mutable-field ownership in its versioned ABI descriptor. Shared
|
|
structures MUST use fixed-width fields, explicit padding, stable enum codes, and
|
|
specified byte order. Addresses and ports use network byte order; other local ABI
|
|
scalars use the descriptor's declared host order. Rust strings, pointers, and
|
|
ordinary Rust enum memory representations MUST NOT be copied as an implicit ABI.
|
|
Kernel and userspace MUST NOT perform unsynchronized read-modify-write updates
|
|
on the same composite value.
|
|
|
|
### 7.2. Hints, generations, and proxy readiness
|
|
|
|
A route hint is provisional. A stale generation MUST trigger current-policy
|
|
validation, not inheritance of old access. Network class or a fake mapping alone
|
|
MUST NOT mean that a proxy connection is ready.
|
|
|
|
In the base profile, the daemon owns `CONNECTING`, `ESTABLISHED`, and `CLOSED`
|
|
upstream state and both relay sockets. TC only needs the admission/delivery
|
|
verdict. A kernel relay extension MUST publish socket pairing and readiness per
|
|
flow only after its proxy handshake succeeds.
|
|
|
|
### 7.3. Event delivery
|
|
|
|
TCP `accept` and UDP reception are the mandatory triggers for userspace flow
|
|
handling. The data path MUST NOT require a reliable ring-buffer notification to
|
|
start a handshake. Ring buffers are diagnostic channels, not guaranteed RPC.
|
|
|
|
TC MUST NOT sleep waiting for userspace or attempt to buffer unbounded traffic
|
|
until a SOCKS reply arrives. Listener queues and pending handshakes MUST be bounded;
|
|
exhaustion results in failure. An extension introducing asynchronous policy RPC
|
|
MUST define request identity, deduplication, deadlines, capacity, and lost-event
|
|
behavior without weakening the base admission rules.
|
|
|
|
## 8. Transport behavior
|
|
|
|
### 8.1. TCP through SOCKS5
|
|
|
|
For `http://example.i2p`, with an explicit `.i2p -> FAKE + i2pd` rule:
|
|
|
|
```mermaid
|
|
sequenceDiagram
|
|
participant App as Application
|
|
participant DNS as FakeDNS
|
|
participant Maps as Mappings and BPF maps
|
|
participant K as TC and TPROXY
|
|
participant D as Listener and dialer
|
|
participant P as i2pd SOCKS5 proxy
|
|
|
|
App->>DNS: A example.i2p
|
|
DNS->>Maps: Commit fake IP, domain, I2P class, generation
|
|
Maps-->>DNS: Publication succeeds
|
|
DNS-->>App: Fake IPv4 address
|
|
App->>K: TCP connection to fake IP, port 80
|
|
K->>Maps: Validate runtime and classify destination
|
|
Maps-->>K: Intercept to transparent listener
|
|
K->>D: Accept connection with original destination
|
|
D->>Maps: Recover domain and validate current policy
|
|
D->>P: Negotiate SOCKS5 and CONNECT example.i2p:80
|
|
P-->>D: CONNECT success
|
|
App->>K: Application payload
|
|
K->>D: Deliver payload
|
|
D->>P: Relay payload after successful handshake
|
|
P-->>D: Response payload
|
|
D-->>App: Relay through accepted socket
|
|
```
|
|
|
|
The SOCKS request MUST carry the original domain for overlay and domain-based
|
|
proxy resolution, never the fake IP. Each TCP flow uses its own upstream SOCKS
|
|
CONNECT connection. A DNS query MUST NOT create a supposedly reusable universal
|
|
TCP tunnel to the domain.
|
|
|
|
An application handshake with the local listener can succeed before the upstream
|
|
CONNECT succeeds. Before proxy success, payload MUST remain bounded by buffering
|
|
limits or backpressure. On proxy error or timeout, NSC MUST close the flow without
|
|
DIRECT retry. Relay MUST preserve byte order, bidirectional backpressure, EOF,
|
|
and half-close behavior, and release mapping references when the flow ends.
|
|
|
|
### 8.2. UDP through SOCKS5
|
|
|
|
SOCKS5 UDP support is mandatory for the NSC implementation. The selected endpoint
|
|
must also support it; an unsupported endpoint causes a failed route rather than
|
|
DIRECT fallback.
|
|
|
|
On the first datagram, the daemon MUST recover the client and original destination,
|
|
evaluate current policy, and establish UDP ASSOCIATE over a TCP control connection.
|
|
It then sends SOCKS-encapsulated datagrams to the negotiated relay endpoint. The
|
|
association ends when the control connection closes, as specified by
|
|
[RFC 1928](https://www.rfc-editor.org/rfc/rfc1928.html).
|
|
|
|
Association state MUST include client identity and namespace, original destination,
|
|
generation, proxy ID, negotiated relay endpoint, and idle deadline. The base
|
|
profile uses a separate association per flow. Sharing is an optional optimization
|
|
that MUST preserve client isolation and response demultiplexing.
|
|
|
|
Replies MUST be accepted only from the authorized relay and matched to a tracked
|
|
flow. The daemon MUST decapsulate them and preserve the application's expected
|
|
peer identity. The relay endpoint and control socket receive narrow service
|
|
exceptions. Queues, datagram sizes, pending associations, and idle lifetimes MUST
|
|
be bounded. Overflow, timeout, invalid replies, and closed associations result in
|
|
drop or failure without implicit DIRECT retry.
|
|
|
|
SOCKS fragmentation is not implemented by this profile: `FRAG != 0` datagrams MUST
|
|
be dropped. This is distinct from IP fragment handling in Section 9. HTTP proxies
|
|
do not supply UDP in this version. ICMP and PMTU handling MUST be defined by the
|
|
backend without permitting arbitrary unrelated IP traffic.
|
|
|
|
### 8.3. HTTP proxies
|
|
|
|
HTTP endpoints use an explicit `http_mode`:
|
|
|
|
| Mode | Required behavior |
|
|
| --- | --- |
|
|
| `connect` | Send CONNECT for the original host and port; enter byte relay only after a successful 2xx response |
|
|
| `forward` | Adapt supported cleartext HTTP/1.1 requests to proxy absolute-form; reject incompatible traffic |
|
|
|
|
CONNECT is the default HTTP mode. A forward-only proxy MUST NOT be treated as a
|
|
general TCP tunnel. The forward adapter MUST validate request authority against
|
|
the original destination and policy, preserve valid message framing, and reject
|
|
an attempted authority change outside the admitted route. It MUST NOT assume that
|
|
TLS, arbitrary TCP, or UDP can be forwarded as plain HTTP. Unsupported protocols
|
|
or CONNECT rejection MUST fail explicitly without a different proxy or DIRECT
|
|
fallback unless a separate explicit policy authorizes that route.
|
|
|
|
HTTP CONNECT and HTTP/1.1 request formatting follow
|
|
[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-connect) and
|
|
[RFC 9112](https://www.rfc-editor.org/rfc/rfc9112.html#name-absolute-form).
|
|
|
|
## 9. Packet-path cost and flow correctness
|
|
|
|
Enforcement coverage and full policy computation are different costs. Every
|
|
possible application exit MUST be controlled, but domain/geodata evaluation MUST
|
|
NOT be repeated for every packet.
|
|
|
|
The fast path SHOULD check runtime/safety admission, validate a trusted service
|
|
exception if present, look up an existing flow decision, and then use compact
|
|
address/prefix policy. A complex miss goes to the transparent listener; an LRU
|
|
miss MUST NOT mean unconditional pass. Flow eviction MAY cause reevaluation or
|
|
failure, but MUST NOT broaden access.
|
|
|
|
A reused TCP 5-tuple MUST NOT inherit the previous connection's permission.
|
|
Backends MUST account for new SYNs, retransmissions, connection incarnation, and
|
|
closure using conntrack or an equivalently validated mechanism. Socket cookies
|
|
MAY be used where the hook exposes reliable socket identity. A tuple alone is
|
|
not an eternal flow identifier; TC parsing is not an implicit replacement for
|
|
conntrack.
|
|
|
|
IP fragments and unsupported headers MUST have an explicit bounded slow path or
|
|
be blocked. Failed parsing MUST NOT imply admission. Return directions and
|
|
service exceptions MUST be checked for interception loops.
|
|
|
|
## 10. Lifecycle, publication, and failure
|
|
|
|
### 10.1. Startup and readiness
|
|
|
|
The lifecycle states are `STARTING`, `READY`, `DEGRADED`, and `STOPPING`.
|
|
|
|
Startup MUST install the independent protected egress guard before enabling
|
|
application interception, initialize ABI-compatible state, create listeners,
|
|
prepare policy and DNS, and verify the packet path. System DNS integration MUST
|
|
be enabled only when mappings and listeners can serve the selected profile.
|
|
READY MUST be published only after the entire path is usable.
|
|
|
|
A partial installation MUST roll back owned changes while retaining the required
|
|
protected default. Graceful shutdown MUST NOT temporarily open clearnet.
|
|
|
|
### 10.2. SIGHUP and policy generations
|
|
|
|
SIGHUP MUST validate the complete new configuration and construct an immutable
|
|
snapshot before publication. Failed validation MUST leave the active policy and
|
|
mapping journal unchanged. Successful reload MUST publish one active generation;
|
|
several unrelated map updates MUST NOT be treated as an atomic transaction.
|
|
|
|
Each decision MUST use a consistent generation. Old snapshots MUST remain until
|
|
readers and dependent flows no longer need them. nftables and BPF changes MUST be
|
|
staged with a temporary admission barrier if the backend cannot otherwise ensure
|
|
consistent enforcement.
|
|
|
|
New flows use the new generation. Existing flows retain their route by default;
|
|
they MUST NOT be migrated to another proxy midstream. Tightened killswitch or
|
|
explicit emergency revocation MUST override cached admission and close or block
|
|
affected flows. Mapping identity remains stable even when routing permission
|
|
changes.
|
|
|
|
### 10.3. Lease and service failure
|
|
|
|
The daemon MUST renew a monotonic runtime lease. The kernel MUST check expiry
|
|
independently of diagnostic event delivery and block new application flows when
|
|
the lease expires. Cached state MUST NOT override a revoked safety condition.
|
|
Detaching TC MUST NOT remove the independent firewall protection.
|
|
|
|
Proxy failure, handshake timeout, map exhaustion, listener overload, and daemon
|
|
failure MUST NOT silently convert a protected flow to DIRECT. Failures MUST be
|
|
observable through counters or structured diagnostics; event loss MUST NOT
|
|
change enforcement.
|
|
|
|
### 10.4. Init contract
|
|
|
|
Init MUST start NSC at boot and MUST NOT automatically restart it after exit or
|
|
failure. A systemd deployment MUST use `Restart=no`. This setting controls
|
|
automatic restarts, so packaging and operations MUST also exclude manual restart,
|
|
stop/start, dependency reactivation, and socket activation within the same live
|
|
client session.
|
|
|
|
Configuration changes use SIGHUP/reload. Binary replacement takes effect at the
|
|
next system boot; package hooks MUST NOT restart the current process. After a
|
|
crash, the firewall protection remains and normal recovery is a system reboot.
|
|
|
|
Reload MUST preserve runtime identity and mappings. Sockets remain open except
|
|
where the new safety policy requires closure. Init integration MUST distinguish
|
|
signal delivery from completed reload and expose the reload result.
|
|
|
|
## 11. Conformance and implementation profiles
|
|
|
|
### 11.1. Required verification
|
|
|
|
A conforming backend MUST verify the following in isolated network namespaces or
|
|
an equivalent controlled environment, including packet capture of physical egress:
|
|
|
|
| Area | Required evidence |
|
|
| --- | --- |
|
|
| DNS defaults | REAL is the default; an explicit `.i2p` FAKE rule selects i2pd; no implicit FAKE fallback |
|
|
| Publication | Mapping and classification are visible before the fake DNS answer; DNS does not send CONNECT |
|
|
| Identity | Shared real IPs do not inherit unrelated domain policy; concurrent flows retain distinct ports and upstream state |
|
|
| Interception | Local OUTPUT reaches TC ingress and TPROXY for TCP and UDP; egress marking is not assumed to reroute |
|
|
| Synthetic pool | Unknown fake IPs and physical pool egress are blocked; capacity exhaustion fails safely |
|
|
| Killswitch | Full blocks clearnet application destinations even through exits/outproxies; allow-proxy requires configured proxies |
|
|
| Service exceptions | Configured DNS upstream works in full; other application traffic to that endpoint does not inherit its exemption; overlay names never reach it |
|
|
| Direct exceptions | Only the selected explicit rule overrides killswitch; mandatory backend constraints remain effective |
|
|
| TCP | Payload ordering, backpressure, half-close, handshake failure, timeout, and cleanup are correct |
|
|
| UDP | ASSOCIATE, response validation, control-socket closure, idle expiry, queue overflow, and `FRAG != 0` behave as specified |
|
|
| HTTP | CONNECT and forward modes are distinguished; unsupported traffic and authority changes are rejected |
|
|
| Cache correctness | Reused tuples, SYN retransmissions, eviction, IP fragments, and reload do not bypass policy |
|
|
| Runtime | SIGHUP preserves mappings; failed reload preserves policy; init does not restart on crash; reboot discards runtime state |
|
|
| Coverage | IPv6, QUIC, external DNS, and return paths cannot bypass the selected protected profile |
|
|
|
|
### 11.2. Deployment descriptor
|
|
|
|
Each supported backend MUST publish a deployment descriptor containing its kernel
|
|
requirements, TC attachment points, firewall hook order, mark allocation, routing
|
|
tables, listener bindings, trusted identities, ABI layouts, map capacities, queue
|
|
limits, handshake deadlines, UDP size/idle limits, and lease renewal/expiry values.
|
|
These are implementation parameters, not alternative routing semantics. Missing
|
|
requirements or unsupported mandatory capabilities MUST prevent readiness.
|
|
|
|
### 11.3. Performance validation
|
|
|
|
Implementations SHOULD measure DIRECT, BLOCK, and PROXY separately: new flows per
|
|
second, throughput, p50/p99 connection latency, CPU per packet, map misses, and
|
|
memory. Comparisons SHOULD include the host baseline, firewall-only enforcement,
|
|
TC with cached decisions, and the complete userspace proxy path. Kernel relay
|
|
SHOULD be considered only after measurements establish a useful improvement.
|
|
|
|
## 12. References
|
|
|
|
- [Linux transparent proxy support](https://docs.kernel.org/networking/tproxy.html): TPROXY, policy routing, and transparent sockets.
|
|
- [Linux BPF UAPI](https://code.googlesource.com/linux/torvalds/linux/+/7b1b868e1d9156484ccce9bf11122c053de82617/include/uapi/linux/bpf.h): TC ingress socket assignment as an optional delivery backend.
|
|
- [Linux SOCKMAP and SOCKHASH](https://docs.kernel.org/bpf/map_sockmap.html): optional socket relay offload.
|
|
- [RFC 1928](https://www.rfc-editor.org/rfc/rfc1928.html): SOCKS5 CONNECT, UDP ASSOCIATE, and UDP encapsulation.
|
|
- [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-connect): HTTP CONNECT.
|
|
- [RFC 9112](https://www.rfc-editor.org/rfc/rfc9112.html#name-absolute-form): HTTP/1.1 forward proxy request formatting.
|
|
- [systemd.service](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html): restart policy and reload completion.
|