24 Commits
Author SHA1 Message Date
Zakk f0924d0952 fix(iptables): spell out the DNS redirect priority for older nftables
nftables 1.0.2, which Ubuntu 22.04 ships, rejects the dstnat keyword on
the output hook ("invalid priority expression value in this context"),
so the DNS redirect table failed to load and the core did not start in
redirect mode. Write the same priority as -101; nftables 1.1.7 lists it
back as "dstnat - 1".

Fixes #2133
2026-11-19 22:20:21 +11:00
Markson Hon 2dd4d683cc Merge pull request #2057 from wywywywycloud/fix/openwrt-lan-bridge-tproxy
fix(openwrt): include LAN bridges in TPROXY by default
2026-11-13 08:51:46 +08:00
HougeLangley 7f03ed9953 iptables: fall back to nft when legacy mangle is unavailable
Auto mode previously trusted the iptables userspace backend alone. On PREEMPT_RT kernels, legacy xtables is unavailable even when the legacy iptables binary is installed. Probe the mangle table read-only and select nft only for the specific missing-table failure. Add regression coverage for backend detection and conservative error handling.
2026-11-05 17:13:51 +08:00
ILIKEFUTANARI e010d19a5d feat: add DNS interception opt-out 2026-10-09 17:43:48 +08:00
Mikhail Levin 5ec0451a66 fix(openwrt): limit fatal DNS redirect setup to Linux proxy modes 2026-10-01 13:05:11 +03:00
Mikhail Levin 392b1c7942 fix(openwrt): make nft DNS redirect idempotent and preserve legacy startup 2026-10-01 01:01:05 +03:00
Mikhail Levin 75ac824b43 fix(openwrt): install native nftables DNS redirects 2026-09-29 21:10:54 +03:00
Mikhail Levin 58af604a99 fix(openwrt): clarify bridge exclusions and retire obsolete flag 2026-09-25 20:26:43 +03:00
Zakk 8b818ffc41 fix(iptables): match the transparent-proxy whitelist with ipset
The iptables path wrote each whitelisted CIDR with its own iptables
process. With the mainland China group (about 15,000 CIDRs) a core start
spent minutes on this, and every packet of a direct connection walked
the list linearly.

Load each family into one hash:net set with a single `ipset restore` and
match it with one rule at the old position. Without ipset, write the
rules with one `iptables-restore --noflush` per family; without that,
keep the per-rule commands. Cleanup destroys the sets.
2026-09-24 01:23:08 +10:00
Zakk 2d16a92bbb fix(service): the findings of a cold read of the refactor and the scan fixes
Deleting nodes stored the renumbered connections, the subscriptions and
the servers in three commits; they are one transaction. Without a
catch-all DNS rule the module keeps its own fallback, as every earlier
release did. The login body is capped at 4 KiB, since it is now read
before the one-at-a-time semaphore. The apply-config error names a
failed restore, so every handler's message says whether the previous
value came back. The Windows system proxy reuses a snapshot pending
from an earlier run instead of refusing to start.
2026-09-20 09:59:29 +10:00
Zakk 6d744139d4 fix(windows): the system proxy restores every user profile to its own settings
When elevated, saveProxyState captured the first readable profile's
proxy values and stopped, then the restore wrote those values into
every profile: users with different proxy settings got the first
user's, or none. The snapshot now holds one entry per SID (the current
user under "" when not elevated); restore writes each profile its own
values, a profile written at setup but not captured is left with the
proxy disabled, and a snapshot from an earlier release (one flat
profile) still restores the way it did.
2026-09-20 09:59:29 +10:00
Zakk ad509ce51b fix(service): the confirmed findings of four independent backend scans
A custom latency test URL that http.NewRequest rejects made a spawned
goroutine dereference nil and exit the process; the URL is validated
before any goroutine starts and the request error is handled. A
Shadowsocks link whose plugin field has no ";" panicked the parser, and
from the automatic subscription update that goroutine was unrecovered;
the parser accepts it and each updater recovers and logs.

The DNS module took the last non-bootstrap upstream as the fallback
while the template emitted upstreams in rule order with deduplication,
so a catch-all rule anywhere but last, or one whose upstream was
deduplicated, was not the fallback. The template names the fallback in
a new default_upstream field and the module honours it.

PUT /routingA stored the rules without regenerating the running core.
It goes through ApplyCoreConfig like the other config writers, with
restore on failure. UpdateSubscription logged a failed core reload and
answered success; it returns the error. PATCH /subscription joins the
mutation turn.

Subscription fetching retried through a direct connection when the
selected proxy failed, leaking the subscription URL; it returns the
error. Subscription documents are capped at 32 MiB and downloaded
assets at 256 MiB. PUT /gfwList validates the downloaded file as a
geosite list before replacing the working one.

The login handler took its one-at-a-time semaphore before reading the
body, so a client sending headers and no body blocked every login; the
body is read first and the HTTP server has header and idle timeouts.

Share links: a VLESS or VMess link without a numeric port is rejected
at parse time instead of producing port 0; an SSR link with a password
that is not base64 is rejected instead of importing empty; the SIP003
path gets its leading slash prepended, not a trailing one appended.

The macOS system proxy quoted shell arguments with strconv.Quote,
which leaves $(...) live; values are single-quoted. The Windows system
proxy snapshot includes AutoConfigURL, which teardown deleted and never
restored. Latency test responses with a non-2xx status are closed. The
version response carries the docker flag the GUI's port hints read.
2026-09-20 09:59:29 +10:00
Zakk d537477a1c fix(service): the findings of a cold read of the upgrade and crash-recovery changes
A SQLite file that an earlier release's migration left empty next to an
intact bolt.db was taken as authoritative; a file without the system
settings a completed migration writes is discarded and the migration
runs again. A database migrated by that earlier release holds its
groups and outbound settings in the two tables the runtime never read;
opening it copies them into the keys it reads, for outbounds that have
none yet.

A start whose host-state recovery failed refused to run, and a start
that rolled back after its own stop tore the host state down a second
time; recovery is logged and retried at the next start, and a rollback
that stopped its process only clears the marker. A system-proxy
snapshot pending from an earlier run blocked every later system-proxy
start; it is reused as the original instead (Linux and macOS here; the
Windows side follows with its per-profile snapshot).

An empty /etc/resolv.conf was backed up as an empty file, which the
restore rejects as truncated; it is written as a marker and restored as
empty. db.Close resets the once so a reopen works.
2026-09-20 09:17:58 +10:00
Zakk 58acf7d40f fix(service): a start that never commits leaves nothing behind on the host
Start persisted running=false, stopped the old core, published the new
process and unlocked, installed the firewall rules, DNS hijack, TUN
routes or system proxy, and only then persisted running=true. A crash in
that window made the next start skip the core and clean only TUN
residue, so redirect rules, a hijacked resolver or the system proxy kept
pointing at a dead listener.

Before it installs anything, Start now stores a host-state marker (the
transparent type, API port and TUN teardown settings) and clears it once
the start commits or is rolled back; startup and the next Start tear
that state down when they find the marker. Every host mutation and the
final commit check that the process they started is still the manager's
current one, so a core that exits during afterStart fails the start
instead of leaving the UI and the store saying running. The system-proxy
implementations persist the user's original proxy settings when they
capture them and restore from that copy when the in-memory one is gone.
A recovery that fails is logged and retried at the next start; it never
blocks the service.
2026-09-20 09:17:11 +10:00
Zakk 1dd2bf28ad feat(service): the tun transparent proxy is the core's own device
transparentType=tun no longer starts the TinyTun process. The template
emits a tun-mips inbound tagged transparent — device name, address, MTU,
the DNS module's address as the relay target, the user's exclusion list
plus v2rayA and the core by name and v2rayA by PID — and the service does
what the operating system needs once the core has the device up.

On Linux that is one table and four policy rules: table 2020 holds the
default route into tun0; marked packets (0x80: the core's sockets, the
direct outbound, the DNS module's upstreams) look up main in full and
leave through the physical interface, or fail with ENETUNREACH when main
has no route for their family rather than fall into the TUN; unmarked
packets take main with its default route suppressed, so LAN and static
routes stay physical, and everything else goes to table 2020. The main
table is never edited, so stopping restores egress by itself. A rule in
our preference range or a route in our table that is not ours is reported
and left alone; our own leftovers from a crash are removed first. Every
command that succeeded is recorded and undone in reverse on stop.

Three things the TinyTun path never hit are now on tun's path, so they
are fixed here: the DNS module is generated in tun mode (TinyTun did DNS
itself); its 127.2.0.17:53 listener is only added when port 53 is free,
instead of making the core exit on a host running another resolver; its
primary listener stays on loopback unless port sharing is on or the user
chose an address, and the DNS REDIRECT rules and their cleanup follow the
module's port instead of a hard-coded 52353, and a ::1 listener is added
when IPv6 is supported, because ip6tables REDIRECT delivers an
application's IPv6 query to ::1 which the IPv4 listener never saw. The
tun branch no longer
skips those rules: they are what catches queries to a LAN resolver, which
the routing keeps off the TUN.

The connectivity monitor probes the core's API port; the TinyTun socks
loop-back port it used is gone. Removed with TinyTun: --tinytun-bin, the
tunProcessBackend (eBPF) and tunBypassInterfaces settings (connected and
static routes bypass the TUN unconditionally now), the /networkInterfaces
endpoint that only served the latter, and the build tag. The version
endpoint reports tunSupported instead of tinytunSupported.

Tests cover the generated inbound and DNS module, the listen-address
rules, the redirect port, and — with V2RAYA_CORE_BIN set — that the
generated document loads in the real core. Windows and macOS route
handling follows in a separate commit; until then those builds report
the TUN as unsupported.
2026-09-19 10:34:55 +10:00
Zakk 6e09c172db fix(transparent): restore the redirect ingress wildcard, trim whitelist IPs, keep DNS readiness advisory
Three regressions from the previous transparent-proxy commit:

- the redirect ingress rules lost the "*" to "+" translation, so an excluded
  interface pattern such as docker* stopped matching and Docker traffic was
  redirected; the egress rules and both tproxy directions still translated it;
- the whitelist now parses its entries, and the GUI submits the textarea lines
  as typed, so a pasted CIDR with surrounding whitespace aborted the whole
  setup where the shell used to swallow it;
- the DNS readiness probe resolves a name, so a dead or slow upstream failed it
  even with the listener up, and the core could no longer start at all. The
  probe is now advisory: it still waits when DNS is healthy, but a failure is
  logged instead of aborting the start.
2026-09-18 05:07:03 +10:00
Zakk a4c0a5a37c fix(transparent): validate rule inputs, real DNS readiness probe, rule cleanup
Interface names and whitelist IPs from the settings were interpolated
into iptables/nft command text run through sh -c; they are now validated
(interface names may still use the "*" wildcard, translated to "+" for
iptables) and rejected with a message naming the value. nftTproxy emitted
"elements = { }" for an empty whitelist, an nft syntax error that failed
the whole setup. waitForDnsPort dialed UDP, which succeeds without a
listener; it now sends a DNS query and waits for an answer. The resolv
hijacker's ticker goroutine never exited because Stop does not close the
channel. A failing transparent pre-stop hook skipped rule deletion and
left the tproxy chains and resolv hijack behind. The DNS REDIRECT rules
ran through raw ExecCommands instead of the iptables backend setter, so
nft-only hosts silently skipped them. On darwin/BSD sysctl was invoked
with the whole command line as the program name.
2026-09-18 02:53:32 +10:00
xuweizhi 22856c189a fix(iptables): add protocol to DNS_REDIRECT redirect rules
iptables requires -p tcp or -p udp when using the REDIRECT target with
--to-port. The generated rule lacked the protocol match, so on legacy
iptables the command failed with "Need TCP, UDP, SCTP or DCCP with port
specification", aborting transparent proxy startup entirely.
2026-08-26 19:39:17 +08:00
zhangthree78 525654ec9b fix: prevent DNS redirect loop causing unbounded memory growth
Fixes defects in the v2.4.8+ transparent-proxy DNS path that cause the
core to exhaust memory within seconds on low-RAM hosts (see discussion
#1915: '2.4.9 内存占用过高' / '有严重的内存泄漏,别用了。本地DNS完全废掉了'):

1. core/dns: upstream queries from NewUpstreamManager /
   GetOrCreateUpstream / getClientForProtocol used bare &dns.Client{}
   with no Dialer configured, so their sockets never carried
   SO_MARK=0x80. The unmarked queries were hijacked by the module's own
   transparent-proxy DNS redirect rules and looped back into :52353 —
   an infinite self-query loop and memory snowball.

2. service/kernel/v2ray/transparent.go: the unconditional DNS hijack
   rules (REDIRECT --to-port 52353) had no fwmark-0x80 exemption, and
   being inserted with -I they sat at the head of nat OUTPUT/PREROUTING,
   so marked traffic was looped back as well.

3. core/dns: per-query info logging (query/route/upstream) produced
   thousands of lines/second under load, amplifying CPU/IO/memory
   pressure.

Fix:
- Route every upstream client through newMarkedDnsClient, whose
  net.Dialer sets SO_MARK=0x80 on all sockets. miekg/dns dials UDP
  through net.Dialer too, so Dialer.Control covers UDP sockets — no
  manual socket path is needed. UDPSize=4096 keeps a sane receive
  buffer for queries without an EDNS0 OPT record.
- Append the DNS redirects with -A and insert the mark exemption with
  -I so the exemption is matched first; also delete the exemption
  rules in the residual-rule cleanup so they don't accumulate across
  restarts.
- redirect mode: insert the DNS_REDIRECT jumps after the TP_PRE/TP_OUT
  jumps so they actually take precedence (-I inserts at chain head),
  keeping local and LAN TCP DNS flowing to the DNS module (:52353)
  instead of the proxy inbound (:52345).
- Gate per-query info logs behind V2RAYA_DNS_DEBUG=1; error logs stay
  always visible.

Verified: unpatched v2.4.11 core RSS 230MB->1GB in ~6s then OOM/hang;
patched build stable at ~25MB idle / ~243MB loaded, DNS and SOCKS proxy
working.
2026-08-16 23:59:43 +08:00
Xing Shi CaiandClaude Fable 5 cfe0e877a0 🐛 (iptables): Exempt DNS module port from generic TPROXY hijack
Locally originated DNS queries are marked 0x40 by DNS_MARK in mangle OUTPUT, then nat OUTPUT REDIRECT rewrites their destination port from 53 to 52353. When the packet re-enters PREROUTING via loopback, the dport-53 TPROXY rule no longer matches, so the generic mark-0x40 rule diverts it to the transparent proxy port 52345 where it is dropped. All local UDP DNS times out and transparent proxy appears completely broken (TCP DNS survives because the proxied connection still reaches 52353).

Add TP_PRE RETURN rules for dport 52353 ahead of the TPROXY rules in the legacy IPv4, legacy IPv6, and nftables variants so already-redirected DNS traffic is delivered to the DNS module untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 10:48:41 +08:00
Markson Joe Hon 1bcd63eb1f fix(iptables): resolve firewall rule bugs and improve cleanup reliability
- Fix nftTproxy.GetCleanCommands using wrong table name ('ip' instead of
  'inet') when IPv6 is disabled, causing nftables table to persist after
  teardown
- Fix legacyRedirect.RemoveIPWhitelist not handling IPv6 CIDRs (always
  used iptables even for IPv6 addresses, causing silent delete failure)
- Suppress errors in ip rule/route del cleanup commands with
  2>/dev/null || true (applies to both legacy and nft TProxy modes)
- Normalize mixed tab/space indentation in nftRedirect's tp_rule chain
  for consistency
2026-07-22 13:09:01 +08:00
Markson Pigeonzilla Plus 1fdeb62bbe fix(windows): fix type mismatch in readRegistryProxyState
k.GetIntegerValue() returns uint64 on Windows, but proxyEnable was
declared as uint32. Add explicit uint32() conversion to fix the
cross-compilation error:

  cannot use k.GetIntegerValue("ProxyEnable") (value of type uint64)
  as uint32 value in assignment
2026-07-02 21:24:31 +08:00
Markson Pigeonzilla Plus 54efcae3ac fix(iptables): fix interface exclusion for OUTPUT path and rename nftables sets
Two fixes for the redirect/tproxy interface exclusion feature:

1. Add missing -o/oifname rules for the OUTPUT path
   - The TP_RULE chain is jumped from both PREROUTING (tp_pre) and
     OUTPUT (tp_out). The existing -i/iifname rules only match the
     PREROUTING path correctly (packets arriving on a given interface).
   - For the OUTPUT path (locally-originated traffic), the input
     interface is always 'lo', so -i never matches the excluded
     interface. Add corresponding -o/oifname rules so that locally-
     originated traffic going out through an excluded interface is
     also bypassed (RETURN before the final REDIRECT/TPROXY action).
   - Applies to both redirect and tproxy modes, legacy iptables and
     nftables implementations, for both IPv4 and IPv6.

2. Rename nftables set 'interface'/'interface6' to 'local_ips'/'local_ips6'
   - These sets store IPv4/IPv6 addresses of local interfaces,
     dynamically maintained by the LocalIPWatcher to prevent proxy
     loops (traffic destined to local IPs returns early).
   - The old name 'interface' was misleading: it suggested it stores
     interface names, but the type is ipv4_addr/ipv6_addr.
   - The rename affects nftRedirect and nftTproxy, including the
     set definitions, chain references (ip daddr @local_ips), and
     AddIPWhitelist/RemoveIPWhitelist nft command strings.
2026-07-02 21:21:18 +08:00
Markson Joe Hon 47f1462baf feat: init a new for v2raya core and fix a firewall mistake 2026-07-02 13:10:12 +08:00