mirror of
https://github.com/3proxy/3proxy.git
synced 2026-11-26 23:59:41 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff3398c6a9 | ||
|
|
4fb5c95704 | ||
|
|
13a57812e5 | ||
|
|
a43c95023d | ||
|
|
75021a2003 | ||
|
|
bebc3894e2 | ||
|
|
ddb74a111c | ||
|
|
1e47e74c49 | ||
|
|
eca362af81 | ||
|
|
c31fe8367f | ||
|
|
f480c9dfe8 | ||
|
|
8de2be3b3b | ||
|
|
aea9ff8c94 | ||
|
|
e7bc76da73 | ||
|
|
207ddb7f02 | ||
|
|
f5ff81d0bc | ||
|
|
8c2ad56665 | ||
|
|
a986ed7a07 | ||
|
|
eceb5a22df | ||
|
|
7eba73fc8f |
No files matched your search
@@ -23,11 +23,8 @@ jobs:
|
||||
pwd
|
||||
echo "RELEASE=$(cat RELEASE)" >> $GITHUB_ENV
|
||||
echo "VERSION=$(date +%y%m%d%H%M%S)" >> $GITHUB_ENV
|
||||
echo "MAJOR=$(cat RELEASE | cut -d "-" -f 1)" >> $GITHUB_ENV
|
||||
echo "SUBMAJOR=$(cat RELEASE | cut -d "-" -f 2)" >> $GITHUB_ENV
|
||||
echo "MINOR=$(cat RELEASE | cut -d "-" -f 3)" >> $GITHUB_ENV
|
||||
- name: echo env
|
||||
run: echo "release $RELEASE version $VERSION major $MAJOR submajor $SUBMAJOR minor $MINOR"
|
||||
run: echo "release $RELEASE version $VERSION"
|
||||
- name: Linux libraries
|
||||
run: |
|
||||
sudo apt update
|
||||
|
||||
@@ -23,9 +23,6 @@ jobs:
|
||||
pwd
|
||||
echo "RELEASE=$(cat RELEASE)" >> $GITHUB_ENV
|
||||
echo "VERSION=$(date +%y%m%d%H%M%S)" >> $GITHUB_ENV
|
||||
echo "MAJOR=$(cat RELEASE | cut -d "-" -f 1)" >> $GITHUB_ENV
|
||||
echo "SUBMAJOR=$(cat RELEASE | cut -d "-" -f 2)" >> $GITHUB_ENV
|
||||
echo "MINOR=$(cat RELEASE | cut -d "-" -f 3)" >> $GITHUB_ENV
|
||||
- name: Linux libraries
|
||||
run: |
|
||||
sudo apt update
|
||||
|
||||
@@ -23,11 +23,8 @@ jobs:
|
||||
pwd
|
||||
echo "RELEASE=$(cat RELEASE)" >> $GITHUB_ENV
|
||||
echo "VERSION=$(date +%y%m%d%H%M%S)" >> $GITHUB_ENV
|
||||
echo "MAJOR=$(cat RELEASE | cut -d "-" -f 1)" >> $GITHUB_ENV
|
||||
echo "SUBMAJOR=$(cat RELEASE | cut -d "-" -f 2)" >> $GITHUB_ENV
|
||||
echo "MINOR=$(cat RELEASE | cut -d "-" -f 3)" >> $GITHUB_ENV
|
||||
- name: echo env
|
||||
run: echo "release $RELEASE version $VERSION major $MAJOR submajor $SUBMAJOR minor $MINOR"
|
||||
run: echo "release $RELEASE version $VERSION"
|
||||
- name: Linux libraries
|
||||
run: |
|
||||
sudo apt update
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
3proxy-0.9.8 Released August, 7 2026
|
||||
3proxy-0.9.9 Released August, 20 2026
|
||||
|
||||
!! Fix: use-after-free on the ftp:// request path in HTTP proxy, a request buffer reallocation left a stale pointer; heap corruption, requires authenticated access
|
||||
!! Fix: buffer overflow in radsend() with an oversized request hostname; RADIUS is experimental, log radius or auth radius with fakeresolve is required to reach it
|
||||
!! Fix: buffer overflow in smtpp when relaying AUTH LOGIN credentials to a server which offers AUTH PLAIN only; requires authorised access to smtpp
|
||||
!! Fix: out-of-bounds read in tlspr on a malformed TLS ClientHello
|
||||
!! Fix: LDAP injection and unsafe counter file names in LdapPlugin; the plugin is unsupported and is not built with 3proxy
|
||||
!! Fix: password and hash comparison in strong authentication is constant-time now
|
||||
!! Fix: bounds validation and match/depth limits in pcre filters
|
||||
+ imapp: IMAPv4 proxy added, supports LOGIN command, AUTH PLAIN and AUTH LOGIN
|
||||
+ STARTTLS support for smtpp, pop3p, imapp and tlspr, on both client and server side; -x option to disable
|
||||
+ wolfSSL is supported as an alternative TLS backend, WOLFSSL_CHECK=true selects it (wolfSSL must be built with --enable-opensslextra)
|
||||
+ Chunked Transfer-Encoding from client is supported by HTTP proxy
|
||||
+ dnspr: -F option added, fake resolve to redirect traffic
|
||||
+ ucrt64 build support; static libraries support in Makefile.win
|
||||
+ minimal and busybox Docker images switched to musl + wolfSSL
|
||||
- splice() support is not built by default anymore, it is slower than the read/write path for most traffic; add -DWITHSPLICE to build it
|
||||
! Fix: hashtable item was added with wrong index on table grow; with large username/password tables it could cause a single record to be missing
|
||||
! Fix: race conditions; stack overflow on FreeBSD
|
||||
! Fix: generated certificates are X.509 v3 with basicConstraints CA:FALSE and extendedKeyUsage serverAuth, required by Apple TLS stack and by Chrome on macOS/iOS
|
||||
! Fix: dnspr was broken since udppm rewrite
|
||||
! Fix: short cleartext passwords failed authentication
|
||||
! Fix: parent negotiation after sending PROXY protocol header
|
||||
! Fix: maxchild dropped to 100 on config reload if not set explicitly
|
||||
! Fix: getrandom() is not used with glibc below 2.25
|
||||
! Fix: IPV6_BOUND_IF definition for legacy MacOS
|
||||
! Fix: cmake build, arm64 Docker build, Makefile.win with UCRT
|
||||
! Multiple minor bugfixes and code cleanup
|
||||
! Fix: DNS replies are validated now: a reply from an address other than the nameserver the query was sent to, and a reply with a question section not matching the query, are dropped; both were accepted before
|
||||
! Fix: socket leak with SOCKSv5 UDP ASSOCIATE through a parent proxy, sockets were accumulated in CLOSE_WAIT state until descriptors ran out
|
||||
! Fix: file descriptor leak in HTTP proxy on the ftp:// request path
|
||||
! Fix: crash with illegal instruction on some platforms (e.g. some musl based Linux builds), caused by a memcpy on overlapping buffers
|
||||
! Fix: extip and ha (HAProxy PROXY protocol) parents are applied to SOCKSv5 UDP ASSOCIATE now
|
||||
! Fix: only socks5 and socks5+ parents are tried for UDP ASSOCIATE, other parent types can not be used for UDP
|
||||
! Fix: udppm through a SOCKSv5 parent did not work
|
||||
! Fix: -Ne and -Ni options were never applied, the option letter was not parsed; -Ne is not applied to the UDP ASSOCIATE reply anymore, -Ni is applied to it
|
||||
! Fix: -4 / -6 handling for UDP in socks; a single UDP association can use both IPv4 and IPv6 destinations now
|
||||
! Fix: a datagram with a null destination address is dropped now
|
||||
! Fix: DNS over TCP: a reply which did not fit a single read was never processed
|
||||
! Documentation: "How to apply ACLs to UDP traffic" added to HOWTO; authentication cache, ACL and UDP notes added to "Optimizing 3proxy for High Load" and to security recommendations
|
||||
+ SOCKSv5 UDP: the destination of every datagram is authorized, so ACLs limiting the destination address, host name or port apply to UDP traffic now; the parent proxy and the external address are selected for the destination of the datagram and not for the UDP ASSOCIATE request
|
||||
+ socks: -U option to control what happens when the destination changes within an UDP association: log it, authorize it, both (default) or neither
|
||||
+ -C option (for TCP services) to terminate the session as soon as any of the sides closes the connection; by default the session is kept until both sides close it (TCP half-close)
|
||||
+ timeouts: LINGER value added (11th, default 5), used to deliver buffered data after one of the sides has closed its sending side and as SO_LINGER value on outgoing connections
|
||||
+17
-27
@@ -1,28 +1,18 @@
|
||||
3proxy-0.9.8 Вышел 7 Августа 2026
|
||||
3proxy-0.9.9 Вышел 20 Августа 2026
|
||||
|
||||
!! Исправление: use-after-free на пути обработки запроса ftp:// в HTTP-прокси, перевыделение буфера запроса оставляло устаревший указатель; повреждение кучи, требуется аутентифицированный доступ
|
||||
!! Исправление: переполнение буфера в radsend() при слишком длинном имени хоста в запросе; RADIUS является экспериментальным, для достижения кода необходимы log radius или auth radius в сочетании с fakeresolve
|
||||
!! Исправление: переполнение буфера в smtpp при передаче учётных данных AUTH LOGIN серверу, поддерживающему только AUTH PLAIN; требуется авторизованный доступ к smtpp
|
||||
!! Исправление: чтение за границами буфера в tlspr при некорректном TLS ClientHello
|
||||
!! Исправление: LDAP-инъекция и небезопасные имена файлов счётчиков в LdapPlugin; плагин не поддерживается и не собирается вместе с 3proxy
|
||||
!! Исправление: сравнение паролей и хешей в strong-аутентификации теперь выполняется за постоянное время
|
||||
!! Исправление: проверка границ и ограничения match/depth в pcre-фильтрах
|
||||
+ imapp: добавлен IMAPv4-прокси, поддерживаются команда LOGIN, AUTH PLAIN и AUTH LOGIN
|
||||
+ Поддержка STARTTLS для smtpp, pop3p, imapp и tlspr, как со стороны клиента, так и со стороны сервера; опция -x для отключения
|
||||
+ wolfSSL поддерживается как альтернативный TLS-бэкенд, выбирается через WOLFSSL_CHECK=true (wolfSSL должен быть собран с --enable-opensslextra)
|
||||
+ HTTP-прокси поддерживает Transfer-Encoding: chunked от клиента
|
||||
+ dnspr: добавлена опция -F, фиктивное разрешение имён для перенаправления трафика
|
||||
+ Поддержка сборки ucrt64; поддержка статических библиотек в Makefile.win
|
||||
+ Docker-образы minimal и busybox переведены на musl + wolfSSL
|
||||
- Поддержка splice() больше не собирается по умолчанию, она медленнее пути read/write для большинства видов трафика; для сборки добавьте -DWITHSPLICE
|
||||
! Исправление: элемент хеш-таблицы добавлялся с неверным индексом при росте таблицы; на больших таблицах пользователей/паролей это могло приводить к отсутствию одной записи
|
||||
! Исправление: состояния гонки; переполнение стека во FreeBSD
|
||||
! Исправление: генерируемые сертификаты имеют формат X.509 v3 с basicConstraints CA:FALSE и extendedKeyUsage serverAuth, что требуется TLS-стеком Apple и Chrome в macOS/iOS
|
||||
! Исправление: dnspr был сломан со времён переписывания udppm
|
||||
! Исправление: короткие пароли в открытом виде не проходили аутентификацию
|
||||
! Исправление: согласование с родителем после отправки заголовка PROXY protocol
|
||||
! Исправление: maxchild сбрасывался в 100 при перезагрузке конфигурации, если не задан явно
|
||||
! Исправление: getrandom() не используется с glibc ниже 2.25
|
||||
! Исправление: определение IPV6_BOUND_IF для устаревших версий MacOS
|
||||
! Исправление: сборка cmake, сборка Docker для arm64, Makefile.win с UCRT
|
||||
! Множество мелких исправлений и очистка кода
|
||||
! Исправление: ответы DNS теперь проверяются: ответ с адреса, отличного от адреса сервера имён, которому был отправлен запрос, а также ответ с секцией вопроса, не совпадающей с запросом, отбрасываются; ранее оба принимались
|
||||
! Исправление: утечка сокетов при SOCKSv5 UDP ASSOCIATE через вышестоящий прокси, сокеты накапливались в состоянии CLOSE_WAIT до исчерпания дескрипторов
|
||||
! Исправление: утечка файловых дескрипторов в HTTP-прокси на пути обработки запроса ftp://
|
||||
! Исправление: аварийное завершение с недопустимой инструкцией на некоторых платформах (например, в некоторых сборках Linux на основе musl) из-за memcpy на перекрывающихся буферах
|
||||
! Исправление: родители типа extip и ha (HAProxy PROXY protocol) теперь применяются к SOCKSv5 UDP ASSOCIATE
|
||||
! Исправление: для UDP ASSOCIATE используются только родители socks5 и socks5+, остальные типы для UDP неприменимы
|
||||
! Исправление: udppm через вышестоящий прокси SOCKSv5 не работал
|
||||
! Исправление: опции -Ne и -Ni никогда не применялись, буква опции не разбиралась; -Ne больше не применяется к ответу на UDP ASSOCIATE, -Ni применяется к нему
|
||||
! Исправление: обработка -4 / -6 для UDP в socks; одна UDP-ассоциация теперь может использовать адреса назначения и IPv4, и IPv6
|
||||
! Исправление: датаграмма с нулевым адресом назначения теперь отбрасывается
|
||||
! Исправление: DNS поверх TCP: ответ, не помещавшийся в одно чтение, никогда не обрабатывался
|
||||
! Документация: в HOWTO добавлен раздел "Как применять ACL к UDP-трафику"; в "Optimizing 3proxy for High Load" и в рекомендации по безопасности добавлены заметки о кэше аутентификации, ACL и UDP
|
||||
+ SOCKSv5 UDP: адрес назначения каждой датаграммы авторизуется, поэтому ACL, ограничивающие адрес назначения, имя хоста или порт, теперь применяются к UDP-трафику; вышестоящий прокси и внешний адрес выбираются для адреса назначения датаграммы, а не для запроса UDP ASSOCIATE
|
||||
+ socks: опция -U для управления тем, что происходит при смене адреса назначения в рамках UDP-ассоциации: журналировать, авторизовать, и то и другое (по умолчанию) или ничего
|
||||
+ Опция -C (для TCP-сервисов) завершает сессию, как только любая из сторон закрывает соединение; по умолчанию сессия сохраняется, пока соединение не закроют обе стороны (полузакрытие TCP)
|
||||
+ timeouts: добавлено значение LINGER (11-е, по умолчанию 5), используется для доставки буферизованных данных после того, как одна из сторон закрыла свою передающую сторону, а также как значение SO_LINGER для исходящих соединений
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 0.9.8 | :white_check_mark: |
|
||||
| < 0.9.8 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Report to 3proxy@3proxy.org or via [GitHub security reporting](https://github.com/3proxy/3proxy/security)
|
||||
|
||||
For High/Critical patched version is released within 2 weeks
|
||||
Vendored
+6
@@ -1,3 +1,9 @@
|
||||
3proxy (0.9.9-1) buster; urgency=medium
|
||||
|
||||
*3proxy 0.9.9 initial build
|
||||
|
||||
-- z3APA3A <3apa3a@3proxy.org> Thu, 20 Aug 2026 18:29:37 +0300
|
||||
|
||||
3proxy (0.9.8-1) buster; urgency=medium
|
||||
|
||||
*3proxy 0.9.8 initial build
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
! Fix: DNS replies are validated now: a reply from an address other than the nameserver the query was sent to, and a reply with a question section not matching the query, are dropped; both were accepted before
|
||||
! Fix: socket leak with SOCKSv5 UDP ASSOCIATE through a parent proxy, sockets were accumulated in CLOSE_WAIT state until descriptors ran out
|
||||
! Fix: file descriptor leak in HTTP proxy on the ftp:// request path
|
||||
! Fix: crash with illegal instruction on some platforms (e.g. some musl based Linux builds), caused by a memcpy on overlapping buffers
|
||||
! Fix: extip and ha (HAProxy PROXY protocol) parents are applied to SOCKSv5 UDP ASSOCIATE now
|
||||
! Fix: only socks5 and socks5+ parents are tried for UDP ASSOCIATE, other parent types can not be used for UDP
|
||||
! Fix: udppm through a SOCKSv5 parent did not work
|
||||
! Fix: -Ne and -Ni options were never applied, the option letter was not parsed; -Ne is not applied to the UDP ASSOCIATE reply anymore, -Ni is applied to it
|
||||
! Fix: -4 / -6 handling for UDP in socks; a single UDP association can use both IPv4 and IPv6 destinations now
|
||||
! Fix: a datagram with a null destination address is dropped now
|
||||
! Fix: DNS over TCP: a reply which did not fit a single read was never processed
|
||||
! Documentation: "How to apply ACLs to UDP traffic" added to HOWTO; authentication cache, ACL and UDP notes added to "Optimizing 3proxy for High Load" and to security recommendations
|
||||
+ SOCKSv5 UDP: the destination of every datagram is authorized, so ACLs limiting the destination address, host name or port apply to UDP traffic now; the parent proxy and the external address are selected for the destination of the datagram and not for the UDP ASSOCIATE request
|
||||
+ socks: -U option to control what happens when the destination changes within an UDP association: log it, authorize it, both (default) or neither
|
||||
+ -C option (for TCP services) to terminate the session as soon as any of the sides closes the connection; by default the session is kept until both sides close it (TCP half-close)
|
||||
+ timeouts: LINGER value added (11th, default 5), used to deliver buffered data after one of the sides has closed its sending side and as SO_LINGER value on outgoing connections
|
||||
+174
-6
@@ -428,13 +428,181 @@ use 3proxy's built-in resolver (nserver / nscache / nscache6).
|
||||
Public resolvers like those from Google have rate limits. For a large number of
|
||||
requests, install a local caching recursor (ISC bind named, PowerDNS recursor, etc).
|
||||
|
||||
<h4>Avoid Large Lists</h4>
|
||||
<h4>Use the Authentication Cache</h4>
|
||||
|
||||
Currently, 3proxy is not optimized to use large ACLs, user lists, etc. All lists
|
||||
are processed linearly. In the devel version, you can use RADIUS authentication to avoid
|
||||
user lists and ACLs in 3proxy itself. Also, RADIUS allows you to easily set an outgoing IP
|
||||
on a per-user basis or implement more sophisticated logic.
|
||||
RADIUS is a new beta feature; test it before using it in production.
|
||||
Authentication and authorization are performed for every request. Password
|
||||
lookup itself is a hash lookup and is cheap, but the ACL is walked linearly,
|
||||
and with RADIUS or plugin authentication every request costs a network round
|
||||
trip. 'authcache' keeps the result of a successful authentication for a number
|
||||
of seconds:
|
||||
<pre>
|
||||
authcache <cachetype> <cachetime> <cachesize>
|
||||
</pre>
|
||||
'cachetype' lists the fields the entry is keyed by, 'cachetime' is the lifetime
|
||||
in seconds, and the optional 'cachesize' limits the number of entries. The
|
||||
cached type must be placed before the real authentication type in the 'auth'
|
||||
command: a cache miss falls through to the next type in the chain, and a hit
|
||||
skips it.
|
||||
|
||||
<p>There are two cached types:
|
||||
<ul>
|
||||
<li>'cache' caches the authentication only; the ACL is still checked on every
|
||||
request. Use it when ACLs must take effect immediately, or when the
|
||||
authentication method returns per-user parameters that the authorization step
|
||||
has to apply.
|
||||
<li>'cacheacl' also caches the authorization result, so the ACL is not walked
|
||||
at all on a hit. This is the one that helps with long ACLs, but the key must
|
||||
cover every field the ACL limits, and it can not be used with redirections.
|
||||
</ul>
|
||||
|
||||
<p><b>'cacheacl' does not work with parent proxies.</b> Redirections are applied
|
||||
while the ACL is walked, so on a 'cacheacl' hit no redirection happens at all:
|
||||
the request is sent directly instead of through the 'parent' proxy of the
|
||||
matching ACL entry, and nothing is reported. The first request for a given key
|
||||
uses the parent and the rest do not, which makes it look intermittent. Use
|
||||
'cache' with parent proxies:
|
||||
<pre>
|
||||
authcache user,pass 60
|
||||
auth cache strong
|
||||
allow user1
|
||||
parent 1000 socks5 10.0.0.1 1080
|
||||
proxy
|
||||
</pre>
|
||||
The one exception is 'parent ... extip': the external address is stored in the
|
||||
cache entry and restored on a hit, but only if 'ext' is a part of the key:
|
||||
<pre>
|
||||
authcache user,pass,ext 60
|
||||
auth cacheacl strong
|
||||
allow user1
|
||||
parent 1000 extip 1.2.3.4 0
|
||||
proxy
|
||||
</pre>
|
||||
Without 'ext' in the key the external address falls back to the default one on
|
||||
every cache hit.
|
||||
|
||||
<p><b>The key must match the ACL.</b> On a 'cacheacl' hit the cached result is
|
||||
reused as is, so any field the ACL limits but the key does not contain makes
|
||||
the cached result apply to a request it was not computed for. Use 'user' and
|
||||
'pass' for the userlist, 'ip' for the sourcelist, 'dstaddr' and 'dsthost' for
|
||||
the targetlist, 'dstport' for the targetportlist and 'dstoper' for the
|
||||
operationlist. For this ACL:
|
||||
<pre>
|
||||
allow user1,user2 * * 80,443
|
||||
deny *
|
||||
</pre>
|
||||
the key needs 'user', 'pass' and 'dstport':
|
||||
<pre>
|
||||
users $/etc/3proxy/passwd
|
||||
authcache user,pass,dstport 60 65536
|
||||
auth cacheacl strong
|
||||
allow user1,user2 * * 80,443
|
||||
deny *
|
||||
proxy
|
||||
</pre>
|
||||
|
||||
<p>With RADIUS the round trip is the expensive part, so cache by whatever
|
||||
identifies the client:
|
||||
<pre>
|
||||
radius secret 1.2.3.4
|
||||
authcache ip,user,pass 600
|
||||
auth cache radius
|
||||
proxy
|
||||
</pre>
|
||||
'cache' rather than 'cacheacl' is used here because RADIUS may return per-user
|
||||
parameters such as the outgoing IP; add 'ext' to the key to cache the external
|
||||
address returned by RADIUS as well.
|
||||
|
||||
<p>Choose 'cachetime' to balance the load against how quickly a password or ACL
|
||||
change has to take effect. Cache entries are <b>not</b> invalidated by a
|
||||
configuration reload, so a long lifetime keeps applying the old decision to
|
||||
existing keys after the new configuration is loaded.
|
||||
|
||||
<p>Note that 'ip' alone, or 'ip,user' without 'pass', assigns every connection
|
||||
from the same address to the same user for the lifetime of the entry without
|
||||
checking the password. That is a deliberate trade-off for high load; do not use
|
||||
it where clients share addresses.
|
||||
|
||||
<h4>Tune UDP Destination Handling with '-U'</h4>
|
||||
|
||||
Within a SOCKSv5 UDP association the destination is taken from every datagram,
|
||||
so 3proxy authorizes and logs every new destination. One association can reach
|
||||
any number of destinations: a DNS forwarder produces one record, but a
|
||||
peer-to-peer or QUIC client can produce hundreds, each costing an authorization
|
||||
(a network round trip with RADIUS or plugin authentication) and a log record.
|
||||
The 'socks' service option '-U' controls this:
|
||||
<pre>
|
||||
socks -U3 # default: log and authorize every new destination
|
||||
socks -U2 # authorize, do not log
|
||||
socks -U1 # log, do not authorize
|
||||
socks -U0 # neither (same as bare -U)
|
||||
</pre>
|
||||
The destination of the first datagram is always authorized and logged, so the
|
||||
association as a whole is still subject to ACLs, authentication and the choice
|
||||
of the parent proxy.
|
||||
|
||||
<p>Before reaching for the option, note that the cost is already avoided when no
|
||||
ACL entry reachable by the client limits the destination: in that case the
|
||||
result can not depend on the destination and no re-authorization is performed
|
||||
whatever '-U' says. '-U' only matters for configurations that do limit the
|
||||
destination.
|
||||
|
||||
<p>For high load:
|
||||
<ul>
|
||||
<li><b>'-U2'</b> is the safe one. Destination ACLs keep working, only the
|
||||
per-destination log records are dropped. Use it when log volume, not CPU, is
|
||||
the problem.
|
||||
<li><b>'-U' ('-U0')</b> removes both costs and is the fastest, but destination
|
||||
ACLs then apply only to the first destination of each association, and the
|
||||
parent proxy and external address chosen for it are kept for the whole
|
||||
association. Use it when UDP destinations are not restricted anyway, or when
|
||||
the restriction is enforced elsewhere (a firewall, or the parent proxy).
|
||||
<li>Keep the default '-U3' when destination ACLs are a security boundary, and
|
||||
make the authorization itself cheap with 'authcache' instead, see "Use the
|
||||
Authentication Cache" above.
|
||||
</ul>
|
||||
|
||||
<h4>Avoid Large ACLs</h4>
|
||||
|
||||
Most of the large data structures are hash tables and scale to a large number of
|
||||
records: the user list loaded by 'users' (including the '$/path/to/file' form),
|
||||
the authentication cache ('authcache'), the DNS cache ('nscache'/'nscache6') and
|
||||
the client table of the UDP portmapper. Their size is not a concern.
|
||||
|
||||
<p>The ACL is the exception and is still processed linearly. Every request walks
|
||||
the access list entry by entry until one matches, and within an entry the
|
||||
userlist, the sourcelist, the targetlist and the targetportlist are walked
|
||||
linearly as well, so the cost is roughly the number of entries multiplied by the
|
||||
size of the lists inside them. The 'bandlimin'/'bandlimout' and
|
||||
'countin'/'countout' rules are separate lists of the same kind and are walked on
|
||||
every request in addition to the access list.
|
||||
|
||||
<p>Two things follow from this:
|
||||
<ul>
|
||||
<li>Order matters. The walk stops at the first matching entry, so put the
|
||||
entries that match most of the traffic first.
|
||||
<li>Prefer fewer, wider entries over many narrow ones. One entry with a long
|
||||
userlist is cheaper than one entry per user, because the outer walk is repeated
|
||||
for every entry while the inner list is only walked for entries that got that
|
||||
far.
|
||||
</ul>
|
||||
|
||||
<p>With a large ACL, cache the authorization result instead of shortening the
|
||||
list. 'cacheacl' walks the ACL once per cache entry rather than once per
|
||||
request:
|
||||
<pre>
|
||||
users $/etc/3proxy/passwd
|
||||
authcache user,pass,dstaddr,dstport 60 65536
|
||||
auth cacheacl strong
|
||||
</pre>
|
||||
Both limitations from "Use the Authentication Cache" above apply: the cache key
|
||||
must contain every field the ACL limits, and 'cacheacl' must not be used
|
||||
together with parent proxies. Where a parent proxy is required, plain 'cache'
|
||||
still removes the authentication cost but leaves the ACL walk on every request.
|
||||
|
||||
<p>RADIUS moves the user list and the ACLs out of 3proxy entirely, and also
|
||||
allows you to set an outgoing IP on a per-user basis or to implement more
|
||||
sophisticated logic. RADIUS is a new beta feature; test it before using it in
|
||||
production.
|
||||
|
||||
<h4>Avoid Changing Configuration Too Often</h4>
|
||||
|
||||
|
||||
@@ -1338,6 +1338,82 @@ the second hop is 192.168.20.1, and the 3rd one is either 192.168.30.1 with a pr
|
||||
of 30% or 192.168.40.1 with a probability of 70%.
|
||||
</p>
|
||||
|
||||
<li><a name="UDPACL">How to apply ACLs to UDP traffic</a>
|
||||
<p>
|
||||
A SOCKSv5 UDP ASSOCIATE request only asks 3proxy to open a relay port, it
|
||||
carries no destination. The destination is taken from every datagram the client
|
||||
sends afterwards, so a single association may reach any number of destinations.
|
||||
3proxy authorizes the destination of every datagram, so ACLs limiting the
|
||||
destination address, host name or port do apply to UDP traffic.
|
||||
</p>
|
||||
<p>
|
||||
Differences from TCP:
|
||||
</p>
|
||||
<ul>
|
||||
<li>A datagram to a denied destination is dropped, the association is not
|
||||
terminated.
|
||||
<li>The parent proxy and the external address are selected for the destination
|
||||
of the datagram and not for the ASSOCIATE request, and are re-established if a
|
||||
later destination selects another ACL entry. Only <code>socks5</code> and
|
||||
<code>socks5+</code> parents can be used for UDP.
|
||||
<li>ACLs are checked for the datagrams sent by the client only. A datagram
|
||||
received on the association is relayed to the client without an ACL check: with
|
||||
a parent proxy only the datagrams from the parent are accepted, an association
|
||||
without a parent accepts a datagram from any source. The source reported to the
|
||||
client is the actual source of the datagram. The address in the log record is the destination the
|
||||
client sent the datagrams to, the source of the received datagrams is not
|
||||
logged.
|
||||
<li>A client may use a single association to reach many destinations. An ACL
|
||||
entry which limits the destination silently drops the datagrams to every other
|
||||
destination, so limiting the destination of UDP traffic can break such clients
|
||||
in a way which is hard to diagnose. Limit it only when it is really required.
|
||||
<li>Bandwidth limiters and traffic counters which limit the destination are
|
||||
selected when the destination is authorized, so they are selected for the
|
||||
destination of the first datagram and are not re-selected for every following
|
||||
destination. They can not be applied per destination to incoming UDP traffic at
|
||||
all.
|
||||
<li>Every change of the destination host name, address or port is authorized
|
||||
again and logged. Use <code>nscache</code> for host names and the
|
||||
authentication cache for anything more expensive than 'iponly'. The
|
||||
<code>-U</code> option of the <code>socks</code> service turns the logging
|
||||
and/or the re-authorization off; with <code>-U0</code> or <code>-U1</code>
|
||||
only the first destination of an association is authorized.
|
||||
</ul>
|
||||
<p>
|
||||
Limit the destinations a client may send datagrams to:
|
||||
</p><pre>
|
||||
auth iponly
|
||||
allow * * 8.8.8.8 53
|
||||
deny *
|
||||
socks -p1080
|
||||
</pre>
|
||||
<p>
|
||||
The ASSOCIATE request succeeds, datagrams to 8.8.8.8:53 are relayed, datagrams
|
||||
to any other destination are dropped.
|
||||
</p>
|
||||
<p>
|
||||
The same with 'strong' (or RADIUS, or plugin) authentication, where every new
|
||||
destination would otherwise be authenticated again:
|
||||
</p><pre>
|
||||
users user1:CL:password
|
||||
authcache user,pass,dstaddr,dstport 60
|
||||
auth cacheacl strong
|
||||
allow user1 * 8.8.8.8 53
|
||||
deny *
|
||||
socks -p1080
|
||||
</pre>
|
||||
<p>
|
||||
With 'cacheacl' the ACL result is not re-evaluated on a cache hit, so every
|
||||
field the ACL limits must be a part of the cache key: 'user' and 'pass' for the
|
||||
userlist, 'dstaddr' and 'dstport' for the targetlist and the targetportlist,
|
||||
'ip' for the sourcelist, 'dsthost' for host names in the targetlist, 'dstoper'
|
||||
for the operationlist. Without the destination in the key the result cached for
|
||||
one destination is applied to any other destination and the destination is not
|
||||
checked at all. Use plain 'cache' instead of 'cacheacl' if ACLs may change
|
||||
during the cache lifetime, or if a parent proxy is used: on a 'cacheacl' hit
|
||||
the ACL is not walked, so no parent proxy is selected and datagrams are sent
|
||||
directly.
|
||||
</p>
|
||||
<li><A NAME="BANDLIM">How to limit bandwidth</a>
|
||||
<p>
|
||||
3proxy supports bandwidth filters. Use the bandlimin/bandlimout and
|
||||
|
||||
@@ -1371,6 +1371,85 @@ pcre_extend deny * 192.168.0.1/16
|
||||
192.168.10.1, второе - 192.168.20.1, а третье - либо 192.168.30.1 с
|
||||
вероятностью 0.3 либо 192.168.40.1 с вероятностью 0.7
|
||||
</p>
|
||||
<li><a name="UDPACL"><i>Как применять ACL к UDP трафику</i></a>
|
||||
<p>
|
||||
Запрос SOCKSv5 UDP ASSOCIATE лишь просит 3proxy открыть порт для ретрансляции
|
||||
и не содержит адреса назначения. Адрес назначения берется из каждой
|
||||
датаграммы, отправленной клиентом, поэтому одна ассоциация может обращаться
|
||||
к любому числу адресов назначения. 3proxy авторизует адрес назначения каждой
|
||||
датаграммы, поэтому ACL, ограничивающие адрес, имя хоста или порт
|
||||
назначения, применяются и к UDP трафику.
|
||||
</p>
|
||||
<p>
|
||||
Отличия от TCP:
|
||||
</p>
|
||||
<ul>
|
||||
<li>Датаграмма к запрещенному адресу назначения отбрасывается, ассоциация
|
||||
при этом не завершается.
|
||||
<li>Вышестоящий прокси и внешний адрес выбираются для адреса назначения
|
||||
датаграммы, а не для запроса ASSOCIATE, и устанавливаются заново, если
|
||||
последующий адрес назначения соответствует другой записи ACL. Для UDP
|
||||
могут использоваться только родители типа <code>socks5</code> и
|
||||
<code>socks5+</code>.
|
||||
<li>ACL проверяются только для датаграмм, отправленных клиентом. Датаграмма,
|
||||
полученная в рамках ассоциации, передается клиенту без проверки ACL: при
|
||||
использовании вышестоящего прокси принимаются только датаграммы от него, а
|
||||
ассоциация без вышестоящего прокси принимает датаграмму от любого источника.
|
||||
Клиенту сообщается фактический адрес источника датаграммы. В журнал записывается адрес назначения, на который клиент
|
||||
отправлял датаграммы, а не адрес источника полученных датаграмм.
|
||||
<li>Клиент может использовать одну ассоциацию для обращения ко многим адресам
|
||||
назначения. Запись ACL, ограничивающая адрес назначения, молча отбрасывает
|
||||
датаграммы ко всем остальным адресам назначения, поэтому ограничение адреса
|
||||
назначения для UDP может нарушить работу таких клиентов, и причину трудно
|
||||
установить. Ограничивайте его, только если это действительно необходимо.
|
||||
<li>Ограничители полосы и счетчики трафика, ограничивающие адрес назначения,
|
||||
выбираются при авторизации адреса назначения, поэтому они выбираются для
|
||||
адреса назначения первой датаграммы и не выбираются заново для каждого
|
||||
последующего адреса назначения. К входящему UDP трафику они не могут быть
|
||||
применены по адресу назначения вообще.
|
||||
<li>Каждое изменение имени хоста, адреса или порта назначения
|
||||
авторизуется заново и записывается в журнал. Используйте <code>nscache</code>
|
||||
для имен хостов и кэш аутентификации для всего, что дороже 'iponly'. Опция
|
||||
<code>-U</code> сервиса <code>socks</code> отключает журналирование и/или
|
||||
повторную авторизацию; при <code>-U0</code> или <code>-U1</code>
|
||||
авторизуется только первый адрес назначения ассоциации.
|
||||
</ul>
|
||||
<p>
|
||||
Ограничить адреса назначения, куда клиент может отправлять датаграммы:
|
||||
</p><pre>
|
||||
auth iponly
|
||||
allow * * 8.8.8.8 53
|
||||
deny *
|
||||
socks -p1080
|
||||
</pre>
|
||||
<p>
|
||||
Запрос ASSOCIATE выполняется успешно, датаграммы к 8.8.8.8:53 передаются,
|
||||
датаграммы к любому другому адресу назначения отбрасываются.
|
||||
</p>
|
||||
<p>
|
||||
То же самое с аутентификацией 'strong' (или RADIUS, или через плагин), при
|
||||
которой иначе каждый новый адрес назначения аутентифицировался бы заново:
|
||||
</p><pre>
|
||||
users user1:CL:password
|
||||
authcache user,pass,dstaddr,dstport 60
|
||||
auth cacheacl strong
|
||||
allow user1 * 8.8.8.8 53
|
||||
deny *
|
||||
socks -p1080
|
||||
</pre>
|
||||
<p>
|
||||
При 'cacheacl' результат проверки ACL не вычисляется заново при попадании
|
||||
в кэш, поэтому каждое поле, ограничиваемое в ACL, должно входить в ключ
|
||||
кэша: 'user' и 'pass' для списка пользователей, 'dstaddr' и 'dstport' для списка
|
||||
адресов и списка портов назначения, 'ip' для списка источников, 'dsthost'
|
||||
для имен хостов в списке назначения, 'dstoper' для списка операций. Без
|
||||
адреса назначения в ключе результат, закэшированный для одного адреса
|
||||
назначения, применяется к любому другому, и адрес назначения не
|
||||
проверяется вообще. Используйте 'cache' вместо 'cacheacl', если ACL могут
|
||||
изменяться в течение времени жизни кэша или если используется вышестоящий
|
||||
прокси: при попадании в кэш 'cacheacl' обход ACL не выполняется, поэтому
|
||||
вышестоящий прокси не выбирается и датаграммы отправляются напрямую.
|
||||
</p>
|
||||
<li><a name="BANDLIM"><i>Как ограничивать скорости приема</i></a>
|
||||
<p>
|
||||
3proxy позволяет устанавливать фильтры ширины потребляемого канала. Для этого
|
||||
|
||||
@@ -221,7 +221,30 @@ built by default and is disabled even when built, because
|
||||
current Linux does not implement SPLICE_F_MOVE, so no real
|
||||
zero-copy takes place and the read/write path is faster for
|
||||
most traffic. Rebuild with -DWITHSPLICE to make -s
|
||||
available, -s0 disables it explicitly. <br>
|
||||
available, -s0 disables it explicitly. <b><br>
|
||||
-C</b> <br>
|
||||
(for TCP services) a connection closed by any of the sides
|
||||
terminates the session, buffered data is delivered before
|
||||
the sockets are closed. By default the session is kept until
|
||||
both sides close the connection (TCP half-close). Half-close
|
||||
is required for the protocols where one of the sides closes
|
||||
its sending side and expects the answer, but it keeps the
|
||||
socket of the side which has already closed the connection
|
||||
in CLOSE_WAIT state. Use -C to close both sockets as soon as
|
||||
any of the sides closes the connection, -C1 to request the
|
||||
default behaviour explicitly. <b><br>
|
||||
-U</b><i>[MODE]</i> <br>
|
||||
(for socks) what to do when the destination changes within
|
||||
an UDP association: <b>1</b> - log it, <b>2</b> - authorize
|
||||
it, <b>3</b> - both, the default, <b>0</b> (same as bare
|
||||
<b>-U</b>) - neither. The destination of the first datagram
|
||||
is always authorized and logged. With <b>-U0</b> and
|
||||
<b>-U1</b> the destination is not authorized again, so ACLs
|
||||
limiting the destination only apply to the first destination
|
||||
of the association, and the parent proxy and the external
|
||||
address selected for it are kept for the whole association.
|
||||
Use <b>-U2</b> to keep the authorization and to drop the
|
||||
per-destination log records only. <br>
|
||||
(for dnspr) simple, do not use resolver and 3proxy cache,
|
||||
always use external DNS server. <br>
|
||||
(for udppm) singlepacket, expect only one packet from both
|
||||
@@ -400,9 +423,9 @@ and %F as filename.</p>
|
||||
<i><BYTE_SHORT> <BYTE_LONG> <STRING_SHORT>
|
||||
<STRING_LONG> <CONNECTION_SHORT>
|
||||
<CONNECTION_LONG> <DNS> <CHAIN>
|
||||
<CONNECT> <CONNECTBACK></i> <br>
|
||||
<CONNECT> <CONNECTBACK> <LINGER></i> <br>
|
||||
Sets timeout values, defaults 1, 5, 30, 60, 180, 1800, 15,
|
||||
60, 15, 5. <b><br>
|
||||
60, 15, 5, 5. <b><br>
|
||||
BYTE_SHORT</b> short timeout for single byte, is usually
|
||||
used for receiving single byte from stream. <b><br>
|
||||
BYTE_LONG</b> long timeout for single byte, is usually used
|
||||
@@ -419,8 +442,13 @@ CONNECTION_LONG</b> inactivity timeout for long connection
|
||||
DNS</b> timeout for DNS request before requesting next
|
||||
server <b><br>
|
||||
CHAIN</b> timeout for reading data from chained connection
|
||||
<br>
|
||||
default timeouts 1 5 30 60 180 1800 15 60 15 5</p>
|
||||
<b><br>
|
||||
LINGER</b> timeout to deliver buffered data after one of the
|
||||
sides has closed its sending side, also used as SO_LINGER
|
||||
value on outgoing connections. Too small value may cause the
|
||||
tail of the data to be lost on slow connections, too large
|
||||
one delays release of the sockets. <br>
|
||||
default timeouts 1 5 30 60 180 1800 15 60 15 5 5</p>
|
||||
|
||||
<p style="margin-left:6%; margin-top: 1em"><b>maxseg</b>
|
||||
<i><value></i> <br>
|
||||
@@ -584,7 +612,15 @@ but the ACL authorization result is also cached and not
|
||||
re-evaluated on each request. Faster than <b>cache</b>, but
|
||||
ACL changes do not take effect for cached users until the
|
||||
cache entry expires. Use <b>cache</b> if ACLs may change
|
||||
during the cache lifetime. <b><br>
|
||||
during the cache lifetime. Because the ACL is not walked on
|
||||
a cache hit, no redirection is applied to a request served
|
||||
from the cache: it is sent directly instead of through the
|
||||
<b>parent</b> proxy of the matching ACL entry, with no error
|
||||
reported. Do not use <b>cacheacl</b> together with parent
|
||||
proxies, use <b>cache</b> instead. The only redirection type
|
||||
which survives is <b>extip</b>, and only if <b>ext</b> is a
|
||||
part of the <b>authcache</b> key, because the external
|
||||
address is then restored from the cache entry. <b><br>
|
||||
radius</b> - authentication with RADIUS. <br>
|
||||
Plugins may add additional authentication types.</p>
|
||||
|
||||
@@ -631,6 +667,19 @@ srvaddr</b> - cache by service (listener) address <b><br>
|
||||
srvport</b> - cache by service (listener) port <br>
|
||||
Multiple types can be combined (e.g.
|
||||
<b>ip,user,dstaddr,dstport</b>). <br>
|
||||
With <b>cacheacl</b> the ACL result is not re-evaluated on a
|
||||
cache hit, so every field the ACL limits must be a part of
|
||||
the cache key, otherwise the result cached for one request
|
||||
is applied to a different one: <b>user</b>/<b>pass</b> for
|
||||
the userlist, <b>ip</b> for the sourcelist,
|
||||
<b>dstaddr</b>/<b>dsthost</b> for the targetlist,
|
||||
<b>dstport</b> for the targetportlist and <b>dstoper</b> for
|
||||
the operationlist. It is especially important for SOCKSv5
|
||||
UDP traffic, where the destination of every datagram is
|
||||
authorized: without <b>dstaddr</b> and <b>dstport</b> in the
|
||||
key the result cached for one destination is applied to any
|
||||
other destination and the destination is not checked at all,
|
||||
see <b>allow</b>. <br>
|
||||
Use auth type <b>cache</b> (or <b>cacheacl</b>) for cached
|
||||
authentication</p>
|
||||
|
||||
@@ -699,8 +748,45 @@ week day numbers or periods, 0 or 7 means Sunday, 1 is
|
||||
Monday, 1-5 means Monday through Friday. <br>
|
||||
Timeperiodlists is a list of time periods in
|
||||
HH:MM:SS-HH:MM:SS format. For example,
|
||||
00:00:00-08:00:00,17:00:00-24:00:00 lists non-working
|
||||
hours.</p>
|
||||
00:00:00-08:00:00,17:00:00-24:00:00 lists non-working hours.
|
||||
<br>
|
||||
A SOCKSv5 UDP ASSOCIATE request carries no destination, the
|
||||
destination of every datagram is taken from the datagram
|
||||
itself. 3proxy authorizes the destination of every datagram,
|
||||
so ACLs limiting the destination address, the destination
|
||||
host name or the destination port do apply to UDP traffic,
|
||||
unless the <b>-U</b> option of the <b>socks</b> service says
|
||||
otherwise. <br>
|
||||
ACLs are only checked for the datagrams sent by the client.
|
||||
A datagram received on the association is relayed to the
|
||||
client without an ACL check: with a parent proxy only the
|
||||
datagrams from the parent are accepted, an association
|
||||
without a parent accepts a datagram from any source. The
|
||||
source reported to the client is the actual source of the
|
||||
datagram. The address in the log record is the destination
|
||||
the client sent the datagrams to, the source of the
|
||||
datagrams received on the association is not logged. <br>
|
||||
A client may use a single association to reach many
|
||||
destinations. An ACL entry which limits the destination
|
||||
silently drops the datagrams to every other destination, so
|
||||
limiting the destination of UDP traffic can break such
|
||||
clients in a way which is hard to diagnose. Limit it only
|
||||
when it is really required. <br>
|
||||
Bandwidth limiters (<b>bandlimin</b>, <b>bandlimout</b>) and
|
||||
traffic counters (<b>countin</b>, <b>countout</b>) which
|
||||
limit the destination are selected when the destination is
|
||||
authorized, so within an UDP association they are selected
|
||||
for the destination of the first datagram and are not
|
||||
re-selected for every following destination. They can not be
|
||||
applied per destination to the incoming UDP traffic at all,
|
||||
because an incoming datagram is not matched against any
|
||||
destination. <br>
|
||||
Only <b>socks5</b> and <b>socks5+</b> parents can be used
|
||||
for UDP. Because every new destination is authorized, use
|
||||
<b>authcache</b>, especially with ´strong´,
|
||||
RADIUS or plugin authentication: <b>cacheacl</b> with the
|
||||
destination in the cache key if no parent proxy is used,
|
||||
<b>cache</b> otherwise, see <b>cacheacl</b>.</p>
|
||||
|
||||
<p style="margin-left:6%; margin-top: 1em"><b>parent</b>
|
||||
<i><weight> <type> <ip> <port>
|
||||
|
||||
@@ -25,6 +25,26 @@ with an unreachable DNS server (because gethostbyname will block other threads).
|
||||
user requests can be logged.
|
||||
<li>Use -xyz+A character filtering sequences for 'logformat', especially with
|
||||
ODBC logging, to prevent SQL and log record injections.
|
||||
<li>With the 'cacheacl' authentication type the ACL result is cached and is not
|
||||
re-evaluated on a cache hit, so every field the ACL limits must be a part of
|
||||
the 'authcache' key. Any field the ACL limits but the key does not contain
|
||||
makes the cached result apply to a request it was not computed for, and that
|
||||
limitation is not enforced. Use 'user' and 'pass' for the userlist, 'ip' for
|
||||
the sourcelist, 'dstaddr' and 'dsthost' for the targetlist, 'dstport' for the
|
||||
targetportlist and 'dstoper' for the operationlist. Use plain 'cache' instead
|
||||
of 'cacheacl' if ACLs may change during the cache lifetime; cache entries are
|
||||
not invalidated by a configuration reload.
|
||||
<li>'cacheacl' must not be used together with parent proxies. The ACL is not
|
||||
walked on a cache hit, so no redirection is applied and the request is sent
|
||||
directly instead of through the 'parent' proxy of the matching ACL entry,
|
||||
without any error. If the parent proxy is the only sanctioned path to the
|
||||
network, this silently bypasses it. Use 'cache' instead. 'parent ... extip'
|
||||
is the only redirection which survives, and only if 'ext' is a part of the
|
||||
'authcache' key.
|
||||
<li>The destination of every datagram of a SOCKSv5 UDP association is
|
||||
authorized, but only with the default '-U3' (or '-U2') of the 'socks' service.
|
||||
With '-U0' or '-U1' only the first destination of an association is authorized,
|
||||
so ACLs limiting the destination do not restrict the rest of the association.
|
||||
<li>Immediately report all service crashes to the developers.
|
||||
<li>Participate in code audit :)
|
||||
</ul>
|
||||
|
||||
+79
-3
@@ -199,6 +199,26 @@ is disabled even when built, because current Linux does not implement
|
||||
SPLICE_F_MOVE, so no real zero-copy takes place and the read/write path is faster
|
||||
for most traffic. Rebuild with -DWITHSPLICE to make -s available, -s0 disables it
|
||||
explicitly.
|
||||
.br
|
||||
.B -C
|
||||
(for TCP services) a connection closed by any of the sides terminates the
|
||||
session, buffered data is delivered before the sockets are closed. By default
|
||||
the session is kept until both sides close the connection (TCP half-close).
|
||||
Half-close is required for the protocols where one of the sides closes its
|
||||
sending side and expects the answer, but it keeps the socket of the side which
|
||||
has already closed the connection in CLOSE_WAIT state. Use -C to close both
|
||||
sockets as soon as any of the sides closes the connection, -C1 to request
|
||||
the default behaviour explicitly.
|
||||
.br
|
||||
.B -U\fI[MODE]\fR
|
||||
(for socks) what to do when the destination changes within an UDP association:
|
||||
\fB1\fR - log it, \fB2\fR - authorize it, \fB3\fR - both, the default,
|
||||
\fB0\fR (same as bare \fB-U\fR) - neither. The destination of the first datagram
|
||||
is always authorized and logged. With \fB-U0\fR and \fB-U1\fR the destination is
|
||||
not authorized again, so ACLs limiting the destination only apply to the first
|
||||
destination of the association, and the parent proxy and the external address
|
||||
selected for it are kept for the whole association. Use \fB-U2\fR to keep the
|
||||
authorization and to drop the per-destination log records only.
|
||||
.br
|
||||
(for dnspr) simple, do not use resolver and 3proxy cache, always use external DNS server.
|
||||
.br
|
||||
@@ -427,9 +447,9 @@ can use %A as produced archive name and %F as filename.
|
||||
|
||||
.br
|
||||
.BR timeouts
|
||||
\fI<BYTE_SHORT>\fR \fI<BYTE_LONG>\fR \fI<STRING_SHORT>\fR \fI<STRING_LONG>\fR \fI<CONNECTION_SHORT>\fR \fI<CONNECTION_LONG>\fR \fI<DNS>\fR \fI<CHAIN>\fR \fI<CONNECT>\fR \fI<CONNECTBACK>\fR
|
||||
\fI<BYTE_SHORT>\fR \fI<BYTE_LONG>\fR \fI<STRING_SHORT>\fR \fI<STRING_LONG>\fR \fI<CONNECTION_SHORT>\fR \fI<CONNECTION_LONG>\fR \fI<DNS>\fR \fI<CHAIN>\fR \fI<CONNECT>\fR \fI<CONNECTBACK>\fR \fI<LINGER>\fR
|
||||
.br
|
||||
Sets timeout values, defaults 1, 5, 30, 60, 180, 1800, 15, 60, 15, 5.
|
||||
Sets timeout values, defaults 1, 5, 30, 60, 180, 1800, 15, 60, 15, 5, 5.
|
||||
.br
|
||||
\fBBYTE_SHORT\fR short timeout for single byte, is usually used for receiving single byte from stream.
|
||||
.br
|
||||
@@ -447,7 +467,12 @@ can use %A as produced archive name and %F as filename.
|
||||
.br
|
||||
\fBCHAIN\fR timeout for reading data from chained connection
|
||||
.br
|
||||
default timeouts 1 5 30 60 180 1800 15 60 15 5
|
||||
\fBLINGER\fR timeout to deliver buffered data after one of the sides has closed
|
||||
its sending side, also used as SO_LINGER value on outgoing connections. Too small
|
||||
value may cause the tail of the data to be lost on slow connections, too large one
|
||||
delays release of the sockets.
|
||||
.br
|
||||
default timeouts 1 5 30 60 180 1800 15 60 15 5 5
|
||||
|
||||
.br
|
||||
.BR maxseg
|
||||
@@ -623,6 +648,13 @@ SOCKSv5, FTP, POP3 and HTTP proxy.
|
||||
authorization result is also cached and not re-evaluated on each request. Faster
|
||||
than \fBcache\fR, but ACL changes do not take effect for cached users until the
|
||||
cache entry expires. Use \fBcache\fR if ACLs may change during the cache lifetime.
|
||||
Because the ACL is not walked on a cache hit, no redirection is applied to a
|
||||
request served from the cache: it is sent directly instead of through the
|
||||
\fBparent\fR proxy of the matching ACL entry, with no error reported. Do not use
|
||||
\fBcacheacl\fR together with parent proxies, use \fBcache\fR instead. The only
|
||||
redirection type which survives is \fBextip\fR, and only if \fBext\fR is a part
|
||||
of the \fBauthcache\fR key, because the external address is then restored from
|
||||
the cache entry.
|
||||
.br
|
||||
\fBradius\fR - authentication with RADIUS.
|
||||
.br
|
||||
@@ -678,6 +710,17 @@ assigned to the same user without actual authentication.
|
||||
.br
|
||||
Multiple types can be combined (e.g. \fBip,user,dstaddr,dstport\fR).
|
||||
.br
|
||||
With \fBcacheacl\fR the ACL result is not re-evaluated on a cache hit, so every
|
||||
field the ACL limits must be a part of the cache key, otherwise the result
|
||||
cached for one request is applied to a different one: \fBuser\fR/\fBpass\fR
|
||||
for the userlist, \fBip\fR for the sourcelist, \fBdstaddr\fR/\fBdsthost\fR
|
||||
for the targetlist, \fBdstport\fR for the targetportlist and \fBdstoper\fR
|
||||
for the operationlist. It is especially important for SOCKSv5 UDP traffic,
|
||||
where the destination of every datagram is authorized: without \fBdstaddr\fR
|
||||
and \fBdstport\fR in the key the result cached for one destination is applied
|
||||
to any other destination and the destination is not checked at all, see
|
||||
\fBallow\fR.
|
||||
.br
|
||||
Use auth type \fBcache\fR (or \fBcacheacl\fR) for cached authentication
|
||||
|
||||
.br
|
||||
@@ -762,6 +805,39 @@ non-privileged (1024-65535) ports on the remote side.
|
||||
.br
|
||||
Timeperiodlists is a list of time
|
||||
periods in HH:MM:SS-HH:MM:SS format. For example, 00:00:00-08:00:00,17:00:00-24:00:00 lists non-working hours.
|
||||
.br
|
||||
A SOCKSv5 UDP ASSOCIATE request carries no destination, the destination of
|
||||
every datagram is taken from the datagram itself. 3proxy authorizes the
|
||||
destination of every datagram, so ACLs limiting the destination address, the
|
||||
destination host name or the destination port do apply to UDP traffic, unless
|
||||
the \fB-U\fR option of the \fBsocks\fR service says otherwise.
|
||||
.br
|
||||
ACLs are only checked for the datagrams sent by the client. A datagram received
|
||||
on the association is relayed to the client without an ACL check: with a parent
|
||||
proxy only the datagrams from the parent are accepted, an association without a
|
||||
parent accepts a datagram from any source. The source reported to the client is
|
||||
the actual source of the datagram. The address in the log record is the destination the
|
||||
client sent the datagrams to, the source of the datagrams received on the
|
||||
association is not logged.
|
||||
.br
|
||||
A client may use a single association to reach many destinations. An ACL entry
|
||||
which limits the destination silently drops the datagrams to every other
|
||||
destination, so limiting the destination of UDP traffic can break such clients
|
||||
in a way which is hard to diagnose. Limit it only when it is really required.
|
||||
.br
|
||||
Bandwidth limiters (\fBbandlimin\fR, \fBbandlimout\fR) and traffic counters
|
||||
(\fBcountin\fR, \fBcountout\fR) which limit the destination are selected when
|
||||
the destination is authorized, so within an UDP association they are selected
|
||||
for the destination of the first datagram and are not re-selected for every
|
||||
following destination. They can not be applied per destination to the incoming
|
||||
UDP traffic at all, because an incoming datagram is not matched against any
|
||||
destination.
|
||||
.br
|
||||
Only \fBsocks5\fR and \fBsocks5+\fR parents can be used for UDP. Because
|
||||
every new destination is authorized, use \fBauthcache\fR, especially with
|
||||
\'strong\', RADIUS or plugin authentication: \fBcacheacl\fR with the
|
||||
destination in the cache key if no parent proxy is used, \fBcache\fR
|
||||
otherwise, see \fBcacheacl\fR.
|
||||
|
||||
.br
|
||||
.BR parent
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: 3proxy
|
||||
Version: 0.9.8
|
||||
Version: 0.9.9
|
||||
Release: 1%{?dist}
|
||||
Summary: 3proxy tiny proxy server
|
||||
License: GPL/LGPL/Apache/BSD
|
||||
|
||||
+1
-1
@@ -298,7 +298,7 @@ void cyclestep(void){
|
||||
default:
|
||||
break;
|
||||
}
|
||||
dologname (tmpbuf, conf.logname, (conf.archiver)?conf.archiver[1]:NULL, conf.logtype, (conf.logtime - t * conf.rotate));
|
||||
dologname (tmpbuf, conf.logname, (conf.archiver)?conf.archiver[1]:NULL, conf.logtype, (conf.logtime - (time_t)t * conf.rotate));
|
||||
remove ((char *) tmpbuf);
|
||||
if(conf.archiver) {
|
||||
int i;
|
||||
|
||||
@@ -36,6 +36,8 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
|
||||
struct hostname * hstentry=NULL;
|
||||
int i;
|
||||
int match = 0;
|
||||
int dstdep = 0;
|
||||
int preauth = (param->preauth == 1 && acentry->action <= REDIRECT);
|
||||
|
||||
username = param->username?param->username:(unsigned char *)"-";
|
||||
if(acentry->src) {
|
||||
@@ -45,7 +47,10 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
|
||||
}
|
||||
if(!ipentry) return 0;
|
||||
}
|
||||
if((acentry->dst && (!SAISNULL(¶m->req) || param->operation==BIND)) || (acentry->dstnames && param->hostname)) {
|
||||
if(preauth && (acentry->dst || acentry->dstnames)) {
|
||||
dstdep = 1;
|
||||
}
|
||||
else if((acentry->dst && (!SAISNULL(¶m->req) || param->operation==BIND)) || (acentry->dstnames && param->hostname)) {
|
||||
for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next)
|
||||
if(IPInentry((struct sockaddr *)¶m->req, ipentry)) {
|
||||
break;
|
||||
@@ -93,7 +98,10 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
|
||||
}
|
||||
if(!ipentry && !hstentry) return 0;
|
||||
}
|
||||
if(acentry->ports && (*SAPORT(¶m->req) || param->operation == BIND)) {
|
||||
if(preauth && acentry->ports) {
|
||||
dstdep = 1;
|
||||
}
|
||||
else if(acentry->ports && (*SAPORT(¶m->req) || param->operation == BIND)) {
|
||||
for (portentry = acentry->ports; portentry; portentry = portentry->next)
|
||||
if(ntohs(*SAPORT(¶m->req)) >= portentry->startport &&
|
||||
ntohs(*SAPORT(¶m->req)) <= portentry->endport) {
|
||||
@@ -125,6 +133,10 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
|
||||
}
|
||||
}
|
||||
if(acentry->weight && (acentry->weight < param->weight)) return 0;
|
||||
if(dstdep) {
|
||||
param->dstindep = 0;
|
||||
return acentry->action != DENY;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -132,6 +144,7 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
|
||||
int checkACL(struct clientparam * param){
|
||||
struct ace* acentry;
|
||||
|
||||
if(param->preauth == 1) param->dstindep = 1;
|
||||
if(!param->srv->acl) {
|
||||
return 0;
|
||||
}
|
||||
@@ -150,7 +163,9 @@ int checkACL(struct clientparam * param){
|
||||
if(param->redirected && acentry->chains && SAISNULL(&acentry->chains->addr) && !*SAPORT(&acentry->chains->addr)) {
|
||||
continue;
|
||||
}
|
||||
if(param->remsock != INVALID_SOCKET && (param->operation != UDPASSOC || param->ctrlsocksrv != INVALID_SOCKET)) {
|
||||
param->lastace = acentry;
|
||||
if(param->preauth) return 2;
|
||||
if((param->operation == UDPASSOC)? (param->ctrlsocksrv != INVALID_SOCKET) : (param->remsock != INVALID_SOCKET)) {
|
||||
return 0;
|
||||
}
|
||||
for(; i < conf.parentretries; i++){
|
||||
@@ -159,9 +174,14 @@ int checkACL(struct clientparam * param){
|
||||
if(!res) break;
|
||||
if(param->remsock != INVALID_SOCKET) param->srv->so._closesocket(param->sostate, param->remsock);
|
||||
param->remsock = INVALID_SOCKET;
|
||||
if(param->ctrlsocksrv != INVALID_SOCKET) {
|
||||
param->srv->so._closesocket(param->sostate, param->ctrlsocksrv);
|
||||
param->ctrlsocksrv = INVALID_SOCKET;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
param->lastace = acentry;
|
||||
return acentry->action;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -102,6 +102,7 @@ int cacheauth(struct clientparam * param){
|
||||
*(SAFAMILY(¶m->sinsl)) = ac.sinsl_family;
|
||||
memcpy(SAADDR(¶m->sinsl), ac.sinsl_addr, SAADDRLEN(¶m->sinsl));
|
||||
}
|
||||
if(param->preauth == 1 && param->srv->acl) param->dstindep = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -110,6 +111,7 @@ int doauth(struct clientparam * param){
|
||||
struct auth *authfuncs;
|
||||
int ret = 0;
|
||||
|
||||
if(param->preauth == 1 && !param->srv->acl) param->dstindep = 1;
|
||||
for(authfuncs=param->srv->authfuncs; authfuncs; authfuncs=authfuncs->next){
|
||||
res = authfuncs->authenticate?(*authfuncs->authenticate)(param):0;
|
||||
if(!res) {
|
||||
@@ -148,7 +150,7 @@ int doauth(struct clientparam * param){
|
||||
if(ret > 9) return ret;
|
||||
}
|
||||
if(!res){
|
||||
ret = alwaysauth(param);
|
||||
ret = (param->preauth == 2)? 0 : alwaysauth(param);
|
||||
if (param->afterauthfilters){
|
||||
FILTER_ACTION action;
|
||||
|
||||
|
||||
+10
-3
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <limits.h>
|
||||
|
||||
static const unsigned char base64digits[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
@@ -23,8 +24,10 @@ static const unsigned char base64val[] = {
|
||||
};
|
||||
#define DECODE64(c) ((c > 32 && c<127)? base64val[(int)c] : BAD)
|
||||
|
||||
unsigned char* en64 (const unsigned char *in, unsigned char *out, int inlen)
|
||||
unsigned char* en64 (const unsigned char *in, unsigned char *out, int inlen, int outsize)
|
||||
{
|
||||
if (inlen < 0 || inlen > (INT_MAX - 2) || outsize < 1) return NULL;
|
||||
if (((inlen + 2) / 3) > ((outsize - 1) / 4)) return NULL;
|
||||
for (; inlen > 0; inlen -= 3, in+=3)
|
||||
{
|
||||
|
||||
@@ -42,6 +45,7 @@ int de64 (const char *in, char *out, int maxlen)
|
||||
int len = 0;
|
||||
register unsigned char digit1, digit2, digit3, digit4;
|
||||
|
||||
if (maxlen < 0) return(-1);
|
||||
if (in[0] == '+' && in[1] == ' ')
|
||||
in += 2;
|
||||
if (*in == '\r')
|
||||
@@ -61,20 +65,23 @@ int de64 (const char *in, char *out, int maxlen)
|
||||
if (digit4 != '=' && DECODE64(digit4) == BAD)
|
||||
return(-1);
|
||||
in += 4;
|
||||
if (len >= maxlen) return (len);
|
||||
*out++ = (DECODE64(digit1) << 2) | (DECODE64(digit2) >> 4);
|
||||
++len;
|
||||
if (digit3 != '=')
|
||||
{
|
||||
if (len >= maxlen) return (len);
|
||||
*out++ = ((DECODE64(digit2) << 4) & 0xf0) | (DECODE64(digit3) >> 2);
|
||||
++len;
|
||||
if (digit4 != '=')
|
||||
{
|
||||
if (len >= maxlen) return (len);
|
||||
*out++ = ((DECODE64(digit3) << 6) & 0xc0) | DECODE64(digit4);
|
||||
++len;
|
||||
}
|
||||
}
|
||||
} while
|
||||
(*in && *in != '\r' && digit4 != '=' && (maxlen-=4) >= 4);
|
||||
} while
|
||||
(*in && *in != '\r' && digit4 != '=');
|
||||
|
||||
return (len);
|
||||
}
|
||||
|
||||
+45
-2
@@ -9,6 +9,48 @@
|
||||
|
||||
|
||||
#include "proxy.h"
|
||||
/* returns 0 on success, 1 if atyp is not supported for family, 2 if the
|
||||
address is null. The address is set in both the 0 and the 2 case. */
|
||||
int socks5_setaddr(int family, int atyp, const unsigned char *addr, PROXYSOCKADDRTYPE *sa){
|
||||
int i, len = 4;
|
||||
|
||||
memset(sa, 0, sizeof(*sa));
|
||||
if(atyp == 4){
|
||||
#ifdef NOIPV6
|
||||
return 1;
|
||||
#else
|
||||
if(family == 4) return 1;
|
||||
len = 16;
|
||||
*SAFAMILY(sa) = AF_INET6;
|
||||
memcpy(SAADDR(sa), addr, 16);
|
||||
#endif
|
||||
}
|
||||
#ifndef NOIPV6
|
||||
else if(family == 6){
|
||||
unsigned char prefix[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255};
|
||||
|
||||
*SAFAMILY(sa) = AF_INET6;
|
||||
memcpy(SAADDR(sa), prefix, 12);
|
||||
memcpy(12 + (unsigned char *)SAADDR(sa), addr, 4);
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
*SAFAMILY(sa) = AF_INET;
|
||||
memcpy(SAADDR(sa), addr, 4);
|
||||
}
|
||||
for(i = 0; i < len && !addr[i]; i++);
|
||||
return (i == len)? 2 : 0;
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
#include <sched.h>
|
||||
|
||||
int switch_ns(struct srvparam *srv, int target_fd) {
|
||||
if(target_fd < 0) return 0;
|
||||
if(srv->saved_nsfd >= 0 && setns(srv->saved_nsfd, CLONE_NEWNET)) return -1;
|
||||
return setns(target_fd, CLONE_NEWNET);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
char * copyright = COPYRIGHT;
|
||||
@@ -130,7 +172,7 @@ int timeouts[12] = {
|
||||
60, /* CHAIN_TO */
|
||||
15, /* CONNECT_TO */
|
||||
5, /* CONNBACK_TO */
|
||||
0,
|
||||
5, /* LINGER_TO */
|
||||
0
|
||||
};
|
||||
|
||||
@@ -644,13 +686,14 @@ int doconnect(struct clientparam * param){
|
||||
|
||||
if (param->operation == ADMIN || (( param->operation == DNSRESOLVE || param->operation == BIND || param->operation == UDPASSOC) && !param->redirected))
|
||||
return 0;
|
||||
if (param->operation == UDPASSOC && param->ctrlsocksrv != INVALID_SOCKET) return 0;
|
||||
if (param->remsock != INVALID_SOCKET){
|
||||
if(param->operation == UDPASSOC) return 0;
|
||||
size = sizeof(param->sinsr);
|
||||
if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsr, &size)==-1) {return (14);}
|
||||
}
|
||||
else {
|
||||
struct linger lg = {1,conf.timeouts[SINGLEBYTE_S]};
|
||||
struct linger lg = {1,conf.timeouts[LINGER_TO]};
|
||||
|
||||
if(SAISNULL(¶m->sinsr)){
|
||||
if(SAISNULL(¶m->req)) {
|
||||
|
||||
+18
@@ -839,6 +839,24 @@ static int h_parent(int argc, unsigned char **argv){
|
||||
chains->cidr = atoi(cidr + 1);
|
||||
}
|
||||
*SAPORT(&chains->addr) = htons((uint16_t)atoi((char *)argv[4]));
|
||||
switch(chains->type){
|
||||
case R_POP3:
|
||||
case R_SMTP:
|
||||
case R_FTP:
|
||||
case R_ADMIN:
|
||||
case R_TLS:
|
||||
case R_DNS:
|
||||
case R_HA:
|
||||
if(!SAISNULL(&chains->addr) || *SAPORT(&chains->addr)){
|
||||
fprintf(stderr, "Chaining error: chain type (%s) is a local redirection, it requires 0.0.0.0 as address and 0 as port on line %d\n", argv[2], linenum);
|
||||
free(chains->exthost);
|
||||
free(chains);
|
||||
return(4);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if(argc > 5) chains->extuser = (unsigned char *)strdup((char *)argv[5]);
|
||||
if(argc > 6) chains->extpass = (unsigned char *)strdup((char *)argv[6]);
|
||||
if(!acl->chains) {
|
||||
|
||||
+6
-6
@@ -70,9 +70,9 @@ int inithashtable(struct hashtable *ht, unsigned tablesize, unsigned poolsize, u
|
||||
_3proxy_mutex_init(&ht->hash_mutex);
|
||||
_3proxy_mutex_lock(&ht->hash_mutex);
|
||||
}
|
||||
if(!(ht->ihashtable = malloc(tablesize * sizeof(uint32_t)))
|
||||
|| !(ht->hashvalues = malloc(poolsize * (sizeof(struct hashentry) + ht->recsize - 4)))
|
||||
|| !(ht->hashhashvalues = malloc(poolsize * ht->hash_size))
|
||||
if(!(ht->ihashtable = malloc((size_t)tablesize * sizeof(uint32_t)))
|
||||
|| !(ht->hashvalues = malloc((size_t)poolsize * (sizeof(struct hashentry) + ht->recsize - 4)))
|
||||
|| !(ht->hashhashvalues = malloc((size_t)poolsize * ht->hash_size))
|
||||
){
|
||||
free(ht->ihashtable);
|
||||
ht->ihashtable = NULL;
|
||||
@@ -126,13 +126,13 @@ static void hashgrow(struct hashtable *ht){
|
||||
if(ht->ihashempty) return;
|
||||
if(ht->poolsize >= ht->growlimit) return;
|
||||
if(newsize > ht->growlimit) newsize = ht->growlimit;
|
||||
newvalues = realloc(ht->hashvalues, newsize * (sizeof(struct hashentry) + ht->recsize - 4));
|
||||
newvalues = realloc(ht->hashvalues, (size_t)newsize * (sizeof(struct hashentry) + ht->recsize - 4));
|
||||
if(!newvalues) return;
|
||||
ht->hashvalues = newvalues;
|
||||
newvalues = realloc(ht->hashhashvalues, newsize * ht->hash_size);
|
||||
newvalues = realloc(ht->hashhashvalues, (size_t)newsize * ht->hash_size);
|
||||
if(!newvalues) return;
|
||||
ht->hashhashvalues = newvalues;
|
||||
memset(ht->hashvalues + (ht->poolsize * (sizeof(struct hashentry) + ht->recsize - 4)), 0, (newsize - ht->poolsize) * (sizeof(struct hashentry) + ht->recsize - 4));
|
||||
memset(ht->hashvalues + ((size_t)ht->poolsize * (sizeof(struct hashentry) + ht->recsize - 4)), 0, (size_t)(newsize - ht->poolsize) * (sizeof(struct hashentry) + ht->recsize - 4));
|
||||
for(i = ht->poolsize + 1; i < newsize; i++) {
|
||||
hvalue(ht,i)->inext = i+1;
|
||||
}
|
||||
|
||||
+4
-6
@@ -182,12 +182,12 @@ void * imappchild(struct clientparam* param) {
|
||||
if(method == CL_PLAIN){
|
||||
i = (int)strlen((char *)param->extusername);
|
||||
res = (int)strlen((char *)pb);
|
||||
if(((i + res + 4) / 3) * 4 + 1 > (int)sizeof(srvbuf)) {RETURN(693);}
|
||||
if(i + res + 2 > (int)sizeof(ibuf)) {RETURN(693);}
|
||||
ibuf[0] = 0;
|
||||
memcpy(ibuf + 1, param->extusername, i);
|
||||
ibuf[i + 1] = 0;
|
||||
memcpy(ibuf + i + 2, pb, res);
|
||||
en64(ibuf, srvbuf, i + res + 2);
|
||||
if(!en64(ibuf, srvbuf, i + res + 2, (int)sizeof(srvbuf))) {RETURN(693);}
|
||||
if( socksend(param, param->remsock, tag, (int)strlen((char *)tag), conf.timeouts[STRING_S]) <= 0 ||
|
||||
socksend(param, param->remsock, (unsigned char *)" AUTHENTICATE PLAIN ", 20, conf.timeouts[STRING_S])!= 20 ||
|
||||
socksend(param, param->remsock, srvbuf, (int)strlen((char *)srvbuf), conf.timeouts[STRING_S]) <= 0 ||
|
||||
@@ -200,15 +200,13 @@ void * imappchild(struct clientparam* param) {
|
||||
{RETURN(699);}
|
||||
i = sockgetlinebuf(param, SERVER, srvbuf, sizeof(srvbuf) - 1, '\n', conf.timeouts[STRING_L]);
|
||||
if(i < 1 || *srvbuf != '+') {RETURN(699);}
|
||||
if(((int)strlen((char *)param->extusername) + 2) / 3 * 4 + 1 > (int)sizeof(ibuf) - 3) {RETURN(693);}
|
||||
en64(param->extusername, ibuf, (int)strlen((char *)param->extusername));
|
||||
if(!en64(param->extusername, ibuf, (int)strlen((char *)param->extusername), (int)sizeof(ibuf))) {RETURN(693);}
|
||||
if( socksend(param, param->remsock, ibuf, (int)strlen((char *)ibuf), conf.timeouts[STRING_S]) <= 0 ||
|
||||
socksend(param, param->remsock, (unsigned char *)"\r\n", 2, conf.timeouts[STRING_S])!=2)
|
||||
{RETURN(699);}
|
||||
i = sockgetlinebuf(param, SERVER, srvbuf, sizeof(srvbuf) - 1, '\n', conf.timeouts[STRING_L]);
|
||||
if(i < 1 || *srvbuf != '+') {RETURN(699);}
|
||||
if(((int)strlen((char *)pb) + 2) / 3 * 4 + 1 > (int)sizeof(ibuf) - 3) {RETURN(693);}
|
||||
en64(pb, ibuf, (int)strlen((char *)pb));
|
||||
if(!en64(pb, ibuf, (int)strlen((char *)pb), (int)sizeof(ibuf))) {RETURN(693);}
|
||||
if( socksend(param, param->remsock, ibuf, (int)strlen((char *)ibuf), conf.timeouts[STRING_S]) <= 0 ||
|
||||
socksend(param, param->remsock, (unsigned char *)"\r\n", 2, conf.timeouts[STRING_S])!=2)
|
||||
{RETURN(699);}
|
||||
|
||||
@@ -109,15 +109,17 @@ struct sockfuncs sso;
|
||||
|
||||
static void genpaths(struct fp_stream *fps){
|
||||
|
||||
size_t len = strlen(path) + 32;
|
||||
|
||||
if(fps->what & (FP_CLIDATA|FP_CLIHEADER)){
|
||||
if(fps->fpd.path_cli) free(fps->fpd.path_cli);
|
||||
fps->fpd.path_cli = malloc(strlen(path) + 10);
|
||||
sprintf(fps->fpd.path_cli, path, counter++);
|
||||
fps->fpd.path_cli = malloc(len);
|
||||
if(fps->fpd.path_cli) sprintf(fps->fpd.path_cli, "%s%07d.tmp", path, counter++);
|
||||
}
|
||||
if(fps->what & (FP_SRVDATA|FP_SRVHEADER)){
|
||||
if(fps->fpd.path_srv) free(fps->fpd.path_srv);
|
||||
fps->fpd.path_srv = malloc(strlen(path) + 10);
|
||||
sprintf(fps->fpd.path_srv, path, counter++);
|
||||
fps->fpd.path_srv = malloc(len);
|
||||
if(fps->fpd.path_srv) sprintf(fps->fpd.path_srv, "%s%07d.tmp", path, counter++);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -139,6 +141,7 @@ static
|
||||
return fps->fpd.h_cli;
|
||||
#else
|
||||
if(fps->fpd.fd_cli != -1) close(fps->fpd.fd_cli);
|
||||
if(!fps->fpd.path_cli) return (fps->fpd.fd_cli = -1);
|
||||
fps->fpd.fd_cli = open(fps->fpd.path_cli, O_BINARY|O_RDWR|O_CREAT|O_TRUNC, 0600);
|
||||
return fps->fpd.fd_cli;
|
||||
#endif
|
||||
@@ -160,6 +163,7 @@ static
|
||||
return fps->fpd.h_srv;
|
||||
#else
|
||||
if(fps->fpd.fd_srv != -1) close(fps->fpd.fd_srv);
|
||||
if(!fps->fpd.path_srv) return (fps->fpd.fd_srv = -1);
|
||||
fps->fpd.fd_srv = open(fps->fpd.path_srv, O_BINARY|O_RDWR|O_CREAT|O_TRUNC, 0600);
|
||||
return fps->fpd.fd_srv;
|
||||
#endif
|
||||
@@ -871,17 +875,17 @@ static int h_cachedir(int argc, unsigned char **argv){
|
||||
size_t len;
|
||||
|
||||
dirp = (argc > 1)? (char *)argv[1] : getenv("TEMP");
|
||||
len = strlen(dirp);
|
||||
len = dirp? strlen(dirp) : 0;
|
||||
if(!dirp || !len || len > 200 || strchr(dirp, '%')) {
|
||||
fprintf(stderr, "FilePlugin: invalid directory path: %s\n", dirp);
|
||||
return (1);
|
||||
}
|
||||
#ifdef _WIN32
|
||||
if(dirp[len-1] == '\\') dirp[len-1] = 0;
|
||||
sprintf(path, "%.256s\\%%07d.tmp", dirp);
|
||||
sprintf(path, "%.256s\\", dirp);
|
||||
#else
|
||||
if(dirp[len-1] == '/') dirp[len-1] = 0;
|
||||
sprintf(path, "%.256s/%%07d.tmp", dirp);
|
||||
sprintf(path, "%.256s/", dirp);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
+11
-2
@@ -831,12 +831,20 @@ for(;;){
|
||||
send_st(param, 9);
|
||||
}
|
||||
if((unsigned)socksend(param, param->clisock, buf, inbuf, conf.timeouts[STRING_S]) != inbuf){
|
||||
param->srv->so._closesocket(param->sostate, ftps);
|
||||
ftps = INVALID_SOCKET;
|
||||
param->remsock = s;
|
||||
RETURN(781);
|
||||
}
|
||||
inbuf = 0;
|
||||
}
|
||||
else {
|
||||
if(!(newbuf = realloc(buf, bufsize + BUFSIZE))){RETURN (21);}
|
||||
if(!(newbuf = realloc(buf, bufsize + BUFSIZE))){
|
||||
param->srv->so._closesocket(param->sostate, ftps);
|
||||
ftps = INVALID_SOCKET;
|
||||
param->remsock = s;
|
||||
RETURN (21);
|
||||
}
|
||||
buf = newbuf;
|
||||
bufsize += BUFSIZE;
|
||||
}
|
||||
@@ -929,7 +937,8 @@ for(;;){
|
||||
if(param->extusername){
|
||||
hlen += sprintf((char*)buf + hlen, "%s: Basic ", (redirect)?"Proxy-Authorization":"Authorization");
|
||||
sprintf((char*)username, "%.128s:%.128s", param->extusername, param->extpassword?param->extpassword:(unsigned char*)"");
|
||||
hlen = (int)(en64(username, buf + hlen, (int)strlen((char *)username)) - buf);
|
||||
if(!(sb = en64(username, buf + hlen, (int)strlen((char *)username), bufsize - hlen))) {RETURN(21);}
|
||||
hlen = (int)(sb - buf);
|
||||
hlen += sprintf((char*)buf + hlen, "\r\n");
|
||||
}
|
||||
hlen += sprintf((char*)buf + hlen, "\r\n");
|
||||
|
||||
+6
-1
@@ -204,6 +204,11 @@ extern int timeouts[12];
|
||||
|
||||
int sockmap(struct clientparam * param, int timeo, int usesplice);
|
||||
int udpsockmap(struct clientparam * param, int timeo);
|
||||
int udpbind(struct clientparam * param);
|
||||
int socks5_setaddr(int family, int atyp, const unsigned char *addr, PROXYSOCKADDRTYPE *sa);
|
||||
#ifdef __linux__
|
||||
int switch_ns(struct srvparam *srv, int target_fd);
|
||||
#endif
|
||||
int socksend(struct clientparam *param, SOCKET sock, unsigned char * buf, int bufsize, int to);
|
||||
int socksendto(struct clientparam *param, SOCKET sock, struct sockaddr * sin, unsigned char * buf, int bufsize, int to);
|
||||
int sockrecvfrom(struct clientparam *param, SOCKET sock, struct sockaddr * sin, unsigned char * buf, int bufsize, int to);
|
||||
@@ -271,7 +276,7 @@ extern int demon;
|
||||
unsigned char * mycrypt(const unsigned char *key, const unsigned char *salt, unsigned char *buf);
|
||||
unsigned char * ntpwdhash (unsigned char *szHash, const unsigned char *szPassword, int tohex);
|
||||
int de64 (const unsigned char *in, unsigned char *out, int maxlen);
|
||||
unsigned char* en64 (const unsigned char *in, unsigned char *out, int inlen);
|
||||
unsigned char* en64 (const unsigned char *in, unsigned char *out, int inlen, int outsize);
|
||||
void tohex(unsigned char *in, unsigned char *out, int len);
|
||||
void fromhex(unsigned char *in, unsigned char *out, int len);
|
||||
|
||||
|
||||
+15
-3
@@ -329,6 +329,11 @@ int MODULEMAINFUNC (int argc, char** argv){
|
||||
#endif
|
||||
#ifdef WITHSPLICE
|
||||
" -s Use splice() - no filtering for data, off by default\n"
|
||||
" -C connection closed by any of the sides terminates the session, by default\n"
|
||||
" the session is kept until both sides close it (TCP half-close)\n"
|
||||
" -U(0-3) (for socks) what to do when the destination changes within an UDP\n"
|
||||
" association: 1 - log, 2 - authorize, 3 - both (default), 0 (same as -U) -\n"
|
||||
" neither. The first destination is always authorized and logged\n"
|
||||
#endif
|
||||
"-g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY) - delay GRACE_DELAY milliseconds before polling if average polling size below GRACE_TRAFF bytes and GRACE_NUM read operations in single directions are detected within 1 second to minimize polling\n"
|
||||
" -fFORMAT logging format (see documentation)\n"
|
||||
@@ -500,8 +505,8 @@ int MODULEMAINFUNC (int argc, char** argv){
|
||||
}
|
||||
break;
|
||||
case 'N':
|
||||
if(argv[i][3] == 'e') getip46(46, (unsigned char *)argv[i]+3, (struct sockaddr *)&srv.extNat);
|
||||
else if(argv[i][3] == 'i') getip46(46, (unsigned char *)argv[i]+3, (struct sockaddr *)&srv.intNat);
|
||||
if(argv[i][2] == 'e') getip46(46, (unsigned char *)argv[i]+3, (struct sockaddr *)&srv.extNat);
|
||||
else if(argv[i][2] == 'i') getip46(46, (unsigned char *)argv[i]+3, (struct sockaddr *)&srv.intNat);
|
||||
else getip46(46, (unsigned char *)argv[i]+2, (struct sockaddr *)&srv.extNat);
|
||||
break;
|
||||
case 'n':
|
||||
@@ -596,6 +601,12 @@ int MODULEMAINFUNC (int argc, char** argv){
|
||||
case 'g':
|
||||
sscanf(argv[i]+2, "%d,%d,%d", &srv.gracetraf, &srv.gracenum, &srv.gracedelay);
|
||||
break;
|
||||
case 'C':
|
||||
srv.halfclose = *(argv[i]+2)? atoi(argv[i]+2) : 0;
|
||||
break;
|
||||
case 'U':
|
||||
srv.udpauth = *(argv[i]+2)? atoi(argv[i]+2) : 0;
|
||||
break;
|
||||
case 's':
|
||||
#ifdef WITHSPLICE
|
||||
if(isudp || srv.service == S_ADMIN)
|
||||
@@ -1247,6 +1258,8 @@ void srvinit(struct srvparam * srv, struct clientparam *param){
|
||||
#ifdef WITHSPLICE
|
||||
srv->usesplice = 0;
|
||||
#endif
|
||||
srv->halfclose = 1;
|
||||
srv->udpauth = 3;
|
||||
memset(param, 0, sizeof(struct clientparam));
|
||||
param->srv = srv;
|
||||
param->version = srv->version;
|
||||
@@ -1349,7 +1362,6 @@ void srvfree(struct srvparam * srv){
|
||||
|
||||
|
||||
void freeparam(struct clientparam * param) {
|
||||
if(param->res == 2) return;
|
||||
if(param->srv){
|
||||
if(param->srv->so.freefunc) param->srv->so.freefunc(param->sostate);
|
||||
_3proxy_mutex_lock(¶m->srv->counter_mutex);
|
||||
|
||||
+4
-4
@@ -70,7 +70,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
|
||||
if(user){
|
||||
len += sprintf((char *)buf + len, "Proxy-Authorization: Basic ");
|
||||
sprintf((char *)username, "%.128s:%.128s", user, pass?pass:(unsigned char *)"");
|
||||
en64(username, buf+len, (int)strlen((char *)username));
|
||||
if(!en64(username, buf+len, (int)strlen((char *)username), 2048 - len)) return 21;
|
||||
len = (int)strlen((char *)buf);
|
||||
len += sprintf((char *)buf + len, "\r\n");
|
||||
}
|
||||
@@ -270,8 +270,6 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
|
||||
int r2;
|
||||
int saved = 0;
|
||||
|
||||
if(param->remsock != INVALID_SOCKET && param->operation != UDPASSOC) {
|
||||
}
|
||||
if((SAISNULL(¶m->req) || !*SAPORT(¶m->req)) && param->operation != UDPASSOC) {
|
||||
return 100;
|
||||
}
|
||||
@@ -287,7 +285,7 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
|
||||
}
|
||||
continue;
|
||||
}
|
||||
param->redirected++;
|
||||
if(cur->type != R_EXTIP && cur->type != R_HA) param->redirected++;
|
||||
done = 1;
|
||||
if(weight <= 0) {
|
||||
weight += 1000;
|
||||
@@ -342,6 +340,7 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
|
||||
}
|
||||
if(cur->next)continue;
|
||||
if(!ha) return 0;
|
||||
if(param->operation == UDPASSOC) return 0;
|
||||
}
|
||||
else if(!*SAPORT(&cur->addr) && !SAISNULL(&cur->addr)) {
|
||||
uint16_t port = *SAPORT(¶m->sinsr);
|
||||
@@ -354,6 +353,7 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
|
||||
}
|
||||
if(param->operation == UDPASSOC){
|
||||
SOCKET s;
|
||||
if(cur->type != R_SOCKS5 && cur->type != R_SOCKS5P) return 70;
|
||||
s = param->remsock;
|
||||
param->remsock = INVALID_SOCKET;
|
||||
param->ctrlsocksrv = s;
|
||||
|
||||
+42
-12
@@ -3,6 +3,19 @@
|
||||
struct nserver nservers[MAXNSERVERS] = {{{0},0}, {{0},0}, {{0},0}, {{0},0}, {{0},0}};
|
||||
struct nserver authnserver;
|
||||
|
||||
static int dnsqmatch(const unsigned char *a, const unsigned char *b, int len){
|
||||
int i;
|
||||
|
||||
for(i = 0; i < len; i++){
|
||||
unsigned char c1 = a[i], c2 = b[i];
|
||||
|
||||
if(c1 >= 'A' && c1 <= 'Z') c1 += 'a' - 'A';
|
||||
if(c2 >= 'A' && c2 <= 'Z') c2 += 'a' - 'A';
|
||||
if(c1 != c2) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_t *retttl, struct clientparam* param, int makeauth){
|
||||
|
||||
@@ -23,9 +36,12 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
||||
SOCKET sock;
|
||||
uint32_t ttl;
|
||||
PROXYSOCKADDRTYPE addr;
|
||||
PROXYSOCKADDRTYPE from;
|
||||
PROXYSOCKADDRTYPE *sinsr, *sinsl;
|
||||
int usetcp = 0;
|
||||
unsigned short serial = 1;
|
||||
unsigned char qbuf[300];
|
||||
int qlen;
|
||||
|
||||
buf = b+2;
|
||||
|
||||
@@ -92,6 +108,9 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
||||
buf[len++] = (makeauth == 1)? 0x0c : (af==AF_INET6? 0x1c:0x01);/* PTR:host address */
|
||||
buf[len++] = 0;
|
||||
buf[len++] = 1; /* INET */
|
||||
qlen = len - 12;
|
||||
memcpy(qbuf, buf + 12, qlen);
|
||||
|
||||
if(usetcp){
|
||||
buf-=2;
|
||||
*(unsigned short*)buf = htons(len);
|
||||
@@ -104,30 +123,41 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
||||
continue;
|
||||
}
|
||||
if(param) param->statscli64 += len;
|
||||
len = sockrecvfrom(NULL, sock, (struct sockaddr *)sinsr, buf, 4096, conf.timeouts[DNS_TO]*1000);
|
||||
len = sockrecvfrom(NULL, sock, (struct sockaddr *)&from, buf, 4096, conf.timeouts[DNS_TO]*1000);
|
||||
if(len > 13 && usetcp){
|
||||
unsigned short us;
|
||||
us = ntohs(*(unsigned short*)buf);
|
||||
len-=2;
|
||||
buf+=2;
|
||||
if(us > 4096 || us < len) len = 0;
|
||||
else if(us > len){
|
||||
if(sockrecvfrom(NULL, sock, (struct sockaddr *)&from, buf+len, us-len, conf.timeouts[DNS_TO]*1000) != us-len) len = 0;
|
||||
else len = us;
|
||||
}
|
||||
}
|
||||
so._shutdown(so.state, sock, SHUT_RDWR);
|
||||
so._closesocket(so.state, sock);
|
||||
if(len <= 13) {
|
||||
continue;
|
||||
}
|
||||
if(param) param->statssrv64 += len;
|
||||
if(usetcp){
|
||||
unsigned short us;
|
||||
us = ntohs(*(unsigned short*)buf);
|
||||
len-=2;
|
||||
buf+=2;
|
||||
if(us > 4096 || us < len || (us > len && sockrecvfrom(NULL, sock, (struct sockaddr *)sinsr, buf+len, us-len, conf.timeouts[DNS_TO]*1000) != us-len)) {
|
||||
continue;
|
||||
}
|
||||
if(!usetcp && (*SAFAMILY(&from) != *SAFAMILY(sinsr) ||
|
||||
memcmp(SAADDR(&from), SAADDR(sinsr), SAADDRLEN(sinsr)) ||
|
||||
*SAPORT(&from) != *SAPORT(sinsr))) {
|
||||
continue; /* not from the server we asked */
|
||||
}
|
||||
if(*(unsigned short *)buf != serial)continue;
|
||||
if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
|
||||
return 0;
|
||||
}
|
||||
if(!(buf[2] & 0x80)) continue; /* not a response */
|
||||
nq = buf[5] + (((unsigned short)buf[4])<<8);
|
||||
if (nq != 1) {
|
||||
continue; /* we did only 1 request */
|
||||
}
|
||||
if(len < 12 + qlen || dnsqmatch(buf + 12, qbuf, qlen)) {
|
||||
continue; /* question does not match the query */
|
||||
}
|
||||
if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
|
||||
return 0;
|
||||
}
|
||||
for(k = 13; k<len && buf[k]; k++) {
|
||||
}
|
||||
k++;
|
||||
|
||||
+4
-4
@@ -237,14 +237,14 @@ void * smtppchild(struct clientparam* param) {
|
||||
param->nwrites++;
|
||||
i = sockgetlinebuf(param, SERVER, buf, sizeof(buf) - 1, '\n', conf.timeouts[STRING_L]);
|
||||
if(i<4 || strncasecmp((char *)buf, "334", 3)) {RETURN(680);}
|
||||
en64(param->extusername, buf, (int)strlen((char *)param->extusername));
|
||||
if(!en64(param->extusername, buf, (int)strlen((char *)param->extusername), (int)sizeof(buf))) {RETURN(683);}
|
||||
socksend(param, param->remsock, buf, (int)strlen((char *)buf), conf.timeouts[STRING_S]);
|
||||
socksend(param, param->remsock, (unsigned char *)"\r\n", 2, conf.timeouts[STRING_S]);
|
||||
param->statscli64+=(i+2);
|
||||
param->nwrites+=2;
|
||||
i = sockgetlinebuf(param, SERVER, buf, sizeof(buf) - 1, '\n', conf.timeouts[STRING_L]);
|
||||
if(i<4 || strncasecmp((char *)buf, "334", 3)) {RETURN(681);}
|
||||
en64(param->extpassword, buf, (int)strlen((char *)param->extpassword));
|
||||
if(!en64(param->extpassword, buf, (int)strlen((char *)param->extpassword), (int)sizeof(buf))) {RETURN(683);}
|
||||
socksend(param, param->remsock, buf, (int)strlen((char *)buf), conf.timeouts[STRING_S]);
|
||||
socksend(param, param->remsock, (unsigned char *)"\r\n", 2, conf.timeouts[STRING_S]);
|
||||
param->statscli64+=(i+2);
|
||||
@@ -259,12 +259,12 @@ void * smtppchild(struct clientparam* param) {
|
||||
*username = 0;
|
||||
i = (int)strlen((char *)param->extusername) + 1;
|
||||
res = (int)strlen((char *)param->extpassword);
|
||||
if(i + 1 + res >= (int)sizeof(username) || ((i + 1 + res + 2) / 3) * 4 + 1 > (int)sizeof(buf)) {RETURN(683);}
|
||||
if(i + 1 + res >= (int)sizeof(username)) {RETURN(683);}
|
||||
memcpy(username+1, param->extusername, i);
|
||||
i++;
|
||||
memcpy(username + i, param->extpassword, res);
|
||||
i+=res;
|
||||
en64(username, buf, i);
|
||||
if(!en64(username, buf, i, (int)sizeof(buf))) {RETURN(683);}
|
||||
i = (int)strlen((char *)buf);
|
||||
socksend(param, param->remsock, buf, i, conf.timeouts[STRING_S]);
|
||||
socksend(param, param->remsock, (unsigned char *)"\r\n", 2, conf.timeouts[STRING_S]);
|
||||
|
||||
+3
-2
@@ -171,12 +171,13 @@ int sockgetlinebuf(struct clientparam * param, DIRECTION which, unsigned char *
|
||||
if(delim != EOF){
|
||||
unsigned char *d = (unsigned char *)memchr(base + *offp, delim, n);
|
||||
if(d) n = (int)(d - (base + *offp)) + 1;
|
||||
memcpy(buf + i, base + *offp, n);
|
||||
/* caller may use param->srvbuf / param->clibuf as buf */
|
||||
memmove(buf + i, base + *offp, n);
|
||||
i += n; *offp += n;
|
||||
if(d || i >= bufsize) return i;
|
||||
}
|
||||
else {
|
||||
memcpy(buf + i, base + *offp, n);
|
||||
memmove(buf + i, base + *offp, n);
|
||||
i += n; *offp += n;
|
||||
if(i >= bufsize) return i;
|
||||
}
|
||||
|
||||
+18
-9
@@ -44,7 +44,13 @@ ssize_t splice(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t le
|
||||
#define MIN(a,b) ((a>b)?b:a)
|
||||
#define RETURN(xxx) { res = xxx; goto CLEANRET; }
|
||||
|
||||
/* Unless half-close is requested for the service, a connection closed by any
|
||||
of the sides terminates the session, remaining buffered data is delivered
|
||||
before the sockets are closed. */
|
||||
#define SESSIONEND (!halfclose && (CLIENTTERMREAD || SERVERTERMREAD))
|
||||
|
||||
int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||
int halfclose = param->srv->halfclose;
|
||||
uint64_t fromclient=0x7fffffffffffffff, fromserver =0x7fffffffffffffff;
|
||||
uint64_t inclientbuf = 0, inserverbuf = 0;
|
||||
int FROMCLIENT = 1, TOCLIENTBUF = 1, TOSERVER = 1,
|
||||
@@ -129,13 +135,13 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||
#ifdef WITHSPLICE
|
||||
|| inserverpipe
|
||||
#endif
|
||||
|| (!SERVERTERMREAD )))
|
||||
|| (!SERVERTERMREAD && !SESSIONEND)))
|
||||
||
|
||||
((!SERVERTERMWRITE) && fromclient && (inclientbuf
|
||||
#ifdef WITHSPLICE
|
||||
|| inclientpipe
|
||||
#endif
|
||||
|| (!CLIENTTERMREAD )))
|
||||
|| (!CLIENTTERMREAD && !SESSIONEND)))
|
||||
){
|
||||
|
||||
|
||||
@@ -354,7 +360,7 @@ log(logbuf);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE){
|
||||
if(fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE && !SESSIONEND){
|
||||
int error;
|
||||
socklen_t len=sizeof(error);
|
||||
#ifdef WITHLOG
|
||||
@@ -396,7 +402,7 @@ log("done read from client to pipe");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE){
|
||||
if(fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE && !SESSIONEND){
|
||||
int error;
|
||||
socklen_t len=sizeof(error);
|
||||
errno = 0;
|
||||
@@ -449,7 +455,7 @@ log("done read from server to pipe\n");
|
||||
else
|
||||
#endif
|
||||
{
|
||||
if(fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF){
|
||||
if(fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF && !SESSIONEND){
|
||||
#ifdef WITHLOG
|
||||
log("read from client to buf");
|
||||
#endif
|
||||
@@ -482,7 +488,7 @@ log("done read from client to buf");
|
||||
}
|
||||
}
|
||||
|
||||
if(fromserver > inserverbuf && FROMSERVER && TOSERVERBUF){
|
||||
if(fromserver > inserverbuf && FROMSERVER && TOSERVERBUF && !SESSIONEND){
|
||||
#ifdef WITHLOG
|
||||
log("read from server to buf");
|
||||
#endif
|
||||
@@ -547,7 +553,7 @@ log("done read from server to buf");
|
||||
// if(!CLIENTTERMREAD || !CLIENTTERMWRITE){
|
||||
if(!after){
|
||||
fds[fdsc].fd = param->clisock;
|
||||
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && ((
|
||||
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && !SESSIONEND && ((
|
||||
#ifdef WITHSPLICE
|
||||
!usesplice &&
|
||||
#endif
|
||||
@@ -607,7 +613,7 @@ log("ready to write to client");
|
||||
// if(!SERVERTERMREAD || !SERVERTERMWRITE){
|
||||
if(!after){
|
||||
fds[fdsc].fd = param->remsock;
|
||||
if(fromserver && !SERVERTERMREAD && !FROMSERVER && ((
|
||||
if(fromserver && !SERVERTERMREAD && !FROMSERVER && !SESSIONEND && ((
|
||||
#ifdef WITHSPLICE
|
||||
!usesplice &&
|
||||
#endif
|
||||
@@ -780,7 +786,9 @@ log("ready reading from server pipe");
|
||||
#ifdef WITHLOG
|
||||
log("entering poll");
|
||||
#endif
|
||||
res = param->srv->so._poll(param->sostate, fds, fdsc, timeo*1000);
|
||||
res = param->srv->so._poll(param->sostate, fds, fdsc,
|
||||
((CLIENTTERMREAD || SERVERTERMREAD)?
|
||||
MIN(timeo, conf.timeouts[LINGER_TO]) : timeo) * 1000);
|
||||
#ifdef WITHLOG
|
||||
log("leaving poll");
|
||||
#endif
|
||||
@@ -825,3 +833,4 @@ CLEANRET:
|
||||
|
||||
return res;
|
||||
}
|
||||
#undef SESSIONEND
|
||||
+15
-47
@@ -7,15 +7,6 @@
|
||||
*/
|
||||
|
||||
#include "proxy.h"
|
||||
#ifdef __linux__
|
||||
#include <sched.h>
|
||||
|
||||
static int switch_ns(struct srvparam *srv, int target_fd) {
|
||||
if(target_fd < 0) return 0;
|
||||
if(srv->saved_nsfd >= 0 && setns(srv->saved_nsfd, CLONE_NEWNET)) return -1;
|
||||
return setns(target_fd, CLONE_NEWNET);
|
||||
}
|
||||
#endif
|
||||
|
||||
#define RETURN(xxx) { param->res = xxx; goto CLEANRET; }
|
||||
|
||||
@@ -116,38 +107,20 @@ void * sockschild(struct clientparam* param) {
|
||||
}
|
||||
|
||||
size = 4;
|
||||
*SAFAMILY(¶m->sinsr) = *SAFAMILY(¶m->req) = AF_INET;
|
||||
switch(c) {
|
||||
#ifndef NOIPV6
|
||||
case 4:
|
||||
if(param->srv->family == 4) RETURN(997);
|
||||
size = 16;
|
||||
*SAFAMILY(¶m->sinsr) = *SAFAMILY(¶m->req) = AF_INET6;
|
||||
#endif
|
||||
case 1:
|
||||
for (i = 0; i<size; i++){
|
||||
if ((res = sockgetcharcli(param, conf.timeouts[SINGLEBYTE_S], 0)) == EOF) {RETURN(441);}
|
||||
buf[i] = (unsigned char)res;
|
||||
}
|
||||
#ifndef NOIPV6
|
||||
if (c == 1 && param->srv->family==6){
|
||||
char prefix[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255};
|
||||
*SAFAMILY(¶m->sinsr) = *SAFAMILY(¶m->req) = AF_INET6;
|
||||
memcpy(SAADDR(¶m->sinsr), prefix, 12);
|
||||
memcpy(12 + (char *)SAADDR(¶m->sinsr), buf, 4);
|
||||
memcpy(SAADDR(¶m->req), prefix, 12);
|
||||
memcpy(12 + (char *)SAADDR(¶m->req), buf, 4);
|
||||
}
|
||||
else {
|
||||
#endif
|
||||
memcpy(SAADDR(¶m->sinsr), buf, size);
|
||||
memcpy(SAADDR(¶m->req), buf, size);
|
||||
#ifndef NOIPV6
|
||||
}
|
||||
#endif
|
||||
if(command == 1 && SAISNULL(¶m->req)) {
|
||||
RETURN(431);
|
||||
}
|
||||
res = socks5_setaddr(param->srv->family, c, buf, ¶m->req);
|
||||
if(res == 1) {RETURN(997);}
|
||||
if(res == 2 && command == 1) {RETURN(431);}
|
||||
param->sinsr = param->req;
|
||||
myinet_ntop(*SAFAMILY(¶m->sinsr), SAADDR(¶m->sinsr), (char *)buf, 64);
|
||||
break;
|
||||
case 3:
|
||||
@@ -219,7 +192,11 @@ void * sockschild(struct clientparam* param) {
|
||||
RETURN(997);
|
||||
}
|
||||
|
||||
if((res = (*param->srv->authfunc)(param))) {
|
||||
if(command == 3) param->preauth = 1;
|
||||
res = (*param->srv->authfunc)(param);
|
||||
param->preauth = 0;
|
||||
if(command == 3 && res == 2) res = 0;
|
||||
if(res) {
|
||||
RETURN(res);
|
||||
}
|
||||
|
||||
@@ -238,18 +215,9 @@ void * sockschild(struct clientparam* param) {
|
||||
#endif
|
||||
|
||||
if(command == 3) {
|
||||
#ifdef __linux__
|
||||
if(switch_ns(param->srv, param->srv->o_nsfd)) {RETURN(11);}
|
||||
#endif
|
||||
if ((param->remsock=param->srv->so._socket(param->sostate, SASOCK(¶m->req), SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {RETURN (11);}
|
||||
#ifdef _WIN32
|
||||
{ unsigned long ul = 1; ioctlsocket(param->remsock, FIONBIO, &ul); }
|
||||
#else
|
||||
fcntl(param->remsock, F_SETFL, O_NONBLOCK | fcntl(param->remsock, F_GETFL));
|
||||
#endif
|
||||
if((res = udpbind(param))) {RETURN(res);}
|
||||
}
|
||||
|
||||
if(command > 1) {
|
||||
else if(command == 2) {
|
||||
if(param->srv->so._bind(param->sostate, param->remsock,(struct sockaddr *)¶m->sinsl,SASIZE(¶m->sinsl))) {
|
||||
*SAPORT(¶m->sinsl) = 0;
|
||||
if(param->srv->so._bind(param->sostate, param->remsock,(struct sockaddr *)¶m->sinsl,SASIZE(¶m->sinsl)))RETURN (12);
|
||||
@@ -260,7 +228,8 @@ fflush(stderr);
|
||||
}
|
||||
sasize = SASIZE(¶m->sinsl);
|
||||
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsl, &sasize);
|
||||
if(command == 3) {
|
||||
}
|
||||
if(command == 3) {
|
||||
param->ctrlsock = param->clisock;
|
||||
#ifdef __linux__
|
||||
if(switch_ns(param->srv, param->srv->i_nsfd)) {RETURN(11);}
|
||||
@@ -283,7 +252,6 @@ fprintf(stderr, "%hu binded to communicate with client\n",
|
||||
);
|
||||
fflush(stderr);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
param->res = 0;
|
||||
|
||||
@@ -299,7 +267,7 @@ CLEANRET:
|
||||
|
||||
sasize = sizeof(sin);
|
||||
if(command != 3 && param->remsock != INVALID_SOCKET) param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&sin, &sasize);
|
||||
if(!SAISNULL(¶m->srv->extNat)){
|
||||
if(command != 3 && !SAISNULL(¶m->srv->extNat)){
|
||||
uint16_t port;
|
||||
port = *SAPORT(&sin);
|
||||
sin = param->srv->extNat;
|
||||
@@ -307,7 +275,7 @@ CLEANRET:
|
||||
}
|
||||
else {
|
||||
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
||||
if(!SAISNULL(¶m->srv->intNat)){
|
||||
if(command == 3 && !SAISNULL(¶m->srv->intNat)){
|
||||
uint16_t port;
|
||||
port = *SAPORT(&sin);
|
||||
sin = param->srv->intNat;
|
||||
|
||||
+9
-3
@@ -551,6 +551,8 @@ struct srvparam {
|
||||
#ifdef WITHSPLICE
|
||||
int usesplice;
|
||||
#endif
|
||||
int halfclose;
|
||||
int udpauth;
|
||||
unsigned bufsize;
|
||||
unsigned authcachetype, authcachetime;
|
||||
unsigned logdumpsrv, logdumpcli;
|
||||
@@ -643,7 +645,9 @@ struct clientparam {
|
||||
paused,
|
||||
version,
|
||||
connlim,
|
||||
predatdone;
|
||||
predatdone,
|
||||
preauth,
|
||||
dstindep;
|
||||
|
||||
unsigned char *hostname,
|
||||
*username,
|
||||
@@ -678,6 +682,7 @@ struct clientparam {
|
||||
|
||||
PROXYSOCKADDRTYPE udp_relay[3];
|
||||
int udp_nhops;
|
||||
struct ace *lastace;
|
||||
time_t time_start;
|
||||
};
|
||||
|
||||
@@ -832,7 +837,7 @@ struct pluginlink {
|
||||
int (*ACLMatches)(struct ace* acentry, struct clientparam * param);
|
||||
int (*alwaysauth)(struct clientparam * param);
|
||||
int (*checkACL)(struct clientparam * param);
|
||||
unsigned char* (*en64)(const unsigned char *in, unsigned char *out, int inlen);
|
||||
unsigned char* (*en64)(const unsigned char *in, unsigned char *out, int inlen, int outsize);
|
||||
int (*de64)(const unsigned char *in, unsigned char *out, int maxlen);
|
||||
void (*tohex)(unsigned char *in, unsigned char *out, int len);
|
||||
void (*fromhex)(unsigned char *in, unsigned char *out, int len);
|
||||
@@ -882,7 +887,8 @@ typedef enum {
|
||||
DNS_TO,
|
||||
CHAIN_TO,
|
||||
CONNECT_TO,
|
||||
CONNBACK_TO
|
||||
CONNBACK_TO,
|
||||
LINGER_TO
|
||||
}TIMEOUT;
|
||||
|
||||
typedef enum {
|
||||
|
||||
+5
-12
@@ -36,26 +36,19 @@ void * udppmchild(struct clientparam* param) {
|
||||
int i;
|
||||
int len = 0;
|
||||
|
||||
if(parsehostname((char *)param->srv->target, param, ntohs(param->srv->targetport))) { RETURN(201) }
|
||||
if(parsehostname((char *)param->srv->target, param, ntohs(param->srv->targetport))) { RETURN(100) }
|
||||
|
||||
#ifndef NOIPV6
|
||||
memcpy(¶m->sinsl, *SAFAMILY(¶m->req) == AF_INET6 ? (struct sockaddr *)¶m->srv->extsa6 : (struct sockaddr *)¶m->srv->extsa, SASIZE(¶m->req));
|
||||
param->sinsl = *SAFAMILY(¶m->req) == AF_INET6? param->srv->extsa6 : param->srv->extsa;
|
||||
#else
|
||||
memcpy(¶m->sinsl, (struct sockaddr *)¶m->srv->extsa, SASIZE(¶m->req));
|
||||
param->sinsl = param->srv->extsa;
|
||||
#endif
|
||||
*SAPORT(¶m->sinsl) = 0;
|
||||
param->remsock = param->srv->so._socket(param->srv->so.state, SASOCK(¶m->sinsl), SOCK_DGRAM, IPPROTO_UDP);
|
||||
if(param->remsock == INVALID_SOCKET) { RETURN(202); }
|
||||
if(param->srv->so._bind(param->srv->so.state, param->remsock, (struct sockaddr *)¶m->sinsl, SASIZE(¶m->sinsl))) { RETURN(203); }
|
||||
#ifdef _WIN32
|
||||
{ unsigned long ul2 = 1; ioctlsocket(param->remsock, FIONBIO, &ul2); }
|
||||
#else
|
||||
fcntl(param->remsock, F_SETFL, O_NONBLOCK | fcntl(param->remsock, F_GETFL));
|
||||
#endif
|
||||
memcpy(¶m->sinsr, ¶m->req, sizeof(param->req));
|
||||
param->sinsr = param->req;
|
||||
param->operation = UDPASSOC;
|
||||
authres = (*param->srv->authfunc)(param);
|
||||
if(authres) { RETURN(authres); }
|
||||
if((authres = udpbind(param))) { RETURN(authres); }
|
||||
if(!param->srv->s_option)hashadd(&udp_table, param, ¶m, MAX_COUNTER_TIME);
|
||||
if(!param->srvbuf){
|
||||
if(!(param->srvbuf = malloc(UDPBUFSIZE)))RETURN(11);
|
||||
|
||||
+271
-84
@@ -8,6 +8,10 @@
|
||||
|
||||
#include "proxy.h"
|
||||
|
||||
/* space reserved in front of the received datagram to prepend the headers
|
||||
of the second and the third hop of a SOCKS5 UDP chain */
|
||||
#define UDPHDROFF 48
|
||||
|
||||
int socks5_udp_build_hdr(unsigned char *buf, PROXYSOCKADDRTYPE *addr)
|
||||
{
|
||||
buf[0] = buf[1] = buf[2] = 0;
|
||||
@@ -48,69 +52,192 @@ static int socks5_udp_skip_hdr(unsigned char *buf, int len)
|
||||
* param->srv->s_option non-zero: return after first datagram sent to client
|
||||
* param->ctrlsock TCP control socket from the client; INVALID_SOCKET if none.
|
||||
*/
|
||||
|
||||
struct udppoll {
|
||||
struct pollfd fds[4];
|
||||
int nfds;
|
||||
int cli, ctrl, ctrlsrv;
|
||||
};
|
||||
|
||||
static void udpfds(struct clientparam *param, struct udppoll *p)
|
||||
{
|
||||
memset(p->fds, 0, sizeof(p->fds));
|
||||
p->nfds = 0;
|
||||
p->cli = p->ctrl = p->ctrlsrv = -1;
|
||||
|
||||
p->fds[p->nfds].fd = param->remsock; /* always index 0 */
|
||||
p->fds[p->nfds].events = POLLIN;
|
||||
p->nfds++;
|
||||
|
||||
if (!param->waitserver64) {
|
||||
p->fds[p->nfds].fd = param->clisock;
|
||||
p->fds[p->nfds].events = POLLIN;
|
||||
p->cli = p->nfds++;
|
||||
}
|
||||
if (param->ctrlsock != INVALID_SOCKET) {
|
||||
p->fds[p->nfds].fd = param->ctrlsock;
|
||||
p->fds[p->nfds].events = POLLIN;
|
||||
p->ctrl = p->nfds++;
|
||||
}
|
||||
if (param->ctrlsocksrv != INVALID_SOCKET) {
|
||||
p->fds[p->nfds].fd = param->ctrlsocksrv;
|
||||
p->fds[p->nfds].events = POLLIN;
|
||||
p->ctrlsrv = p->nfds++;
|
||||
}
|
||||
}
|
||||
|
||||
static void udplog(struct clientparam *param)
|
||||
{
|
||||
unsigned char buf[400];
|
||||
int len;
|
||||
|
||||
if(!param->srv->logfunc) return;
|
||||
len = sprintf((char *)buf, "UDPMAP ");
|
||||
if(param->hostname) len += sprintf((char *)buf + len, "%.256s", param->hostname);
|
||||
else len += myinet_ntop(*SAFAMILY(¶m->req), SAADDR(¶m->req), (char *)buf + len, 64);
|
||||
sprintf((char *)buf + len, ":%hu", ntohs(*SAPORT(¶m->req)));
|
||||
param->srv->logfunc(param, buf);
|
||||
}
|
||||
|
||||
int udpbind(struct clientparam *param)
|
||||
{
|
||||
SOCKET s;
|
||||
SASIZETYPE sasize;
|
||||
|
||||
#ifdef __linux__
|
||||
if (switch_ns(param->srv, param->srv->o_nsfd)) return 11;
|
||||
#endif
|
||||
s = param->srv->so._socket(param->sostate, SASOCK(¶m->sinsl), SOCK_DGRAM, IPPROTO_UDP);
|
||||
#ifdef __linux__
|
||||
if (switch_ns(param->srv, param->srv->i_nsfd)) {
|
||||
if (s != INVALID_SOCKET) param->srv->so._closesocket(param->sostate, s);
|
||||
return 11;
|
||||
}
|
||||
#endif
|
||||
if (s == INVALID_SOCKET) return 11;
|
||||
#ifdef _WIN32
|
||||
{ unsigned long ul = 1; ioctlsocket(s, FIONBIO, &ul); }
|
||||
#else
|
||||
fcntl(s, F_SETFL, O_NONBLOCK | fcntl(s, F_GETFL));
|
||||
#endif
|
||||
param->remsock = s;
|
||||
if (param->srv->so._bind(param->sostate, param->remsock,
|
||||
(struct sockaddr *)¶m->sinsl, SASIZE(¶m->sinsl))) {
|
||||
*SAPORT(¶m->sinsl) = 0;
|
||||
if (param->srv->so._bind(param->sostate, param->remsock,
|
||||
(struct sockaddr *)¶m->sinsl, SASIZE(¶m->sinsl))) {
|
||||
param->srv->so._closesocket(param->sostate, param->remsock);
|
||||
param->remsock = INVALID_SOCKET;
|
||||
return 12;
|
||||
}
|
||||
}
|
||||
sasize = SASIZE(¶m->sinsl);
|
||||
param->srv->so._getsockname(param->sostate, param->remsock,
|
||||
(struct sockaddr *)¶m->sinsl, &sasize);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void udpreset(struct clientparam *param)
|
||||
{
|
||||
param->redirected = 0;
|
||||
param->udp_nhops = 0;
|
||||
memset(param->udp_relay, 0, sizeof(param->udp_relay));
|
||||
#ifndef NOIPV6
|
||||
param->sinsl = *SAFAMILY(¶m->req) == AF_INET6? param->srv->extsa6 : param->srv->extsa;
|
||||
#else
|
||||
param->sinsl = param->srv->extsa;
|
||||
#endif
|
||||
param->sinsr = param->req;
|
||||
}
|
||||
|
||||
/*
|
||||
* Authorize param->req and (re)build the server side of the association:
|
||||
* a parent proxy chain and/or an external address may be selected by the ACL.
|
||||
* Returns the authorization result. param->remsock is INVALID_SOCKET if the
|
||||
* socket can not be created, in this case the association can not continue.
|
||||
*/
|
||||
static int udpreconnect(struct clientparam *param)
|
||||
{
|
||||
int res;
|
||||
|
||||
if (param->ctrlsocksrv != INVALID_SOCKET) {
|
||||
param->srv->so._closesocket(param->sostate, param->ctrlsocksrv);
|
||||
param->ctrlsocksrv = INVALID_SOCKET;
|
||||
}
|
||||
if (param->remsock != INVALID_SOCKET) {
|
||||
param->srv->so._closesocket(param->sostate, param->remsock);
|
||||
param->remsock = INVALID_SOCKET;
|
||||
}
|
||||
udpreset(param);
|
||||
res = (*param->srv->authfunc)(param);
|
||||
if (res) {
|
||||
if (param->ctrlsocksrv != INVALID_SOCKET) {
|
||||
param->srv->so._closesocket(param->sostate, param->ctrlsocksrv);
|
||||
param->ctrlsocksrv = INVALID_SOCKET;
|
||||
}
|
||||
if (param->remsock != INVALID_SOCKET) {
|
||||
param->srv->so._closesocket(param->sostate, param->remsock);
|
||||
param->remsock = INVALID_SOCKET;
|
||||
}
|
||||
udpreset(param);
|
||||
}
|
||||
if (udpbind(param)) return res? res : 11;
|
||||
return res;
|
||||
}
|
||||
|
||||
int udpsockmap(struct clientparam *param, int timeo)
|
||||
{
|
||||
PROXYSOCKADDRTYPE sin;
|
||||
PROXYSOCKADDRTYPE cliaddr;
|
||||
PROXYSOCKADDRTYPE from;
|
||||
struct pollfd fds[4];
|
||||
PROXYSOCKADDRTYPE lastdst;
|
||||
struct udppoll p;
|
||||
SASIZETYPE sasize;
|
||||
int len, res, nfds;
|
||||
int nhops = param->udp_nhops;
|
||||
int clisock_idx = -1, ctrlsock_idx = -1, ctrlsocksrv_idx = -1;
|
||||
int len, res, nhops;
|
||||
int firstpacket = 1;
|
||||
|
||||
if(param->srv->service == S_UDPPM) nhops++;
|
||||
int havedst = 0, lastres = 0;
|
||||
char lastname[256] = "";
|
||||
struct ace *lastace = NULL;
|
||||
|
||||
if (param->srvbufsize < UDPBUFSIZE) {
|
||||
unsigned char *newbuf = realloc(param->srvbuf, UDPBUFSIZE);
|
||||
if (!newbuf) return 21;
|
||||
param->srvbuf = newbuf;
|
||||
param->srvbufsize = UDPBUFSIZE;
|
||||
}
|
||||
sin = param->sincr;
|
||||
|
||||
/* Build poll array once — sockets don't change across iterations */
|
||||
nfds = 0;
|
||||
fds[nfds].fd = param->remsock; /* always index 0 */
|
||||
fds[nfds].events = POLLIN;
|
||||
nfds++;
|
||||
|
||||
if (!param->waitserver64) {
|
||||
fds[nfds].fd = param->clisock;
|
||||
fds[nfds].events = POLLIN;
|
||||
clisock_idx = nfds++;
|
||||
cliaddr = param->sincr;
|
||||
if(param->ctrlsock != INVALID_SOCKET){
|
||||
sasize = sizeof(cliaddr);
|
||||
param->srv->so._getpeername(param->sostate, param->ctrlsock, (struct sockaddr *)&cliaddr, &sasize);
|
||||
}
|
||||
sin = cliaddr;
|
||||
|
||||
if (param->ctrlsock != INVALID_SOCKET) {
|
||||
fds[nfds].fd = param->ctrlsock;
|
||||
fds[nfds].events = POLLIN;
|
||||
ctrlsock_idx = nfds++;
|
||||
}
|
||||
|
||||
if (param->ctrlsocksrv != INVALID_SOCKET) {
|
||||
fds[nfds].fd = param->ctrlsocksrv;
|
||||
fds[nfds].events = POLLIN;
|
||||
ctrlsocksrv_idx = nfds++;
|
||||
}
|
||||
nhops = param->udp_nhops;
|
||||
if(param->srv->service == S_UDPPM) nhops++;
|
||||
udpfds(param, &p);
|
||||
|
||||
for (;;) {
|
||||
res = param->srv->so._poll(param->sostate, fds, nfds, timeo * 1000);
|
||||
res = param->srv->so._poll(param->sostate, p.fds, p.nfds, timeo * 1000);
|
||||
if (res < 0) return 481;
|
||||
if (res == 0) return 92;
|
||||
|
||||
/* datagram from client */
|
||||
if (clisock_idx >= 0 && fds[clisock_idx].revents) {
|
||||
int recvoff = 0, k;
|
||||
if (p.cli >= 0 && p.fds[p.cli].revents) {
|
||||
unsigned char *base = param->srvbuf + UDPHDROFF;
|
||||
PROXYSOCKADDRTYPE dst;
|
||||
char dstnamebuf[256];
|
||||
char *dstname = NULL;
|
||||
int i, k, w, off;
|
||||
|
||||
sasize = sizeof(sin);
|
||||
for (k = 1; k < nhops; k++)
|
||||
recvoff += 4 + (int)SAADDRLEN(¶m->udp_relay[k]) + 2;
|
||||
len = param->srv->so._recvfrom(param->sostate, param->clisock,
|
||||
(char *)param->srvbuf + recvoff, UDPBUFSIZE - recvoff,
|
||||
(char *)base, UDPBUFSIZE - UDPHDROFF,
|
||||
0, (struct sockaddr *)&sin, &sasize);
|
||||
if (len < 0 && (errno == EAGAIN || errno == EINTR)) continue;
|
||||
if (len <= 0) return 482;
|
||||
|
||||
if (SAADDRLEN(&sin) != SAADDRLEN(¶m->sincr) ||
|
||||
memcmp(SAADDR(&sin), SAADDR(¶m->sincr), SAADDRLEN(&sin)))
|
||||
if (SAADDRLEN(&sin) != SAADDRLEN(&cliaddr) ||
|
||||
memcmp(SAADDR(&sin), SAADDR(&cliaddr), SAADDRLEN(&sin)))
|
||||
continue;
|
||||
if (firstpacket) {
|
||||
if (!SAISNULL(¶m->req) && *SAPORT(¶m->req) &&
|
||||
@@ -118,70 +245,130 @@ int udpsockmap(struct clientparam *param, int timeo)
|
||||
!memcmp(SAADDR(¶m->req), SAADDR(&sin), SAADDRLEN(¶m->req)) &&
|
||||
memcmp(SAPORT(¶m->req), SAPORT(&sin), 2))
|
||||
continue;
|
||||
param->sincr = sin;
|
||||
cliaddr = sin;
|
||||
firstpacket = 0;
|
||||
} else if (memcmp(SAPORT(&sin), SAPORT(¶m->sincr), 2)) {
|
||||
} else if (memcmp(SAPORT(&sin), SAPORT(&cliaddr), 2)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if(param->bandlimfunc && (*param->bandlimfunc)(param, 0, len)) continue;
|
||||
|
||||
if (nhops == 0) {
|
||||
int i;
|
||||
if (len < 10 || param->srvbuf[0] || param->srvbuf[1] || param->srvbuf[2])
|
||||
return 483;
|
||||
switch (param->srvbuf[3]) {
|
||||
case 1:
|
||||
*SAFAMILY(¶m->sinsr) = AF_INET;
|
||||
memcpy(SAADDR(¶m->sinsr), param->srvbuf + 4, 4);
|
||||
i = 8;
|
||||
break;
|
||||
case 4:
|
||||
if (len < 22) return 484;
|
||||
*SAFAMILY(¶m->sinsr) = AF_INET6;
|
||||
memcpy(SAADDR(¶m->sinsr), param->srvbuf + 4, 16);
|
||||
i = 20;
|
||||
break;
|
||||
case 3: {
|
||||
int sz = param->srvbuf[4], j;
|
||||
if (len < 7 + sz) return 485;
|
||||
for (j = 4; j < 4 + sz; j++) param->srvbuf[j] = param->srvbuf[j + 1];
|
||||
param->srvbuf[4 + sz] = 0;
|
||||
i = 5 + sz;
|
||||
if (!getip46(param->srv->family, param->srvbuf + 4,
|
||||
(struct sockaddr *)¶m->sinsr))
|
||||
return 100;
|
||||
break;
|
||||
if (len < 10 || base[0] || base[1] || base[2]) return 483;
|
||||
memset(&dst, 0, sizeof(dst));
|
||||
switch (base[3]) {
|
||||
case 1:
|
||||
if (socks5_setaddr(param->srv->family, 1, base + 4, &dst)) continue;
|
||||
i = 8;
|
||||
break;
|
||||
#ifndef NOIPV6
|
||||
case 4:
|
||||
if (len < 22) return 484;
|
||||
if (socks5_setaddr(param->srv->family, 4, base + 4, &dst)) continue;
|
||||
i = 20;
|
||||
break;
|
||||
#endif
|
||||
case 3: {
|
||||
int sz = base[4];
|
||||
if (len < 7 + sz) return 485;
|
||||
memcpy(dstnamebuf, base + 5, sz);
|
||||
dstnamebuf[sz] = 0;
|
||||
dstname = dstnamebuf;
|
||||
i = 5 + sz;
|
||||
if (!getip46(param->srv->family, (unsigned char *)dstnamebuf,
|
||||
(struct sockaddr *)&dst)) {
|
||||
if (!nhops) return 100;
|
||||
memset(&dst, 0, sizeof(dst));
|
||||
*SAFAMILY(&dst) = AF_INET;
|
||||
}
|
||||
default: return 997;
|
||||
break;
|
||||
}
|
||||
default: return 997;
|
||||
}
|
||||
memcpy(SAPORT(&dst), base + i, 2);
|
||||
i += 2;
|
||||
|
||||
if (!havedst
|
||||
|| SAADDRLEN(&lastdst) != SAADDRLEN(&dst)
|
||||
|| memcmp(SAADDR(&lastdst), SAADDR(&dst), SAADDRLEN(&dst))
|
||||
|| memcmp(SAPORT(&lastdst), SAPORT(&dst), 2)
|
||||
|| strncmp(lastname, dstname? dstname : "", sizeof(lastname) - 1)) {
|
||||
int ares = 0, reconnect = 0;
|
||||
|
||||
if ((param->srv->udpauth & 1) && havedst && !lastres) {
|
||||
PROXYSOCKADDRTYPE newdst = dst;
|
||||
|
||||
param->req = lastdst;
|
||||
if (param->hostname) free(param->hostname);
|
||||
param->hostname = *lastname? (unsigned char *)strdup(lastname) : NULL;
|
||||
udplog(param);
|
||||
dst = newdst;
|
||||
}
|
||||
memcpy(SAPORT(¶m->sinsr), param->srvbuf + i, 2);
|
||||
i += 2;
|
||||
if (param->hostname) free(param->hostname);
|
||||
param->hostname = dstname? (unsigned char *)strdup(dstname) : NULL;
|
||||
param->req = dst;
|
||||
if (!nhops) param->sinsr = dst;
|
||||
|
||||
if (!havedst) reconnect = 1;
|
||||
else if (!nhops && *SAFAMILY(&dst) != *SAFAMILY(¶m->sinsl)) reconnect = 1;
|
||||
if (havedst && (param->srv->udpauth & 2) && !param->dstindep) {
|
||||
param->preauth = 2;
|
||||
ares = (*param->srv->authfunc)(param);
|
||||
param->preauth = 0;
|
||||
if (ares == 2) {
|
||||
if (param->lastace != lastace) reconnect = 1;
|
||||
ares = 0;
|
||||
}
|
||||
else if (!ares && (param->redirected ||
|
||||
(lastace && lastace->chains))) reconnect = 1;
|
||||
}
|
||||
if (reconnect) {
|
||||
ares = udpreconnect(param);
|
||||
if (param->remsock == INVALID_SOCKET) return ares;
|
||||
nhops = param->udp_nhops;
|
||||
if(param->srv->service == S_UDPPM) nhops++;
|
||||
udpfds(param, &p);
|
||||
}
|
||||
lastres = ares;
|
||||
lastdst = dst;
|
||||
strncpy(lastname, dstname? dstname : "", sizeof(lastname) - 1);
|
||||
lastname[sizeof(lastname) - 1] = 0;
|
||||
havedst = 1;
|
||||
if (!ares) lastace = param->lastace;
|
||||
else if (param->srv->udpauth & 1) {
|
||||
param->res = ares;
|
||||
udplog(param);
|
||||
param->res = 0;
|
||||
}
|
||||
}
|
||||
if (lastres) continue;
|
||||
|
||||
if (!nhops) {
|
||||
if (len > i) {
|
||||
param->srv->so._sendto(param->sostate, param->remsock,
|
||||
(char *)param->srvbuf + i, len - i, 0,
|
||||
(struct sockaddr *)¶m->sinsr, SASIZE(¶m->sinsr));
|
||||
(char *)base + i, len - i, 0,
|
||||
(struct sockaddr *)¶m->sinsr, SASIZE(¶m->sinsr));
|
||||
param->statscli64 += (len - i);
|
||||
param->nwrites++;
|
||||
}
|
||||
} else {
|
||||
int off = 0;
|
||||
off = 0;
|
||||
for (k = 1; k < nhops; k++)
|
||||
off += socks5_udp_build_hdr(param->srvbuf + off, ¶m->udp_relay[k]);
|
||||
off += 4 + (int)SAADDRLEN(¶m->udp_relay[k]) + 2;
|
||||
for (k = 1, w = UDPHDROFF - off; k < nhops; k++)
|
||||
w += socks5_udp_build_hdr(param->srvbuf + w, ¶m->udp_relay[k]);
|
||||
param->srv->so._sendto(param->sostate, param->remsock,
|
||||
(char *)param->srvbuf, off + len, 0,
|
||||
(struct sockaddr *)¶m->udp_relay[0], SASIZE(¶m->udp_relay[0]));
|
||||
(char *)param->srvbuf + (UDPHDROFF - off), off + len, 0,
|
||||
(struct sockaddr *)¶m->udp_relay[0], SASIZE(¶m->udp_relay[0]));
|
||||
param->statscli64 += len;
|
||||
param->nwrites++;
|
||||
}
|
||||
}
|
||||
|
||||
/* datagram from server / parent relay */
|
||||
if (fds[0].revents) {
|
||||
int hdrsize = (nhops == 0) ? 4 + (int)SAADDRLEN(¶m->sinsr) + 2 : 0;
|
||||
if (p.fds[0].revents) {
|
||||
int hdrsize = (nhops == 0) ? 4 + (int)SAADDRLEN(¶m->sinsl) + 2 : 0;
|
||||
int sendoff = 0, sendlen;
|
||||
sasize = sizeof(from);
|
||||
if (hdrsize > UDPBUFSIZE) return 468;
|
||||
len = param->srv->so._recvfrom(param->sostate, param->remsock,
|
||||
(char *)param->srvbuf + hdrsize, UDPBUFSIZE - hdrsize, 0,
|
||||
(struct sockaddr *)&from, &sasize);
|
||||
@@ -201,9 +388,9 @@ int udpsockmap(struct clientparam *param, int timeo)
|
||||
sendlen = len;
|
||||
if (nhops == 0) {
|
||||
param->srvbuf[0] = param->srvbuf[1] = param->srvbuf[2] = 0;
|
||||
param->srvbuf[3] = (*SAFAMILY(¶m->sinsr) == AF_INET) ? 1 : 4;
|
||||
memcpy(param->srvbuf + 4, SAADDR(¶m->sinsr), SAADDRLEN(¶m->sinsr));
|
||||
memcpy(param->srvbuf + 4 + SAADDRLEN(¶m->sinsr), SAPORT(¶m->sinsr), 2);
|
||||
param->srvbuf[3] = (*SAFAMILY(&from) == AF_INET) ? 1 : 4;
|
||||
memcpy(param->srvbuf + 4, SAADDR(&from), SAADDRLEN(¶m->sinsl));
|
||||
memcpy(param->srvbuf + 4 + SAADDRLEN(¶m->sinsl), SAPORT(&from), 2);
|
||||
sendlen = len + hdrsize;
|
||||
} else if (nhops >= 2) {
|
||||
int off = 0, k;
|
||||
@@ -219,13 +406,13 @@ int udpsockmap(struct clientparam *param, int timeo)
|
||||
}
|
||||
if (sendlen > 0)
|
||||
param->srv->so._sendto(param->sostate, param->clisock,
|
||||
(char *)param->srvbuf + sendoff, sendlen, 0,
|
||||
(struct sockaddr *)&sin, SASIZE(&sin));
|
||||
(char *)param->srvbuf + sendoff, sendlen, 0,
|
||||
(struct sockaddr *)&sin, SASIZE(&sin));
|
||||
if (param->srv->s_option && param->srv->service == S_UDPPM) return 0;
|
||||
}
|
||||
|
||||
if ((ctrlsock_idx >= 0 && fds[ctrlsock_idx].revents) ||
|
||||
(ctrlsocksrv_idx >= 0 && fds[ctrlsocksrv_idx].revents)) return 0;
|
||||
if ((p.ctrl >= 0 && p.fds[p.ctrl].revents) ||
|
||||
(p.ctrlsrv >= 0 && p.fds[p.ctrlsrv].revents)) return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+3
-3
@@ -1,14 +1,14 @@
|
||||
#ifndef VERSION
|
||||
#define VERSION "3proxy-0.9.8"
|
||||
#define VERSION "3proxy-0.9.9"
|
||||
#endif
|
||||
#ifndef BUILDDATE
|
||||
#define BUILDDATE ""
|
||||
#endif
|
||||
#define MAJOR3PROXY 0
|
||||
#define SUBMAJOR3PROXY 9
|
||||
#define MINOR3PROXY 8
|
||||
#define MINOR3PROXY 9
|
||||
#define SUBMINOR3PROXY 0
|
||||
#define RELEASE3PROXY "3proxy-0.9.8(" BUILDDATE ")\0"
|
||||
#define RELEASE3PROXY "3proxy-0.9.9(" BUILDDATE ")\0"
|
||||
#ifndef YEAR3PROXY
|
||||
#define YEAR3PROXY "2026"
|
||||
#endif
|
||||
Reference in new issue
Block a user