Windows прозрачный прокси сервер windows

enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.23.11 netmask 255.255.255.0 broadcast 192.168.23.255
inet6 fe80::a00:27ff:fec2:bae4 prefixlen 64 scopeid 0x20 ether 08:00:27:c2:ba:e4 txqueuelen 1000 (Ethernet)
RX packets 6412 bytes 8676619 (8.2 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1726 bytes 289128 (282.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

enp0s8: flags=4098<BROADCAST,MULTICAST> mtu 1500
ether 08:00:27:79:a7:e3 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10 loop txqueuelen 1 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

Интерфейс enp0s8 на данный момент не используется, мы его включим, когда захотим использовать конфигурацию Proxy NAT или NAT. Именно тогда логичным будет назначить ему статический ip.

4. Приступим к установке 3proxy

4.1 Установка базовых пакетов для компиляции 3proxy из исходников

root@debian9:~# apt-get install build-essential libevent-dev libssl-dev -y

4.2. Создадим папку для скачивания архива с исходниками

root@debian9:~# mkdir -p /opt/proxy

4.3. Перейдем в эту папку

root@debian9:~# cd /opt/proxy

4.4. Теперь загрузим последний пакет 3proxy. На момент написания статьи последней стабильной версией была 0.8.12 (18/04/2018) Скачаем её с официального сайта 3proxy

root@debian9:/opt/proxy# wget https://github.com/z3APA3A/3proxy/archive/0.8.12.tar.gz

4.5. Распакуем скачанный архив

root@debian9:/opt/proxy# tar zxvf 0.8.12.tar.gz

4.6. Переходим в распакованный каталог для сборки программы

root@debian9:/opt/proxy# cd 3proxy-0.8.12

4.7. Далее нужно добавить строчку в файл заголовка, чтобы наш сервер был полностью анонимным (реально работает, всё проверено, ip клиентов скрываются)

root@debian9:/opt/proxy/3proxy-0.8.12# nano +29 src/proxy.h

Добавляем строку

#define ANONYMOUS 1

Нажимаем Ctrl+x и Enter, чтобы сохранить изменения.

4.8. Приступим к сборке программы

root@debian9:/opt/proxy/3proxy-0.8.12# make -f Makefile.Linux

Makelog

make[2]: Leaving directory ‘/opt/proxy/3proxy-0.8.12/src/plugins/TransparentPlugin’
make[1]: Leaving directory ‘/opt/proxy/3proxy-0.8.12/src’

Ошибок нет, продолжаем.

4.9. Установим программу в систему

root@debian9:/opt/proxy/3proxy-0.8.12# make -f Makefile.Linux install

4.10. Переходим в корневой каталог и проверяем, куда установилась программа

root@debian9:/opt/proxy/3proxy-0.8.12# cd ~/
root@debian9:~# whereis 3proxy

3proxy: /usr/local/bin/3proxy /usr/local/etc/3proxy

4.11. Создадим папку для конфигурационных файлов и логов в домашнем каталоге пользователя

root@debian9:~# mkdir -p /home/joke/proxy/logs

4.12. Переходим в каталог, где должен быть конфиг

root@debian9:~# cd /home/joke/proxy/

4.13. Создаем пустой файл и копируем туда конфиг

root@debian9:/home/joke/proxy# cat > 3proxy.conf

3proxy.conf

daemon
pidfile /home/joke/proxy/3proxy.pid
nserver 8.8.8.8
nscache 65536
users tester:CL:1234
timeouts 1 5 30 60 180 1800 16 60
log /home/joke/proxy/logs/3proxy.log D
logformat «- +_L%t.%. %N.%p %E %U %C:%c %R:%r %O %I %h %T»
rotate 3
auth strong
flush
allow tester
socks -p3128
proxy -p8080

Для сохранения нажимаем Ctrl + Z

4.14. Создадим pid — файл, чтобы не было ошибок при запуске.

root@debian9:/home/joke/proxy# cat > 3proxy.pid

Для сохранения нажимаем Ctrl + Z

4.15. Запускаем прокси сервер!

root@debian9:/home/joke/proxy# 3proxy /home/joke/proxy/3proxy.conf

4.16. Посмотрим, слушает ли сервер порты

root@debian9:~/home/joke/proxy# netstat -nlp

netstat log

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 504/3proxy
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 338/sshd
tcp 0 0 0.0.0.0:3128 0.0.0.0:* LISTEN 504/3proxy
tcp6 0 0 :::22 :::* LISTEN 338/sshd
udp 0 0 0.0.0.0:68 0.0.0.0:* 352/dhclient

Как и было написано в конфиге, веб-прокси слушает у нас порт 8080, Socks5-прокси — 3128.

4.17. Для автозапуска службы прокси после перезагрузки нужно добавить её в cron.

root@debian9:/home/joke/proxy# crontab -e

Добавляем строку

@reboot /usr/local/bin/3proxy /home/joke/proxy/3proxy.conf

Нажимаем Enter, так как cron должен видеть символ конца строки и сохраняем файл.

Должно быть сообщение о установке нового crontab-а.

crontab: installing new crontab

4.18. Перезагрузим систему и попробуем подключиться через браузер к прокси. Для проверки используем браузер Firefox (для веб-прокси) и дополнение FoxyProxy для socks5 с аутентификацией.

root@debian9:/home/joke/proxy# reboot

4.19. Проверив работу прокси после перезагрузки, можно посмотреть логи. На этом настройка прокси-сервера завершена.

3 proxy log

1542573996.018 PROXY.8080 00000 tester 192.168.23.10:50915 217.12.15.54:443 1193 6939 0 CONNECT_ads.yahoo.com:443_HTTP/1.1
1542574289.634 SOCK5.3128 00000 tester 192.168.23.10:51193 54.192.13.69:443 0 0 0 CONNECT_normandy.cdn.mozilla.net:443

Настройка и запуск конфигурации Transparent Proxy NAT

В данной конфигурации все устройства внутренней сети будут прозрачно работать в интернете через удаленный прокси-сервер. Абсолютно все tcp-соединения будут перенаправляться в один либо несколько (реально расширяет ширину канала, пример конфигурации №2!) прокси-серверов. Служба DNS будет использовать возможности 3proxy (dnspr). UDP наружу «ходить» не будет, так как мы пока не используем механизм forward (по-умолчанию отключен в ядре Linux).

1. Настало время включить интерфейс enp0s8

root@debian9:~# nano /etc/network/interfaces

/etc/network/interfaces file

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug enp0s3
iface enp0s3 inet dhcp

# The secondary network interface
allow-hotplug enp0s8
iface enp0s8 inet static
address 192.168.201.254
netmask 255.255.255.0

Тут мы назначили интерфейсу enp0s8 статический адрес 192.168.201.254 и маску 255.255.255.0
Сохраняем конфиг Ctrl+X и перезагружаемся

root@debian9:~# reboot

2. Проверяем интерфейсы

root@debian9:~# ifconfig

ifconfig log

enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.23.11 netmask 255.255.255.0 broadcast 192.168.23.255
inet6 fe80::a00:27ff:fec2:bae4 prefixlen 64 scopeid 0x20 ether 08:00:27:c2:ba:e4 txqueuelen 1000 (Ethernet)
RX packets 61 bytes 7873 (7.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 65 bytes 10917 (10.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

enp0s8: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.201.254 netmask 255.255.255.0 broadcast 192.168.201.255
inet6 fe80::a00:27ff:fe79:a7e3 prefixlen 64 scopeid 0x20 ether 08:00:27:79:a7:e3 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 648 (648.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10 loop txqueuelen 1 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

3. Всё получилось, теперь необходимо настроить 3proxy для прозрачного проксирования.

root@debian9:~# cd /home/joke/proxy/
root@debian9:/home/joke/proxy# cat > 3proxytransp.conf

Пример конфигурации прозрачного прокси-сервера №1

daemon
pidfile /home/joke/proxy/3proxy.pid
nserver 8.8.8.8
nscache 65536
timeouts 1 5 30 60 180 1800 16 60
log /home/joke/proxy/logs/3proxy.log D
logformat «- +_L%t.%. %N.%p %E %U %C:%c %R:%r %O %I %h %T»
rotate 3
flush
auth iponly
dnspr
allow *
parent 1000 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ 3128 tester 1234
plugin /opt/proxy/3proxy-0.8.12/src/TransparentPlugin.ld.so transparent_plugin
tcppm -i0.0.0.0 888 127.0.0.1 11111

4. Теперь запускаем 3proxy с новым конфигом
root@debian9:/home/joke/proxy# /usr/local/bin/3proxy /home/joke/proxy/3proxytransp.conf

5. Снова добавим в crontab
root@debian9:/home/joke/proxy# crontab -e
@reboot /usr/local/bin/3proxy /home/joke/proxy/3proxytransp.conf

6. Посмотрим, что теперь слушает наш прокси
root@debian9:~# netstat -nlp

netstat log

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 349/sshd
tcp 0 0 0.0.0.0:888 0.0.0.0:* LISTEN 354/3proxy
tcp6 0 0 :::22 :::* LISTEN 349/sshd
udp 0 0 0.0.0.0:53 0.0.0.0:* 354/3proxy
udp 0 0 0.0.0.0:68 0.0.0.0:* 367/dhclient

7. Теперь прокси готов принимать любые TCP-соединения на порту 888, DNS на порту 53, чтобы потом их перенаправить в удаленный socks5 — прокси и DNS Гугл 8.8.8.8. Нам осталось настроить правила netfilter (iptables) и DHCP для выдачи адресов.

8. Установим пакет iptables-persistent и dhcpd

root@debian9:~# apt-get install iptables-persistent isc-dhcp-server

9. Правим файл запуска dhcpd
root@debian9:~# nano /etc/dhcp/dhcpd.conf

dhcpd.conf

# dhcpd.conf
#
# Sample configuration file for ISC dhcpd
#

# option definitions common to all supported networks…
option domain-name «example.org»;
option domain-name-servers ns1.example.org, ns2.example.org;

default-lease-time 600;
max-lease-time 7200;

ddns-update-style none;

# If this DHCP server is the official DHCP server for the local
# network, the authoritative directive should be uncommented.

authoritative;

# A slightly different configuration for an internal subnet.
subnet 192.168.201.0 netmask 255.255.255.0 {
range 192.168.201.10 192.168.201.250;
option domain-name-servers 192.168.201.254;
option routers 192.168.201.254;
option broadcast-address 192.168.201.255;
default-lease-time 600;
max-lease-time 7200;
}

11. Перезагружаемся и проверяем службу на порту 67
root@debian9:~# reboot
root@debian9:~# netstat -nlp

netstat log

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 389/sshd
tcp 0 0 0.0.0.0:888 0.0.0.0:* LISTEN 310/3proxy
tcp6 0 0 :::22 :::* LISTEN 389/sshd
udp 0 0 0.0.0.0:20364 0.0.0.0:* 393/dhcpd
udp 0 0 0.0.0.0:53 0.0.0.0:* 310/3proxy
udp 0 0 0.0.0.0:67 0.0.0.0:* 393/dhcpd
udp 0 0 0.0.0.0:68 0.0.0.0:* 405/dhclient
udp6 0 0 :::31728 :::* 393/dhcpd
raw 0 0 0.0.0.0:1 0.0.0.0:* 393/dhcpd

12. Осталось перенаправить все tcp запросы на порт 888 и сохранить правило в iptables

root@debian9:~# iptables -t nat -A PREROUTING -s 192.168.201.0/24 -p tcp -j REDIRECT --to-ports 888

root@debian9:~# iptables-save > /etc/iptables/rules.v4

13. Для расширения полосы канала можно использовать сразу несколько прокси-серверов. Общая сумма должна быть 1000. Новые соединения устанавливаются с вероятностью 0.2, 0.2, 0.2, 0.2, 0,1, 0,1 к указанным прокси-серверам.

Примечание: если у нас web-прокси то вместо socks5 нужно писать connect, если socks4, то socks4 (socks4 НЕ ПОДДЕРЖИВАЕТ АВТОРИЗАЦИЮ ЛОГИН/ПАРОЛЬ!)

Пример конфигурации прозрачного прокси-сервера №2

daemon
pidfile /home/joke/proxy/3proxy.pid
nserver 8.8.8.8
nscache 65536
maxconn 500
timeouts 1 5 30 60 180 1800 16 60
log /home/joke/proxy/logs/3proxy.log D
logformat «- +_L%t.%. %N.%p %E %U %C:%c %R:%r %O %I %h %T»
rotate 3
flush
auth iponly
dnspr
allow *

parent 200 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№1 3128 tester 1234
parent 200 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№2 3128 tester 1234
parent 200 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№3 3128 tester 1234
parent 200 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№4 3128 tester 1234
parent 100 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№5 3128 tester 1234
parent 100 socks5 IP_АДРЕС_ВНЕШНЕГО_ПРОКСИ№6 3128 tester 1234

plugin /opt/proxy/3proxy-0.8.12/src/TransparentPlugin.ld.so transparent_plugin
tcppm -i0.0.0.0 888 127.0.0.1 11111

Настройка и запуск конфигурации NAT + Transparent Proxy

В данной конфигурации мы будем использовать обычный механизм NAT с выборочным или полным прозрачным проксированием отдельных адресов или подсетей. Пользователи внутренней сети будут работать с определенными сервисами/подсетями даже не догадываясь, что они работают через прокси. Все https соединения работают прекрасно, никаких сертификатов генерировать/подменять не нужно.

Для начала определимся, какие подсети/сервисы мы хотим проксировать. Предположим, что внешние прокси-сервера находятся там, где работает такой сервис, как pandora.com. Теперь осталось определить его подсети/адреса.

1. Пингуем

root@debian9:~# ping pandora.com
PING pandora.com (208.85.40.20) 56(84) bytes of data.

2. Набираем в гугле BGP 208.85.40.20

Переходим на сайт bgp.he.net/net/208.85.40.0/24#_netinfo
Видно, что искомаю подсеть это AS40428 Pandora Media, Inc

bgp.he.net/net/208.85.40.0/24#_netinfo

Открываем префиксы v4

bgp.he.net/AS40428#_prefixes

Вот и искомые подсети!

199.116.161.0/24
199.116.162.0/24
199.116.164.0/23
199.116.164.0/24
199.116.165.0/24
208.85.40.0/24
208.85.41.0/24
208.85.42.0/23
208.85.42.0/24
208.85.43.0/24
208.85.44.0/24
208.85.46.0/23
208.85.46.0/24
208.85.47.0/24

3. Для уменьшения количества подсетей нужно выполнить агрегацию. Переходим на сайт ip-calculator.ru/aggregate и копируем туда наш список. Как результат — 6 подсетей вместо 14-ти.

199.116.161.0/24
199.116.162.0/24
199.116.164.0/23
208.85.40.0/22
208.85.44.0/24
208.85.46.0/23

4. Очищаем правила iptables

root@debian9:~# iptables -F
root@debian9:~# iptables -X
root@debian9:~# iptables -t nat -F
root@debian9:~# iptables -t nat -X

Включаем механизм forward и NAT

root@debian9:~# echo 1 > /proc/sys/net/ipv4/ip_forward
root@debian9:~# iptables -A FORWARD -i enp0s3 -o enp0s8 -j ACCEPT
root@debian9:~# iptables -A FORWARD -i enp0s8 -o enp0s3 -j ACCEPT
root@debian9:~# iptables -t nat -A POSTROUTING -o enp0s3 -s 192.168.201.0/24 -j MASQUERADE

Чтобы forward был включен постоянно после перезагрузки изменим файл

root@debian9:~# nano /etc/sysctl.conf

И раскомментируем строку

net.ipv4.ip_forward = 1

Ctrl+X для сохранения файла

5. Заворачиваем подсети pandora.com в прокси

root@debian9:~# iptables -t nat -A PREROUTING -s 192.168.201.0/24 -d 199.116.161.0/24,199.116.162.0/24,199.116.164.0/23,208.85.40.0/22,208.85.44.0/24,208.85.46.0/23 -p tcp -j REDIRECT --to-ports 888

6. Сохраним правила

root@debian9:~# iptables-save > /etc/iptables/rules.v4

Настройка и запуск конфигурации Transparent Proxy via router

В данной конфигурации прозрачный прокси-сервер может быть отдельным ПК или виртуальной машиной за домашним/корпоративным роутером. Достаточно прописать статические маршруты на роутере или устройствах и вся подсеть будет использовать прокси без необходимости каких-либо дополнительных настроек.

ВАЖНО! Необходимо, чтобы наш шлюз получал статический IP от роутера, либо был настроен на статику сам.

1. Настраиваем статический адрес шлюза (адаптер enp0s3)

root@debian9:~# nano /etc/network/interfaces

/etc/network/interfaces file

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug enp0s3
iface enp0s3 inet static
address 192.168.23.2
netmask 255.255.255.0
gateway 192.168.23.254

# The secondary network interface
allow-hotplug enp0s8
iface enp0s8 inet static
address 192.168.201.254
netmask 255.255.255.0

2. Разрешаем устройствам из подсети 192.168.23.0/24 использовать проксирование

root@debian9:~# iptables -t nat -A PREROUTING -s 192.168.23.0/24 -d 199.116.161.0/24,199.116.162.0/24,199.116.164.0/23,208.85.40.0/22,208.85.44.0/24,208.85.46.0/23 -p tcp -j REDIRECT --to-ports 888

3. Сохраним правила
root@debian9:~# iptables-save > /etc/iptables/rules.v4

4. Пропишем подсети на роутере

Router network list

199.116.161.0 255.255.255.0 192.168.23.2
199.116.162.0 255.255.255.0 192.168.23.2
199.116.164.0 255.255.254.0 192.168.23.2
208.85.40.0 255.255.252.0 192.168.23.2
208.85.44.0 255.255.255.0 192.168.23.2
208.85.46.0 255.255.254.0 192.168.23.2

Использованные материалы/ресурсы

1. Официальный сайт программы 3proxy 3proxy.ru

2. Инструкция по установке 3proxy из исходников www.ekzorchik.ru/2015/02/how-to-take-your-socks-proxy

3. Ветка разработчика 3proxy на GitHub github.com/z3APA3A/3proxy/issues/274

Решил написать мини-обзор по установке и настройке прокси-сервера Squid под Windows. Сразу хочу сказать, что статья рассчитана на начинающих, которые хотят познакомиться со Squid как таковым, поэтому прошу все коменты типа «фи, как это можно юзать под виндой» оставить при себе.

Для ценителей истинного Squid прошу пожаловать в наш специальный обзор на эту тему — Прокси Squid на Linux с авторизацией в Active Directory. А пока разберем более простой вариант. Конечно, версия под Windows не так хороша как под родные unix-like системы, но для первого знакомства подойдет.

Прокси бывает очень полезен, когда нужно несколько разграничить доступ в интернет либо просто выпусить в интернет несколько компов, а скорость подключения оставляет желать лучшего. Прокси обычно устанавливают на отдельный комп, чаще всего на тот, который собственно и «раздает» интернет в локальную сеть, браузеры других компов настраивают на работу с этим прокси-сервером. Далее уже на прокси пишутся правила: кому и когда на какие сайты ходить можно, куда ходить нельзя, что можно скачивать, что нельзя и т.д. Вариантов бесконечное множество.

Итак, Squid — это кэширующий прокси с внушительным набором функций. Распространяется по лицензии GNU GPL (читай бесплатно). Немного о Squid можно почитать в Wiki. Готовые к скачиванию дистрибутивы под винду можно найти на официальном ресурсе здесь. Крайняя стабильная версия Squid — 2.7, разрабатываемая версия — 3.0, при этом под unix-like платформы 3.0 уже идет как резиная версия, а под Windows как Beta из-за некоторых проблем с адаптацией под винду. По этой причине для знакомства мы рекомендуем воспользоваться именно версией 2.7.

Надеюсь, что пока никаких вопросов нет, поэтому давайте скачаем дистрибутив и займемся установкой. После загрузки распаковываем архив в котором будет папка squid. Помещаем эту папку прямо на диск С. Должно получиться так, чтобы в папке C:squid находились все подпапки типа etc, bin, sbin и пр. Кто-то спросит нафига там столько подпапок? Отвечаем: в отличие от Windows, в которой программа чаще всего распологается в одном каталоге, в unix-like системах каждый каталог предусмотрен под какие-то определенные нужды. Один каталог — под файлы настроек для всех установленных программ, второй каталог — под исполняемые файлы всех программ, третий каталог — плагины, четвертый — логи и т.д. Т.е. разные файлы одной программы хранятся сразу в нескольких папках. Пока нам надо усвоить то, что исполняемый файл Squid находится в каталоге sbin, файл настроек в каталоге etc, а все логи будут записываться в каталог varlog.

Самое главное что нам нужно сделать — это написать конфигурационный файл. В папке etc есть файл squid.conf.default копируем рядом и переименовываем копию в squid.conf. Должно получиться вот так:

После этого аналогичным образом копируем:
mime.conf.default в mime.conf и cachemgr.conf.default в cachemgr.conf.Открываем squid.conf в любом текстовом редакторе, например, в блокноте и стираем всё, чтобы у нас получился пустой файл, сохраняемся. mime.conf и cachermgr.conf трогать не нужно.

Прокси работает следующим образом: в настройках каждого браузера на компах локальной сети устанавливается опция с IP-адресом и портом прокси, например вот так (адрес моего прокси-сервера 192.168.1.2 и порт 3128):

Т.о. весь web-трафик от браузеров идет на указанный адрес, Squid в свою очередь передает эти запросы от своего имени в интернет. Входящий трафик из интернета попадает сначала на прокси и потом переадресовывается в локальную сеть клиентскому браузеру. Эта схема распространена повсеместно, но у нее есть один очевидный недостаток — все браузеры нужно руками настраивать на работу с прокси-сервером, иначе доступа в интернет не будет вообще. У прокси есть второй режим работы, называемый transparent, т.е. прозрачный. В прозрачном режиме в браузерах вообще ничего настраивать не нужно, как будто и нас нет никакого прокси. В этом случае все запросы идут на шлюз по умолчанию, коим должен являться маршрутизатор, раздающий интернет в локальной сети. На маршрутизаторе нужно добавить правило перенаправления, чтобы все web-запросы шли на комп с прокси. Этот вариант более интересный, однако здесь требуется дополнительная настройка маршрутизатора. К тому же Squid по Windows не поддерживает функцию прозрачного проксирования, поэтому мы пока не будем рассматривать этот вариант.
Вернемся к нашему пустому файлу конфигурации. Первым делом нам надо указать на каком IP-адресе и порту будет работать прокси. IP-адрес берется адрес компа в локальной сети (пусть у нас он будет 192.168.1.2), а порт в принципе можно выбрать любой, но обычно придерживаются стандартных значений, коими являются 3128 или 8080. Пишем в файл строку:
http_port 192.168.1.2:3128
Еще Squid любит, чтобы ПК, на котором он установлен как-то назывался. Для этого в конфиурационный файл нужно добавить строку visible_hostname [имя]. Мы напишем так:
visible_hostname myproxy
Решение о том, какой трафик и куда пропускать или запрещать принимается на основании правил, которые в свою очередь строятся из списков доступа.

Сейчас мы определим несколько списоков доступа и сделаем одно правило. В данном случае значение слова «список» нужно понимать несколько иначе: одна строка, которая начинается со слова acl это и есть один список. Две строки — два списка, много строк acl — списки. Общий синтаксис для списков выглядит вот так:
acl [имя_списка] [тип параметра] [параметр 1] [параметр 2] … [параметр n].
Первым идет служебное слово acl, затем имя списка. Имя может быть произвольным за одним исключением, о нем чуть позже. Тип параметра — чаще всего используются значения src (источник) или dst (получатель). Параметры — это кокретные значения, которые относятся к src или dst.
В конфигурационном файле обязательно должен присутствовать как минимум один список доступа, который описывает всех клиентов прокси. Все клиенты обозначаются стандартным словом all. В итоге наша первая команда дорожна выглядеть вот так:
acl all src 0.0.0.0/0.0.0.0
В данном случае 0.0.0.0/0.0.0.0 обозначает любые адреса и маски. Затем определим нашу локальную сеть, список назовем LAN:
acl LAN src 192.168.1.0/255.255.255.0
Следующий список доступа будет описывать у нас тип проходящего трафика. Для начала мы возьмем обычный HTTP-трафик, который передается по 80-му и 443 портам. В следующей строке пишем:
acl HTTP port 80 443
И теперь напишем правило, которое будет разрешать хождения HTTP-трафика со всех компов нашей локальной сети. Правила обозначаются командой
http_access [allow (разрешить) или deny (запретить)] [перечисление имен списков доступа через пробел].

Мы напишем вот такое правило:
http_access allow LAN HTTP
Надо сказать еще одну важную вещь. Когда мы пишем перечисление нескольких параметров через пробел, то нужно знать, что в списках доступа каждый пробел понимается как «ИЛИ», а в правилах доступа как «И». Например, наше написанное правило звучит так: доступ (http_access) разрешить (allow) если пакет с данными можно отнести к списку доступа LAN И в тоже самое время пакет можно отнести к списку доступа HTTP. А вот список доступа HTTP будет звучать так: пакет данных идет на порт 80 ИЛИ на порт 443. Это нужно понимать, чтобы правильно составлять списки доступа и правила. Когда пишем списки доступа, то можно их писать в любом порядке, а вот очередность написания правил играет ключевую роль. Пакет с данными обрабатывает до первого правила, под котрое он подходит по своим параметрам.
Далее я покажу простой пример ограничения доступа в интернет. Например, на компом с адресом 192.168.1.10 у нас сидит работник, которому нужно ограничить доступ. Нет ничего проще. Сначала пишем список доступа:
acl Vasya src 192.168.1.10
После этого нужно создать правило блокировки и поместить его до того правила, которое разршает доступ и интернет всем компам локальной сети. В итоге оба правила должны выглядеть так:
http_access deny Vasya
http_access allow LAN HTTP
Мы прописали самые необходимые вещи, теперь конфигурационный файл можно сохранить. Целиком он должен выглядеть вот так:

http_port 192.168.1.1:3128
visible_hostname myproxy

acl all src 0.0.0.0/0.0.0.0
acl LAN src 192.168.1.0/255.255.255.0
acl HTTP port 80 443
acl Vasya src 192.168.1.10


http_access deny Vasya
http_access allow LAN HTTP

Далее нам нужно сформировать каталоги для хранения кэша. Делается это просто: в командной строке надо набрать
С:squidsbinsquid.exe -z

После этого установим Squid в качестве службы Windows, набрав
С:squidsbinsquid.exe -i

Теперь идем в Панель управления/Администрирование/Службы, ищем там Squid и запускаем его. Остается настроить какой-нибудь браузер на наш прокси-сервер и проверить работоспособность.

По мере сил и возможностей мы периодически дополняем и редактируем этот обзор.

Если вам хочется иметь функциональность Squid, но нет сил/времени/навыков настраивать всё это — обязательно посмотрите другие альтернативы — BlockAdultProxy или 3proxy

Transparent Proxy Tool

part_1.png

part_2.png

Overview

This transparent proxy tool allows you to redirect all TCP traffic through a SOCKS5 proxy created via an SSH tunnel. The tool supports both Windows (limited functionality with manual proxy configuration) and Linux (full transparent proxy capability using redsocks and iptables).

Features

  • Creates SSH tunnels with SOCKS5 proxy capability
  • Supports both password and key-based SSH authentication
  • Transparent traffic redirection (Linux only) using redsocks and iptables
  • Comprehensive traffic verification to ensure proper redirection
  • Detailed logging for troubleshooting

Requirements

  • Python 3.11.0 or higher
  • root privileges
  • SSH client installed and available in PATH
  • On Linux: iptables, redsocks, and net-tools installed

Installation

  1. Clone the repository
  2. Install dependencies:
pip install -r requirements.txt --break-system-packages
  1. For Linux systems, ensure redsocks is installed (btw i’m not using arch, just saying)
# Debian/Ubuntu
sudo apt install redsocks net-tools

Configuration

Create a .env file in the project root with the following variables:

REMOTE_HOST=your.ssh.server.com    # SSH server address
SSH_USER=username                  # SSH username
SSH_AUTH_METHOD=password           # Use 'password' or 'key'
SSH_AUTH_VALUE=yourpassword        # Password or path to private key
SSH_TUNNEL_PORT=2050               # Local port for SOCKS5 proxy
REDSOCKS_PORT=5020                 # Port for redsocks service

Usage

Running the Tool

Verifying Proxy Operation

After starting the tool, it will:

  1. Set up an SSH tunnel with SOCKS5 capability
  2. Start redsocks service (Linux only)
  3. Configure iptables for traffic redirection (Linux only)
  4. Verify traffic redirection is working properly

The program will show:

  • ✓ If iptables rules are correctly configured
  • Number of packets being redirected
  • Your current public IP address (should be different from your actual IP)
  • Results of DNS resolution tests
  • Active connections through the proxy

Platform-Specific Information

Linux

  • Full transparent proxy capability
  • All TCP traffic is automatically redirected through the proxy
  • No application configuration needed

Windows

  • NOT SUPPORTED

Understanding Redsocks Logs

Redsocks logs provide valuable information about the proxy operation. Here’s how to interpret common log entries:

1746266222.079531 notice main.c:165 main(...) redsocks started, conn_max=128
  • Indicates redsocks has started successfully with maximum 128 connections
1746266222.083519 info redsocks.c:1243 redsocks_accept_client(...) [127.0.0.1:41460->127.0.0.1:5020]: accepted
  • Shows a client connection was accepted from 127.0.0.1:41460 to the redsocks port (5020)
1746266264.804697 warning redsocks.c:1437 redsocks_fini_instance(...) There are connected clients during shutdown!
  • Warning that clients were still connected when redsocks was shutting down
1746266264.804869 notice redsocks.c:678 redsocks_drop_client(...) [127.0.0.1:41460->127.0.0.1:5020]: client tries to connect to the proxy using proxy!
  • This indicates a proxy loop — the client is trying to connect to the proxy through itself

Common issues visible in logs:

  • Connection loops (proxy connecting through itself)
  • Connection rejections
  • Authentication failures
  • Timeouts when connecting to destination servers

Troubleshooting

  • Check the main.log file for detailed error information
  • Ensure SSH server is accessible from your network
  • Verify SSH credentials are correct
  • Ensure redsocks, iptables and net-tools are properly installed
  • Run verification checks to confirm traffic redirection is working properly

Stopping the Service

Press Ctrl+C to gracefully stop the service. This will:

  • Clean up iptables rules (Linux only)
  • Stop the redsocks service (Linux only)
  • Terminate the SSH tunnel

Security Considerations

  • Running with administrator/root privileges is required
  • SSH connections disable strict host key checking to prevent warnings
  • Consider using key-based authentication for better security

Setup a Transparent Proxy using Squid Proxy Server. In this post, we introduce Squid proxy, its advantages, and working principle then show you how to set up a transparent proxy using Squid.

After setting up a transparent proxy, you don’t need to define proxy settings on each user’s web browser. In this setup, the Squid server acts as a gateway between users and the internet. When any user accesses the internet, the transparent proxy redirects all the internet traffic from port 80 to the squid proxy’s port 3128.

Since the internet became publicly available, there has been ongoing competition to achieve the fastest internet connections. Proxy cache servers are one of the multiple means used to obtain steadily higher speeds. One of these servers is the Squid Proxy Cache Server. This article discusses Squid Proxy, how it works, and its advantages.

What is Squid Proxy?

An open source proxy server called Squid serves cache and proxy services for the Web. It operates as a reverse proxy, delivering client requests to servers, or a forward proxy, receiving and transmitting client requests to servers.

To create a new solution for a specific use case, Squid is commonly used in conjunction with a variety of other open source tools, including iptables and dnsmasq. Besides, Squid is designed to run on Unix like systems, including Linux and macOS.

Moreover, Squid is a highly configurable software program that is modified to match the specific needs of an individual or a company. Many companies prefer it due to its flexibility, configurability, and capacity to manage large traffic volumes.

How Does Squid Works?

how transparent proxy works

All in all, a proxy server for caching called Squid acts as a link between client computers and the Internet. Caching frequently accessed web pages, files, and other data increases the network speed and decreases the quantity of data transferred over the network.

Squid examines its cache when a client computer requests a website to see whether it already contains a copy of the content. If so, it delivers cached page to the client. If the page isn’t already in the cache, Squid fetches it from the Internet and stores a copy for later use in its cache.

Furthermore, Squid performs various tasks like request filtering, network optimization, and authentication. Let’s have a look at its process:

  • Client sends a request: A client, such as a web browser, sends a request for a resource, such as a web page, to the Squid proxy.
  • Squid checks the cache: Checks its cache to see if it already has a copy of the requested resource.
  • It returns cached resource: If the resource is in the cache, Squid returns the cached resource to the client.
  • Squid retrieves the resource: If the resource is not in the cache, Squid forwards the request to the appropriate server, retrieves the resource on behalf of the client, and caches the resource for future use.
  • It returns the resource to the client: Returns the retrieved resource to the client.

Advantages of Squid Proxy

Squid proxy not only secures your system proxy but also serves numerous advantages:

  • Security: Establish an additional layer of security for your network by setting Squid to filter out harmful or unwanted traffic.
  • Filtering: Squid proxy is beneficial for parental control, network security, and content filtering. You set it up to restrict access to particular sites or kinds of content.
  • Load balancing: Squid divides incoming requests among several backend servers, helping in load balancing and improving performance.
  • Access control: Administrators build up authentication and authorization procedures using Squid to control Internet access.
  • Authentication: Squid is set up to ask for user authentication before providing access to the internet. That proves to be beneficial in a corporate environment.
  • Customisation: Squid is highly flexible and adaptive to a company’s special needs.
  • Traffic optimization: Squid proxy compresses data, reduces the number of network requests, and prevents redundant data transfers, which may significantly increase web access speed.
  • Compatibility: Squid proxy is a flexible solution for various network settings because it supports numerous protocols, including HTTP, HTTPS, FTP, and others.

Overall, Squid proxy is a helpful tool for many users because it can improve the internet connection speed, security, and efficiency for both individuals and organizations.

We have arrived to the main part of of how to Setup a Transparent Proxy using Squid Proxy Server.

Setup a Transparent Proxy using Squid Proxy Server

This section explains how to set up Squid as a transparent proxy on Linux server.

Prerequisites

  • A server running Linux Operating System.
  • A root user or a user with sudo privileges.

Update the System

Before starting, it is always recommended to update your system with the latest packages.

To update Ubuntu and Debian based Linux distributions, run the following command.

				
					apt update -y
apt upgrade -y
				
			

If you want to update CentOS, RHEL, and Fedora based Linux distributions, run the following command.

Once your system is updated, proceed to the next step.

Setting Up IP Forwarding

In order to use Squid as a transparent proxy, you will need to enable IP forwarding on your server. Enable it by editing sysctl.conf file.

Uncomment the following line:

Save the file then run the following command to implement the changes.

Installing Squid Proxy Server

Next, you need to install the Squid proxy server package on your server. By default, this package is included in the default repository of all major Linux distributions.

For Ubuntu and Debian based Linux distributions, run the following command to install the Squid package.

If you want to install Squid on CentOS, RHEL and Fedora based Linux distributions, run the following command to install the Squid package.

After installing the Squid package, start the Squid service and enable it to start at system reboot.

				
					systemctl start squid
systemctl enable squid
				
			

Check the status of Squid with the following command.

Setup a Transparent Proxy using Squid Proxy Server. verify squid status

If you want to verify the Squid version, run the following command.

You should see the Squid version information on the following screen.

verify squid version

Configuring Squid as a Transparent Proxy

By default, the Squid main configuration file is located at /etc/squid/squid.conf. You need to edit it and modify some changes.

				
					nano /etc/squid/squid.conf
				
			

Change the following lines:

				
					http_access allow all
http_port 3128 intercept
visible_hostname squid.proxy

				
			

Save and close the file when you are finished. Then, restart the Squid service to implement the changes.

Once you are done, proceed to the next step.

Configuring Firewall Rules

Next step is to add some firewall rules to forward packets received at port 80 to Squid.

Configure Iptabes Firewall for Squid

If you are using iptables firewall then you add rules with the following command.

				
					iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3128
iptables --t nat -A POSTROUTING --out-interface eth1 -j MASQUERADE

				
			

You need to add modify the eth0 network interface if you have another interface configured on your server. Now, you list all your added rules with the following command.

You should see all iptables rules on the following screen.

Setup a Transparent Proxy using Squid Proxy Server. verify iptables rules

If you did any misconfiguration and want to delete all rules, run the following command.

Configure Firewalld Firewall for Squid

If you are using Firewalld firewall service then you add all rules with the following commands.

				
					firewall-cmd --permanent --zone=public --add-forward- port=port=80:proto=tcp:toport=3128:toaddr=squid-ip
firewall-cmd --permanent --zone=public --add-port=3128/tcp
firewall-cmd --permanent --add-masquerade
				
			

After adding all rules, reload the Firewalld service to implement the changes.

Configure Client to Use Squid Proxy Server

After setting up a Squid as a transparent proxy, you need to configure a client machine to route all internet traffic via the Squid server. Follow the below steps to configure the client machine.

Step 1 – Log in to your Ubuntu desktop in my example or your Windows desktop and open the Network settings. You should see the following screen.  If using Windows you find these settings in your browser settings.

Step 2 – Click on the + icon beside the Wired connection. You should see the Network configuration wizard.

configure network

Step 3 – Click on the IPv4 tab then provide private IP from Squid IP range, subnet mask, provide Squid server IP in gateway field, DNS IP then click on the Add button to save the changes. You should see the newly added network interface on the following screen.

At this point, your Squid server is configured as a transparent proxy. When any user accesses the internet, all request goes via the Squid server.

Thank you for reading Setup a Transparent Proxy using Squid Proxy Server. We shall conclude. 

Setup a Transparent Proxy using Squid Proxy Server Conclusion

In this post, you have learned how to install and configure Squid as a Transparent proxy on Linux. You can now track all user’s activity from the Squid server. As more people become aware of the benefits of using web proxies, their use has increased. Lastly, Proxy servers are becoming more common, especially among individual and casual customers, due to improved online security and accessibility.

Following, Squid proxies are often used by those seeking a two in one solution. It works as a caching tool in addition to serving as a reliable proxy server. Using a single Squid proxy does not necessitate the installation of any extra servers.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 11 поддержка процессоров ryzen
  • Windows terminal preview download
  • Как сделать монитор основным дисплеем на windows 10
  • Команда для установки windows store
  • Как сбросить пароль учетной записи на windows 10 при входе в систему