Compare commits
No commits in common. "f4b1fce0ad9c70f10a68e4e1d40cae7aa2e30ed7" and "5502f216058a7619a499ff5efdaeed7bfdf35649" have entirely different histories.
f4b1fce0ad
...
5502f21605
5 changed files with 38 additions and 890 deletions
|
|
@ -1,5 +1,4 @@
|
|||
# nsc (Network security control)
|
||||
A kernel-space traffic routing engine featuring overlay network integration, Xray-core GeoDB compatibility, a network kill switch, and advanced policy-based routing.
|
||||
# nsc (Network security control) - clearnet killswitch, smart L7 traffic routers collection and much more
|
||||
|
||||
<div align = "center">
|
||||
|
||||
|
|
@ -23,8 +22,6 @@ A kernel-space traffic routing engine featuring overlay network integration, Xra
|
|||
|
||||
**The current project spec**: [click](https://anthrill.namily.tech/how.html#nsc)
|
||||
|
||||
**Routing documentation**: [Overview](doc/HOW_WORKS_ROUTING.md) · [Specification](doc/ROUTING_DEV.md)
|
||||
|
||||
Our resources:
|
||||
- http://anthrill.i2p (about, docs, wiki)
|
||||
- https://namily.tech (VPN, docs, wiki mirrors)
|
||||
|
|
|
|||
|
|
@ -1,40 +1,12 @@
|
|||
# NSC Routing Overview
|
||||
# Basic NSC routing principles
|
||||
|
||||
NSC transparently routes local application traffic by domain/geosite, destination
|
||||
IP/geoip, and overlay namespace. The normative behavior is defined in the
|
||||
[NSC Routing Specification](ROUTING_DEV.md), including its
|
||||
[architecture diagram](ROUTING_DEV.md#22-architecture-diagram).
|
||||
NSC implements its own DNS server, which resolves domains according to the configured routing policies.
|
||||
|
||||
The NSC DNS service is called FakeDNS, but its default mode is **REAL**: it returns
|
||||
answers from an authorized resolver without substituting synthetic addresses.
|
||||
Rules can explicitly select **FAKE** or **BLOCK** for matching names. This keeps
|
||||
ordinary DNS compatible with applications that reject synthetic answers.
|
||||
The current sniffing-based routing flow works as follows:
|
||||
|
||||
With a `.i2p -> FAKE + i2pd` routing rule, opening `http://example.i2p` works as follows:
|
||||
* The user enters a domain in their browser, for example `http://reg.i2p`.
|
||||
* The NSC FakeDNS server responds with an address from the [RFC 2544](https://www.rfc-editor.org/info/rfc2544/) benchmarking address space (`198.18.0.0/15`) and stores the corresponding `domain:IP` mapping.
|
||||
* When the application attempts to connect to the assigned IP address, NSC intercepts the connection and looks up the original domain using the stored mapping.
|
||||
* NSC then establishes a connection to the appropriate overlay network proxy (mostly SOCKS) and forwards the intercepted traffic through it. Supported interception backends include TPROXY and eBPF.
|
||||
* Responses from the overlay network are forwarded back to the original application as if it were communicating directly with the resolved address.
|
||||
|
||||
1. The application sends an ordinary DNS query. FakeDNS recognizes the I2P namespace,
|
||||
allocates an address from `198.18.0.0/15`, and records the original domain.
|
||||
2. Before replying, FakeDNS publishes the mapping, I2P classification, and route
|
||||
hint to kernel-visible BPF maps. No SOCKS CONNECT is sent at DNS time.
|
||||
3. The application connects to the fake address and destination port. OUTPUT policy
|
||||
routing, TC ingress, and TPROXY deliver the flow to an NSC transparent listener.
|
||||
4. The daemon recovers `example.i2p`, checks the current policy and killswitch, and
|
||||
sends SOCKS5 CONNECT with the original domain and actual destination port.
|
||||
5. After proxy success, the daemon relays bytes in both directions. UDP uses a
|
||||
separate SOCKS5 UDP ASSOCIATE lifecycle. HTTP proxies use an explicit CONNECT
|
||||
or cleartext HTTP forward mode.
|
||||
|
||||
TC performs compact packet and flow checks; complex domain/geodata policy remains
|
||||
in userspace. TPROXY supplies local delivery, while the base payload relay runs
|
||||
in userspace. Kernel payload relay is an optional extension.
|
||||
|
||||
When the killswitch is enabled, **full** permits only overlay application
|
||||
destinations; **allow-proxy** additionally permits clearnet through proxies
|
||||
configured in NSC. Narrow trusted service exceptions cover required proxy/overlay
|
||||
transports and explicitly configured DNS upstreams, including in full mode.
|
||||
Overlay names are never sent to a public DNS upstream. A direct application
|
||||
exception must be explicit in a routing rule.
|
||||
|
||||
Mappings survive SIGHUP reloads. The supported lifecycle is one daemon process
|
||||
from system boot until reboot, with no live-session restart. After reboot the
|
||||
in-memory journal is discarded and allocation starts from scratch.
|
||||
|
|
|
|||
|
|
@ -1,681 +0,0 @@
|
|||
# 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.
|
||||
157
src/config.rs
157
src/config.rs
|
|
@ -1,56 +1,47 @@
|
|||
use crate::geoparsers::geoip2::Rules;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum KillSwitchPolicy {
|
||||
#[serde(rename = "allow-proxy")]
|
||||
#[serde(alias = "allow-proxy")]
|
||||
AllowProxies,
|
||||
#[serde(rename = "full")]
|
||||
#[serde(alias = "full")]
|
||||
Strict,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum ClearnetPolicy {
|
||||
#[serde(rename = "killswitched")]
|
||||
Killswitched,
|
||||
#[serde(rename = "allowed")]
|
||||
#[serde(alias = "killswitched")]
|
||||
Killwitched,
|
||||
#[serde(alias = "allowed")]
|
||||
Allowed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Policy {
|
||||
pub clearnet: Option<ClearnetPolicy>,
|
||||
pub killswitch_mode: Option<KillSwitchPolicy>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Proxy {
|
||||
pub alias: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
/// Paths to `geolite2.mmdb`, `geosite.dat`.
|
||||
/// Paths to `geosite.dat', `geolite2.mmdb`
|
||||
pub geo_files: [String; 2],
|
||||
/// Path used by the legacy separate rules loader.
|
||||
/// Routing settings similar to v2ray
|
||||
pub routing: String,
|
||||
#[serde(rename = "rule")]
|
||||
pub rules: Rules,
|
||||
#[serde(rename = "proxy")]
|
||||
pub proxies: Vec<Proxy>,
|
||||
/// Clearnet routing policies
|
||||
pub policy: Option<Policy>,
|
||||
}
|
||||
|
||||
impl FromStr for Config {
|
||||
type Err = toml::de::Error;
|
||||
|
||||
fn from_str(data: &str) -> Result<Self, Self::Err> {
|
||||
toml::from_str(data)
|
||||
}
|
||||
}
|
||||
// TODO: Think how to add other anonymisers
|
||||
// Like VPN on localhost:10808
|
||||
// it can be like:
|
||||
// ```toml
|
||||
// [[proxy]]
|
||||
// name = "VPN"
|
||||
// addr = "127.0.0.1:10808"
|
||||
// type = "SOCKS5" # ...
|
||||
// ```
|
||||
//
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
|
|
@ -60,8 +51,6 @@ impl Default for Config {
|
|||
String::from("/var/nsc/geodata/geosite.dat"),
|
||||
],
|
||||
routing: String::from("/etc/nsc/routing.toml"),
|
||||
rules: Vec::new(),
|
||||
proxies: Vec::new(),
|
||||
policy: Some(Policy {
|
||||
clearnet: Some(ClearnetPolicy::Allowed),
|
||||
killswitch_mode: Some(KillSwitchPolicy::AllowProxies),
|
||||
|
|
@ -69,105 +58,3 @@ impl Default for Config {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::geoparsers::geoip2::{RouteAction, RouteType};
|
||||
|
||||
#[test]
|
||||
fn parses_inline_rules_proxies_and_policy() {
|
||||
let data = r#"
|
||||
[[rule]]
|
||||
action = "block"
|
||||
target = "geosite:category-ads-all"
|
||||
|
||||
[[rule]]
|
||||
action = "block"
|
||||
target = "geosite:win-spy"
|
||||
|
||||
[[rule]]
|
||||
action = "proxy"
|
||||
proxy_name = "xray"
|
||||
target = "clearnet"
|
||||
|
||||
[[proxy]]
|
||||
alias = "xray"
|
||||
url = "socks5://localhost:10808"
|
||||
|
||||
[[proxy]]
|
||||
alias = "i2p_outproxy"
|
||||
url = "http://localhost:4444"
|
||||
|
||||
[policy]
|
||||
clearnet = "killswitched"
|
||||
killswitch_mode = "allow-proxy"
|
||||
"#;
|
||||
let config: Config = data.parse().unwrap();
|
||||
assert_eq!(config.rules.len(), 3);
|
||||
assert_eq!(config.rules[0].action, RouteAction::Block);
|
||||
assert_eq!(
|
||||
config.rules[0].target,
|
||||
RouteType::GeoSite("category-ads-all".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
config.rules[1].target,
|
||||
RouteType::GeoSite("win-spy".to_owned())
|
||||
);
|
||||
assert_eq!(config.rules[0].proxy_name, None);
|
||||
assert_eq!(config.rules[2].action, RouteAction::Proxy);
|
||||
assert_eq!(config.rules[2].target, RouteType::Clearnet);
|
||||
assert_eq!(config.rules[2].proxy_name.as_deref(), Some("xray"));
|
||||
assert_eq!(config.proxies.len(), 2);
|
||||
assert_eq!(config.proxies[0].alias, "xray");
|
||||
assert_eq!(config.proxies[0].url, "socks5://localhost:10808");
|
||||
assert_eq!(config.proxies[1].alias, "i2p_outproxy");
|
||||
assert_eq!(config.proxies[1].url, "http://localhost:4444");
|
||||
assert_eq!(
|
||||
config.policy,
|
||||
Some(Policy {
|
||||
clearnet: Some(ClearnetPolicy::Killswitched),
|
||||
killswitch_mode: Some(KillSwitchPolicy::AllowProxies),
|
||||
})
|
||||
);
|
||||
let serialized = toml::to_string(&config).unwrap();
|
||||
assert_eq!(serialized.parse::<Config>().unwrap(), config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_direct_geoip_and_full_killswitch() {
|
||||
let config: Config = r#"
|
||||
[[rule]]
|
||||
action = "direct"
|
||||
target = "geoip:RU"
|
||||
|
||||
[policy]
|
||||
clearnet = "allowed"
|
||||
killswitch_mode = "full"
|
||||
"#
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert_eq!(config.rules[0].action, RouteAction::Direct);
|
||||
assert_eq!(config.rules[0].target, RouteType::GeoIp("RU".to_owned()));
|
||||
assert!(config.proxies.is_empty());
|
||||
assert_eq!(
|
||||
config.policy.unwrap().killswitch_mode,
|
||||
Some(KillSwitchPolicy::Strict)
|
||||
);
|
||||
assert_eq!(config.geo_files, Config::default().geo_files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_enum_values_and_empty_targets() {
|
||||
for data in [
|
||||
"[[rule]]\naction = 'unknown'\ntarget = 'clearnet'",
|
||||
"[[rule]]\naction = 'block'\ntarget = 'unknown'",
|
||||
"[[rule]]\naction = 'block'\ntarget = 'geosite:'",
|
||||
"[[rule]]\naction = 'block'\ntarget = 'geoip:'",
|
||||
"[policy]\nclearnet = 'unknown'",
|
||||
"[policy]\nkillswitch_mode = 'unknown'",
|
||||
] {
|
||||
assert!(data.parse::<Config>().is_err(), "accepted {data}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use crate::config::Config;
|
||||
use maxminddb::{Reader, geoip2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
use std::net::IpAddr;
|
||||
|
||||
// For now only MMDB because i cant found .proto schemes of
|
||||
|
|
@ -9,61 +9,34 @@ use std::net::IpAddr;
|
|||
|
||||
/// Interface enum for `dst_addr` info
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub enum RouteType {
|
||||
/// GeoSite type, like `category-ads-all`
|
||||
GeoSite(String),
|
||||
/// Result with GeoCode like "RU"
|
||||
GeoIp(String),
|
||||
Clearnet,
|
||||
// String because enum will used as interface in result of `route_packet`.
|
||||
}
|
||||
|
||||
impl TryFrom<String> for RouteType {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
if value == "clearnet" {
|
||||
return Ok(Self::Clearnet);
|
||||
}
|
||||
match value.split_once(':') {
|
||||
Some(("geosite", name)) if !name.is_empty() => Ok(Self::GeoSite(name.to_owned())),
|
||||
Some(("geoip", name)) if !name.is_empty() => Ok(Self::GeoIp(name.to_owned())),
|
||||
_ => Err(format!("invalid rule target: {value}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RouteType> for String {
|
||||
fn from(target: RouteType) -> Self {
|
||||
match target {
|
||||
RouteType::GeoSite(name) => format!("geosite:{name}"),
|
||||
RouteType::GeoIp(name) => format!("geoip:{name}"),
|
||||
RouteType::Clearnet => "clearnet".to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Routing actions
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub enum RouteAction {
|
||||
#[serde(alias = "block")]
|
||||
Block,
|
||||
#[serde(alias = "proxy")]
|
||||
Proxy,
|
||||
#[serde(alias = "direct")]
|
||||
Direct,
|
||||
}
|
||||
|
||||
pub type Rules = Vec<Rule>;
|
||||
|
||||
/// Type for deserializing the routing rules like:
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Rule {
|
||||
pub target: RouteType,
|
||||
pub action: RouteAction,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_name: Option<String>,
|
||||
}
|
||||
|
||||
pub struct GeoIpService {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue