Building a Lightweight Bypass Gateway Based on HTTP Proxy: A Practical Guide to redsocks2 + iptables
This article was last updated 287 days ago. The information within may have evolved or changed; if anything is outdated or broken, please feel free to leave a message in the comments section.
Article Abstract
Addressing the needs for scientific internet access in home networks, this article proposes a lightweight bypass gateway scheme based on HTTP proxy to solve the limitations of existing schemes that rely on specific hardware and global proxies. Through the combination of redsocks2 and iptables, precise traffic forwarding is achieved: the former converts target traffic into proxy protocols, and the latter completes traffic interception and redirection. This scheme does not require modifying routing tables or deploying virtual network cards, adapts to existing HTTP proxy services (such as Shadowsocks on Apple TV), provides stable and low-latency proxy forwarding for devices requiring local scientific internet access, while maintaining a decoupled design from the main router to avoid single points of failure affecting the global network, making it suitable for home network scenarios that require flexible traffic splitting.
Qwen3-14B · 2026-06-18

1 Introduction

Speaking of my home's scientific internet access environment, after three major optimizations, the structure is like this:

image.png

Currently, this structure runs well. If a device on the intranet needs to have ”global” scientific internet access capability, you only need to associate the source IP address of that device with the wan2 port of iKuai (which is connected to the lan port of AC86u) in ”Flow Control” - “Shunting Settings” - “Port Shunting” on iKuai:

image.png


Even to cope with special situations when the AC86u fails, an OpenWrt virtual machine with OpenClash installed was deployed in the intranet PVE as an emergency device:

image.png

For the detailed setup process, please refer to the article:Soft Router Series: Discussion on the Best Deployment Scheme for iKuai + OpenWrt (Goodbye, Bypass Router)。


However, the existing scheme also has some limitations:

  1. Reliance on routers with specific hardware

    The current scheme relies on routers with scientific internet access capabilities, such as iKuai and AC86u (or OpenWrt). However, whether it is iKuai or routers with scientific capabilities, only a minority of households own them. Therefore, for users without these devices, this scheme is actually meaningless. Even for myself, if one day Telecom cancels support for triple-dialing, I will definitely no longer use iKuai; and if the AC86u router breaks, I might not be willing to spend a high price to buy a better one. In either case, this scheme will fail.

  2. Many devices actually only need ”local” scientific internet access

In fact, for most intranet devices, ”local” scientific internet access is enough. For example, my productivity device (Mac mini) and the NAS acting as a PT downloader do not need global scientific internet access. Especially for devices that need to frequently access domestic content, global scientific internet access may instead bring side effects (slow access or wasted proxy subscription traffic). Therefore, for these devices, scientific internet access is only needed in specific scenarios, such as accessing certain blocked websites through the Chrome browser, or certain local applications that require scientific internet access to function normally (such as GitHub Desktop). These needs can be fully met through browser smart proxy plug-ins (such as SmartProxy) or network proxy tools (such as Proxifier), combined with the HTTP proxy function provided by Shadowsocks on Apple TV, without any need for global scientific internet access.

Based on the above considerations, and considering that the existing Apple TV has already provided HTTP proxy services through Shadowsocks (of course, this can also be replaced by proxies provided by other scientific software on Apple TV, or HTTP or SOCKS5 proxies on other devices; Apple TV is not mandatory), I hope to build a lightweight, stable, and low-latency bypass gateway scheme on this basis that does not rely on the egress router and can be independently deployed on the intranet. This will construct a system that can cover the scientific internet access needs of all devices on the intranet: for devices that need ”local” scientific capabilities, they can directly access via HTTP proxy; while for a small number of devices that need ”global” scientific capabilities, they can access via bypass gateway forwarding.

After determining the need to build a bypass gateway, a common approach is to use scientific internet access software to achieve automatic forwarding of intranet traffic based on transparent proxy (TProxy) or virtual network card (TUN). Such schemes are already technically mature and have broad community practice support.

However, considering that I already have a stable and available HTTP proxy service (the stability of Apple TV is still very reassuring), redeploying a complete proxy system based on TProxy or TUN would not only increase the complexity of configuration and maintenance but also might not bring substantial advantages. Therefore, I turned to think about whether I could build a simpler, more efficient, lightweight, and stable bypass gateway around the existing HTTP (or SOCKS5) proxy.

2 Connecting the Past and the Future: My Redefinition of the Gateway


The rest of this article will focus on the ”bypass gateway”, and the word ”gateway” often has different meanings in different technical contexts. To avoid misunderstanding and to facilitate the subsequent analysis, I plan to split, sort out, and define the meaning of ”gateway” in a way that is closer to actual usage scenarios. It can be said that this is a”redefinition” with my personal understanding and practical background”, hoping to help everyone better understand the core issues faced when building a bypass gateway scheme.


In network projects, ”gateway” is a role that is often mentioned but easily misunderstood. Simply put, the responsibility of a gateway is toreceive data frames (L2 layer) sent by devices within the same broadcast domain whose destination MAC address is its own, strip out the data packets (L3 layer, even if the destination IP of these packets is not itself), and then complete processing or forwarding actions according to established policies。

Within the scope of this article, a qualified gateway needs to have the following capabilities:

  1. L3 layer packet identification and reception capability

It must be able to identify and receive those packets whose ”destination IP is not itself”. Because for most conventional devices, if the destination IP is inconsistent with their own network card IP, they will not receive the packet unless the network card is in promiscuous mode or a specific forwarding mechanism is enabled. The reason why the gateway device is an ”exception” is precisely because it is designed to act on behalf of others.

  1. Packet processing decision-making capability

The gateway device needs to make decisions on the received packets based on pre-set policies: how should it handle this packet?

Such policies may include: querying the routing table to determine the next hop, making ACL judgments based on a rule engine, and using traffic splitting tools to determine whether it requires scientific internet access, etc.

Once a judgment is made, the device will send the packet to the corresponding subsequent processing module, such as direct routing forwarding, NAT mapping, or other more complex intermediate processing logic.

  1. Protocol conversion capability (one of the intermediate processing logics)

Some packets are not suitable for direct forwarding according to the original protocol during processing, but need to enter a specific ”protocol conversion path” to complete cross-protocol and cross-system bridging. This is very common in many practical scenarios:

  • For example, VoIP gateway, is responsible for converting analog signals in traditional telephone networks (such as PSTN) into IP-based voice protocols (such as SIP or H.323), thereby achieving interoperability between traditional telephony and network voice calls;
  • Another example is NAT64 gateway, used in IPv6-only network environments to automatically convert IPv6 requests into IPv4 packets, supporting access to legacy websites that do not support IPv6.

These ”protocol-converting gateways” enable ”translated dialogue” between systems that otherwise could not communicate by acting as an intermediary bridge, and this conversion logic also becomes an indispensable part of certain types of bypass gateways.

Although gateways in most home networks may not involve complex protocol conversion,once you need to cross the ”language barrier” between network protocols, this capability becomes particularly critical— which is exactly what this article will focus on later.

  1. Final forwarding of packets

After completing policy decisions and protocol processing, the gateway needs to send the packets to the ”next stop.”

The meaning of this next stop depends on the preceding processing path:

  • If it is traditional routing and forwarding, it might be a certain LAN/WAN port, accompanied by NAT or routing hops;
  • If it is proxy traffic based on policy routing, it might be the transit server of a proxy provider;
  • If it has undergone protocol conversion, the ”next stop” might be a local or remote HTTP/SOCKS proxy server.

In short, the gateway's task is to complete the entire chain of ”receive → decide → optional convert → forward,”and only with these four capabilities can it be called a ”true” gateway.

But it is important to note:

Identification and processing are only part of the responsibility; performance is the key to whether it is up to the task

In some professional scenarios, such as Layer 3 switches in enterprise networks, packet identification and forwarding are typically handled by dedicated ASIC chips, achieving line-rate processing with extremely high efficiency. In home or self-built environments, however, most gateway devices (including bypass methods) rely on their own system's CPU to handle all of this: whether through tools like iptables, nftables, ebtables, or redsocks2, Clash, tun2socks, the processing logic for this traffic requires CPU intervention.

While this approach brings high flexibility, it also places higher demands on system resources:Once device performance is insufficient, policies are complex, or concurrency is too high, forwarding capability can become a bottleneck, risking high latency, packet loss, or even a complete network collapse.

A gateway is not necessarily just a single device; it can also be a system composed of multiple devices

When many people hear ”gateway,” they immediately think of a single device: maybe a software router, maybe a bypass gateway. But in reality,the gateway's responsibility is to be a ”connector of paths” and a ”converter of protocols,” rather than ”stuffing all functions into a single device”. In actual deployment, especially in scenarios pursuing flexibility, modularity, or high availability, the gateway's functions can be completely broken down into multiple roles, completed collaboratively by multiple devices.


3 Why Don't I Directly Use Apple TV as a ”Bypass Gateway”?

In the previous section, the reason I wanted to clarify the concept of a ”gateway” is because it relates to why I do not directly use Apple TV as a so-called ”bypass gateway” in the local network in this article, even though many online tutorials take it for granted to use Apple TV directly as a ”bypass router gateway”:

image.png

In fact, strictly speaking,Apple TV does not possess the necessary characteristics to act as a true ”gateway”: it is essentially a consumer-grade media terminal, neither designed as a network forwarding device nor possessing any ability to receive and process packets whose ”destination IP is not itself.” In other words, if you point a device's default gateway to Apple TV in a local area network, if the packets it receives are not addressed to its own IP, itwill simply ignore them, let alone forward or proxy them on their behalf. On this point, Apple TV actually fails to meet the core capability we discussed earlier: ”a gateway must be able to forward packets whose destination IP is not its own IP.”

But in reality, some people will find that—under certain conditions—Apple TV seems to ”magically” possess some kind of traffic forwarding capability, and can even be used as a ”proxy gateway.” This is actually because another less-noticed factor comes into play:HomeKit Home Hub feature:

image.png

image.png

This feature was originally designed to allow Apple TV to act as a control center in a HomeKit network, coordinating internet access for smart devices that lack full network configuration capabilities (such as Thread or Bluetooth Low Energy devices): when the Home Hub feature is enabled, Apple TV temporarily enables a service similar to ”Internet Connection Sharing,” receiving traffic whose destination IP is not its own, and then forwarding it after converting the source address of the received traffic to its own IP according to its local routing (which is essentially single-LAN port forwarding + NAT). If proxy software happens to be installed on Apple TV at the same time, then when a device on the local network points its default gateway to its interface IP, Apple TV can indeed provide proxy capabilities.

However, although on a technical level this capabilityindeed ”looks like a gateway”, but it is essentially still a mechanism temporarily ”unlocked” for a specific purpose. Its stability is questionable, and it cannot assume the high-performance, high-throughput role of a true gateway (Apple itself has never mentioned in any documentation that Apple TV can act as a gateway after enabling the Home Hub feature—it can't be a hidden perk, right?). Some netizens have actually realized this issue as well:

image.png

And the Surge team has also issued warnings regarding this usage:
image.png

In short, after enabling the Home Hub feature, Apple TV can indeed take on some ”bypass gateway” work, but this is just a coincidental ”side job” rather than the role it is supposed to play. Therefore, ”usable” does not mean ”suitable,” let alone ”reliable.”

Essentially, Apple TV imposes quite a few permission restrictions on various apps installed on it (including proxy software). The positioning of these proxy apps is simply tobarely satisfy the proxy needs of the Apple TV device itself, rather than to build a complete proxy gateway. Given that most traffic on Apple TV is dominated by HTTP/HTTPS communication based on the TCP protocol, it is already quite good that these apps can provide a basic external HTTP proxy function.

In a nutshell: using Apple TV as a bypass gateway is not really a proper solution. If anything, it is more suitable fortemporary emergency use on a single deviceto get by; but if you want to cover multiple devices, or even use it stably in the long term, you'd better forget about it — whether in terms of performance, controllability, or stability, the gap between it and a true gateway is very obvious.

4 Building a Lightweight and Stable ”Bypass Gateway”

1 Overview

In a home network, although the bypass gateway does not directly assume the responsibility of the network egress, it plays the key role of a ”transit station” — it intercepts or receives traffic sent by intranet devices and decides where this traffic should be sent based on specific policies. In this process, what really plays a role is the cooperation of two core types of tools:network traffic forwarding tools(such as iptables, nftables) andproxy protocol forwarders(such as redsocks2, tun2socks).

The former is responsible for ”bringing the traffic in,” deciding which traffic needs to be intercepted and redirected; while the latter is responsible for ”how to handle this traffic”—which can be converting the original network requests into proxy protocol formats such as HTTP or SOCKS and handing them over to the upstream proxy, or directly handing the traffic over to proxy programs (such as Clash, Shadowsocks) on the local machine for further processing. Understanding the division of responsibilities and collaboration methods of these two types of tools is the core of designing an efficient, stable, and easy-to-maintain bypass gateway solution.

This section will analyze the functional characteristics, common options, and adaptation scenarios of these two types of tools one by one, and ultimately select the combination scheme that best suits the context of this article.


In my previous articles, I have clearly expressed reservations about the traditional ”one-armed bypass router” mode implemented by OpenWRT, especially the practice of pointing the default gateway of intranet devices directly to the WAN port of OpenWRT. Although simple to deploy, it has many problems: once OpenWRT fails, the entire network goes down; OpenWRT consumes unnecessary performance to process a large amount of direct-connection traffic that originally does not need proxying; and NAT coordination and port mapping with the main router are also prone to issues.

Similarly, using Apple TV as a so-called ”bypass router” gateway essentially adopts a similar approach: letting all traffic from intranet devices pass through the proxy tools installed on Apple TV for processing (most crucially relying on the incidental capabilities provided by the ”Home Hub” feature). This approach looks novel, but in reality, it just replaces OpenWRT with Apple TV, and technical shortcomings, single points of failure, and poor controllability still exist.

Therefore, I would like to emphasize one point in particular:The concept of ”bypass gateway” discussed in this article is not the same thing at all as the ”bypass router” tutorials widely circulated on the Internet: Although the names and deployment methods are similar, the structure, ideas, and goals are completely different.

The ”bypass gateway” I am referring to is atransit role specifically designed for ”proxy forwarding” scenarios: It is not responsible for providing NAT or acting as a network egress, but instead focuses on taking all received external access traffic (imported via default gateway or policy routing)uniformly receiving and converting it into proxy protocol (such as HTTP, SOCKS) request packets, and then forwarding them to the upstream proxy server。

This sounds no different from a traditional ”bypass router”—after all, it is also receiving all the traffic that needs to access the Internet. But the real difference lies inits clear and dedicated responsibility, not participating in unnecessary complex network functions such as NAT, traffic control, and DNS hijacking, making it lighter and more stable in structure, with more concentrated and controllable performance overhead。

In other words, it is not a multi-functional router that ”wants to manage everything,” but astreamlined node solely responsible for forwarding proxy traffic. You can think of it as aprotocol translator—when traffic comes in, it does only one thing: translates it into the proxy protocol, and then immediately hands it over to the remote proxy server for processing, without caching, analyzing, or making decisions. The whole process is clean and straightforward.

Precisely because of its single responsibility and simple implementation, its performance requirements on the running device are very low. Under this ”simplicity managing complexity” architecture, it can still deliver considerable proxy performance, making it suitable for deployment by users who pursue stable and efficient forwarding.

Such a node can be deployed to run on an LXC container or a lightweight virtual machine, decoupling it from the main router. The main router still assumes the core control and traffic scheduling responsibilities of the entire network, while the bypass gateway node only serves a small number of devices that require global proxy capabilities. This decoupled design not only improves the flexibility and controllability of the proxy link, but also avoids the risk ofdamaging the core functions of the entire networkin most cases—of course,for terminal devices configured with the bypass gateway node as the default gateway, access anomalies may still occur due to its disconnection, but such impacts are usually locally controllable and will not affect the whole network。

Therefore, this article is not trying to rehabilitate the ”one-armed bypass router,” but rather to build amore modern bypass gateway solution that is better suited to actual needs。


2 Introduction to Network Traffic Forwarding Tools

2.1 Overview

In the previous content, we discussed the various capabilities of a ”gateway” as a network traffic transit station: that is, ”receiving data streams whose target IP is not itself, making judgments according to pre-agreed decisions, handing them over to subsequent functional modules (such as protocol processors) for processing, and then forwarding them out in some way." Andthe core of the entire process ”from packet reception to before the protocol converter” falls on the system's traffic forwarding tools(corresponding to points 1 and 2 of the gateway capabilities).

For Linux-based systems, operations such as forwarding, redirecting, and releasing network traffic are usually handled by the netfilter framework in the kernel. There are two main interfaces through which users interact with netfilter via commands or scripts:iptables and nftables。

The goals of both are similar, both used to formulate complex traffic processing rules, but their styles, syntax, and eras of applicability differ slightly. When actually deploying a bypass gateway, we only need to configure a few rules to achieve interception and redirection of target device traffic, so there is no need to study all of their mechanisms in depth. However, understanding the differences between them and the reasons for choosing one of the tools is still very necessary.

In this chapter, we will briefly introduce their respective backgrounds, characteristics, and usage recommendations to help you make the right choice when deploying your own gateway forwarding rules.

4.2.2 iptables: An old-school but still widely used traffic control tool

iptables can be said to be the first stop for most people to get in touch with Linux network control. It has been widely used since the Linux 2.4 kernel, managing the lifecycle of network traffic through four major ”tables” (filter, nat, mangle, raw) and five ”chains” (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING).

Although its syntax is somewhat imperative and not very friendly, there is plenty of documentation and the community is mature,especially in distributions like Debian and Ubuntu, where iptables is still used by default even today, so in many practical deployment scenarios, continuing to use it is the simplest and most direct solution.

If you are using older versions of LXC or Docker base images, or want to get the job done with minimal hassle, iptables is fully capable of meeting your traffic redirection and forwarding needs.

4.2.3 nftables: A next-generation framework for the future

With the development of the kernel, the modularity and rule expansion of iptables became increasingly complex, eventually giving birth to nftables, a more modern successor. It was introduced starting from Linux 3.13, aiming to unify and simplify firewall management.

Compared to iptables, nftables provides more consistent syntax, structured data support, and built-in debugging tools. More importantly:it is the main direction of the future netfilter system.

Many new distributions (such as newer Debian, Fedora, Arch Linux) have enabled nftables by default, while iptables indirectly calls nftables at the lower level through the iptables-nft compatibility layer, meaning that while you appear to be writing iptables, the kernel is actually running nftables rules.

However, precisely because of the existence of this compatibility layer, using both at the same time on some systems may cause rule confusion.If you plan to maintain this set of forwarding rules for a long time, and the system default support is good, it is recommended to go directly with nftables.

4.2.4 My Recommendation

For scenarios like bypass gateways with ”clear functions and simple rules,” the difference between the two is not significant. When making an actual choice, you might as well follow this principle:

  • Use whichever one the system provides by default.
  • If you are not familiar with the syntax, the one with more online tutorials is usually iptables, which is suitable for quick implementation.
  • If you want to flexibly expand more control rules in the future, or if you are using a newer system environment (such as Debian 12, Ubuntu 22.04 or above), you can directly choose nftables.

3 Introduction to Proxy Protocol Forwarders

3.1 Overview

In the previous chapters, we have intercepted the received data packets through traffic forwarding tools (such as iptables/nftables) and can redirect them to a local or remote port, but this is only the first step. Next, there must be a component toreceive these raw TCP/IP traffic and convert them into proxy protocols (such as HTTP, SOCKS5) that the upstream proxy server can understand, and this component is the so-calledproxy protocol forwarders(corresponding to point 3 of the gateway capabilities).

4.3.2 redsocks2

redsocks is one of the earliest traffic forwarding tools. Its design goal is simple and direct: listen to a local port, receive TCP traffic, repackage it into proxy protocol traffic (supporting HTTP CONNECT, SOCKS4/5), and then send it to the specified upstream proxy server.

What we are more focused on here is the modified version based on redsocks, redsocks2(actually still called redsocks, but habitually referred to as redsocks2 for distinction), which has made many enhancements on top of the original version, such as:

image.png

Note 1: It should be noted thatredsocks2 is spontaneously maintained by the community,and is not an officially released version, but it has become a de facto standard in many practical projects (especially bypass gateway projects). Its official GitHub address is ”https://github.com/semigodking/redsocks“.

Note 2: If you are using a proxy service that still supports the Shadowsocks protocol, redsocks2 can also directly connect as a client without setting up an additional local proxy program, which is one of its built-in features. However, it should be noted that Shadowsocks, as an early-designed protocol, is gradually being regarded as an ”old protocol” in practical use today: on one hand, its protocol characteristics are relatively obvious,making it easy to be identified and interfered with; on the other hand, in terms of connection stability and anti-interference, it is also gradually failing to meet the needs of more complex network environments. Therefore, most current high-availability proxy solutions have shifted to more modern protocol stacks, such as VLESS, trojan, Reality, etc. Therefore, this article still focuses on the role of redsocks2 as a protocol forwarder, mainly used in conjunction with existing HTTP or SOCKS5 proxies, rather than using it as a ”shadowsocks” client.

4.3.3 tun2socks

tun2socks is another traffic forwarding approach. Its core difference is that it does not handle TCP/UDP traffic separately, but simulates a virtual TUN device, redirects all traffic to this virtual network card, and then directly performs SOCKS5 proxy forwarding before the kernel protocol stack.

Features of tun2socks:

  • Mainly based on the SOCKS5 protocol (some versions support HTTP CONNECT)
  • Can transparently proxy the entire device (such as Android, OpenWRT)
  • Good support for UDP (depending on the implementation version)
  • Moderate performance, but simple architecture

Usually,tun2socks is suitable for scenarios that require transparent proxying of the entire machine, such as proxying directly through the TUN device egress on devices like mobile phones and routers. However, if you just want to intercept traffic on specific ports/rules, tun2socks feels a bit like ”using a sledgehammer to crack a nut.”

4.3.4 My recommendation: redsocks2

For building the bypass gateway this time, my goal was actually very clear: I wanted it to be lightweight, stable, and most importantly, easy to deploy and maintain in the future. redsocks2 happens to meet these requirements perfectly. Its performance has always been reliable, it runs without unexpected issues, and it is particularly suitable for this kind of ”plug-and-play” relay node. Moreover, the configuration is very intuitive, requiring no extra hassle with virtual TUN network cards or modifying routing tables, saving a lot of trouble. Coincidentally, it supports multiple upstream proxy protocols, especially HTTP, which works perfectly with the HTTP service provided by Shadowsocks running on my Apple TV.

Overall, redsocks2 is the most suitable solution for the current bypass gateway scenario: lightweight enough, stable enough, and hassle-free enough.

4 Final Forwarding Destination

In the ”bypass gateway” scenario discussed in this article, the task of the proxy protocol forwarder (redsocks2 is used in this article) is to take the traffic intercepted and redirected by iptables or nftables,perform protocol conversion according to the actually configured upstream proxy type, and then forward it to the upstream proxy server (point 4 of the gateway capabilities).

As for the type of upstream proxy server, there is no mandatory requirement. You can choose either an HTTP proxy or a SOCKS5 proxy according to your own network environment. Take my own situation as an example: since I have an Apple TV at home with Shadowrocket installed, which happens to provide a usable HTTP proxy, I just used this ready-made egress directly. If you have a stable SOCKS5 node of your own, that is also completely fine.For redsocks2, you only need to specify the correct proxy protocol and address in the configuration; there is no essential difference between the two.

It should be noted that:iptables/nftables, redsocks2, and the final proxy service itself do not need to be deployed on the same device(of course, deploying them on the same device is also completely fine). You can design the most suitable structure according to your actual situation, for example:

  • My own deployment method is to deploy iptables/nftables and redsocks2 together in an LXC container
  • while Shadowrocket running separately on the Apple TV provides the HTTP proxy as the final egress

This architecture has clear decoupling and simple maintenance. If any link fails, it is also easier to locate and replace. In short,there is no fixed answer to how to implement a bypass gateway. The key is to make the most stable and hassle-free deployment based on your own network environment and device capabilities.

5 Deploying redsocks2

1 Environment Description

Since the HTTP proxy is ready-made (provided by Shadowrocket on Apple TV), I mainly just need to get redsocks2 working. The best performance is achieved by using LXC to deploy redsocks2.

Although I have quite a few running LXCs on my PVE, they all have their own purposes:

image.png

After thinking about it, I decided to create another separate Debian LXC to deploy redsocks2. I can just use the iptables on this LXC directly to intercept traffic and redirect it to the local redsocks2, which is simple and convenient:
image.png

Note 1: I have already written about the specific steps for creating a new LXC in my previous article, so I won't repeat them here. Those who are not sure can refer to the article ”Docker Series: Using LXC based on Turnkey-gameserver to set up a Minecraft Bedrock Edition server“.

Note 2: The redsocks2 LXC does not require many resources. For example, 1-2 CPU cores at minimum is about enough, and 256MB or 512MB of RAM is sufficient. The actual situation depends on your own household's actual usage of the bypass gateway.

Note 3: I used LXC because I already had PVE, but in factUbuntu / DebianYou can use bare metal or LXD directly,Alpine Linux / Arch / Gentooalso natively support LXC, and QNAP NAS can also use Linux Station to run. In short, just choose the method that suits you.

Note 4: Virtual machines are the same, except that compared to LXC, virtual machines consume a lot more resources, which I think is not very cost-effective. For virtual platforms that do not support LXC, just use virtual machines directly.

Note 5: For the initialization of the Debian system, please refer to the article ”Debian series system routine initialization steps compilation“.

2 Installing redsocks2

1、Install Dependencies

apt update 
apt install -y build-essential libevent-dev libssl-dev git pkg-config

Explain the role of each package:

  • build-essential: Contains basic build tools such as gcc, make, etc.
  • libevent-dev: The main event-driven library dependency for redsocks.
  • libssl-dev: OpenSSL development package, providing encryption support.
  • git: Needed if you haven't cloned the code yet.
  • pkg-config: Some makefiles will use it to check dependency versions and compilation parameters.

To avoid tedious troubleshooting later due to missing features or compilation failures, I chose to enable all modules of redsocks2 at once (mainly for fear of compilation errors~).

2、Clone the source code and compile

git clone https://github.com/semigodking/redsocks.git
cd redsocks
make

3、 Confirm that gcc and make are installed

gcc --version
make --version

If not installed:

apt install build-essential

4、Compile

If you run the make command directly to compile, it will support the shadowsocks protocol by default and will not support HTTPS proxy. For my intranet environment, redsocks2 only needs to be used with an HTTP proxy (or socks5 proxy), so there is no need to support the shadowsocks protocol, nor is an HTTPS proxy needed, so you only need to run the following command:

make DISABLE_SHADOWSOCKS=true

If you also want to support HTTPS proxy at the same time, just run the following command:

make DISABLE_SHADOWSOCKS=true ENABLE_HTTPS_PROXY=true

Finally compiled successfully:

image.png

After successful compilation, an executable file named redsocks2 will be generated, which can be viewed with the command:

ls -lh redsocks2

The output is as follows:

image.png

If it can print the help information normally, it can be used normally:

./redsocks2 -h

The output is as follows:

image.png

Note: I do not recommend keeping the shadowsocks functional module, as this will introduce additional encryption library dependencies (such as libsodium, mbedtls), increasing compilation complexity and the chance of errors, especially when you do not plan to actually use it, which is completely meaningless (at first I wanted to keep the shadowsocks feature, but it ended up giving me a hard time, so I had to give up~).

3 Creating the ”redsocks2.conf” Configuration File

After installation, redsocks2 needs to create a configuration file ”redsocks.conf”. Assuming the proxy server address is 192.168.1.1, the HTTP proxy service port is 8080, and the SOCKS5 proxy port is 1080, the configuration file content is as follows:

base {
    log_debug = off;
    log_info = on;
    log = stderr;
    daemon = off;
    redirector = iptables;
}

redsocks {
    // 监听本地 TCP 流量
    bind = "0.0.0.0:12345";
    // HTTP 代理服务器
    relay = "192.168.1.1:8080";
    type = http-connect;
    login = "";
    password = "";
}

redudp {
    // 监听本地 UDP 流量
    bind = "0.0.0.0:12346";
    // 代理服务器是 socks5(要求支持UDP)
    relay = "192.168.1.1:1080";
    type = socks5;
    login = "";
    password = "";
    // 必填,用于 REDIRECT 模式
    dest = "8.8.8.8:53";
    udp_timeout = 30;
    udp_timeout_stream = 180;
}

Configuration description:

  • redsocks section: Responsible for proxy forwarding of TCP traffic.
  • redudp section: Responsible for proxy forwarding of UDP traffic.
  • bind = “0.0.0.0:12345": Listens to TCP requests on port 12345 of all network cards of the LXC container
  • relay = “192.168.1.1:8080”: This is the address and port of the HTTP proxy
  • type = http-relay: Indicates that the target proxy is an HTTP proxy.
  • bind = “0.0.0.0:12346": UDP requests on port 12346 of all network cards of the LXC container.
  • relay = “192.168.1.1:1080”: This is the address and port of the SOCKS5 proxy
  • type = socks5: Indicates that the target proxy is a SOCKS5 proxy.
  • dest = “8.8.8.8:53” is the target address and port that the UDP module needs to specify. Even if it is only for transit purposes, it must be filled in. These two values will not be used in your actual traffic, they are only required to start redudp.

Note 1: Both the redsocks.conf configuration file and the redsocks2 executable file are in the redsocks directory.

Note 2: Personally, I suggest that a bypass gateway built with redsocks2 supporting the TCP protocol is generally sufficient. If you want to use the redudp section to proxy the UDP protocol, you must use a SOCKS5 proxy, and this SOCKS5 proxy must support the UDP protocol (not all SOCKS5 proxies support the UDP protocol, for example, the SOCKS5 proxy provided by merlinclash does not support UDP by default. From this perspective, although redsocks2 supports UDP protocol proxying, there are still limitations when actually using it. From this perspective, Proxifier is truly awesome).

Note 3: As for DNS, it does not need to point to the bypass gateway. It is still recommended to point directly to the main router (requires the main router to configure DNS hijacking). If it points to commonly used domestic DNS servers and the main router does not have DNS hijacking configured, then in this bypass gateway mode, you need to configure appropriate iptables and ebtables rules on the bypass gateway to redirect DNS requests to the main router (see the iptables section later in the article).

4 Running redsocks2

In the redsocks directory, just run the following command directly:

./redsocks2 -c redsocks.conf

Note 1: The ”-c” parameter specifies the configuration file associated when redsocks2 starts.

5 Setting redsocks2 to Start Automatically on Boot

Create systemd service unit file:

vim /etc/systemd/system/redsocks2.service

Paste and save the following content (taking my environment as an example, I directly cloned redsocks2 via git to the root directory):

[Unit]
Description=Redsocks2 Proxy Gateway
After=network.target

[Service]
Type=simple
ExecStart=/root/redsocks/redsocks2 -c /root/redsocks/redsocks.conf
User=root
Group=root
WorkingDirectory=/root/redsocks
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
  • ExecStart: Set to the command you actually use to execute redsocks2, ensuring the path is correct.
  • WorkingDirectory: Set to the directory where redsocks2 runs, ensuring the redsocks.conf configuration file is also in the correct path.
  • User and Group: Used to specify which user and group redsocks2 should run as. Avoid running it as the root user (don't follow my example); you can create a dedicated user for it (such as redsocks).
  • Restart=always: If redsocks2 exits unexpectedly or crashes, it will be automatically restarted.
  • RestartSec=3: Restart 3 seconds after the process crashes.

Reload the systemd configuration and enable the service:

systemctl daemon-reload
systemctl enable redsocks2.service

Start the redsocks2 service:

systemctl start redsocks2.service

Check the service status:

systemctl status redsocks2.service

If everything is normal, it will display as follows:

image.png

6 Enabling Kernel IP Forwarding Functionality

In Linux systems, net.ipv4.ip_forward controls the kernel's Layer 3 forwarding capability. The default setting is 0, which prohibits IP packets from being forwarded between different interfaces. If you want the device to be used as a router, bypass gateway, or any transit node, you must enable it. Otherwise, even if iptables NAT (such as SNAT, DNAT) or REDIRECT rules are configured, packets will still only be processed locally and cannot complete the forwarding chain.

Temporary enablement method:

echo 1 > /proc/sys/net/ipv4/ip_forward

To keep it effective after a system reboot, you should modify /etc/sysctl.conf accordingly:

vim /etc/sysctl.conf

Find the following line:

#net.ipv4.ip_forward=1

Uncomment it and ensure it is set to =1:

image.png

If you deployed WordPress via source code, you only need to specify the path when executing, which will list your plugin list:

sysctl -p

Note: Unenabled IP forwarding is one of the most common hidden issues in bypass proxy setup. Be sure to prioritize confirming this during the debugging phase.

7 Configuring iptables

The following is the iptables configuration adapted to the previous redsocks2.conf example in the article:

# 创建一个新的 chain
iptables -t nat -N REDSOCKS

# 排除本地回环接口(lo)上的流量
iptables -t nat -A REDSOCKS -i lo -j RETURN

# 排除目标地址是本机自身 IP(假设本机IP是x.x.x.x)的流量
iptables -t nat -A REDSOCKS -d x.x.x.x -j RETURN

# REDIRECT 所有其他 TCP 流量到本地 12345 端口
iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 12345

# REDIRECT 所有其他 UDP 流量到本地 12346 端口(可选,用于redudp)
iptables -t nat -A REDSOCKS -p udp -j REDIRECT --to-ports 12346

# 应用 REDSOCKS 规则到 PREROUTING(入口数据包)
iptables -t nat -A PREROUTING -p tcp -j REDSOCKS
iptables -t nat -A PREROUTING -p udp -j REDSOCKS

------------------------------------------------------------------------------
如果客户端的DNS指向公网DNS,才需要配置以下两条规则:

# 把所有 UDP 53 DNS 查询流量转发回主路由(假设主路由mac地址是00:11:22:33:44:55)
ebtables -t nat -A PREROUTING -p IPv4 --ip-proto udp --ip-dport 53 -j dnat --to-destination 00:11:22:33:44:55

# 对转发到主路由的DNS查询包进行源地址NAT,确保DNS响应能返回旁路网关(假设旁路网关的IP是 x.x.x.x)
iptables -t nat -A POSTROUTING -p udp --dport 53 -j SNAT --to-source x.x.x.x

Question: Why do the last two rules (ebtables and iptables) need to be configured on the bypass gateway when the client's DNS points to a public DNS? Answering this question requires a little bit of networking basics.


You can use the following command to display the list of iptables rules with line numbers in the bypass gateway, making it easy for you to locate a specific rule:

iptables -t nat -L --line-numbers

In my case, it displays as follows:

image.png

You can use the following command to view the list of ebtables rules in the bypass gateway by table:

ebtables -t nat -L

In my case, it displays as follows:

image.png

In fact, it simply redirects all TCP traffic received by the bypass gateway to the local port 12345; forwards traffic with a destination port of UDP 53 directly to the main router and performs source NAT on the UDP packets to the bypass gateway's address; and redirects all other received UDP traffic to the local port 12346 (provided that a UDP proxy is configured, which I didn't configure anyway). It's very simple. At this point, the bypass gateway setup is complete. All devices requiring global proxy capabilities only need to point their default gateway to the IP address of the device where redsocks2 is deployed (the DNS server can keep its original settings; pointing it to the bypass gateway is also fine, though a bit redundant).

Note 1: The configurations of iptables and ebtables are, by default, onlytemporarily effectiveIf you do not manually save the configuration, they will all disappear after a reboot (because the Linux network stack initialization does not automatically restore the rules you temporarily added). There are several methods; please search for tutorials yourself, as I'm too lazy to write them down and it is not the focus of this article.

Note 2: In actual deployment, for both simplicity and compatibility, I chose not to introduce ebtables, and only configured TCP transparent proxy via iptables while letting DNS resolution point to the main router. This way, the bypass router does not need to handle UDP traffic at all, simplifying the overall architecture and allowing us to abandon ebtables. The benefit is that maintenance is more convenient, as you only need to save the iptables configuration (you can use iptables-persistent to automatically import the iptables configuration at boot).

Note 3: Although it is possible to modify the destination MAC address via ebtables and combine it with iptables for SNAT, allowing the bypass gateway to fully take over the UDP traffic sent by the device and avoid routing conflicts, this solution may still encounter compatibility issues when dealing with applications that build their own tunnel networks, such as Tailscale and ZeroTier. These applications typically rely on local routing tables or virtual network cards to manage outbound traffic, and the intermediate hijacking by the bypass gateway may instead disrupt their normal connections. Therefore, when deploying a bypass gateway, it is recommended that connected devices be kept as clean as possible and not have such special applications installed, in order to ensure the stability and consistency of the bypass solution.

8 Summary

This article introduces how to use redsocks2 with an HTTP proxy to build a lightweight, stable, and high-performance bypass gateway. Strictly speaking, this solution built with redsocks2 + HTTP proxy cannot handle all types of network traffic; it is essentially atransparent proxy gateway for HTTP/HTTPS traffic. However, in most daily office or home environments, the HTTP/HTTPS protocols usually account for as high as 80% to 90% of ordinary users” TCP traffic. Therefore, even if this solution only targets HTTP/HTTPS, it can still cover the vast majority of censorship circumvention needs, achieving an effect close to a ”global proxy".

The advantage of this method lies in its simple deployment and low resource consumption, making it suitable for users who already have a main router framework but wish to apply global censorship circumvention to certain devices, especially for friends who cannot or do not want to mess with TUN/TProxy, providing an easy-to-maintain, migrate, and restore solution (especially with an Apple TV, though it should be noted that all censorship circumvention software on Apple TV only provides HTTP proxies externally).

Of course, this solution is not perfect. For example, UDP traffic relies on SOCKS5 proxies that support special forwarding, and many TCP applications (SSH, SMTP, IMAP, MySQL, Redis, RDP, WebSocket, etc.) do not have ideal compatibility with HTTP proxies. Most crucially, a ready-made HTTP proxy is still required.


In fact, specialized censorship circumvention software also has conditional support for UDP proxying, such as the explanation from Merlinclash:

image.png

image.png

Poor my AC-86U~, which is also one of the reasons I researched bypass gateways: if I get annoyed in the future, I'll just switch completely to the bypass gateway solution for censorship circumvention. Anyway, it's not supported now, so it has absolutely no impact on me~.


If you have higher requirements for the transparent proxy capabilities of the bypass gateway (for example, wishing to bypass the UDP protocol, or achieve full TCP traffic transparent forwarding), you can further expand on the basis of the solution in this article, combining tools like tun2socks to convert existing HTTP/SOCKS5 proxy traffic into transparent proxy access, achieving more complete traffic takeover. If you wish to build a transparent proxy system with more complete functions and finer control, you can also consider using modern proxy platforms such as sing-box and Hysteria to rebuild an independent proxy environment.

But even without expansion, the redsocks2 + HTTP proxy mode shown in this article has already achieved a good balance among usability, stability, and simplicity. It is a solution highly worth trying first when deploying a bypass gateway in a home network, and it can already meet the needs of the vast majority of people.

Below is an overview of the support of some common applications in bypass gateway mode when the upstream proxy of redsocks2 is an HTTP proxy or a SOCKS5 proxy, which is completely sufficient for most people:

Application Upstream is HTTP proxy Upstream is SOCKS5 proxy Remarks/Notes
apt Supports Supports Outgoing requests are HTTP/HTTPS, all of which can be transparently proxied
curl Supports Supports Fully compatible with transparent proxy, no extra parameters required
wget Supports Supports Behaves similarly to curl; some versions have unstable support for SOCKS, but this does not affect bypass mode
git (HTTPS protocol) Supports Supports Sends HTTPS requests, which can be taken over by redsocks2
git (SSH protocol) Not supported Not supported Outgoing is SSH protocol, which is not HTTP traffic and cannot be transparently forwarded
ssh Not supported Not supported Same as above, SSH protocol cannot be processed by redsocks2
Browsers (such as Chrome) Supports Supports Communicates based on HTTP protocol, can be fully transparently proxied, providing a good experience
Electron apps (such as VSCode) Supports Supports Uses the system network stack, behaves similarly to browsers, transparent proxy takes effect

To intuitively demonstrate the pros and cons between the "redsocks2 + HTTP/SOCKS5 proxy" solution adopted in this article and the more common "proxy software + TProxy/TUN transparent proxy" approach, I have also made a comparison:

Comparison Item redsocks2 + HTTP/SOCKS5 proxy proxy software + TProxy/TUN transparent proxy
Deployment Complexity Low, only requires configuring traffic forwarding and basic firewall rules High, requires a deep understanding of TProxy/TUN mechanisms and complex firewall policies
Dependent Components Only requires an existing HTTP/SOCKS5 proxy, no additional proxy software running Requires deployment and long-term maintenance of a complete proxy software system
System Resource Usage Extremely low, redsocks2 itself is very lightweight, and resource overhead is negligible High, running the proxy software itself brings certain CPU and memory consumption
Feature Coverage Supports TCP traffic bypass, meeting the vast majority of proxy needs Supports fully transparent TCP+UDP traffic bypass, offering more comprehensive features
Stability Extremely high, few components, simple forwarding logic, low probability of errors Low, many running components, long-term stability depends on the proxy software
Troubleshooting Difficulty Low, clear troubleshooting path, packet capture analysis is simple and direct High, involves firewalls, routing tables, and internal software mechanisms, making issues complex
Environmental Adaptability Strong, only requires an HTTP/SOCKS5 proxy to run, adapting to various intranet environments Moderate, requires a relatively stable and open Linux environment, with limited adaptability
O&M Cost Extremely low, almost maintenance-free in the long run after deployment High, requires attention to proxy software upgrades, rule updates, and exception handling

As can be seen, "redsocks2 + HTTP/SOCKS5 proxy" greatly reduces the deployment threshold and maintenance burden (sufficiently lightweight, with minimal performance requirements) while maintaining availability and performance. It is highly suitable for scenarios where one wishes to quickly and robustly build a bypass proxy gateway in an existing network environment (as long as there is an available HTTP/SOCKS5 proxy~). Overall, both have their applicable scenarios, but if the goal is to pursue lightweight, stable, low O&M costs, and better environmental universality, the solution in this article undoubtedly has more advantages.

It should be noted that although the solution introduced in this article ultimately presentslightweight, stable, and low-latencycharacteristics, achieving this result is not a simple process. During the setup process, one not only needs to master the use of iptables and ebtables , but also involves TCP/IP network basics, DNS query principles, HTTP/SOCKS5 protocol forwarding mechanisms, containerization technologies (such as LXC or virtual machine environment setup and management), and Linux system administration, package manager usage, and toolchain compilation and debugging capabilities. At the same time, in order to quickly locate issues when they arise, you also need to have certain troubleshooting skills, such as packet capture analysis, log troubleshooting, and route tracking.

In a sense, compared to directly adopting a more highly integrated and configuration-wizard-friendlyscientific software + TProxy/TUN transparent proxysolution, the approach in this article actually places higher demands on underlying knowledge and independent configuration capabilities. It is precisely this control over details that makes the final bypass gateway not only lightweight and efficient, but also highly controllable and universal.

Therefore, if you hope to obtain a truly lightweight, stable, and low-maintenance bypass gateway system through the method in this article, it is recommended to have a certain understanding of the relevant basic knowledge before starting: this will not only make the setup process smoother, but also help you be more at ease during future maintenance and expansion.

View Related Categories · 3 Matches
📌 Content Structure Prompt:
This content is part of the following knowledge map, where you can view the complete content path: Blog Knowledge Map。
📎 Related Articles
Share this article
The blog content is original, please indicate the source when reposting! The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if needed, you can join theTelegram Groupto discuss questions together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗ
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Kaomoji
Emoji
Little Dinosaur
Flower!
Previous
Next
       

👋 Welcome to “Wudi's Personal Blog”

Here, long-term exploration is mainly carried out around the following directions:

🧱 Personal Digital Infrastructure and Blog System Construction
☁️ Cloudflare and Network Architecture Practice
🧠 AI and Knowledge System Exploration
🛡️ Network Security and Access Optimization
🎵 Music and Sound Cognition
👁️ Cognitive Perspectives and Worldviews