Compare commits

...

62 Commits

Author SHA1 Message Date
Vladimir Dubrovin
9f477e2fb2 Update CMakeLists.txt
Some checks are pending
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-30 19:13:43 +03:00
Vladimir Dubrovin
ac20f189c8 Update documentation 2026-04-30 19:11:17 +03:00
Vladimir Dubrovin
043f0dd8ab Move pcre code to 3proxy
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-30 18:51:12 +03:00
Vladimir Dubrovin
8b08f39438 Link PCRE statically 2026-04-30 18:30:04 +03:00
Vladimir Dubrovin
289fc04987 Update CMakeLists.txt 2026-04-30 18:13:28 +03:00
Vladimir Dubrovin
30bee085e9 move ssl code to 3proxy, remove SSLPlugin, switch md4/md5/blake to OpenSSL where possible 2026-04-30 17:58:16 +03:00
Vladimir Dubrovin
d674d1d51b Fix sasize in sockmap 2026-04-30 13:48:10 +03:00
Vladimir Dubrovin
a3fb7aff07 Clean up UDP code 2026-04-30 11:32:12 +03:00
Vladimir Dubrovin
b1ac46da79 Remove linux futext implementation
Some checks failed
Build Win32 3proxy-lite with Watcom / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win32 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win64 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win-arm64 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-28 18:06:54 +03:00
Vladimir Dubrovin
d125261e8c fix: hashtables on recsize < 4 2026-04-28 16:32:30 +03:00
Vladimir Dubrovin
a4527783d6 Correctly process half-closed connections; add grace sleep before closing sockets 2026-04-28 16:15:18 +03:00
Vladimir Dubrovin
fb70d06d3e Add linger sleep on connection close 2026-04-28 14:55:37 +03:00
Vladimir Dubrovin
57d687fcb8 add 3proxy_crypt man 2026-04-28 14:41:14 +03:00
Vladimir Dubrovin
ada24a98ec Use semaphore/mutex insted of pipe for threads sync 2026-04-28 14:00:15 +03:00
Vladimir Dubrovin
ba2584cebf change 3proxy.cfg.3 to 3proxy.cfg.5 2026-04-28 12:34:53 +03:00
Vladimir Dubrovin
05096c222a Return standalone udppm; do not build standalone modules by default in cmake
Allow to set prefix in cmake, 3proxy_ by default
2026-04-28 12:21:11 +03:00
Vladimir Dubrovin
6c3c5f31a2 Update mans
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-27 21:11:25 +03:00
Vladimir Dubrovin
319a74de06 Update proxymain.c 2026-04-27 20:12:28 +03:00
Vladimir Dubrovin
e088a5d7f9 Remove udppm from build 2026-04-27 20:05:34 +03:00
Vladimir Dubrovin
f01c8bfee9 Code cleanup 2026-04-27 19:58:34 +03:00
Vladimir Dubrovin
a7cdfa578d split auth.c 2026-04-27 15:30:35 +03:00
Vladimir Dubrovin
d52701518d udppm switched to hashtable and supports multiple connections; no standalone udppm 2026-04-27 15:12:39 +03:00
Vladimir Dubrovin
7ddea44ffd Fix: blake crypt
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-27 13:23:32 +03:00
Vladimir Dubrovin
760a521df8 remove pwl_mutex
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-26 20:43:13 +03:00
Vladimir Dubrovin
62ceb36157 Use hashtables for password lists 2026-04-26 20:38:58 +03:00
Vladimir Dubrovin
62be3c7b5b cash the hash for auth cache 2026-04-26 19:56:38 +03:00
Vladimir Dubrovin
85c431b96e Merge branch 'master' of https://github.com/3proxy/3proxy 2026-04-25 11:52:57 +03:00
Vladimir Dubrovin
90c312f4cd Changelog added 2026-04-25 11:52:54 +03:00
Vladimir Dubrovin
451b3d180c Allow hashtables to grow index
Some checks failed
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-24 21:08:57 +03:00
Vladimir Dubrovin
f63a83f554 Fix blake2 for watcom 2026-04-24 18:13:30 +03:00
Vladimir Dubrovin
6b61cfde4c Fix for older Windows (7 and below) / VC 2026-04-24 17:04:03 +03:00
Vladimir Dubrovin
e6c3427cab fix hashtable init
Some checks failed
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-22 12:02:20 +03:00
Vladimir Dubrovin
4f0f3c81e1 add 'cacheacl' auth type, dstaddr, dstport, dsthost, dstoper, srvaddr and srvport authcache types; allow to configure authcache by service
'auth cacheacl ...' is identical to 'auth cache ...' except ACL is not checked for cached authentication. dstaddr, dstport, dsthost and dstoper (operation) are intended to be used with cacheacl. For example

authcache user,ip,password,dstaddr 600
auth cacheacl iponly strong

allows user to access destination ip without ACL/password revalidation if he has cached attempt to the same ip from the same ip with the same username and password.

srvaddr, srvport are useful to only match with cached attempts to the same `internal` address / service port.
2026-04-21 21:49:52 +03:00
Vladimir Dubrovin
bfbbf1f446 Fix FilePlugin warnings
Some checks failed
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-21 16:28:28 +03:00
Vladimir Dubrovin
b79906da02 Add FilePlugin to builds 2026-04-21 16:23:23 +03:00
Vladimir Dubrovin
68ef9dcc59 Fix Windows compilation 2026-04-21 16:10:17 +03:00
Vladimir Dubrovin
3957210609 Allow different hash lengths; fix bug on hashtable grow 2026-04-20 18:49:53 +03:00
Vladimir Dubrovin
ee00956b74 hash username/password with terminators 2026-04-20 11:59:58 +03:00
Vladimir Dubrovin
083a70393f Minor hashtable refactor 2026-04-20 10:40:38 +03:00
Vladimir Dubrovin
d9b1493260 Fix hashadd
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-19 19:22:22 +03:00
Vladimir Dubrovin
7102afe856 authcache switched to hashtables, overflow fixed
- authcache switched to use hashtables, size parameter added
- overflow fixed on hashinit
- hashtable prefers new values on insert if table is full
- hashtable is able to compact/grow
2026-04-19 19:16:33 +03:00
Vladimir Dubrovin
a3729354b8 Allow hashtable to grow
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-18 17:24:01 +03:00
Vladimir Dubrovin
45796f66c7 Cleanup 3proxy_crypt 2026-04-18 15:47:07 +03:00
Vladimir Dubrovin
260cbf7a3d Use uint32_t for hashtable indicies 2026-04-18 15:36:14 +03:00
Vladimir Dubrovin
bba9871ed8 Use 3proxy_crypt instead of mycrypt 2026-04-18 15:19:06 +03:00
Vladimir Dubrovin
f1af44f3a9 Refactor hashtables to use indices instead of pointers, use blake2 as a hash, mycrypt renamed to 3proxy_crypt 2026-04-18 15:12:43 +03:00
Vladimir Dubrovin
4ee7f71fb9 Использовать tablesize в хештаблице 2026-04-17 21:15:21 +03:00
Vladimir Dubrovin
98604b5421 Add hashcompact 2026-04-17 20:40:27 +03:00
Vladimir Dubrovin
a0d580b36d move hashtable/resolve/sql functions to separate files 2026-04-17 19:29:50 +03:00
Vladimir Dubrovin
4c0e3a1bac Check OpenSSL version for SNI/TLS 1.3/alpn
Some checks failed
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-14 17:36:35 +03:00
Vladimir Dubrovin
454f5e1d54 -Ne / -Ni description added to man
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-13 21:37:46 +03:00
Vladimir Dubrovin
c4ac696919 Update documentation for parent tcps/https/etc 2026-04-13 21:32:04 +03:00
Vladimir Dubrovin
afbdad0ac7 Fix for first in chain https/tcps parent 2026-04-13 21:09:46 +03:00
Vladimir Dubrovin
a1a65c3fd5 ssl_client_mode = 3 added, allow 'secure' parent types ending with 's': https, tcps, socks5s, connect+s, etc.
example:

plugin SSLPlugin.ld.so ssl_plugin

allow user1
parent 1000 http 1.1.1.1 1111
allow user2
parent 1000 https 2.2.2.2 2222
ssl_client_mode 3
ssl_client
proxy

With ssl_client_mode 3 TLS is only handshaked for https parent type and is not handshaked for http parent.
2026-04-13 20:53:38 +03:00
Vladimir Dubrovin
2fd536781f Add unix sockets to man 2026-04-13 11:54:24 +03:00
Vladimir Dubrovin
878a432481 Support unix socket for parent and tcppm; abstract (fileless) unix sockets for linux support
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
Use unix:/path/to/socket, e.g.

tcppm 1234 unix:/path/to/socket 1234

Under linux abstract sockets are supported with '@' prefix, e.g.

parent 1000 http unix:@virtual.3proxy.socket 1111

Destination port numbers are not used in tcppm/parent, but you must specify any positive value to match the syntaxis.
2026-04-12 19:18:15 +03:00
Vladimir Dubrovin
3f92dc7355 Fix dockerfiles
Some checks are pending
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2026-04-12 15:18:20 +03:00
Vladimir Dubrovin
bae96b0823 Support plugins in chroot in Dockerfile.busybox 2026-04-12 14:55:54 +03:00
Vladimir Dubrovin
f77f65ac4e Fix: SOCKSv5 parent reply parsing for domain name address 2026-04-12 14:16:48 +03:00
Vladimir Dubrovin
2d6eeff5f3 FIx typos, update documentation 2026-04-12 13:58:42 +03:00
Vladimir Dubrovin
c206349ee2 Support unix sockets for internal and -i
Example configuration:

log
auto -iunix:/path/to/3proxy.sock

test with

curl --unix-socket /path/to/3proxy.sock https://3proxy.ru
2026-04-12 00:30:35 +03:00
Vladimir Dubrovin
77b0dc3397 Documentation update
Some checks failed
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
RPM/DEB build aarch64 / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
RPM/DEB build armhf / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
RPM/DEB build x86-64 / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
Build Win32 3proxy-lite with Watcom / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win32 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win64 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Build Win-arm64 3proxy with MSVC / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2026-04-11 14:47:09 +03:00
135 changed files with 6474 additions and 4466 deletions

View File

@ -45,7 +45,7 @@ jobs:
mkdir dist\3proxy\doc\ru mkdir dist\3proxy\doc\ru
mkdir dist\3proxy\doc\html mkdir dist\3proxy\doc\html
mkdir dist\3proxy\doc\html\plugins mkdir dist\3proxy\doc\html\plugins
mkdir dist\3proxy\doc\html\man3 mkdir dist\3proxy\doc\html\man5
mkdir dist\3proxy\doc\html\man8 mkdir dist\3proxy\doc\html\man8
mkdir dist\3proxy\doc\devel mkdir dist\3proxy\doc\devel
copy bin\3proxy.exe dist\3proxy\bin\ copy bin\3proxy.exe dist\3proxy\bin\
@ -57,7 +57,7 @@ jobs:
copy doc\html\*.* dist\3proxy\doc\html\ copy doc\html\*.* dist\3proxy\doc\html\
copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\ copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\
copy doc\html\man8\*.* dist\3proxy\doc\html\man8\ copy doc\html\man8\*.* dist\3proxy\doc\html\man8\
copy doc\html\man3\*.* dist\3proxy\doc\html\man3\ copy doc\html\man5\*.* dist\3proxy\doc\html\man5\
copy doc\devel\*.rtf dist\3proxy\doc\devel\ copy doc\devel\*.rtf dist\3proxy\doc\devel\
copy copying dist\3proxy\ copy copying dist\3proxy\
copy authors dist\3proxy\ copy authors dist\3proxy\

View File

@ -51,7 +51,7 @@ jobs:
mkdir dist\3proxy\doc\ru mkdir dist\3proxy\doc\ru
mkdir dist\3proxy\doc\html mkdir dist\3proxy\doc\html
mkdir dist\3proxy\doc\html\plugins mkdir dist\3proxy\doc\html\plugins
mkdir dist\3proxy\doc\html\man3 mkdir dist\3proxy\doc\html\man5
mkdir dist\3proxy\doc\html\man8 mkdir dist\3proxy\doc\html\man8
mkdir dist\3proxy\doc\devel mkdir dist\3proxy\doc\devel
copy bin\3proxy.exe dist\3proxy\bin\ copy bin\3proxy.exe dist\3proxy\bin\
@ -63,7 +63,7 @@ jobs:
copy doc\html\*.* dist\3proxy\doc\html\ copy doc\html\*.* dist\3proxy\doc\html\
copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\ copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\
copy doc\html\man8\*.* dist\3proxy\doc\html\man8\ copy doc\html\man8\*.* dist\3proxy\doc\html\man8\
copy doc\html\man3\*.* dist\3proxy\doc\html\man3\ copy doc\html\man5\*.* dist\3proxy\doc\html\man5\
copy doc\devel\*.rtf dist\3proxy\doc\devel\ copy doc\devel\*.rtf dist\3proxy\doc\devel\
copy copying dist\3proxy\ copy copying dist\3proxy\
copy authors dist\3proxy\ copy authors dist\3proxy\

View File

@ -53,7 +53,7 @@ jobs:
mkdir dist\3proxy\doc\ru mkdir dist\3proxy\doc\ru
mkdir dist\3proxy\doc\html mkdir dist\3proxy\doc\html
mkdir dist\3proxy\doc\html\plugins mkdir dist\3proxy\doc\html\plugins
mkdir dist\3proxy\doc\html\man3 mkdir dist\3proxy\doc\html\man5
mkdir dist\3proxy\doc\html\man8 mkdir dist\3proxy\doc\html\man8
mkdir dist\3proxy\doc\devel mkdir dist\3proxy\doc\devel
copy bin\3proxy.exe dist\3proxy\bin64\ copy bin\3proxy.exe dist\3proxy\bin64\
@ -65,7 +65,7 @@ jobs:
copy doc\html\*.* dist\3proxy\doc\html\ copy doc\html\*.* dist\3proxy\doc\html\
copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\ copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\
copy doc\html\man8\*.* dist\3proxy\doc\html\man8\ copy doc\html\man8\*.* dist\3proxy\doc\html\man8\
copy doc\html\man3\*.* dist\3proxy\doc\html\man3\ copy doc\html\man5\*.* dist\3proxy\doc\html\man5\
copy doc\devel\*.rtf dist\3proxy\doc\devel\ copy doc\devel\*.rtf dist\3proxy\doc\devel\
copy copying dist\3proxy\ copy copying dist\3proxy\
copy authors dist\3proxy\ copy authors dist\3proxy\

View File

@ -51,7 +51,7 @@ jobs:
mkdir dist\3proxy\doc\ru mkdir dist\3proxy\doc\ru
mkdir dist\3proxy\doc\html mkdir dist\3proxy\doc\html
mkdir dist\3proxy\doc\html\plugins mkdir dist\3proxy\doc\html\plugins
mkdir dist\3proxy\doc\html\man3 mkdir dist\3proxy\doc\html\man5
mkdir dist\3proxy\doc\html\man8 mkdir dist\3proxy\doc\html\man8
mkdir dist\3proxy\doc\devel mkdir dist\3proxy\doc\devel
copy bin\3proxy.exe dist\3proxy\bin64\ copy bin\3proxy.exe dist\3proxy\bin64\
@ -63,7 +63,7 @@ jobs:
copy doc\html\*.* dist\3proxy\doc\html\ copy doc\html\*.* dist\3proxy\doc\html\
copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\ copy doc\html\plugins\*.* dist\3proxy\doc\html\plugins\
copy doc\html\man8\*.* dist\3proxy\doc\html\man8\ copy doc\html\man8\*.* dist\3proxy\doc\html\man8\
copy doc\html\man3\*.* dist\3proxy\doc\html\man3\ copy doc\html\man5\*.* dist\3proxy\doc\html\man5\
copy doc\devel\*.rtf dist\3proxy\doc\devel\ copy doc\devel\*.rtf dist\3proxy\doc\devel\
copy copying dist\3proxy\ copy copying dist\3proxy\
copy authors dist\3proxy\ copy authors dist\3proxy\

View File

@ -2,7 +2,7 @@ name: C/C++ CI cmake
on: on:
push: push:
branches: [ "master" ] branches: [ "master", "unix_socket" ]
paths: [ '**.c', '**.h', '**.cmake', 'CMakeLists.txt', '.github/configs', '.github/workflows/c-cpp-cmake.yml' ] paths: [ '**.c', '**.h', '**.cmake', 'CMakeLists.txt', '.github/configs', '.github/workflows/c-cpp-cmake.yml' ]
pull_request: pull_request:
branches: [ "master" ] branches: [ "master" ]

9
.gitignore vendored
View File

@ -258,3 +258,12 @@ pip-log.txt
#Mr Developer #Mr Developer
.mr.developer.cfg .mr.developer.cfg
CLAUDE.md CLAUDE.md
bin/3proxy_crypt
bin/3proxy_ftppr
bin/3proxy_pop3p
bin/3proxy_proxy
bin/3proxy_smtpp
bin/3proxy_socks
bin/3proxy_tcppm
bin/3proxy_tlspr
bin/3proxy_udppm

11
CHANGELOG Normal file
View File

@ -0,0 +1,11 @@
3proxy-0.9.6 Released April, 11 2026
+ ssl_client and multiple configuration options added to SSLPlugin, SSLPlugin code significantly improved and bugfixed. See https://github.com/3proxy/3proxy/wiki/SSLPlugin. 3proxy can now be used as stunnel replacement for many scenarios.
+ HAProxy proxy protocol v1 support as client and server, add -H option for service to expect HA proxy v1 protocol header, use ha parent type: parent 1000 ha 0.0.0.0 0 to send v1 header.
+ tlspr is supported in auto
+ tlspr supports -s option, it breaks HELLO packet to prevent some DPIs from detecting SNI
+ maxseg configuration option and TCP_MAXSEG socket flag support added. It sets maximum size of TCP segment to fix PathMTU discovery problems
+ -Ne / -Ni options added to specify external / internal NAT address for SOCKSv5
+ cmake environment added
! External pcre2 (pcre2-8) library is used for PCRE, pcre code is removed from 3proxy
! Multiple minor bugfixes

11
CHANGELOG.rus Normal file
View File

@ -0,0 +1,11 @@
3proxy-0.9.6 Вышел 11 Апреля 2026
+ В SSLPlugin добавлены ssl_client и множество опций конфигурации, код SSLPlugin значительно улучшен и исправлен. См. https://github.com/3proxy/3proxy/wiki/SSLPlugin. 3proxy теперь может использоваться как замена stunnel во многих сценариях.
+ Поддержка прокси-протокола HAProxy v1 на стороне клиента и сервера. Добавлена опция -H для сервиса, чтобы ожидать заголовок прокси-протокола HA v1. Используйте тип родителя ha: parent 1000 ha 0.0.0.0 0 для отправки заголовка v1.
+ tlspr поддерживается в режиме auto
+ tlspr поддерживает опцию -s, которая разбивает HELLO-пакет для предотвращения обнаружения SNI некоторыми DPI
+ Добавлена опция конфигурации maxseg и поддержка флага сокета TCP_MAXSEG. Устанавливает максимальный размер TCP-сегмента для решения проблем с обнаружением PathMTU
+ Добавлены опции -Ne / -Ni для указания внешнего/внутреннего NAT-адреса для SOCKSv5
+ Добавлено окружение cmake
! Внешняя библиотека pcre2 (pcre2-8) используется для PCRE, код pcre удалён из 3proxy
! Множество мелких исправлений ошибок

View File

@ -54,6 +54,28 @@ option(3PROXY_USE_SPLICE "Use Linux splice() for zero-copy (Linux only)" ON)
option(3PROXY_USE_POLL "Use poll() instead of select() (Unix only)" ON) option(3PROXY_USE_POLL "Use poll() instead of select() (Unix only)" ON)
option(3PROXY_USE_WSAPOLL "Use WSAPoll instead of select() (Windows only)" ON) option(3PROXY_USE_WSAPOLL "Use WSAPoll instead of select() (Windows only)" ON)
option(3PROXY_USE_NETFILTER "Enable Linux netfilter support (Linux only)" ON) option(3PROXY_USE_NETFILTER "Enable Linux netfilter support (Linux only)" ON)
option(3PROXY_USE_UNIX_SOCKETS "Enable Unix domain socket support (Unix only)" ON)
# Binary name prefix for standalone modules and crypt (default: 3proxy_)
# For crypt: if prefix is empty, "my" is used instead ( mycrypt)
set(3PROXY_BINARY_PREFIX "3proxy_" CACHE STRING "Prefix for standalone module and crypt binary names")
# Standalone module build options (OFF by default)
option(3PROXY_BUILD_ALL "Build all standalone binaries" OFF)
option(3PROXY_BUILD_PROXY "Build standalone proxy binary" OFF)
option(3PROXY_BUILD_SOCKS "Build standalone socks binary" OFF)
option(3PROXY_BUILD_POP3P "Build standalone pop3p binary" OFF)
option(3PROXY_BUILD_SMTPP "Build standalone smtpp binary" OFF)
option(3PROXY_BUILD_FTPPR "Build standalone ftppr binary" OFF)
option(3PROXY_BUILD_TCPPM "Build standalone tcppm binary" OFF)
option(3PROXY_BUILD_UDPPM "Build standalone udppm binary" OFF)
option(3PROXY_BUILD_TLSPR "Build standalone tlspr binary" OFF)
if(3PROXY_BUILD_ALL)
foreach(_M PROXY SOCKS POP3P SMTPP FTPPR TCPPM UDPPM TLSPR)
set(3PROXY_BUILD_${_M} ON)
endforeach()
endif()
# Output directory # Output directory
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
@ -83,7 +105,6 @@ if(WIN32)
# MSVC-specific settings # MSVC-specific settings
add_compile_definitions( add_compile_definitions(
MSVC MSVC
WITH_SSL
) )
# Use static runtime library # Use static runtime library
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
@ -101,7 +122,6 @@ if(WIN32)
# clang-cl (Clang with MSVC frontend) # clang-cl (Clang with MSVC frontend)
add_compile_definitions( add_compile_definitions(
MSVC MSVC
WITH_SSL
) )
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
add_compile_options( add_compile_options(
@ -159,10 +179,15 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_compile_definitions(WITH_NETFILTER) add_compile_definitions(WITH_NETFILTER)
endif() endif()
if(3PROXY_USE_UNIX_SOCKETS)
add_compile_definitions(WITH_UN)
endif()
set(DEFAULT_PLUGINS set(DEFAULT_PLUGINS
StringsPlugin StringsPlugin
TrafficPlugin TrafficPlugin
TransparentPlugin TransparentPlugin
FilePlugin
) )
elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD|Darwin|OpenBSD|NetBSD") elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD|Darwin|OpenBSD|NetBSD")
@ -176,10 +201,15 @@ elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD|Darwin|OpenBSD|NetBSD")
add_compile_options(-fno-strict-aliasing) add_compile_options(-fno-strict-aliasing)
endif() endif()
if(3PROXY_USE_UNIX_SOCKETS)
add_compile_definitions(WITH_UN)
endif()
set(DEFAULT_PLUGINS set(DEFAULT_PLUGINS
StringsPlugin StringsPlugin
TrafficPlugin TrafficPlugin
TransparentPlugin TransparentPlugin
FilePlugin
) )
else() else()
@ -188,10 +218,15 @@ else()
add_compile_options(-fno-strict-aliasing) add_compile_options(-fno-strict-aliasing)
endif() endif()
if(3PROXY_USE_UNIX_SOCKETS)
add_compile_definitions(WITH_UN)
endif()
set(DEFAULT_PLUGINS set(DEFAULT_PLUGINS
StringsPlugin StringsPlugin
TrafficPlugin TrafficPlugin
TransparentPlugin TransparentPlugin
FilePlugin
) )
endif() endif()
@ -217,14 +252,14 @@ endif()
# OpenSSL # OpenSSL
set(OPENSSL_FOUND FALSE) set(OPENSSL_FOUND FALSE)
if(3PROXY_USE_OPENSSL) if(3PROXY_USE_OPENSSL)
find_package(OpenSSL QUIET) find_package(OpenSSL REQUIRED)
if(OpenSSL_FOUND) if(OpenSSL_FOUND)
set(OPENSSL_FOUND TRUE) set(OPENSSL_FOUND TRUE)
add_compile_definitions(WITH_SSL) add_compile_definitions(WITH_SSL)
message(STATUS "OpenSSL found: ${OPENSSL_VERSION}") message(STATUS "OpenSSL found: ${OPENSSL_VERSION}")
else()
message(STATUS "OpenSSL not found, SSLPlugin will not be built")
endif() endif()
else()
message(STATUS "OpenSSL disabled by user request")
endif() endif()
# PCRE2 # PCRE2
@ -232,9 +267,10 @@ set(PCRE2_FOUND FALSE)
if(3PROXY_USE_PCRE2) if(3PROXY_USE_PCRE2)
find_package(PCRE2 QUIET) find_package(PCRE2 QUIET)
if(PCRE2_FOUND) if(PCRE2_FOUND)
add_compile_definitions(WITH_PCRE)
message(STATUS "PCRE2 found: ${PCRE2_VERSION}") message(STATUS "PCRE2 found: ${PCRE2_VERSION}")
else() else()
message(STATUS "PCRE2 not found, PCREPlugin will not be built") message(STATUS "PCRE2 not found, PCRE support will not be built")
endif() endif()
endif() endif()
@ -265,21 +301,32 @@ if(NOT ODBC_FOUND)
add_compile_definitions(NOODBC) add_compile_definitions(NOODBC)
endif() endif()
# Set NORADIUS if OpenSSL is not available (RADIUS requires MD5 from OpenSSL)
if(NOT OPENSSL_FOUND)
add_compile_definitions(NORADIUS)
endif()
# Source files for 3proxy core # Source files for 3proxy core
set(3PROXY_CORE_SOURCES set(3PROXY_CORE_SOURCES
src/3proxy.c src/3proxy.c
src/auth.c src/auth.c
src/acl.c
src/limiter.c
src/redirect.c
src/authradius.c src/authradius.c
src/hash.c
src/hashtables.c
src/resolve.c
src/sql.c
src/conf.c src/conf.c
src/datatypes.c src/datatypes.c
src/plugins.c src/plugins.c
src/stringtable.c src/stringtable.c
) )
# MD4/MD5 sources for mycrypt # BLAKE2 source for 3proxy_crypt
set(MD_SOURCES set(MD_SOURCES
src/libs/md4.c src/libs/blake2b-ref.c
src/libs/md5.c
) )
# ============================================================================ # ============================================================================
@ -304,7 +351,7 @@ target_include_directories(base64_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
# These are used by the main 3proxy executable # These are used by the main 3proxy executable
# ============================================================================ # ============================================================================
# Server modules object library (without WITHMAIN) # Server modules object library (without WITHMAIN, without UDP)
add_library(srv_modules OBJECT add_library(srv_modules OBJECT
src/proxy.c src/proxy.c
src/pop3p.c src/pop3p.c
@ -315,13 +362,17 @@ add_library(srv_modules OBJECT
src/auto.c src/auto.c
src/socks.c src/socks.c
src/webadmin.c src/webadmin.c
src/udppm.c
src/dnspr.c src/dnspr.c
) )
target_include_directories(srv_modules PRIVATE target_include_directories(srv_modules PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src
) )
# UDP port mapper server module (without WITHMAIN)
add_library(srvudppm_obj OBJECT src/udppm.c)
target_include_directories(srvudppm_obj PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
# mainfunc object (proxymain.c compiled with MODULEMAINFUNC=mainfunc for 3proxy) # mainfunc object (proxymain.c compiled with MODULEMAINFUNC=mainfunc for 3proxy)
add_library(mainfunc OBJECT src/proxymain.c) add_library(mainfunc OBJECT src/proxymain.c)
@ -332,9 +383,12 @@ target_compile_definitions(mainfunc PRIVATE MODULEMAINFUNC=mainfunc)
add_library(ftp_obj OBJECT src/ftp.c) add_library(ftp_obj OBJECT src/ftp.c)
target_include_directories(ftp_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) target_include_directories(ftp_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
# mycrypt object for 3proxy (without WITHMAIN) # 3proxy_crypt object for 3proxy (without WITHMAIN)
add_library(mycrypt_obj OBJECT src/mycrypt.c) add_library(3proxy_crypt_obj OBJECT src/3proxy_crypt.c)
target_include_directories(mycrypt_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) target_include_directories(3proxy_crypt_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
if(OpenSSL_FOUND)
target_include_directories(3proxy_crypt_obj PRIVATE ${OPENSSL_INCLUDE_DIR})
endif()
# ============================================================================ # ============================================================================
# Main 3proxy executable # Main 3proxy executable
@ -345,17 +399,32 @@ add_executable(3proxy
${3PROXY_CORE_SOURCES} ${3PROXY_CORE_SOURCES}
${MD_SOURCES} ${MD_SOURCES}
$<TARGET_OBJECTS:srv_modules> $<TARGET_OBJECTS:srv_modules>
$<TARGET_OBJECTS:srvudppm_obj>
$<TARGET_OBJECTS:mainfunc> $<TARGET_OBJECTS:mainfunc>
$<TARGET_OBJECTS:common_obj> $<TARGET_OBJECTS:common_obj>
$<TARGET_OBJECTS:base64_obj> $<TARGET_OBJECTS:base64_obj>
$<TARGET_OBJECTS:ftp_obj> $<TARGET_OBJECTS:ftp_obj>
$<TARGET_OBJECTS:mycrypt_obj> $<TARGET_OBJECTS:3proxy_crypt_obj>
) )
if(OpenSSL_FOUND)
target_sources(3proxy PRIVATE src/ssllib.c src/ssl.c)
endif()
if(PCRE2_FOUND)
target_sources(3proxy PRIVATE src/pcre.c)
endif()
target_include_directories(3proxy PRIVATE target_include_directories(3proxy PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/src/libs ${CMAKE_CURRENT_SOURCE_DIR}/src/libs
) )
if(OpenSSL_FOUND)
target_include_directories(3proxy PRIVATE ${OPENSSL_INCLUDE_DIR})
endif()
if(PCRE2_FOUND)
target_include_directories(3proxy PRIVATE ${PCRE2_INCLUDE_DIRS})
endif()
target_link_libraries(3proxy PRIVATE Threads::Threads) target_link_libraries(3proxy PRIVATE Threads::Threads)
@ -367,36 +436,85 @@ if(ODBC_FOUND)
endif() endif()
endif() endif()
if(OpenSSL_FOUND)
target_link_libraries(3proxy PRIVATE OpenSSL::SSL OpenSSL::Crypto)
endif()
# PCRE2 linking (try static first on Linux/FreeBSD, fallback to dynamic)
if(PCRE2_FOUND)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux" OR
CMAKE_SYSTEM_NAME MATCHES "FreeBSD|OpenBSD|NetBSD" OR
CMAKE_SYSTEM_NAME STREQUAL "Unix")
# Try static linking for Linux/BSD
find_library(PCRE2_STATIC_LIB
NAMES pcre2-8-static libpcre2-8.a pcre2-8.a
PATHS ${PC_PCRE2_LIBRARY_DIRS}
/usr/lib/x86_64-linux-gnu
/usr/lib
/usr/local/lib
/lib
)
if(PCRE2_STATIC_LIB AND PCRE2_STATIC_LIB MATCHES "\\.a$")
target_link_libraries(3proxy PRIVATE
-Wl,-Bstatic
${PCRE2_STATIC_LIB}
-Wl,-Bdynamic
)
message(STATUS "Using static PCRE2: ${PCRE2_STATIC_LIB}")
elseif(TARGET PCRE2::PCRE2)
target_link_libraries(3proxy PRIVATE PCRE2::PCRE2)
message(STATUS "Using dynamic PCRE2 (PCRE2::PCRE2)")
else()
target_link_libraries(3proxy PRIVATE ${PCRE2_LIBRARIES})
message(STATUS "Using dynamic PCRE2: ${PCRE2_LIBRARIES}")
endif()
elseif(TARGET PCRE2::PCRE2)
target_link_libraries(3proxy PRIVATE PCRE2::PCRE2)
else()
target_link_libraries(3proxy PRIVATE ${PCRE2_LIBRARIES})
endif()
endif()
if(WIN32) if(WIN32)
target_link_libraries(3proxy PRIVATE ${WINDOWS_LIBS}) target_link_libraries(3proxy PRIVATE ${WINDOWS_LIBS})
if(OpenSSL_FOUND)
target_link_libraries(3proxy PRIVATE OpenSSL::SSL OpenSSL::Crypto)
endif()
if(COMPILER_IS_MSVC AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/3proxy.rc) if(COMPILER_IS_MSVC AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/3proxy.rc)
target_sources(3proxy PRIVATE 3proxy.rc) target_sources(3proxy PRIVATE 3proxy.rc)
endif() endif()
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_libraries(3proxy PRIVATE dl) target_link_libraries(3proxy PRIVATE dl)
if(OpenSSL_FOUND)
target_link_libraries(3proxy PRIVATE OpenSSL::SSL OpenSSL::Crypto)
endif()
endif() endif()
# Build mycrypt utility # Build 3proxy_crypt utility
add_executable(mycrypt add_executable(3proxy_crypt
src/mycrypt.c src/3proxy_crypt.c
${MD_SOURCES} ${MD_SOURCES}
$<TARGET_OBJECTS:base64_obj> $<TARGET_OBJECTS:base64_obj>
) )
target_compile_definitions(mycrypt PRIVATE WITHMAIN) target_compile_definitions(3proxy_crypt PRIVATE WITHMAIN)
target_include_directories(mycrypt PRIVATE target_include_directories(3proxy_crypt PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/src/libs ${CMAKE_CURRENT_SOURCE_DIR}/src/libs
) )
target_link_libraries(mycrypt PRIVATE Threads::Threads) if(OpenSSL_FOUND)
target_include_directories(3proxy_crypt PRIVATE ${OPENSSL_INCLUDE_DIR})
endif()
target_link_libraries(3proxy_crypt PRIVATE Threads::Threads)
if(OpenSSL_FOUND)
target_link_libraries(3proxy_crypt PRIVATE OpenSSL::SSL OpenSSL::Crypto)
endif()
if("${3PROXY_BINARY_PREFIX}" STREQUAL "")
set_target_properties(3proxy_crypt PROPERTIES OUTPUT_NAME "mycrypt")
else()
set_target_properties(3proxy_crypt PROPERTIES OUTPUT_NAME "${3PROXY_BINARY_PREFIX}crypt")
endif()
# Build standalone proxy executables # Build standalone proxy executables
foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr) foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
string(TOUPPER "${PROXY_NAME}" _MODULE_OPT)
if(NOT 3PROXY_BUILD_${_MODULE_OPT})
continue()
endif()
if(PROXY_NAME STREQUAL "ftppr" OR PROXY_NAME STREQUAL "proxy") if(PROXY_NAME STREQUAL "ftppr" OR PROXY_NAME STREQUAL "proxy")
# ftppr and proxy use ftp_obj # ftppr and proxy use ftp_obj
add_executable(${PROXY_NAME} add_executable(${PROXY_NAME}
@ -411,6 +529,10 @@ foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
) )
endif() endif()
set_target_properties(${PROXY_NAME} PROPERTIES
OUTPUT_NAME "${3PROXY_BINARY_PREFIX}${PROXY_NAME}"
)
target_include_directories(${PROXY_NAME} PRIVATE target_include_directories(${PROXY_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src
) )
@ -420,6 +542,10 @@ foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
NOPORTMAP NOPORTMAP
) )
if(NOT PROXY_NAME STREQUAL "udppm")
target_compile_definitions(${PROXY_NAME} PRIVATE NOUDPMAIN)
endif()
target_link_libraries(${PROXY_NAME} PRIVATE Threads::Threads) target_link_libraries(${PROXY_NAME} PRIVATE Threads::Threads)
if(PROXY_NAME STREQUAL "proxy") if(PROXY_NAME STREQUAL "proxy")
@ -437,6 +563,10 @@ foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
if(PROXY_NAME STREQUAL "proxy" OR PROXY_NAME STREQUAL "smtpp") if(PROXY_NAME STREQUAL "proxy" OR PROXY_NAME STREQUAL "smtpp")
target_sources(${PROXY_NAME} PRIVATE $<TARGET_OBJECTS:base64_obj>) target_sources(${PROXY_NAME} PRIVATE $<TARGET_OBJECTS:base64_obj>)
endif() endif()
if(PROXY_NAME STREQUAL "udppm")
target_sources(${PROXY_NAME} PRIVATE src/hash.c)
endif()
endforeach() endforeach()
# Plugin output directory # Plugin output directory
@ -455,35 +585,30 @@ foreach(PLUGIN ${DEFAULT_PLUGINS})
add_subdirectory(src/plugins/${PLUGIN}) add_subdirectory(src/plugins/${PLUGIN})
endforeach() endforeach()
if(OPENSSL_FOUND)
add_subdirectory(src/plugins/SSLPlugin)
endif()
if(PCRE2_FOUND)
add_subdirectory(src/plugins/PCREPlugin)
endif()
if(PAM_FOUND) if(PAM_FOUND)
add_subdirectory(src/plugins/PamAuth) add_subdirectory(src/plugins/PamAuth)
endif() endif()
# Build full list of plugins to be built # Build full list of plugins to be built
set(ALL_PLUGINS ${DEFAULT_PLUGINS}) set(ALL_PLUGINS ${DEFAULT_PLUGINS})
if(OPENSSL_FOUND)
list(APPEND ALL_PLUGINS SSLPlugin)
endif()
if(PCRE2_FOUND)
list(APPEND ALL_PLUGINS PCREPlugin)
endif()
if(PAM_FOUND) if(PAM_FOUND)
list(APPEND ALL_PLUGINS PamAuth) list(APPEND ALL_PLUGINS PamAuth)
endif() endif()
# Installation rules # Installation rules
install(TARGETS 3proxy mycrypt proxy socks pop3p smtpp ftppr tcppm udppm tlspr install(TARGETS 3proxy 3proxy_crypt
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
) )
foreach(PROXY_NAME proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
string(TOUPPER "${PROXY_NAME}" _MODULE_OPT)
if(3PROXY_BUILD_${_MODULE_OPT})
install(TARGETS ${PROXY_NAME}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
endif()
endforeach()
# Install plugins # Install plugins
file(GLOB PLUGINFILES "${PLUGIN_OUTPUT_DIR}/*${PLUGIN_SUFFIX}") file(GLOB PLUGINFILES "${PLUGIN_OUTPUT_DIR}/*${PLUGIN_SUFFIX}")
if(WIN32) if(WIN32)
@ -617,10 +742,32 @@ endif()
# Install man pages # Install man pages
if(NOT WIN32) if(NOT WIN32)
file(GLOB MAN3_FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/*.3") # Config man page (section 5) no prefix
file(GLOB MAN8_FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/*.8") file(GLOB MAN5_FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/*.5")
install(FILES ${MAN3_FILES} DESTINATION ${CMAKE_INSTALL_MANDIR}/man3) install(FILES ${MAN5_FILES} DESTINATION ${CMAKE_INSTALL_MANDIR}/man5)
install(FILES ${MAN8_FILES} DESTINATION ${CMAKE_INSTALL_MANDIR}/man8) # Main 3proxy man page no prefix
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/3proxy.8"
DESTINATION ${CMAKE_INSTALL_MANDIR}/man8
)
# 3proxy_crypt man page no prefix (already has 3proxy_)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/man/3proxy_crypt.8")
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/3proxy_crypt.8"
DESTINATION ${CMAKE_INSTALL_MANDIR}/man8
)
endif()
# Module man pages installed with binary prefix only if module is built
foreach(_MAN proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
string(TOUPPER "${_MAN}" _MODULE_OPT)
if(3PROXY_BUILD_${_MODULE_OPT})
set(_MAN_SRC "${CMAKE_CURRENT_SOURCE_DIR}/man/${_MAN}.8")
if(EXISTS "${_MAN_SRC}")
install(FILES "${_MAN_SRC}"
DESTINATION ${CMAKE_INSTALL_MANDIR}/man8
RENAME "${3PROXY_BINARY_PREFIX}${_MAN}.8"
)
endif()
endif()
endforeach()
endif() endif()
# Summary # Summary
@ -654,3 +801,10 @@ message(STATUS " ODBC: ${ODBC_FOUND}")
message(STATUS "") message(STATUS "")
message(STATUS " Plugins to build: ${ALL_PLUGINS}") message(STATUS " Plugins to build: ${ALL_PLUGINS}")
message(STATUS "") message(STATUS "")
message(STATUS " Standalone modules:")
message(STATUS " Binary prefix: \"${3PROXY_BINARY_PREFIX}\"")
foreach(_M proxy socks pop3p smtpp ftppr tcppm udppm tlspr)
string(TOUPPER "${_M}" _MO)
message(STATUS " BUILD_${_MO}: ${3PROXY_BUILD_${_MO}}")
endforeach()
message(STATUS "")

57
Dockerfile.busybox Normal file
View File

@ -0,0 +1,57 @@
# 3proxy.full is fully functional 3proxy build based on busybox:glibc
#
# Examples are for podman, for docker change 'podman' to 'docker'
#
#to build:
# podman build -f Dockerfile.busybox -t 3proxy.busybox .
#to run:
#
# echo nserver 8.8.8.8 >/path/to/local/config/directory/3proxy.cfg
# echo proxy -p3129 >>/path/to/local/config/directory/3proxy.cfg
# podman run --read-only -p 3129:3129 -v /path/to/local/config/directory:/etc/3proxy --name 3proxy.busybox 3proxy.busybox
#
# use "log" without pathname in config to log to stdout.
# plugins are located in /usr/local/3proxy/libexec (/libexec for chroot config)
# symlinked as /lib and /lib64 in both root and chroot configurations, so no need
# to specify full path to plugin. SSLPlugin is supported.
#
# Since 0.9.6 image is distroless, no reason to use chroot, chroot
# configuration is supported for compatibility only.
FROM docker.io/gcc AS buildenv
COPY . 3proxy
RUN cd 3proxy &&\
apt --assume-yes update && apt --assume-yes install libssl-dev libpcre2-dev &&\
make -f Makefile.Linux &&\
strip bin/3proxy &&\
strip bin/*so &&\
mkdir /dist &&\
mkdir /dist/etc &&\
mkdir /dist/etc/3proxy &&\
mkdir /dist/bin &&\
mkdir /dist/usr &&\
mkdir /dist/usr/local &&\
mkdir /dist/usr/local/3proxy &&\
mkdir /dist/usr/local/3proxy/conf &&\
mkdir /dist/usr/local/3proxy/libexec &&\
cp bin/3proxy /dist/bin &&\
cp bin/*.so /dist/usr/local/3proxy/libexec &&\
cp scripts/3proxy.cfg.inchroot /dist/etc/3proxy/3proxy.cfg
RUN cd /dist &&\
ln -s /lib lib64 &&\
ln -s /lib usr/lib &&\
ln -s /lib usr/lib64 &&\
cp /lib64/ld-*.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libdl.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libcrypto.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libssl.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libpcre2-8.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libz.so.* /dist/usr/local/3proxy/libexec &&\
cp "/lib/`gcc -dumpmachine`"/libzstd.so.* /dist/usr/local/3proxy/libexec &&\
ls -lR /dist
FROM docker.io/busybox:glibc
COPY --from=buildenv /dist /
RUN ln -sf /usr/local/3proxy/libexec/* /lib/ && cd /usr/local/3proxy/ && ln -s libexec lib && ln -s libexec lib64 && mkdir usr && ln -s libexec usr/lib && ln -s libexec usr//lib64
CMD ["/bin/3proxy", "/etc/3proxy/3proxy.cfg"]

View File

@ -1,14 +1,14 @@
# 3proxy.full is fully functional 3proxy build based on busybox:glibc # 3proxy.full is fully functional distroless 3proxy build
# #
# Example are for podman, for docker change 'podman' to 'docker' # Examples are for podman, for docker change 'podman' to 'docker'
# #
#to build: #to build:
# podman build -f Dockerfile.full -t 3proxy.full . # podman build -f Dockerfile.full -t 3proxy.full .
#to run: #to run:
# #
# echo nserver 8.8.8.8 >/path/to/local/config/directory/3proxy.cfg # echo nserver 8.8.8.8 >/path/to/local/config/directory/3proxy.cfg
# echo proxy -p3129 >>/path/to/local/config/directory/3proxy.cfg # echo proxy -p3129 >>/path/to/local/config/directory/3proxy.cfg
# podman run --read-only -p 3129:3129 -v /path/to/local/config/directory:/etc/3proxy -name 3proxy.full 3proxy.full # podman run --read-only -p 3129:3129 -v /path/to/local/config/directory:/etc/3proxy --name 3proxy.full 3proxy.full
# #
# use "log" without pathname in config to log to stdout. # use "log" without pathname in config to log to stdout.
# plugins are located in /usr/local/3proxy/libexec (/libexec for chroot config) # plugins are located in /usr/local/3proxy/libexec (/libexec for chroot config)
@ -16,7 +16,7 @@
# to specify full path to plugin. SSLPlugin is supported. # to specify full path to plugin. SSLPlugin is supported.
# #
# Since 0.9.6 image is distroless, no reason to use chroot, chroot # Since 0.9.6 image is distroless, no reason to use chroot, chroot
# configuration is supported for compatility only. # configuration is supported for compatibility only.
FROM docker.io/gcc AS buildenv FROM docker.io/gcc AS buildenv

View File

@ -5,9 +5,12 @@
# library support. Add -DSAFESQL for poorely written ODBC library / drivers. # library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/ BUILDDIR = ../bin/
PREFIX ?= 3proxy_
CRYPT_PREFIX ?= $(PREFIX)
MANDIR ?= /usr/share/man
CC ?= cc CC ?= cc
CFLAGS := -c -fno-strict-aliasing -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL $(CFLAGS) CFLAGS := -c -fno-strict-aliasing -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_UN $(CFLAGS)
COUT = -o COUT = -o
LN ?= ${CC} LN ?= ${CC}
LDFLAGS += -pthread -fno-strict-aliasing LDFLAGS += -pthread -fno-strict-aliasing
@ -29,15 +32,18 @@ AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Mak
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.FreeBSD MAKEFILE = Makefile.FreeBSD
PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin FilePlugin
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false) OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true) ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl LIBS += -l crypto -l ssl
PLUGINS += SSLPlugin CFLAGS += -DWITH_SSL
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
endif endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -lpcre2-8 2>/dev/null && rm testpcre testpcre.o && echo true||echo false) PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic 2>/dev/null && rm testpcre testpcre.o && echo true||echo false)
ifeq ($(PCRE_CHECK), true) ifeq ($(PCRE_CHECK), true)
PLUGINS += PCREPlugin CFLAGS += -DWITH_PCRE
PCRE_OBJS = pcre$(OBJSUFFICS)
PCRE_LIBS = -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic
endif endif
PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false) PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false)
ifeq ($(PAM_CHECK), true) ifeq ($(PAM_CHECK), true)
@ -49,14 +55,25 @@ include Makefile.inc
install: all install: all
if [ ! -d "/usr/local/3proxy/bin" ]; then mkdir -p /usr/local/3proxy/bin/; fi if [ ! -d "/usr/local/3proxy/bin" ]; then mkdir -p /usr/local/3proxy/bin/; fi
install bin/3proxy /usr/local/3proxy/bin/3proxy install bin/3proxy /usr/local/3proxy/bin/3proxy
install bin/mycrypt /usr/local/3proxy/bin/mycrypt install bin/$(CRYPT_PREFIX)crypt /usr/local/3proxy/bin/$(CRYPT_PREFIX)crypt
for f in proxy socks pop3p smtpp ftppr tcppm udppm tlspr; do \
if [ -f bin/$(PREFIX)$$f ]; then install bin/$(PREFIX)$$f /usr/local/3proxy/bin/$(PREFIX)$$f; fi; \
done
install scripts/rc.d/3proxy /usr/local/etc/rc.d/3proxy install scripts/rc.d/3proxy /usr/local/etc/rc.d/3proxy
install scripts/add3proxyuser.sh /usr/local/3proxy/bin/ install scripts/add3proxyuser.sh /usr/local/3proxy/bin/
if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then /usr/local/3proxy/3proxy.cfg already exists ; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then echo /usr/local/3proxy/3proxy.cfg already exists; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi
if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi
touch /usr/local/3proxy/passwd touch /usr/local/3proxy/passwd
touch /usr/local/3proxy/counters touch /usr/local/3proxy/counters
touch /usr/local/3proxy/bandlimiters touch /usr/local/3proxy/bandlimiters
install -d $(MANDIR)/man8
install -m 644 man/3proxy.8 $(MANDIR)/man8/3proxy.8
for f in proxy socks pop3p smtpp ftppr tcppm udppm tlspr; do \
if [ -f man/$$f.8 ]; then install -m 644 man/$$f.8 $(MANDIR)/man8/$(PREFIX)$$f.8; fi; \
done
install -m 644 man/3proxy_crypt.8 $(MANDIR)/man8
install -d $(MANDIR)/man5
install -m 644 man/3proxy.cfg.5 $(MANDIR)/man5/3proxy.cfg.5
echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user
allplugins: allplugins:

View File

@ -5,9 +5,11 @@
# library support. Add -DSAFESQL for poorely written ODBC library / drivers. # library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/ BUILDDIR = ../bin/
PREFIX ?= 3proxy_
CRYPT_PREFIX ?= $(PREFIX)
CC ?= gcc CC ?= gcc
CFLAGS := -g -fPIC -O2 -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER $(CFLAGS) CFLAGS := -g -fPIC -O2 -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER -D WITH_UN $(CFLAGS)
COUT = -o COUT = -o
LN ?= ${CC} LN ?= ${CC}
DCFLAGS ?= DCFLAGS ?=
@ -32,15 +34,18 @@ MAKEFILE = Makefile.Linux
#LIBS = -lcrypto -lssl -ldl #LIBS = -lcrypto -lssl -ldl
LIBS ?= -ldl LIBS ?= -ldl
#PLUGINS = SSLPlugin StringsPlugin TrafficPlugin PCREPlugin TransparentPlugin PamAuth #PLUGINS = SSLPlugin StringsPlugin TrafficPlugin PCREPlugin TransparentPlugin PamAuth
PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin FilePlugin
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false) OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true) ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl LIBS += -l crypto -l ssl
PLUGINS += SSLPlugin CFLAGS += -DWITH_SSL
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
endif endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -lpcre2-8 2>/dev/null && rm testpcre testpcre.o && echo true||echo false) PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic 2>/dev/null && rm testpcre testpcre.o && echo true||echo false)
ifeq ($(PCRE_CHECK), true) ifeq ($(PCRE_CHECK), true)
PLUGINS += PCREPlugin CFLAGS += -DWITH_PCRE
PCRE_OBJS = pcre$(OBJSUFFICS)
PCRE_LIBS = -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic
endif endif
PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false) PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false)
ifeq ($(PAM_CHECK), true) ifeq ($(PAM_CHECK), true)
@ -61,14 +66,15 @@ INSTALL = /usr/bin/install
INSTALL_BIN = $(INSTALL) -m 755 INSTALL_BIN = $(INSTALL) -m 755
INSTALL_DATA = $(INSTALL) -m 644 INSTALL_DATA = $(INSTALL) -m 644
INSTALL_OBJS = bin/3proxy \ INSTALL_OBJS = bin/3proxy \
bin/ftppr \ bin/$(CRYPT_PREFIX)crypt \
bin/mycrypt \ bin/$(PREFIX)ftppr \
bin/pop3p \ bin/$(PREFIX)pop3p \
bin/proxy \ bin/$(PREFIX)proxy \
bin/socks \ bin/$(PREFIX)smtpp \
bin/tcppm \ bin/$(PREFIX)socks \
bin/udppm \ bin/$(PREFIX)tcppm \
bin/tlspr bin/$(PREFIX)tlspr \
bin/$(PREFIX)udppm
INSTALL_CFG = scripts/3proxy.cfg.chroot INSTALL_CFG = scripts/3proxy.cfg.chroot
@ -82,8 +88,7 @@ INSTALL_SYSTEMD_SCRIPT = scripts/3proxy.service
CHROOTDIR = $(DESTDIR)$(chroot_prefix)/3proxy CHROOTDIR = $(DESTDIR)$(chroot_prefix)/3proxy
CHROOTREL = ../..$(chroot_prefix)/3proxy CHROOTREL = ../..$(chroot_prefix)/3proxy
MANDIR1 = $(DESTDIR)$(man_prefix)/man/man1 MANDIR5 = $(DESTDIR)$(man_prefix)/man/man5
MANDIR3 = $(DESTDIR)$(man_prefix)/man/man3
MANDIR8 = $(DESTDIR)$(man_prefix)/man/man8 MANDIR8 = $(DESTDIR)$(man_prefix)/man/man8
BINDIR = $(DESTDIR)$(exec_prefix)/bin BINDIR = $(DESTDIR)$(exec_prefix)/bin
ETCDIR = $(DESTDIR)/etc/3proxy ETCDIR = $(DESTDIR)/etc/3proxy
@ -126,10 +131,14 @@ install-etc: install-etc-dir install-etc-default-config
done; done;
install-man: install-man:
$(INSTALL_BIN) -d $(MANDIR3) $(INSTALL_BIN) -d $(MANDIR5)
$(INSTALL_BIN) -d $(MANDIR8) $(INSTALL_BIN) -d $(MANDIR8)
$(INSTALL_DATA) man/*.3 $(MANDIR3) $(INSTALL_DATA) man/3proxy.cfg.5 $(MANDIR5)
$(INSTALL_DATA) man/*.8 $(MANDIR8) $(INSTALL_DATA) man/3proxy.8 $(MANDIR8)
for f in proxy socks pop3p smtpp ftppr tcppm udppm tlspr; do \
if [ -f man/$$f.8 ]; then $(INSTALL_DATA) man/$$f.8 $(MANDIR8)/$(PREFIX)$$f.8; fi; \
done
$(INSTALL_DATA) man/3proxy_crypt.8 $(MANDIR8)
install-init: install-init:
$(INSTALL_BIN) -d $(INITDDIR) $(INSTALL_BIN) -d $(INITDDIR)

View File

@ -6,7 +6,7 @@
# library support. Add -DSAFESQL for poorely written ODBC library / drivers. # library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/ BUILDDIR = ../bin/
CC = cc CC ?= cc
CFLAGS = -xO3 -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL CFLAGS = -xO3 -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o ./ COUT = -o ./
LN = $(CC) LN = $(CC)
@ -27,7 +27,20 @@ AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Mak
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.Solaris MAKEFILE = Makefile.Solaris
PLUGINS = StringsPlugin TrafficPlugin PLUGINS = StringsPlugin TrafficPlugin TransparentPlugin FilePlugin
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl
CFLAGS += -DWITH_SSL
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic 2>/dev/null && rm testpcre testpcre.o && echo true||echo false)
ifeq ($(PCRE_CHECK), true)
CFLAGS += -DWITH_PCRE
PCRE_OBJS = pcre$(OBJSUFFICS)
PCRE_LIBS = -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic
endif
include Makefile.inc include Makefile.inc

View File

@ -1,36 +0,0 @@
#
# 3 proxy Makefile for Solaris/gcc
#
#
# remove -DNOODBC from CFLAGS and add -lodbc to LDFLAGS to compile with ODBC
# library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/
CC = gcc
CFLAGS = -O2 -fno-strict-aliasing -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o ./
LN = $(CC)
LDFLAGS = -O3
DCFLAGS = -fPIC
DLFLAGS = -shared
DLSUFFICS = .ld.so
LIBS = -lpthread -lsocket -lnsl -lresolv -ldl
LIBSPREFIX = -l
LIBSSUFFIX =
LNOUT = -o ./
EXESUFFICS =
OBJSUFFICS = .o
DEFINEOPTION = -D
COMPFILES = *~
REMOVECOMMAND = rm -f
AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -executable -delete) || true
TYPECOMMAND = cat
COMPATLIBS =
MAKEFILE = Makefile.Solaris-gcc
PLUGINS = StringsPlugin TrafficPlugin
include Makefile.inc
allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done

View File

@ -1,2 +0,0 @@
SUBDIRS = src man
EXTRA_DIST = doc cfg

View File

@ -1,24 +0,0 @@
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
BUILDDIR = ../bin/
CC = cl
CFLAGS = /FD /MDd /nologo /W3 /ZI /Wp64 /GS /Gs /RTCsu /EHs- /GA /GF /DEBUG /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /machine:I386 /DEBUG
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.debug
include Makefile.inc
allplugins:

View File

@ -8,13 +8,13 @@ BUILDDIR = ../bin/
CC = cl CC = cl
VERSION = $(VERSION) VERSION = $(VERSION)
BUILDDATE = $(BUILDDATE) BUILDDATE = $(BUILDDATE)
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "WITH_SSL" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c $(BUILDDATE) $(VERSION) CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "WITH_SSL" /D "WITH_PCRE" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c $(BUILDDATE) $(VERSION)
COUT = /Fo COUT = /Fo
LN = link LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no LDFLAGS = /nologo /subsystem:console /incremental:no
DLFLAGS = /DLL DLFLAGS = /DLL
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib Crypt32.lib libcrypto.lib libssl.lib LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib Crypt32.lib libcrypto.lib libssl.lib pcre2-8.lib
LIBSPREFIX = LIBSPREFIX =
LIBSSUFFIX = .lib LIBSSUFFIX = .lib
LIBEXT = .lib LIBEXT = .lib
@ -27,7 +27,9 @@ REMOVECOMMAND = del
TYPECOMMAND = type TYPECOMMAND = type
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.msvc MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin FilePlugin SSLPlugin PCREPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin FilePlugin
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
PCRE_OBJS = pcre$(OBJSUFFICS)
VERFILE = 3proxy.res $(VERFILE) VERFILE = 3proxy.res $(VERFILE)
VERSIONDEP = 3proxy.res $(VERSIONDEP) VERSIONDEP = 3proxy.res $(VERSIONDEP)
AFTERCLEAN = if exist src\*.res (del src\*.res) && if exist src\*.err (del src\*.err) AFTERCLEAN = if exist src\*.res (del src\*.res) && if exist src\*.err (del src\*.err)

View File

@ -1,113 +0,0 @@
#
# 3 proxy Makefile for GCC/Linux/Cygwin
#
#
# remove -DNOODBC from CFLAGS and add -lodbc to LIBS to compile with ODBC
# library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/
CC = mips-openwrt-linux-gcc
CFLAGS ?= -g -O2 -fno-strict-aliasing -c -pthread -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER
COUT = -o
LN = $(CC)
DCFLAGS = -fPIC
LDFLAGS ?= -O2 -fno-strict-aliasing -pthread -s
DLFLAGS = -shared
DLSUFFICS = .ld.so
# -lpthreads may be reuqired on some platforms instead of -pthreads
LIBSPREFIX = -l
LIBSSUFFIX =
LNOUT = -o
EXESUFFICS =
OBJSUFFICS = .o
DEFINEOPTION = -D
COMPFILES = *~
REMOVECOMMAND = rm -f
AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -executable -delete) || true
TYPECOMMAND = cat
COMPATLIBS =
MAKEFILE = Makefile.openwrt-mips
# PamAuth requires libpam, you may require pam-devel package to be installed
# SSLPlugin requires -lcrypto -lssl
#LIBS = -lcrypto -lssl -ldl
LIBS ?= -ldl
#PLUGINS = SSLPlugin StringsPlugin TrafficPlugin PCREPlugin TransparentPlugin PamAuth
PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | cc -x c $(CFLAGS) $(LDFLAGS) -l crypto -l ssl -o testssl - 2>/dev/null && rm testssl && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl
PLUGINS += SSLPlugin
endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | cc -x c $(CFLAGS) $(LDFLAGS) -l pcre2-8 -o testpcre - 2>/dev/null && rm testpcre && echo true||echo false)
ifeq ($(PCRE_CHECK), true)
PLUGINS += PCREPlugin
endif
PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | cc -x c $(CFLAGS) $(LDFLAGS) -l pam -o testpam - 2>/dev/null && rm testpam && echo true||echo false)
ifeq ($(PAM_CHECK), true)
PLUGINS += PamAuth
endif
include Makefile.inc
allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done
DESTDIR =
prefix = /usr/local
exec_prefix = $(prefix)
man_prefix = $(prefix)/share
INSTALL = /usr/bin/install
INSTALL_BIN = $(INSTALL) -m 755
INSTALL_DATA = $(INSTALL) -m 644
INSTALL_OBJS = src/3proxy \
src/ftppr \
src/mycrypt \
src/pop3p \
src/proxy \
src/socks \
src/tcppm \
src/udppm
INSTALL_CFG_OBJS = scripts/3proxy.cfg \
scripts/add3proxyuser.sh
INSTALL_CFG_DEST = config
INSTALL_CFG_OBJS2 = passwd counters bandlimiters
MANDIR1 = $(DESTDIR)$(man_prefix)/man/man1
MANDIR3 = $(DESTDIR)$(man_prefix)/man/man3
MANDIR8 = $(DESTDIR)$(man_prefix)/man/man8
BINDIR = $(DESTDIR)$(exec_prefix)/bin
ETCDIR = $(DESTDIR)$(prefix)/etc/3proxy
install-bin:
$(INSTALL_BIN) -d $(BINDIR)
$(INSTALL_BIN) -s $(INSTALL_OBJS) $(BINDIR)
install-etc-dir:
$(INSTALL_BIN) -d $(ETCDIR)
install-etc-default-config:
if [ -f $(ETCDIR)/$(INSTALL_CFG_DEST) ]; then \
: ; \
else \
$(INSTALL_DATA) $(INSTALL_CFG_OBJS) $(ETCDIR)/$(INSTALL_CFG_DEST) \
fi
install-etc: install-etc-dir
for file in $(INSTALL_CFG_OBJS2); \
do \
touch $(ETCDIR)/$$file; chmod 0600 $(ETCDIR)/$$file; \
done;
install-man:
$(INSTALL_BIN) -d $(MANDIR3)
$(INSTALL_BIN) -d $(MANDIR8)
$(INSTALL_DATA) man/*.3 $(MANDIR3)
$(INSTALL_DATA) man/*.8 $(MANDIR8)
install: install-bin install-etc install-man

View File

@ -6,10 +6,13 @@
# library support. Add -DSAFESQL for poorely written ODBC library / drivers. # library support. Add -DSAFESQL for poorely written ODBC library / drivers.
BUILDDIR = ../bin/ BUILDDIR = ../bin/
PREFIX ?= 3proxy_
CRYPT_PREFIX ?= $(PREFIX)
MANDIR ?= /usr/share/man
CC ?= gcc CC ?= gcc
# you may need -L/usr/pkg/lib for older NetBSD versions # you may need -L/usr/pkg/lib for older NetBSD versions
CFLAGS := -g -O2 -fno-strict-aliasing -c -pthread -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL $(CFLAGS) CFLAGS := -g -O2 -fno-strict-aliasing -c -pthread -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_UN $(CFLAGS)
COUT = -o COUT = -o
LN ?= $(CC) LN ?= $(CC)
LDFLAGS ?= -O2 -fno-strict-aliasing -pthread LDFLAGS ?= -O2 -fno-strict-aliasing -pthread
@ -31,15 +34,18 @@ AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Mak
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.unix MAKEFILE = Makefile.unix
PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin PLUGINS ?= StringsPlugin TrafficPlugin TransparentPlugin FilePlugin
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false) OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testssl.o - 2>/dev/null && $(CC) $(LDFLAGS) -otestssl testssl.o -lcrypto -lssl 2>/dev/null && rm testssl testssl.o && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true) ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl LIBS += -l crypto -l ssl
PLUGINS += SSLPlugin CFLAGS += -DWITH_SSL
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
endif endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -lpcre2-8 2>/dev/null && rm testpcre testpcre.o && echo true||echo false) PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n\#include <pcre2.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpcre.o - 2>/dev/null && $(CC) -o testpcre testpcre.o $(LDFLAGS) -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic 2>/dev/null && rm testpcre testpcre.o && echo true||echo false)
ifeq ($(PCRE_CHECK), true) ifeq ($(PCRE_CHECK), true)
PLUGINS += PCREPlugin CFLAGS += -DWITH_PCRE
PCRE_OBJS = pcre$(OBJSUFFICS)
PCRE_LIBS = -Wl,-Bstatic -lpcre2-8 -Wl,-Bdynamic
endif endif
PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false) PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d \\\\ | $(CC) -x c $(CFLAGS) -o testpam.o - 2>/dev/null && $(CC) $(LDFLAGS) -o testpam testpam.o -lpam 2>/dev/null && rm testpam testpam.o && echo true||echo false)
ifeq ($(PAM_CHECK), true) ifeq ($(PAM_CHECK), true)
@ -49,17 +55,28 @@ endif
include Makefile.inc include Makefile.inc
install: all install: all
if [ ! -d "/usr/local/3proxy/bin" ]; then mkdir -p /usr/local/3proxy/bin/; fi if [ ! -d "/usr/local/3proxy/bin" ]; then mkdir -p /usr/local/3proxy/bin/; fi
install bin/3proxy /usr/local/3proxy/bin/3proxy install bin/3proxy /usr/local/3proxy/bin/3proxy
install bin/mycrypt /usr/local/3proxy/bin/mycrypt install bin/$(CRYPT_PREFIX)crypt /usr/local/3proxy/bin/$(CRYPT_PREFIX)crypt
install scripts/rc.d/3proxy /usr/local/etc/rc.d/3proxy for f in proxy socks pop3p smtpp ftppr tcppm udppm tlspr; do \
install scripts/add3proxyuser.sh /usr/local/3proxy/bin/ if [ -f bin/$(PREFIX)$$f ]; then install bin/$(PREFIX)$$f /usr/local/3proxy/bin/$(PREFIX)$$f; fi; \
if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then /usr/local/3proxy/3proxy.cfg already exists ; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi done
if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi install scripts/rc.d/3proxy /usr/local/etc/rc.d/3proxy
touch /usr/local/3proxy/passwd install scripts/add3proxyuser.sh /usr/local/3proxy/bin/
touch /usr/local/3proxy/counters if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then echo /usr/local/3proxy/3proxy.cfg already exists; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi
touch /usr/local/3proxy/bandlimiters if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi
echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user touch /usr/local/3proxy/passwd
touch /usr/local/3proxy/counters
touch /usr/local/3proxy/bandlimiters
install -d $(MANDIR)/man8
install -m 644 man/3proxy.8 $(MANDIR)/man8/3proxy.8
for f in proxy socks pop3p smtpp ftppr tcppm udppm tlspr; do \
if [ -f man/$$f.8 ]; then install -m 644 man/$$f.8 $(MANDIR)/man8/$(PREFIX)$$f.8; fi; \
done
install -m 644 man/3proxy_crypt.8 $(MANDIR)/man8
install -d $(MANDIR)/man5
install -m 644 man/3proxy.cfg.5 $(MANDIR)/man5/3proxy.cfg.5
echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user
allplugins: allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done @list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done

View File

@ -27,6 +27,8 @@ TYPECOMMAND = type
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.watcom MAKEFILE = Makefile.watcom
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
PCRE_OBJS = pcre$(OBJSUFFICS)
VERFILE = $(VERFILE) VERFILE = $(VERFILE)
VERSION = $(VERSION) VERSION = $(VERSION)
VERSIONDEP = 3proxy.res $(VERSIONDEP) VERSIONDEP = 3proxy.res $(VERSIONDEP)

View File

@ -26,7 +26,7 @@ REMOVECOMMAND = rm -f
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.win MAKEFILE = Makefile.win
PLUGINS := utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PLUGINS := utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin FilePlugin
VERFILE := 3proxyres.o $(VERFILE) VERFILE := 3proxyres.o $(VERFILE)
VERSION := $(VERSION) VERSION := $(VERSION)
VERSIONDEP := 3proxyres.o $(VERSIONDEP) VERSIONDEP := 3proxyres.o $(VERSIONDEP)
@ -37,7 +37,8 @@ ifndef OPENSSL_CHECK
OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -l crypto -l ssl -o testssl - 2>/dev/null && rm testssl && echo true||echo false) OPENSSL_CHECK = $(shell echo "\#include <openssl/ssl.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -l crypto -l ssl -o testssl - 2>/dev/null && rm testssl && echo true||echo false)
ifeq ($(OPENSSL_CHECK), true) ifeq ($(OPENSSL_CHECK), true)
LIBS += -l crypto -l ssl LIBS += -l crypto -l ssl
PLUGINS += SSLPlugin CFLAGS += -DWITH_SSL
SSL_OBJS = ssllib$(OBJSUFFICS) ssl$(OBJSUFFICS)
endif endif
PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -l pam -o testpam - 2>/dev/null && rm testpam && echo true||echo false) PAM_CHECK = $(shell echo "\#include <security/pam_appl.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -l pam -o testpam - 2>/dev/null && rm testpam && echo true||echo false)
ifeq ($(PAM_CHECK), true) ifeq ($(PAM_CHECK), true)
@ -45,7 +46,9 @@ ifeq ($(PAM_CHECK), true)
endif endif
PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n#include <pcre2.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -lpcre2-8 -o testpcre - 2>/dev/null && rm testpcre && echo true||echo false) PCRE_CHECK = $(shell echo "\#define PCRE2_CODE_UNIT_WIDTH 8\\n#include <pcre2.h>\\n int main(){return 0;}" | tr -d '\\\\' | cc -x c $(CFLAGS) $(LDFLAGS) -lpcre2-8 -o testpcre - 2>/dev/null && rm testpcre && echo true||echo false)
ifeq ($(PCRE_CHECK), true) ifeq ($(PCRE_CHECK), true)
PLUGINS += PCREPlugin CFLAGS += -DWITH_PCRE
PCRE_OBJS = pcre$(OBJSUFFICS)
PCRE_LIBS = -lpcre2-8
endif endif
endif endif

276
README
View File

@ -1,276 +0,0 @@
# 3APA3A 3proxy tiny proxy server
(c) 2002-2025 by Vladimir '3APA3A' Dubrovin <3proxy@3proxy.org>
Branches:
Master (stable) branch - 3proxy 0.9
Devel branch - 3proxy 10 (don't use it)
* Download
Binaries and sources for released (master) versions (Windows, Linux):
https://github.com/z3APA3A/3proxy/releases
Docker images:
https://hub.docker.com/r/3proxy/3proxy
Archive of old versions: https://github.com/z3APA3A/3proxy-archive
* Documentation
Documentation (man pages and HTML) available with download, on https://3proxy.org/
and in github wiki https://github.com/3proxy/3proxy/wiki
* Windows installation
3proxy [path_to_config_file] --install
installs and starts proxy as Windows service
(config file should be located in the same directory or may be optionally specified)
3proxy --remove
removes the service (should be stopped before via
'net stop 3proxy').
* To build in Linux
With Makefile:
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
ln -s Makefile.Linux Makefile
make
sudo make install
Default configuration (for Linux/Unix):
3proxy uses 2 configuration files:
/etc/3proxy/3proxy.cfg (before-chroot). This configuration file is executed before chroot and should not be modified.
/usr/local/3proxy/conf/3proxy.cfg symlinked from /etc/3proxy/conf/3proxy.cfg (after-chroot) is a main configuration file. Modify this file, if required.
All paths in /usr/local/3proxy/conf/3proxy.cfg are relative to chroot directory (/usr/local/3proxy). For future versions it's planned to move
3proxy chroot direcory to /var.
Log files are created in /usr/local/3proxy/logs symlinked from /var/log/3proxy.
By default, socks is started on 0.0.0.0:1080 and proxy on 0.0.0.0:3128 with basic auth, no users are added by default.
use /etc/3proxy/conf/add3proxyuser.sh script to add users.
usage: /etc/3proxy/conf/add3proxyuser.sh username password [day_limit] [bandwidth]
day_limit - traffic limit in MB per day
bandwidth - bandwith in bits per second 1048576 = 1Mbps
or modify /etc/3proxy/conf/ files directly.
With CMake:
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
CMake does not use chroot configuration, config file is /etc/3proxy/3proxy.cfg
* For MacOS X / FreeBSD / *BSD
With Makefile:
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
ln -s Makefile.FreeBSD Makefile
make
(binaries are in bin/ directory)
With CMake (recommended):
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
This installs binaries to /usr/local/bin/, configuration to /etc/3proxy/,
plugins to /usr/local/lib/3proxy/, rc scripts to rc.d for BSD and launchd plist to /Library/LaunchDaemons/ for MacOS.
Service management on macOS:
# Load and start service
sudo launchctl load /Library/LaunchDaemons/org.3proxy.3proxy.plist
# Stop service
sudo launchctl stop org.3proxy.3proxy
# Start service
sudo launchctl start org.3proxy.3proxy
# Unload and disable service
sudo launchctl unload /Library/LaunchDaemons/org.3proxy.3proxy.plist
Features:
1. General
+ IPv6 support for incoming and outgoing connection,
can be used as a proxy between IPv4 and IPv6 networks
in either direction.
+ HTTP/1.1 Proxy with keep-alive client and server support,
transparent proxy support.
+ HTTPS (CONNECT) proxy (compatible with HTTP/2 / SPDY)
+ Anonymous and random client IP emulation for HTTP proxy mode
+ FTP over HTTP support.
+ DNS caching with built-in resolver
+ DNS proxy
+ DNS over TCP support, redirecting DNS traffic via parent
proxy
+ SOCKSv4/4.5 Proxy
+ SOCKSv5 Proxy
+ SOCKSv5 UDP and BIND support (fully compatible with
SocksCAP/FreeCAP for UDP)
+ Transparent SOCKS redirection for HTTP, POP3, FTP, SMTP
+ SNI proxy (based on TLS hostname)
+ TLS (SSL) server - may be used as https:// type proxy
+ POP3 Proxy
+ FTP proxy
+ TCP port mapper (port forwarding)
+ UDP port mapper (port forwarding)
+ SMTP proxy
+ Threaded application (no child process).
+ Web administration and statistics
+ Plugins for functionality extension
+ Native 32/64 bit application
2. Proxy chaining and network connections
+ Can be used as a bridge between client and different proxy type
(e.g. convert incoming HTTP proxy request from client to SOCKSv5
request to parent server).
+ Connect back proxy support to bypass firewalls
+ Parent proxy support for any type of incoming connection
+ Username/password authentication for parent proxy(s).
+ HTTPS/SOCKS4/SOCKS5 and ip/port redirection parent support
+ Random parent selection
+ Chain building (multihop proxing)
+ Load balancing between few network connections by choosing network
interface
3. Logging
+ tuneable log format compatible with any log parser
+ stdout logging
+ file logging
+ syslog logging (Unix)
+ ODBC logging
+ RADIUS accounting
+ log file rotation
+ automatic log file processing with external archiver (for files)
+ Character filtering for log files
+ different log files for different servces are supported
4. Access control
+ ACL-driven Access control by username, source IP,
destination IP/hostname, destination port and destination action
(POST, PUT, GET, etc), weekday and daytime.
+ ACL-driven (user/source/destination/protocol/weekday/daytime or
combined) bandwith limitation for incoming and (!)outgoing trafic.
+ ACL-driven traffic limitation per day, week or month for incoming and
outgoing traffic
+ Connection limitation and ratelimting
+ User authentication by username / password
+ RADIUS Authentication and Authorization
+ User authentication by DNS hostname
+ Authentication cache with possibility to limit user to single IP address
+ Access control by username/password for SOCKSv5 and HTTP/HTTPS/FTP
+ Cleartext or encrypted (crypt/MD5 or NT) passwords.
+ Connection redirection
+ Access control by requested action (CONNECT/BIND,
HTTP GET/POST/PUT/HEAD/OTHER).
+ All access control entries now support weekday and time limitations
+ Hostnames and * templates are supported instead of IP address
5. Extensions
+ Regular expression filtering (with PCRE2) via PCREPlugin
+ Authentication with Windows username/password (cleartext only)
+ SSL/TLS decryptions with certificate spoofing
+ Transparent redirection support for Linux and *BSD
6. Configuration
+ support for configuration files
+ support for includes in configuration files
+ interface binding
+ socket options
+ running as daemon process
+ utility for automated networks list building
+ configuration reload on any file change
Unix
+ support for chroot
+ support for setgid
+ support for setuid
+ support for signals (SIGUSR1 to reload configuration)
Windows
+ support --install as service
+ support --remove as service
+ support for service START, STOP, PAUSE and CONTINUE commands (on
PAUSE no new connection accepted, but active connections still in
progress, on CONTINUE configuration is reloaded)
Windows 95/98/ME
+ support --install as service
+ support --remove as service
6. Compilation
+ MSVC (static)
+ OpenWatcom (static)
+ Intel Windows Compiler (msvcrt.dll)
+ Windows/gcc (msvcrt.dll)
+ Cygwin/gcc (cygwin.dll)
+ Unix/gcc
+ Unix/ccc
+ Solaris
+ Mac OS X, iPhone OS
+ Linux and derivered systems
+ Lite version for Windows 95/98/NT/2000/XP/2003
+ 32 bit and 64 bit versions for Windows Vista and above, Windows 2008 server and above
3proxy Combined proxy server may be used as
executable or service (supports installation and removal).
It uses config file to read it's configuration (see
3proxy.cfg.sample for details).
3proxy.exe is all-in-one, it doesn't require all others .exe
to work.
See 3proxy.cfg.sample for examples, see man 3proxy.cfg
proxy HTTP proxy server, binds to port 3128
ftppr FTP proxy server, binds to port 21
socks SOCKS 4/5 proxy server, binds to port 1080
ftppr FTP proxy server, please do not mess it with FTP over HTTP
proxy used in browsers
pop3p POP3 proxy server, binds to port 110. You must specify
POP3 username as username@target.host.ip[:port]
port is 110 by default.
Exmple: in Username configuration for you e-mail reader
set someuser@pop.example.org, to obtains mail for someuser
from pop.somehost.ru via proxy.
smtpp SMTP proxy server, binds to port 25. You must specify
SMTP username as username@target.host.ip[:port]
port is 25 by default.
Exmple: in Username configuration for you e-mail reader
set someuser@mail.example.org, to send mail as someuser
via mail.somehost.ru via proxy.
tcppm TCP port mapping. Maps some TCP port on local machine to
TCP port on remote host.
tlspr TLS proxy (SNI proxy) - sniffs hostname from TLS handshake
udppm UDP port mapping. Maps some UDP port on local machine to
UDP port on remote machine. Only one user simulationeously
can use UDP mapping, so it cann't be used for public service
in large networks. It's OK to use it to map to DNS server
in small network or to map Counter-Strike server for single
client (you can use few mappings on different ports for
different clients in last case).
mycrypt Program to obtain crypted password fro cleartext. Supports
both MD5/crypt and NT password.
mycrypt password
produces NT password
mycrypt salt password
produces MD5/crypt password with salt "salt".
Run utility with --help option for command line reference.
Latest version is available from https://3proxy.org/
Want to donate the project? https://3proxy.org/donations/

303
README.md Normal file
View File

@ -0,0 +1,303 @@
# 3APA3A 3proxy tiny proxy server
(c) 2002-2025 by Vladimir '3APA3A' Dubrovin <3APA3A@security.nnov.ru>
## Branches
- **Master** (stable) branch - 3proxy 0.9
- **Devel** branch - 3proxy 10 (don't use it)
## Download
Binaries and sources for released (master) versions (Windows, Linux):
https://github.com/z3APA3A/3proxy/releases
Docker images:
https://hub.docker.com/r/3proxy/3proxy
Archive of old versions:
https://github.com/z3APA3A/3proxy-archive
## Documentation
Documentation (man pages and HTML) available with download, on https://3proxy.org/ and in github wiki https://github.com/3proxy/3proxy/wiki
## Windows Installation
Install and start proxy as Windows service:
```bash
3proxy [path_to_config_file] --install
```
Config file should be located in the same directory or may be optionally specified.
Remove the service (should be stopped before via `net stop 3proxy`):
```bash
3proxy --remove
```
## Building on Linux
### With Makefile
```bash
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
ln -s Makefile.Linux Makefile
make
sudo make install
```
### Default Configuration (Linux/Unix)
3proxy uses 2 configuration files:
- `/etc/3proxy/3proxy.cfg` (before-chroot) - This configuration file is executed before chroot and should not be modified.
- `/usr/local/3proxy/conf/3proxy.cfg` symlinked from `/etc/3proxy/conf/3proxy.cfg` (after-chroot) - Main configuration file. Modify this file if required.
All paths in `/usr/local/3proxy/conf/3proxy.cfg` are relative to chroot directory (`/usr/local/3proxy`). For future versions it's planned to move 3proxy chroot directory to `/var`.
Log files are created in `/usr/local/3proxy/logs` symlinked from `/var/log/3proxy`.
By default, socks is started on 0.0.0.0:1080 and proxy on 0.0.0.0:3128 with basic auth, no users are added by default.
### Adding Users
Use `/etc/3proxy/conf/add3proxyuser.sh` script to add users:
```bash
/etc/3proxy/conf/add3proxyuser.sh username password [day_limit] [bandwidth]
```
Parameters:
- `day_limit` - traffic limit in MB per day
- `bandwidth` - bandwidth in bits per second (1048576 = 1Mbps)
Or modify `/etc/3proxy/conf/` files directly.
### With CMake
```bash
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
```
CMake does not use chroot configuration, config file is `/etc/3proxy/3proxy.cfg`
## MacOS X / FreeBSD / *BSD
### With Makefile
```bash
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
ln -s Makefile.FreeBSD Makefile
make
```
Binaries are in `bin/` directory.
### With CMake (recommended)
```bash
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
```
This installs:
- Binaries to `/usr/local/bin/`
- Configuration to `/etc/3proxy/`
- Plugins to `/usr/local/lib/3proxy/`
- rc scripts to `rc.d` for BSD
- launchd plist to `/Library/LaunchDaemons/` for MacOS
### Service Management on macOS
```bash
# Load and start service
sudo launchctl load /Library/LaunchDaemons/org.3proxy.3proxy.plist
# Stop service
sudo launchctl stop org.3proxy.3proxy
# Start service
sudo launchctl start org.3proxy.3proxy
# Unload and disable service
sudo launchctl unload /Library/LaunchDaemons/org.3proxy.3proxy.plist
```
## Features
### 1. General
- IPv4 / IPv6 support for incoming and outgoing connection, can be used as a proxy between IPv4 and IPv6 networks in either direction
- Unix domain sockets support
- HTTP/1.1 Proxy with keep-alive client and server support, transparent proxy support
- HTTPS (CONNECT) proxy (compatible with HTTP/2 / SPDY)
- Anonymous and random client IP emulation for HTTP proxy mode
- FTP over HTTP support
- DNS caching with built-in resolver
- DNS proxy
- DNS over TCP support, redirecting DNS traffic via parent proxy
- SOCKSv4/4.5 Proxy
- SOCKSv5 Proxy
- SOCKSv5 UDP and BIND support (fully compatible with SocksCAP/FreeCAP for UDP)
- Transparent SOCKS redirection for HTTP, POP3, FTP, SMTP
- SNI proxy (based on TLS hostname)
- TLS (SSL) server and client, 3proxy may be used as https:// type proxy or stunnel replacement
- POP3 Proxy
- FTP proxy
- TCP port mapper (port forwarding)
- UDP port mapper (port forwarding)
- SMTP proxy
- Threaded application (no child process)
- Web administration and statistics
- Plugins for functionality extension
- Native 32/64 bit application
### 2. Proxy Chaining and Network Connections
- Can be used as a bridge between client and different proxy type (e.g. convert incoming HTTP proxy request from client to SOCKSv5 request to parent server)
- Connect back proxy support to bypass firewalls
- Parent proxy support for any type of incoming connection
- Username/password authentication for parent proxy(s)
- HTTPS/SOCKS4/SOCKS5 and ip/port redirection parent support
- Random parent selection
- Chain building (multihop proxing)
- Load balancing between few network connections by choosing network interface
### 3. Logging
- Tuneable log format compatible with any log parser
- stdout logging
- File logging
- Syslog logging (Unix)
- ODBC logging
- RADIUS accounting
- Log file rotation
- Automatic log file processing with external archiver (for files)
- Character filtering for log files
- Different log files for different services are supported
### 4. Access Control
- ACL-driven Access control by username, source IP, destination IP/hostname, destination port and destination action (POST, PUT, GET, etc), weekday and daytime
- ACL-driven (user/source/destination/protocol/weekday/daytime or combined) bandwidth limitation for incoming and (!)outgoing traffic
- ACL-driven traffic limitation per day, week or month for incoming and outgoing traffic
- Connection limitation and ratelimiting
- User authentication by username / password
- RADIUS Authentication and Authorization
- User authentication by DNS hostname
- Authentication cache with possibility to limit user to single IP address
- Access control by username/password for SOCKSv5 and HTTP/HTTPS/FTP
- Cleartext or encrypted passwords
- Connection redirection
- Access control by requested action (CONNECT/BIND, HTTP GET/POST/PUT/HEAD/OTHER)
- All access control entries now support weekday and time limitations
- Hostnames and * templates are supported instead of IP address
### 5. Extensions
- Regular expression filtering (with PCRE2) via PCREPlugin
- Authentication with Windows username/password (cleartext only)
- SSL/TLS decryptions with certificate spoofing
- Transparent redirection support for Linux and *BSD
### 6. Configuration
- Support for configuration files
- Support for includes in configuration files
- Interface binding
- Socket options
- Running as daemon process
- Utility for automated networks list building
- Configuration reload on any file change
**Unix:**
- Support for chroot
- Support for setgid
- Support for setuid
- Support for signals (SIGUSR1 to reload configuration)
**Windows:**
- Support `--install` as service
- Support `--remove` as service
- Support for service START, STOP, PAUSE and CONTINUE commands (on PAUSE no new connection accepted, but active connections still in progress, on CONTINUE configuration is reloaded)
**Windows 95/98/ME:**
- Support `--install` as service
- Support `--remove` as service
### 7. Compilation
- MSVC (static)
- OpenWatcom (static)
- Intel Windows Compiler (msvcrt.dll)
- Windows/gcc (msvcrt.dll)
- Cygwin/gcc (cygwin.dll)
- Unix/gcc
- Unix/ccc
- Solaris
- Mac OS X, iPhone OS
- Linux and derived systems
- Lite version for Windows 95/98/NT/2000/XP/2003
- 32 bit and 64 bit versions for Windows Vista and above, Windows 2008 server and above
## Executables
### 3proxy
Combined proxy server may be used as executable or service (supports installation and removal). It uses config file to read its configuration (see `3proxy.cfg.sample` for details). `3proxy.exe` is all-in-one, it doesn't require all others .exe to work. See `3proxy.cfg.sample` for examples, see `man 3proxy.cfg`
### proxy
HTTP proxy server, binds to port 3128
### ftppr
FTP proxy server, binds to port 21. Please do not mess it with FTP over HTTP proxy used in browsers
### socks
SOCKS 4/5 proxy server, binds to port 1080
### pop3p
POP3 proxy server, binds to port 110. You must specify POP3 username as `username@popserver[:port]` (port is 110 by default).
Example: in Username configuration for your e-mail reader set `someuser@pop.somehost.ru`, to obtain mail for someuser from pop.somehost.ru via proxy.
### smtpp
SMTP proxy server, binds to port 25. You must specify SMTP username as `username@smtpserver[:port]` (port is 25 by default).
Example: in Username configuration for your e-mail reader set `someuser@mail.somehost.ru`, to send mail as someuser via mail.somehost.ru via proxy.
### tcppm
TCP port mapping. Maps some TCP port on local machine to TCP port on remote host.
### tlspr
TLS proxy (SNI proxy) - sniffs hostname from TLS handshake
### udppm
UDP port mapping. Maps some UDP port on local machine to UDP port on remote machine. Only one user simultaneously can use UDP mapping, so it can't be used for public service in large networks. It's OK to use it to map to DNS server in small network or to map Counter-Strike server for single client (you can use few mappings on different ports for different clients in last case).
### 3proxy_crypt
Program to obtain crypted password for cleartext. Supports both salted and NT password.
```bash
3proxy_crypt password # produces NT password
3proxy_crypt salt password # produces password hash with salt "salt"
```
---
Run utility with `--help` option for command line reference.
Latest version is available from https://3proxy.org/
Want to donate the project? https://3proxy.org/donations/

View File

@ -2,7 +2,7 @@
# Yes, 3proxy.cfg can be executable, in this case you should place # Yes, 3proxy.cfg can be executable, in this case you should place
# something like # something like
#config /usr/local/3proxy/3proxy.cfg #config /usr/local/3proxy/3proxy.cfg
# to show which configuration 3proxy should re-read on realod. # to show which configuration 3proxy should re-read on reload.
#system "echo Hello world!" #system "echo Hello world!"
# you may use system to execute some external command if proxy starts # you may use system to execute some external command if proxy starts
@ -24,7 +24,7 @@ timeouts 1 5 30 60 180 1800 15 60
# Here we can change timeout values # Here we can change timeout values
users 3APA3A:CL:3apa3a "test:CR:$1$qwer$CHFTUFGqkjue9HyhcMHEe1" users 3APA3A:CL:3apa3a "test:CR:$1$qwer$CHFTUFGqkjue9HyhcMHEe1"
# note that "" required, overvise $... is treated as include file name. # note that "" required, otherwise $... is treated as include file name.
# $1$qwer$CHFTUFGqkjue9HyhcMHEe1 is 'test' in MD5 crypt format. # $1$qwer$CHFTUFGqkjue9HyhcMHEe1 is 'test' in MD5 crypt format.
#users $/usr/local/etc/3proxy/passwd #users $/usr/local/etc/3proxy/passwd
# this example shows you how to include passwd file. For included files # this example shows you how to include passwd file. For included files
@ -39,7 +39,7 @@ service
#log /var/log/3proxy/log D #log /var/log/3proxy/log D
log c:\3proxy\logs\3proxy.log D log c:\3proxy\logs\3proxy.log D
# log allows to specify log file location and rotation, D means logfile # log allows you to specify log file location and rotation, D means logfile
# is created daily # is created daily
#logformat "L%d-%m-%Y %H:%M:%S %z %N.%p %E %U %C:%c %R:%r %O %I %h %T" #logformat "L%d-%m-%Y %H:%M:%S %z %N.%p %E %U %C:%c %R:%r %O %I %h %T"
@ -60,7 +60,7 @@ log c:\3proxy\logs\3proxy.log D
# #
#Compatible with ISA 2000/2004 firewall FWSEXTD.log (fields are TAB-delimited): #Compatible with ISA 2000/2004 firewall FWSEXTD.log (fields are TAB-delimited):
# #
#"- + L%C %U unnknown:0:0.0 N %Y-%m-%d %H:%M:%S fwsrv 3PROXY - %n %R %r %D %O %I %r TCP Connect - - - %E - - - - -" #"- + L%C %U unknown:0:0.0 N %Y-%m-%d %H:%M:%S fwsrv 3PROXY - %n %R %r %D %O %I %r TCP Connect - - - %E - - - - -"
# #
#Compatible with HTTPD standard log (Apache and others) #Compatible with HTTPD standard log (Apache and others)
# #
@ -90,7 +90,7 @@ auth iponly
# auth specifies type of user authentication. If you specify none proxy # auth specifies type of user authentication. If you specify none proxy
# will not do anything to check name of the user. If you specify # will not do anything to check name of the user. If you specify
# nbname proxy will send NetBIOS name request packet to UDP/137 of # nbname proxy will send NetBIOS name request packet to UDP/137 of
# client and parse request for NetBIOS name of messanger service. # client and parse request for NetBIOS name of messenger service.
# Strong means that proxy will check password. For strong authentication # Strong means that proxy will check password. For strong authentication
# unknown user will not be allowed to use proxy regardless of ACL. # unknown user will not be allowed to use proxy regardless of ACL.
# If you do not want username to be checked but wanna ACL to work you should # If you do not want username to be checked but wanna ACL to work you should
@ -102,7 +102,7 @@ auth iponly
#parent 1000 http 192.168.1.2 80 * * * 80 #parent 1000 http 192.168.1.2 80 * * * 80
#allow * 192.168.1.0/24 * 25,53,110,20-21,1024-65535 #allow * 192.168.1.0/24 * 25,53,110,20-21,1024-65535
# we will allow everything if username matches ADMINISTRATOR or root or # we will allow everything if username matches ADMINISTRATOR or root or
# client ip is 127.0.0.1 or 192.168.1.1. Overwise we will redirect any request # client ip is 127.0.0.1 or 192.168.1.1. Otherwise we will redirect any request
# to port 80 to our Web-server 192.168.0.2. # to port 80 to our Web-server 192.168.0.2.
# We will allow any outgoing connections from network 192.168.1.0/24 to # We will allow any outgoing connections from network 192.168.1.0/24 to
# SMTP, POP3, FTP, DNS and unprivileged ports. # SMTP, POP3, FTP, DNS and unprivileged ports.
@ -124,7 +124,7 @@ internal 192.168.1.1
# have open proxy in your network in this case. # have open proxy in your network in this case.
auth none auth none
# no authentication is requires # no authentication is required
dnspr dnspr
@ -134,7 +134,7 @@ dnspr
#external $./external.ip #external $./external.ip
#internal $./internal.ip #internal $./internal.ip
# this is just an alternative form fo giving external and internal address # this is just an alternative form for giving external and internal address
# allows you to read this addresses from files # allows you to read this addresses from files
auth none auth none
@ -149,7 +149,7 @@ tcppm 25 mail.my.provider 25
# Now we can use our proxy as SMTP and DNS server. # Now we can use our proxy as SMTP and DNS server.
# -s switch for UDP means "single packet" service - instead of setting # -s switch for UDP means "single packet" service - instead of setting
# association for period of time association will only be set for 1 packet. # association for period of time association will only be set for 1 packet.
# It's very userfull for services like DNS but not for some massive services # It's very useful for services like DNS but not for some massive services
# like multimedia streams or online games. # like multimedia streams or online games.
auth strong auth strong
@ -158,7 +158,7 @@ internal 127.0.0.1
allow 3APA3A 127.0.0.1 allow 3APA3A 127.0.0.1
maxconn 3 maxconn 3
admin admin
#only allow acces to admin interface for user 3APA3A from 127.0.0.1 address #only allow access to admin interface for user 3APA3A from 127.0.0.1 address
#via 127.0.0.1 address. #via 127.0.0.1 address.
# map external 80 and 443 ports to internal Web server # map external 80 and 443 ports to internal Web server
@ -178,14 +178,14 @@ admin
#chroot /usr/local/jail #chroot /usr/local/jail
#setgid 65535 #setgid 65535
#setuid 65535 #setuid 65535
# now we needn't any root rights. We can chroot and setgid/setuid. # now we no longer need root rights. We can chroot and setgid/setuid.
auth strong auth strong
flush flush
# We want to protect internal interface # We want to protect internal interface
deny * * 127.0.0.1,192.168.1.1 deny * * 127.0.0.1,192.168.1.1
# and llow HTTP and HTTPS traffic. # and allow HTTP and HTTPS traffic.
allow * * * 80-88,8080-8088 HTTP allow * * * 80-88,8080-8088 HTTP
allow * * * 443,8443 HTTPS allow * * * 443,8443 HTTPS
proxy -n proxy -n

View File

@ -1,10 +1,11 @@
man/3proxy.8 man/3proxy.8
man/3proxy.cfg.3 man/3proxy.cfg.5
man/ftppr.8 man/3proxy_ftppr.8
man/pop3p.8 man/3proxy_pop3p.8
man/tlspr.8 man/3proxy_tlspr.8
man/proxy.8 man/3proxy_proxy.8
man/smtpp.8 man/3proxy_smtpp.8
man/socks.8 man/3proxy_socks.8
man/tcppm.8 man/3proxy_tcppm.8
man/udppm.8 man/3proxy_udppm.8
man/3proxy_crypt.8

26
doc/changelog/0/7/0 Normal file
View File

@ -0,0 +1,26 @@
3proxy 0.7
This release is partially forced: while no new significant functions are
added, 0.7 is code is much more stable and less buggy than 0.6. Since
there is no new development for a long time, except few minor bugfixes,
I decided to finally release 0.7. You may want it if you:
Use HTTP proxy
Use 3proxy under *BSD/Mac OS X/iPhone OS
Use plugins, specially traffic related ones, like PCRE.
I have no time for active developement. There are interesting features
in nearly ready state, e.g. SSL support / SSL decryption via
certificates spoofing, NAT support and SSL auto-detection. You can step
into development, if you are interested.
There are some configuration changes:
auth iponly is now default (because most misconfigurations were
because of default auth none)
maxconn is now 500 by default (because WebKit browsers ignore
standards and create a lot of connections even if proxy is configured)
NTLM is disabled by default (-n options, -n1 to enable) because
NTLMv1 is disabled by default in Windows since Vista and there is no
NTLMv2 library with compatible license. Report me, if any.

35
doc/changelog/0/7/1 Normal file
View File

@ -0,0 +1,35 @@
3proxy-0.7.1.4
!! Fix transparent flag not reset after keep-alive connection, can lead to
3proxy-0.7.1.3
! traffic displayed incorrectly
! archiver doesn't add suffix if logname contains macro
! fix potential race condition on configuration reload
! fix FTP over HTTP authentication
3proxy-0.7.1.2
! Request / header size limitation relaxed for HTTP proxy
3proxy 0.7.1.1
! Linux compilation issues resolved
3proxy 0.7.1
Minor improvements and bugfixes:
+ Windows icons added
+ Warnings added for most common misconfigurations
+ ftppr NLSD command supported
! Ignore NTLM handshake if NTLM is not enabled
!! memcpy replaced with memmove for overlapped region
! better EINTR handling on *nix
! FTP proxy debugging output removed (introduced in 0.7), binding for data connection corrected
! memory leak fixed in ldapauth plugin

9
doc/changelog/0/8/0 Normal file
View File

@ -0,0 +1,9 @@
+ IPv6 support
+ back connect support
+ name resolution over TCP, parent proxy support for dnspr
+ SSLPlugin for TLS/SSL traffic decryption
! multiple race conditions fixed
! reduced memory usage
! Generate Forwarded: header instead of X-Forwarded-For:
! Default name resolution is non-blocking in *nix
! multiple race conditions fixed on configuration reload

1
doc/changelog/0/8/1 Normal file
View File

@ -0,0 +1 @@
!!Fix: destination IP may be not checked against ACL

2
doc/changelog/0/8/10 Normal file
View File

@ -0,0 +1,2 @@
! Fix: parent proxy can be used in some cases where it shouldn't
! Fix: bandlimiters may not work for older connections on configuration reload

9
doc/changelog/0/8/11 Normal file
View File

@ -0,0 +1,9 @@
Minor bugfixes / improvements:
! Fixed: deadlock on insufficient resources
! Fixed: race condition in ssl_plugin
! Fixed: minor memory leak on configuration reload
! Fixed: recursion detection was not working
! Fixed: %n for IPv6 in logging terminates log record
! Fixed: reverse PTR validation (required for dnsauth)
! Fixed: error on external 0.0.0.0 for NOIPV6 (light version)
+ Better support for IPv6 in ftppr

5
doc/changelog/0/8/12 Normal file
View File

@ -0,0 +1,5 @@
Bugfixes:
! Fixed hostname support in SOCKSv5 UDP portmapping
! -fno-strict-aliasing added to gcc options (compiling without this option can lead to unpredictable issues under Debian with gcc 6 and potentially others)
! Fixed LDAP plugin compilation issues (LDAP plugin is still listed as unsupported though)
and some minor fixes and improvements.

3
doc/changelog/0/8/13 Normal file
View File

@ -0,0 +1,3 @@
Bugfixes:
!! Fixed out-of-bound write and few minor bugs on configuration saving in admin
! fixed: $ is not correctly handled in the beginning of quoted line on configuration parsing

3
doc/changelog/0/8/2 Normal file
View File

@ -0,0 +1,3 @@
!! Fix transparent flag not reset after keep-alive connection, can lead to DoS by authenticated user.
! Do not use SO_REUSEADDR by default (leads to random 00013 errors under some glibc versions)
! Use SASIZE() instead of sizeof() in bind() for FreeBSD compatibility

1
doc/changelog/0/8/3 Normal file
View File

@ -0,0 +1 @@
! fixed: use SASIZE() instead of sizeof() in connect() for FreeBSD compatibility

5
doc/changelog/0/8/4 Normal file
View File

@ -0,0 +1,5 @@
+ Build PamPlugin on *nix
+ stacksize and -S options, stacksize defaults changed for FreeBSD
+ extip redirection type added
! SSL plugin fix to correct handling of certificates path
! fixed random errors on IPv6 connect

1
doc/changelog/0/8/5 Normal file
View File

@ -0,0 +1 @@
!Fix: mutex was used prior to initialization on 'log' command processing

1
doc/changelog/0/8/6 Normal file
View File

@ -0,0 +1 @@
! Fix: random 00012 errors in some configurations

15
doc/changelog/0/8/7 Normal file
View File

@ -0,0 +1,15 @@
! Fix 'daemon' command for Linux
! Fix 'extip' redirections 00009 errors
! Fix counters for older Win platforms
! Resolve logging race conditions
! attempt to fix pam_auth race conditions
! FTP proxy workaround for broken gethostname() on some libc limplementations
! authcache IP matching corrected
! fix SOCKSv5 BIND/UDP ASSOC
! use setreuid/setregid instead of setuid / setgid
+ OpenWatcom makefiles for Windows
+ -u2 support for proxy
+ support %i in logformat
+ force/noforce configuration commands to disconnect / do not disconnect clients if nolonger match ACL after configuration change
+ support longer external passwords

3
doc/changelog/0/8/8 Normal file
View File

@ -0,0 +1,3 @@
!! Fix resolver for non-compressed reply parsing (on mixed-case sensitive resolvers)
! Fix plugins export on OpenWatcom compiler (light version)
! Fix SOCKSv5

1
doc/changelog/0/8/9 Normal file
View File

@ -0,0 +1 @@
! Fix: tcppm may fail if used with parent proxy

6
doc/changelog/0/9/0 Normal file
View File

@ -0,0 +1,6 @@
+ Socket options, interface binding
+ Connection limiting / connection rate limiting
+ RADIUS support (beta)
+ Zero copy (splice) support for Linux
+ Possibility to limit user to single IP (via authentication cache)
! bugfixes, improvements

8
doc/changelog/0/9/1 Normal file
View File

@ -0,0 +1,8 @@
Bugfixes:
! Fixed: socket may be closed before all data received/sent
! Fixed: bandlimin non-working
! Fixed: countall/nocountall
! Fixed: few race conditions
Improvements:
+ deb/rpm build, systemd support (experimental)

9
doc/changelog/0/9/2 Normal file
View File

@ -0,0 +1,9 @@
Bugfixes:
! Fixed: bandwidth limiters (once again)
! Fixed: data filtering plugins (PCREPlugin, SSLPlugin). SSLPlugin use on Linux requires to disable splice (-s0)
! FIxed: standalone proxies do not react on HUP (Ctrl+C) in Linux/Unix
! Fixed: few minor bugs
Improvements:
+ deb for arm platforms (experimental)
+ Openssl 1.1 support for SSLPlugin

11
doc/changelog/0/9/3 Normal file
View File

@ -0,0 +1,11 @@
Bugfixes:
! Fixed: systemd description file (proxy may fail to start after reboot or via systemctl)
! Fixed: group/account creation in installation scripts
! Fixed: countall/nocounall do not work in some configurations
! Fixed: counters do not work if counter file is not specified
! Fixed: counters without rotation (type N) are incorrectly shown in web admin interface
! Fixed: %n may be incomplete or missed in long log records
! Fixed: connect back functionality does not work
Improvements:
+ Docker builds

4
doc/changelog/0/9/4 Normal file
View File

@ -0,0 +1,4 @@
! Fix: invalid handling of '-' character in ACL hostname
! Fix: minor bugfixes and improvements
+ parentretry command added (defaults to 2) to retry connections to parent proxies
- icqpr related code (OSCAR proxy) removed, due to drop of OSCAR support by messengers

7
doc/changelog/0/9/5 Normal file
View File

@ -0,0 +1,7 @@
!! Security fix: proxy can potentially crash on on some platforms due to overlapping regions in strcpy() (thanks to @lenix123 for reporting)
+ new proxy service type: `tlspr` - SNI proxy, may also be used as parent `tls` type, sniffs hostname from TLS handhake, read more in https://github.com/3proxy/3proxy/wiki/tlspr https://github.com/3proxy/3proxy/wiki/How-To-(incomplete)#TLSPR
+ new proxy service type: `auto` - autodetect proxy type between `proxy` and `socks`
+ SSLPlugin is rewritten, production-ready, supports TLS (SSL) server (may be used to create https:// type proxy), certificates checks and cypher options, see https://github.com/3proxy/3proxy/wiki/SSLPlugin
+ -g option is added for grace delay to reduce CPU load, see https://github.com/3proxy/3proxy/wiki/High-Load
! Multiple minor bugfixes
! More supported sockets options

9
doc/changelog/0/9/6 Normal file
View File

@ -0,0 +1,9 @@
+ ssl_client and multiple configuration options added to SSLPlugin, SSLPlugin code significantly improved and bugfixed. See https://github.com/3proxy/3proxy/wiki/SSLPlugin. 3proxy can now be used as stunnel replacement for many scenarios.
+ HAProxy proxy protocol v1 support as client and server, add -H option for service to expect HA proxy v1 protocol header, use ha parent type: parent 1000 ha 0.0.0.0 0 to send v1 header.
+ tlspr is supported in auto
+ tlspr supports -s option, it breaks HELLO packet to prevent some DPIs from detecting SNI
+ maxseg configuration option and TCP_MAXSEG socket flag support added. It sets maximum size of TCP segment to fix PathMTU discovery problems
+ -Ne / -Ni options added to specify external / internal NAT address for SOCKSv5
+ cmake environment added
! External pcre2 (pcre2-8) library is used for PCRE, pcre code is removed from 3proxy
! Multiple minor bugfixes

View File

@ -33,8 +33,9 @@
<li><a href="#NAMES">How to resolve names through a parent proxy</a></li> <li><a href="#NAMES">How to resolve names through a parent proxy</a></li>
<li><a href="#ISFTP">How to set up an FTP proxy</a></li> <li><a href="#ISFTP">How to set up an FTP proxy</a></li>
<li><a href="#TLSPR">How to set up an SNI proxy (tlspr)</a></li> <li><a href="#TLSPR">How to set up an SNI proxy (tlspr)</a></li>
<li><a href="#SSLPLUGIN">How to set up TLS/SSL with SSLPlugin (https proxy, mTLS)</a></li> <li><a href="#SSLPLUGIN">How to set up TLS/SSL (https proxy, mTLS)</a></li>
<li><a href="#CERTIFICATES">How to create CA and certificates for SSLPlugin</a></li> <li><a href="#CERTIFICATES">How to create CA and certificates for SSL</a></li>
<li><a href="#PCRE">How to use PCRE filtering (regular expressions)</a></li>
<li><A HREF="#AUTH">How to limit service access</A> <li><A HREF="#AUTH">How to limit service access</A>
<li><A HREF="#USERS">How to create a user list</A> <li><A HREF="#USERS">How to create a user list</A>
<li><A HREF="#ACL">How to limit user access to resources</A> <li><A HREF="#ACL">How to limit user access to resources</A>
@ -49,6 +50,8 @@
<li><a href="#NSCACHING">How to configure name resolution and DNS caching</a> <li><a href="#NSCACHING">How to configure name resolution and DNS caching</a>
<li><a href="#IPV6">How to use IPv6</a> <li><a href="#IPV6">How to use IPv6</a>
<li><a href="#CONNBACK">How to use connect back</a> <li><a href="#CONNBACK">How to use connect back</a>
<li><a href="#HAPROXY">How to use HAProxy PROXY protocol</a>
<li><a href="#MAXSEG">How to set TCP maximum segment size (MSS)</a>
</ul> </ul>
<li><A HREF="#CLIENT">Client configuration</A> <li><A HREF="#CLIENT">Client configuration</A>
<li><A HREF="#ADMIN">Administering and information analysis</A> <li><A HREF="#ADMIN">Administering and information analysis</A>
@ -498,7 +501,7 @@ ISA 2004 proxy WEB.w3c (fields are TAB-delimited):
</pre> </pre>
ISA 2000/2004 firewall FWSEXTD.log (fields are TAB-delimited): ISA 2000/2004 firewall FWSEXTD.log (fields are TAB-delimited):
<pre> <pre>
&quot;- + L%C %U unnknown:0:0.0 N %Y-%m-%d &quot;- + L%C %U unknown:0:0.0 N %Y-%m-%d
%H:%M:%S fwsrv 3PROXY - %n %R %r %H:%M:%S fwsrv 3PROXY - %n %R %r
%D %O %I %r TCP Connect - - %D %O %I %r TCP Connect - -
- %E - - - - -&quot; - %E - - - - -&quot;
@ -637,9 +640,12 @@ allow *
proxy proxy
</pre> </pre>
</p> </p>
<li><a name="SSLPLUGIN"><i>How to set up TLS/SSL with SSLPlugin (https proxy, mTLS)</i></a> <li><a name="SSLPLUGIN"><i>How to set up TLS/SSL (https proxy, mTLS)</i></a>
<p> <p>
SSLPlugin provides TLS/SSL support for 3proxy. It can be used to: Since version 0.9.7, SSL/TLS support is built into 3proxy when compiled with OpenSSL
(WITH_SSL). Previously available as SSLPlugin, the functionality is now integrated
into the main binary. The plugin line is no longer required.
SSL/TLS support can be used to:
<ul> <ul>
<li>Create an https:// proxy (TLS-encrypted connection between client and proxy)</li> <li>Create an https:// proxy (TLS-encrypted connection between client and proxy)</li>
<li>Implement MITM for TLS traffic inspection</li> <li>Implement MITM for TLS traffic inspection</li>
@ -652,7 +658,6 @@ SSLPlugin provides TLS/SSL support for 3proxy. It can be used to:
<br>To create an https:// proxy, you need a server certificate and key. The certificate must not be self-signed <br>To create an https:// proxy, you need a server certificate and key. The certificate must not be self-signed
and should contain Subject Alternative Names (SAN) for the proxy hostname/IP. and should contain Subject Alternative Names (SAN) for the proxy hostname/IP.
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key ssl_server_key /etc/3proxy/certs/server.key
ssl_serv ssl_serv
@ -668,7 +673,6 @@ Configure clients to use https://proxy-host:3129/ as the proxy URL.
<b>Client certificate authentication (mTLS):</b> <b>Client certificate authentication (mTLS):</b>
<br>To require clients to authenticate with a certificate, use ssl_server_verify and provide the CA certificate: <br>To require clients to authenticate with a certificate, use ssl_server_verify and provide the CA certificate:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key ssl_server_key /etc/3proxy/certs/server.key
ssl_server_ca_file /etc/3proxy/certs/ca.crt ssl_server_ca_file /etc/3proxy/certs/ca.crt
@ -683,7 +687,6 @@ Only clients with a valid certificate signed by the CA can connect.
<b>MITM for TLS traffic inspection:</b> <b>MITM for TLS traffic inspection:</b>
<br>To intercept and decrypt TLS traffic, you need a CA certificate to generate spoofed server certificates: <br>To intercept and decrypt TLS traffic, you need a CA certificate to generate spoofed server certificates:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_ca_file /etc/3proxy/certs/ca.crt ssl_server_ca_file /etc/3proxy/certs/ca.crt
ssl_server_ca_key /etc/3proxy/certs/ca.key ssl_server_ca_key /etc/3proxy/certs/ca.key
ssl_client_verify ssl_client_verify
@ -701,7 +704,6 @@ Without ssl_client_verify, the proxy is vulnerable to MITM attacks.
<b>TLS client (connect to upstream via TLS):</b> <b>TLS client (connect to upstream via TLS):</b>
<br>To connect to upstream servers via TLS with client certificate authentication: <br>To connect to upstream servers via TLS with client certificate authentication:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_client_cert /etc/3proxy/certs/client.crt ssl_client_cert /etc/3proxy/certs/client.crt
ssl_client_key /etc/3proxy/certs/client.key ssl_client_key /etc/3proxy/certs/client.key
ssl_client_verify ssl_client_verify
@ -709,7 +711,29 @@ ssl_client_ca_file /etc/ssl/certs/ca-certificates.crt
ssl_cli ssl_cli
proxy -p3128 proxy -p3128
</pre> </pre>
<li><a name="CERTIFICATES"><i>How to create CA and certificates for SSLPlugin</i></a> <p>
<b>Conditional TLS for parent proxy (ssl_client_mode 3):</b>
<br>With ssl_client_mode 3, TLS handshake to parent proxy is performed only if the parent type ends with 's' (secure types). This allows mixing secure and non-secure parent proxies in the same configuration:
</p><pre>
ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key
ssl_client_mode 3
auth strong
allow user1
parent 1000 https parent1.example.com 443
allow user2
parent 1000 socks5 parent2.example.com 1080
ssl_serv
ssl_cli
proxy -p3128
ssl_noserv
ssl_nocli
</pre>
<p>
This creates an HTTPS proxy (ssl_serv) that accepts TLS connections from clients. For parent proxy connections, user1's traffic goes through an https parent with TLS encryption (secure type), while user2's traffic goes through a regular socks5 parent without TLS. Secure parent types include: tcps, https, connects, connect+s, socks4s, socks5s, socks4+s, socks5+s, pop3s, smtps, ftps.
</p>
<li><a name="CERTIFICATES"><i>How to create CA and certificates for SSL</i></a>
<p> <p>
<b>Creating a Certificate Authority (CA):</b> <b>Creating a Certificate Authority (CA):</b>
<br>For MITM or mTLS, you need a CA. Generate a CA private key and certificate: <br>For MITM or mTLS, you need a CA. Generate a CA private key and certificate:
@ -824,6 +848,65 @@ openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \
openssl pkcs12 -export -out client.p12 -passout pass: \ openssl pkcs12 -export -out client.p12 -passout pass: \
-inkey client.key -in client.crt -certfile ca.crt -inkey client.key -in client.crt -certfile ca.crt
</pre> </pre>
<li><a name="PCRE"><i>How to use PCRE filtering (regular expressions)</i></a>
<p>
Since version 0.9.7, PCRE (Perl Compatible Regular Expressions) filtering is built into
3proxy when compiled with PCRE2 support (WITH_PCRE). Previously available as PCREPlugin,
the functionality is now integrated into the main binary. The plugin line is no longer required.
</p>
<p>
PCRE filtering can be used to create matching and replacement rules with regular expressions
for client requests, client and server headers, and client and server data.
</p>
<p>
<b>Commands:</b>
</p><pre>
pcre TYPE FILTER_ACTION REGEXP [ACE]
pcre_rewrite TYPE FILTER_ACTION REGEXP REWRITE_EXPRESSION [ACE]
pcre_extend FILTER_ACTION [ACE]
pcre_options OPTION1 [...]
</pre>
<p>
<ul>
<li><b>TYPE</b> - type of filtered data (comma-delimited list):
<ul>
<li><b>request</b> - content of the client's request (e.g., HTTP GET request string)
<li><b>cliheader</b> - content of the client request headers
<li><b>srvheader</b> - content of the server's reply headers
<li><b>clidata</b> - data received from the client (e.g., HTTP POST data)
<li><b>srvdata</b> - data received from the server (e.g., HTML page)
</ul>
<li><b>FILTER_ACTION</b> - action on match:
<ul>
<li><b>allow</b> - allow this request without checking the rest of the rules
<li><b>deny</b> - deny this request without checking the rest of the rules
<li><b>dunno</b> - continue with the rest of the rules (useful with pcre_rewrite)
</ul>
<li><b>REGEXP</b> - PCRE (Perl) regular expression. Use * if no regexp matching is required.
<li><b>REWRITE_EXPRESSION</b> - substitution string. May contain Perl-style substrings
$1, $2, etc. $0 means the whole matched string. \r and \n may be used to insert new lines.
<li><b>ACE</b> - access control entry (user names, source IPs, destination IPs, ports, etc.),
identical to allow/deny/bandlimin commands. The regular expression is only matched if the ACL
matches the connection data.
</ul>
</p>
<p>
<b>Examples:</b>
</p><pre>
# Block requests containing specific keywords for certain users
pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16
# Block responses with specific content type
pcre srvheader deny "Content-type: application"
# Replace content in both directions (censorship)
pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser
pcre_extend deny * 192.168.0.1/16
</pre>
<p>
<b>Note:</b> Regular expressions don't require authentication and cannot replace
authentication and/or allow/deny ACLs.
</p>
<li><A NAME="AUTH">How to limit service access</A> <li><A NAME="AUTH">How to limit service access</A>
<p> <p>
First, always specify the internal interface to accept incoming connections with the First, always specify the internal interface to accept incoming connections with the
@ -944,7 +1027,7 @@ or
<pre> <pre>
users $"c:\Program Files\3proxy\passwords" users $"c:\Program Files\3proxy\passwords"
</pre> </pre>
It's possible to create NT and crypt passwords with the mycrypt utility included It's possible to create NT and crypt passwords with the 3proxy_crypt utility included
in the distribution. in the distribution.
<br>The user list is system-wide. To manage user access to a specific service, use ACLs. <br>The user list is system-wide. To manage user access to a specific service, use ACLs.
</p> </p>
@ -1278,6 +1361,53 @@ allowed traffic in megabytes (MB). nocountin allows you to set exclusions.
allow * * 1.1.1.1 allow * * 1.1.1.1
tcppm -R0.0.0.0:1234 3128 1.1.1.1 3128</pre> tcppm -R0.0.0.0:1234 3128 1.1.1.1 3128</pre>
For browser settings, the proxy is host.dyndns.example.org:3128. For browser settings, the proxy is host.dyndns.example.org:3128.
</p>
<li><a name="HAPROXY"><i>How to use HAProxy PROXY protocol</i></a>
<p>
3proxy supports HAProxy PROXY protocol v1 for both receiving and sending client
IP information. This is useful when 3proxy is behind a load balancer or when
passing client information to a parent proxy.
</p>
<p>
<b>Receiving PROXY protocol header:</b>
<br>Use the <code>-H</code> option to make 3proxy expect a PROXY protocol v1 header
on incoming connections. This allows 3proxy to receive the real client IP address
from HAProxy or another load balancer:
</p><pre>
proxy -H -p3128
socks -H -p1080
</pre>
<p>
The PROXY protocol header must be sent before any protocol-specific data.
</p>
<p>
<b>Sending PROXY protocol header to parent proxy:</b>
<br>Use the <code>ha</code> parent type to send a PROXY protocol v1 header to
the parent proxy. This must be the last parent in the chain:
</p><pre>
allow *
parent 1000 ha
parent 1000 socks5 parent.example.com 1080
socks
</pre>
<p>
This configuration sends the client IP information to the SOCKS5 parent proxy
via the PROXY protocol.
</p>
<li><a name="MAXSEG"><i>How to set TCP maximum segment size (MSS)</i></a>
<p>
Use the <code>maxseg</code> command to set the TCP maximum segment size (MSS)
for outgoing connections. This can be useful to work around path MTU discovery
issues or to optimize traffic for specific network conditions:
</p><pre>
maxseg 1400
proxy -p3128 -OcTCP_NODELAY,TCP_MAXSEG -OsTCP_NODELAY,TCP_MAXSEG
</pre>
<p>
The value is specified in bytes. This setting uses the TCP_MAXSEG socket option
and may not be supported on all platforms. A typical use case is to reduce MSS
to avoid fragmentation in VPN tunnels or to work around MTU issues with certain
network paths.
</p> </p>
</ul> </ul>

View File

@ -33,8 +33,9 @@
<li><a href="#NAMES">Как разрешать имена на родительском прокси?</a></li> <li><a href="#NAMES">Как разрешать имена на родительском прокси?</a></li>
<li><a href="#ISFTP">Как настроить FTP прокси?</a></li> <li><a href="#ISFTP">Как настроить FTP прокси?</a></li>
<li><a href="#TLSPR">Как настроить SNI proxy (tlspr)</a></li> <li><a href="#TLSPR">Как настроить SNI proxy (tlspr)</a></li>
<li><a href="#SSLPLUGIN">Как настроить TLS/SSL с помощью SSLPlugin (https прокси, mTLS)</a></li> <li><a href="#SSLPLUGIN">Как настроить TLS/SSL (https прокси, mTLS)</a></li>
<li><a href="#CERTIFICATES">Как создать CA и сертификаты для SSLPlugin</a></li> <li><a href="#CERTIFICATES">Как создать CA и сертификаты для SSL</a></li>
<li><a href="#PCRE">Как использовать PCRE-фильтрацию (регулярные выражения)</a></li>
<li><a href="#AUTH">Как ограничить доступ к службе</a> <li><a href="#AUTH">Как ограничить доступ к службе</a>
<li><a href="#USERS">Как создать список пользователей</a> <li><a href="#USERS">Как создать список пользователей</a>
<li><a href="#ACL">Как ограничить доступ пользователей к ресурсам</a> <li><a href="#ACL">Как ограничить доступ пользователей к ресурсам</a>
@ -48,6 +49,8 @@
<li><a href="#NSCACHING">Как управлять разрешением имен и кэшированием DNS</a> <li><a href="#NSCACHING">Как управлять разрешением имен и кэшированием DNS</a>
<li><a href="#IPV6">Как использовать IPv6</a> <li><a href="#IPV6">Как использовать IPv6</a>
<li><a href="#CONNBACK">Как использовать connect back</a> <li><a href="#CONNBACK">Как использовать connect back</a>
<li><a href="#HAPROXY">Как использовать протокол HAProxy PROXY</a>
<li><a href="#MAXSEG">Как установить максимальный размер сегмента TCP (MSS)</a>
</ul> </ul>
<li><a href="#CLIENT">Конфигурация и настройка клиентов</a> <li><a href="#CLIENT">Конфигурация и настройка клиентов</a>
<ul> <ul>
@ -511,7 +514,7 @@
- Internal External 0x0 Allowed&quot;</pre> - Internal External 0x0 Allowed&quot;</pre>
Формат ISA 2000/2004 firewall FWSEXTD.log (поля разделены табуляцией): Формат ISA 2000/2004 firewall FWSEXTD.log (поля разделены табуляцией):
<pre> <pre>
&quot;- + L%C %U unnknown:0:0.0 N %Y-%m-%d &quot;- + L%C %U unknown:0:0.0 N %Y-%m-%d
%H:%M:%S fwsrv 3PROXY - %n %R %r %H:%M:%S fwsrv 3PROXY - %n %R %r
%D %O %I %r TCP Connect - - %D %O %I %r TCP Connect - -
- %E - - - - -&quot;</pre> - %E - - - - -&quot;</pre>
@ -646,9 +649,12 @@ proxy
</pre> </pre>
</p> </p>
<li><a name="SSLPLUGIN"><i>Как настроить TLS/SSL с помощью SSLPlugin (https прокси, mTLS)</i></a> <li><a name="SSLPLUGIN"><i>Как настроить TLS/SSL (https прокси, mTLS)</i></a>
<p> <p>
SSLPlugin обеспечивает поддержку TLS/SSL для 3proxy. Он может использоваться для: Начиная с версии 0.9.7 поддержка TLS/SSL встроена в 3proxy при компиляции с OpenSSL
(WITH_SSL). Ранее доступная как SSLPlugin, функциональность теперь интегрирована
в основной бинарный файл. Строка plugin больше не нужна.
TLS/SSL может использоваться для:
<ul> <ul>
<li>Создания https:// прокси (TLS-шифрованное соединение между клиентом и прокси)</li> <li>Создания https:// прокси (TLS-шифрованное соединение между клиентом и прокси)</li>
<li>Реализации MITM для инспекции TLS-трафика</li> <li>Реализации MITM для инспекции TLS-трафика</li>
@ -661,7 +667,6 @@ SSLPlugin обеспечивает поддержку TLS/SSL для 3proxy. О
<br>Для создания https:// прокси требуется сертификат и ключ сервера. Сертификат не должен быть самоподписанным <br>Для создания https:// прокси требуется сертификат и ключ сервера. Сертификат не должен быть самоподписанным
и должен содержать альтернативные имена (SAN) для имени хоста/IP прокси. и должен содержать альтернативные имена (SAN) для имени хоста/IP прокси.
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key ssl_server_key /etc/3proxy/certs/server.key
ssl_serv ssl_serv
@ -677,7 +682,6 @@ proxy -p3128
<b>Аутентификация по клиентскому сертификату (mTLS):</b> <b>Аутентификация по клиентскому сертификату (mTLS):</b>
<br>Чтобы требовать от клиентов аутентификацию по сертификату, используйте ssl_server_verify и укажите CA-сертификат: <br>Чтобы требовать от клиентов аутентификацию по сертификату, используйте ssl_server_verify и укажите CA-сертификат:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key ssl_server_key /etc/3proxy/certs/server.key
ssl_server_ca_file /etc/3proxy/certs/ca.crt ssl_server_ca_file /etc/3proxy/certs/ca.crt
@ -692,7 +696,6 @@ proxy -p3129
<b>MITM для инспекции TLS-трафика:</b> <b>MITM для инспекции TLS-трафика:</b>
<br>Для перехвата и расшифровки TLS-трафика требуется CA-сертификат для генерации подделанных серверных сертификатов: <br>Для перехвата и расшифровки TLS-трафика требуется CA-сертификат для генерации подделанных серверных сертификатов:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_ca_file /etc/3proxy/certs/ca.crt ssl_server_ca_file /etc/3proxy/certs/ca.crt
ssl_server_ca_key /etc/3proxy/certs/ca.key ssl_server_ca_key /etc/3proxy/certs/ca.key
ssl_client_verify ssl_client_verify
@ -710,7 +713,6 @@ CA-сертификат должен быть доверенным для кли
<b>TLS-клиент (соединение с вышестоящим сервером через TLS):</b> <b>TLS-клиент (соединение с вышестоящим сервером через TLS):</b>
<br>Для соединения с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату: <br>Для соединения с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату:
</p><pre> </p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_client_cert /etc/3proxy/certs/client.crt ssl_client_cert /etc/3proxy/certs/client.crt
ssl_client_key /etc/3proxy/certs/client.key ssl_client_key /etc/3proxy/certs/client.key
ssl_client_verify ssl_client_verify
@ -718,7 +720,29 @@ ssl_client_ca_file /etc/ssl/certs/ca-certificates.crt
ssl_cli ssl_cli
proxy -p3128 proxy -p3128
</pre> </pre>
<li><a name="CERTIFICATES"><i>Как создать CA и сертификаты для SSLPlugin</i></a> <p>
<b>Условное TLS для parent прокси (ssl_client_mode 3):</b>
<br>При ssl_client_mode 3 TLS-рукопожатие с родительским прокси выполняется только если тип parent прокси заканчивается на 's' (защищённые типы). Это позволяет смешивать защищённые и незащищённые родительские прокси в одной конфигурации:
</p><pre>
ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key
ssl_client_mode 3
auth strong
allow user1
parent 1000 https parent1.example.com 443
allow user2
parent 1000 socks5 parent2.example.com 1080
ssl_serv
ssl_cli
proxy -p3128
ssl_noserv
ssl_nocli
</pre>
<p>
Создаётся HTTPS-прокси (ssl_serv), принимающий TLS-соединения от клиентов. Для соединений с родительским прокси трафик user1 идёт через https родитель с TLS-шифрованием (защищённый тип), а трафик user2 — через обычный socks5 родитель без TLS. Защищённые типы parent прокси: tcps, https, connects, connect+s, socks4s, socks5s, socks4+s, socks5+s, pop3s, smtps, ftps.
</p>
<li><a name="CERTIFICATES"><i>Как создать CA и сертификаты для SSL</i></a>
<p> <p>
<b>Создание удостоверяющего центра (CA):</b> <b>Создание удостоверяющего центра (CA):</b>
<br>Для MITM или mTLS требуется CA. Сгенерируйте закрытый ключ CA и сертификат: <br>Для MITM или mTLS требуется CA. Сгенерируйте закрытый ключ CA и сертификат:
@ -834,6 +858,66 @@ openssl pkcs12 -export -out client.p12 -passout pass: \
-inkey client.key -in client.crt -certfile ca.crt -inkey client.key -in client.crt -certfile ca.crt
</pre> </pre>
<li><a name="PCRE"><i>Как использовать PCRE-фильтрацию (регулярные выражения)</i></a>
<p>
Начиная с версии 0.9.7 фильтрация PCRE встроена в 3proxy при компиляции с поддержкой
PCRE2 (WITH_PCRE). Ранее доступная как PCREPlugin, функциональность теперь интегрирована
в основной бинарный файл. Строка plugin больше не нужна.
</p>
<p>
PCRE-фильтрация может использоваться для создания правил поиска и замены с регулярными
выражениями для запросов клиентов, заголовков клиента и сервера, а также данных.
</p>
<p>
<b>Команды:</b>
</p><pre>
pcre TYPE FILTER_ACTION REGEXP [ACE]
pcre_rewrite TYPE FILTER_ACTION REGEXP REWRITE_EXPRESSION [ACE]
pcre_extend FILTER_ACTION [ACE]
pcre_options OPTION1 [...]
</pre>
<p>
<ul>
<li><b>TYPE</b> - тип фильтруемых данных (список через запятую):
<ul>
<li><b>request</b> - содержимое запроса клиента (например, строка HTTP GET-запроса)
<li><b>cliheader</b> - содержимое заголовков запроса клиента
<li><b>srvheader</b> - содержимое заголовков ответа сервера
<li><b>clidata</b> - данные полученные от клиента (например, данные POST-запроса)
<li><b>srvdata</b> - данные полученные от сервера (например, HTML-страница)
</ul>
<li><b>FILTER_ACTION</b> - действие при совпадении:
<ul>
<li><b>allow</b> - разрешить запрос без проверки остальных правил
<li><b>deny</b> - запретить запрос без проверки остальных правил
<li><b>dunno</b> - продолжить проверку правил (полезно для pcre_rewrite)
</ul>
<li><b>REGEXP</b> - регулярное выражение PCRE (Perl). Используйте * если проверка не требуется.
<li><b>REWRITE_EXPRESSION</b> - строка замены. Может содержать Perl-подстановки
$1, $2 и т.д. $0 - вся найденная подстрока. \r и \n для вставки новых строк.
<li><b>ACE</b> - элемент списка контроля доступа (имена пользователей, IP источника,
IP назначения, порты и т.д.), аналогичный командам allow/deny/bandlimin.
Регулярное выражение проверяется только при совпадении ACL с данными соединения.
</ul>
</p>
<p>
<b>Примеры:</b>
</p><pre>
# Блокировать запросы с определёнными ключевыми словами для некоторых пользователей
pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16
# Блокировать ответы с определённым content-type
pcre srvheader deny "Content-type: application"
# Замена содержимого в обоих направлениях (цензура)
pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser
pcre_extend deny * 192.168.0.1/16
</pre>
<p>
<b>Примечание:</b> Регулярные выражения не требуют авторизации и не могут заменить
авторизацию и/или ACL allow/deny.
</p>
<li><a name="AUTH"><i>Как ограничить доступ к службе</i></a> <li><a name="AUTH"><i>Как ограничить доступ к службе</i></a>
<p> <p>
Во-первых, для ограничения доступа необходимо указать внутренний интерфейс, Во-первых, для ограничения доступа необходимо указать внутренний интерфейс,
@ -958,7 +1042,7 @@ openssl pkcs12 -export -out client.p12 -passout pass: \
или или
<pre> <pre>
users $"c:\Program Files\3proxy\passwords"</pre> users $"c:\Program Files\3proxy\passwords"</pre>
Шифрованные NT и crypt пароли можно создавать с помощью утилиты mycrypt. Шифрованные NT и crypt пароли можно создавать с помощью утилиты 3proxy_crypt.
<br>Список пользователей един для всех служб. Разграничение доступа по службам <br>Список пользователей един для всех служб. Разграничение доступа по службам
необходимо производить с помощью списков доступа. необходимо производить с помощью списков доступа.
</p> </p>
@ -1336,6 +1420,54 @@ openssl pkcs12 -export -out client.p12 -passout pass: \
tcppm -R0.0.0.0:1234 3128 1.1.1.1 3128</pre> tcppm -R0.0.0.0:1234 3128 1.1.1.1 3128</pre>
В настройках браузера указывается host.dyndns.example.org:3128. В настройках браузера указывается host.dyndns.example.org:3128.
</p> </p>
<li><a name="HAPROXY"><i>Как использовать протокол HAProxy PROXY</i></a>
<p>
3proxy поддерживает протокол HAProxy PROXY v1 как для приёма, так и для
отправки информации об IP-адресе клиента. Это полезно, когда 3proxy находится
за балансировщиком нагрузки или при передаче информации о клиенте родительскому прокси.
</p>
<p>
<b>Приём заголовка PROXY протокола:</b>
<br>Используйте опцию <code>-H</code>, чтобы 3proxy ожидал заголовок PROXY протокола v1
на входящих соединениях. Это позволяет 3proxy получать реальный IP-адрес клиента
от HAProxy или другого балансировщика нагрузки:
</p><pre>
proxy -H -p3128
socks -H -p1080
</pre>
<p>
Заголовок PROXY протокола должен быть отправлен до любых протокольных данных.
</p>
<p>
<b>Отправка заголовка PROXY протокола родительскому прокси:</b>
<br>Используйте тип родительского прокси <code>ha</code> для отправки заголовка
PROXY протокола v1 родительскому прокси. Это должен быть последний родитель в цепочке:
</p><pre>
allow *
parent 1000 ha
parent 1000 socks5 parent.example.com 1080
socks
</pre>
<p>
Эта конфигурация отправляет информацию об IP-адресе клиента SOCKS5 родительскому
прокси через PROXY протокол.
</p>
<li><a name="MAXSEG"><i>Как установить максимальный размер сегмента TCP (MSS)</i></a>
<p>
Используйте команду <code>maxseg</code> для установки максимального размера
сегмента TCP (MSS) для исходящих соединений. Это может быть полезно для обхода
проблем с Path MTU Discovery или для оптимизации трафика в специфических
сетевых условиях:
</p><pre>
maxseg 1400
proxy -p3128 -OcTCP_NODELAY,TCP_MAXSEG -OsTCP_NODELAY,TCP_MAXSEG
</pre>
<p>
Значение указывается в байтах. Эта настройка использует опцию сокета TCP_MAXSEG
и может не поддерживаться на всех платформах. Типичный случай использования -
уменьшение MSS для избежания фрагментации в VPN туннелях или для обхода проблем
с MTU на определённых сетевых путях.
</p>
</ul> </ul>
<hr> <hr>
<li><a name="CLIENT"><b>Конфигурация клиентов</b></a> <li><a name="CLIENT"><b>Конфигурация клиентов</b></a>

View File

@ -4,6 +4,7 @@
<a href="howtoe.html">How To (English, very incomplete)</a><br> <a href="howtoe.html">How To (English, very incomplete)</a><br>
<a href="howtor.html">How To (Russian)</a><br> <a href="howtor.html">How To (Russian)</a><br>
<h3>Man pages:</h3> <h3>Man pages:</h3>
<br><A HREF="man8/3proxy_crypt.8.html">3proxy_crypt.8</A>
<br><A HREF="man8/3proxy.8.html">3proxy.8</A> <br><A HREF="man8/3proxy.8.html">3proxy.8</A>
<br><A HREF="man8/ftppr.8.html">ftppr.8</A> <br><A HREF="man8/ftppr.8.html">ftppr.8</A>
<br><A HREF="man8/pop3p.8.html">pop3p.8</A> <br><A HREF="man8/pop3p.8.html">pop3p.8</A>
@ -13,5 +14,5 @@
<br><A HREF="man8/tcppm.8.html">tcppm.8</A> <br><A HREF="man8/tcppm.8.html">tcppm.8</A>
<br><A HREF="man8/tlspr.8.html">tlspr.8</A> <br><A HREF="man8/tlspr.8.html">tlspr.8</A>
<br><A HREF="man8/udppm.8.html">udppm.8</A> <br><A HREF="man8/udppm.8.html">udppm.8</A>
<br><A HREF="man3/3proxy.cfg.3.html">3proxy.cfg.3</A> <br><A HREF="man5/3proxy.cfg.5.html">3proxy.cfg.5</A>
</body></html> </body></html>

View File

@ -195,7 +195,7 @@ to <b>3proxy@3proxy.org</b></p>
</h2> </h2>
<p style="margin-left:6%; margin-top: 1em">3proxy.cfg(3), <p style="margin-left:6%; margin-top: 1em">3proxy.cfg(5),
proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8),
kill(1), syslogd(8), <br> kill(1), syslogd(8), <br>
https://3proxy.org/</p> https://3proxy.org/</p>

View File

@ -0,0 +1,168 @@
<!-- Creator : groff version 1.24.1 -->
<html>
<head>
</head>
<body>
<h1 align="center">3proxy_crypt</h1>
<a href="#NAME">NAME</a><br>
<a href="#SYNOPSIS">SYNOPSIS</a><br>
<a href="#DESCRIPTION">DESCRIPTION</a><br>
<a href="#OPTIONS">OPTIONS</a><br>
<a href="#EXAMPLE">EXAMPLE</a><br>
<a href="#NOTES">NOTES</a><br>
<a href="#BUGS">BUGS</a><br>
<a href="#SEE ALSO">SEE ALSO</a><br>
<a href="#AUTHORS">AUTHORS</a><br>
<hr>
<h2>NAME
<a name="NAME"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em"><b>3proxy_crypt</b>
- utility to generate encrypted passwords for 3proxy</p>
<h2>SYNOPSIS
<a name="SYNOPSIS"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em"><b>3proxy_crypt</b>
<i>password</i> <b><br>
3proxy_crypt</b> <i>salt password</i></p>
<h2>DESCRIPTION
<a name="DESCRIPTION"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em"><i><b>3proxy_crypt</b></i>
is a utility to generate encrypted password hashes for use
with 3proxy configuration. Encrypted passwords allow the
system to avoid storing passwords in cleartext in
configuration files.</p>
<p style="margin-left:6%; margin-top: 1em">When invoked
with a single argument, it produces an NT password hash
(MD4-based, suitable for NTLM authentication). The output is
prefixed with <b>NT:</b>.</p>
<p style="margin-left:6%; margin-top: 1em">When invoked
with two arguments (salt and password), it produces a
BLAKE2b password hash. The salt length is limited to 64
characters. The output is prefixed with <b>CR:</b>.</p>
<p style="margin-left:6%; margin-top: 1em">The resulting
hash can be used in the 3proxy configuration file with the
<b>users</b> directive instead of a cleartext password.</p>
<h2>OPTIONS
<a name="OPTIONS"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em"><i>password</i></p>
<p style="margin-left:15%;">Cleartext password to
encrypt.</p>
<table width="100%" border="0" rules="none" frame="void"
cellspacing="0" cellpadding="0">
<tr valign="top" align="left">
<td width="6%"></td>
<td width="5%">
<p><i>salt</i></p></td>
<td width="4%"></td>
<td width="65%">
<p>Salt string for BLAKE2b hashing (max 64 characters).</p></td>
<td width="20%">
</td></tr>
</table>
<h2>EXAMPLE
<a name="EXAMPLE"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em">Generate NT
password hash:</p>
<p style="margin-left:15%;">3proxy_crypt
MySecretPassword</p>
<p style="margin-left:6%;">Result:</p>
<p style="margin-left:15%;">NT:3F7E6D8D96E8E7A9B0C1D2E3F4A5B6C7</p>
<p style="margin-left:6%;">Generate BLAKE2b password hash
with salt:</p>
<p style="margin-left:15%;">3proxy_crypt MySalt
MySecretPassword</p>
<p style="margin-left:6%;">Result:</p>
<p style="margin-left:15%;">CR:$3$MySalt$...</p>
<p style="margin-left:6%;">Using in 3proxy.cfg:</p>
<p style="margin-left:15%;">users
user1:CR:$3$MySalt$...</p>
<h2>NOTES
<a name="NOTES"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em">The NT hash uses
the RSA MD4 Message-Digest Algorithm. The BLAKE2b hash uses
the BLAKE2 cryptographic hash function.</p>
<p style="margin-left:6%; margin-top: 1em">When a password
hash is prefixed with <b>NT:</b> or <b>CR:</b>, 3proxy uses
the corresponding algorithm to verify passwords instead of
comparing cleartext strings.</p>
<h2>BUGS
<a name="BUGS"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em">Report all bugs
to <b>3proxy@3proxy.org</b></p>
<h2>SEE ALSO
<a name="SEE ALSO"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em">3proxy(8),
3proxy.cfg(5), <br>
https://3proxy.org/</p>
<h2>AUTHORS
<a name="AUTHORS"></a>
</h2>
<p style="margin-left:6%; margin-top: 1em">3proxy is
designed by Vladimir 3APA3A Dubrovin
(<i>3proxy@3proxy.org</i>)</p>
<hr>
</body>
</html>

View File

@ -128,7 +128,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/ftppr.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="3%"> <td width="3%">
@ -194,7 +198,7 @@ with FTP proxy support, configure <i>internal_ip</i> and
FTP proxy support, use <i>internal_ip</i> and <i>port</i> as FTP proxy support, use <i>internal_ip</i> and <i>port</i> as
the FTP server. The address of the real FTP server must be the FTP server. The address of the real FTP server must be
configured as a part of the FTP username. The format for the configured as a part of the FTP username. The format for the
username is <i>username</i><b>@</b><i>server</i>, where username is <i>username</i>@<i>server</i>, where
<i>server</i> is the address of the FTP server and <i>server</i> is the address of the FTP server and
<i>username</i> is the user&acute;s login on this FTP <i>username</i> is the user&acute;s login on this FTP
server. The login itself may contain an &acute;@&acute; server. The login itself may contain an &acute;@&acute;

View File

@ -128,7 +128,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/pop3p.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="3%"> <td width="3%">
@ -192,8 +196,8 @@ MUA (Mail User Agent) with POP3 support. Set the client to
use <i>internal_ip</i> and <i>port</i> as a POP3 server. The use <i>internal_ip</i> and <i>port</i> as a POP3 server. The
address of the real POP3 server must be configured as a part address of the real POP3 server must be configured as a part
of the POP3 username. The format for the username is of the POP3 username. The format for the username is
<i>username</i><b>@</b><i>server</i>, where <i>server</i> is <i>username</i>@<i>server</i>, where <i>server</i> is the
the address of the POP3 server and <i>username</i> is the address of the POP3 server and <i>username</i> is the
user&acute;s login on this POP3 server. The login itself may user&acute;s login on this POP3 server. The login itself may
contain an &acute;@&acute; sign. Only cleartext contain an &acute;@&acute; sign. Only cleartext
authentication is supported, because challenge-response authentication is supported, because challenge-response

View File

@ -127,7 +127,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/proxy.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="4%"> <td width="4%">

View File

@ -128,7 +128,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/smtpp.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="3%"> <td width="3%">
@ -192,7 +196,7 @@ MUA (Mail User Agent) with SMTP authentication support. Set
the client to use <i>internal_ip</i> and <i>port</i> as an the client to use <i>internal_ip</i> and <i>port</i> as an
SMTP server. The address of the real SMTP server must be SMTP server. The address of the real SMTP server must be
configured as a part of the SMTP username. The format for configured as a part of the SMTP username. The format for
the username is <i>username</i><b>@</b><i>server</i>, where the username is <i>username</i>@<i>server</i>, where
<i>server</i> is the address of the SMTP server and <i>server</i> is the address of the SMTP server and
<i>username</i> is the user&acute;s login on this SMTP <i>username</i> is the user&acute;s login on this SMTP
server. The login itself may contain an &acute;@&acute; server. The login itself may contain an &acute;@&acute;

View File

@ -162,7 +162,11 @@ and does not work with port translation.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/socks.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="4%"> <td width="4%">

View File

@ -116,7 +116,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/tcppm.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="3%"> <td width="3%">
@ -160,12 +164,18 @@ connections on</p>
<p style="margin-left:6%;"><i>remote_host</i></p> <p style="margin-left:6%;"><i>remote_host</i></p>
<p style="margin-left:15%;">- IP address of the host the <p style="margin-left:15%;">- IP address of the host the
connection is forwarded to</p> connection is forwarded to. Unix domain sockets can be
specified with the syntax <i>unix:/path/to/socket</i> (e.g.,
unix:/var/run/app.sock). On Linux, abstract (fileless) Unix
sockets use the syntax <i>unix:@socketname</i> (e.g.,
unix:@app.socket).</p>
<p style="margin-left:6%;"><i>remote_port</i></p> <p style="margin-left:6%;"><i>remote_port</i></p>
<p style="margin-left:15%;">- remote port the connection is <p style="margin-left:15%;">- remote port the connection is
forwarded to</p> forwarded to. Ignored when using Unix socket destination,
but must be specified (use any positive value) for syntax
compatibility.</p>
<h2>CLIENTS <h2>CLIENTS
<a name="CLIENTS"></a> <a name="CLIENTS"></a>

View File

@ -132,7 +132,11 @@ accordance with the routing table.</p></td></tr>
<p style="margin-top: 1em">Internal address. IP address the <p style="margin-top: 1em">Internal address. IP address the
proxy accepts connections to. By default, connections to any proxy accepts connections to. By default, connections to any
interface are accepted. It&acute;s usually unsafe.</p></td></tr> interface are accepted. It&acute;s usually unsafe. Unix
domain sockets can be specified with
<i>-iunix:/path/to/socket</i> syntax (e.g.,
-iunix:/var/run/tlspr.sock). On Linux, abstract sockets use
<i>-iunix:@socketname</i> syntax.</p></td></tr>
<tr valign="top" align="left"> <tr valign="top" align="left">
<td width="6%"></td> <td width="6%"></td>
<td width="4%"> <td width="4%">

View File

@ -1,10 +1,13 @@
<h3>3proxy PCRE (Perl Compatible Regular Expressions) Filtering</h3>
<h3>3proxy Perl Compatible Regular Expressions (PCRE) Plugin</h3> <p><b>Note:</b> Since version 0.9.7, PCRE filtering is built into 3proxy and does not require
a separate plugin. All pcre_* commands are available directly when 3proxy is compiled with
PCRE2 support (WITH_PCRE). The plugin line is no longer needed.</p>
This filtering plugin can be used to create matching and replacement <p>This filtering functionality can be used to create matching and replacement
rules with regular expressions for client requests, client and rules with regular expressions for client requests, client and
server headers, and client and server data. It adds 3 additional server headers, and client and server data. It adds 3 additional
configuration commands: configuration commands:</p>
<pre> <pre>
pcre TYPE FILTER_ACTION REGEXP [ACE] pcre TYPE FILTER_ACTION REGEXP [ACE]
@ -78,16 +81,10 @@ authentication and/or allow/deny ACLs.
<h4>Example:</h4> <h4>Example:</h4>
<pre> <pre>
plugin PCREPlugin.dll pcre_plugin
pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16 pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16
pcre srvheader deny "Content-type: application" pcre srvheader deny "Content-type: application"
pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser
pcre_extend deny * 192.168.0.1/16 pcre_extend deny * 192.168.0.1/16
</pre> </pre>
<h4>Download:</h4> &copy; Vladimir Dubrovin, License: BSD style
<ul>
<li>Plugin is included in the 3proxy 0.6 binary and source distribution
<li>Example configuration (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A>
</li></ul>

View File

@ -1,8 +1,12 @@
<h3>Плагин регулярных выражений совместимых с Perl (PCRE) для 3proxy</h3> <h3>Фильтрация PCRE (Perl Compatible Regular Expressions) в 3proxy</h3>
Фильтрующий плагин используется для создания правил поиска и замены <p><b>Примечание:</b> Начиная с версии 0.9.7 фильтрация PCRE встроена в 3proxy и не требует
отдельного плагина. Все команды pcre_* доступны напрямую при компиляции 3proxy с поддержкой
PCRE2 (WITH_PCRE). Строка plugin больше не нужна.</p>
<p>Фильтрующий плагин используется для создания правил поиска и замены
регулярных выражений в запросе, заголовков запроса и ответа и данных. регулярных выражений в запросе, заголовков запроса и ответа и данных.
Добавляет поддержку 3х новых команд в файле конфигурации: Добавляет поддержку 3х новых команд в файле конфигурации:</p>
<pre> <pre>
pcre TYPE FILTER_ACTION REGEXP [ACE] pcre TYPE FILTER_ACTION REGEXP [ACE]
@ -76,15 +80,10 @@ PCRE_BSR_UNICODE
<h4>Пример:</h4> <h4>Пример:</h4>
<pre> <pre>
plugin PCREPlugin.dll pcre_plugin
pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16 pcre request deny "porn|sex" user1,user2,user3 192.168.0.0/16
pcre srvheader deny "Content-type: application" pcre srvheader deny "Content-type: application"
pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser pcre_rewrite clidata,srvdata dunno "porn|sex|pussy" "***" baduser
pcre_extend deny * 192.168.0.1/16 pcre_extend deny * 192.168.0.1/16
</pre> </pre>
<h4>Загрузить:</h4> &copy; Vladimir Dubrovin, License: BSD style
<ul>
<li>Плагин включен в дистрибутив 3proxy 0.6
<li>Пример конфигурации (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A>
</li></ul>

View File

@ -1,6 +1,11 @@
<h3>3proxy SSL/TLS Plugin</h3> <h3>3proxy SSL/TLS Support</h3>
This plugin can be used to transparently decrypt SSL/TLS data, provide TLS encryption for proxy traffic, and authenticate using client certificates. <p><b>Note:</b> Since version 0.9.7, SSL/TLS support is built into 3proxy and does not require
a separate plugin. All ssl_* commands are available directly when 3proxy is compiled with
OpenSSL support (WITH_SSL). The plugin line is no longer needed.</p>
<p>SSL/TLS support can be used to transparently decrypt SSL/TLS data, provide TLS encryption
for proxy traffic, and authenticate using client certificates.</p>
<h4>For transparent certificate spoofing (MITM):</h4> <h4>For transparent certificate spoofing (MITM):</h4>
@ -44,7 +49,7 @@ ssl_cli (or ssl_client) - establish TLS connection to upstream server for servic
<br><b>ssl_client_ca_store</b> /path/to/castore - CA store for ssl_client_verify (OpenSSL 3.0+) <br><b>ssl_client_ca_store</b> /path/to/castore - CA store for ssl_client_verify (OpenSSL 3.0+)
<br><b>ssl_client_sni</b> hostname - SNI hostname to send to upstream server (overrides the requested hostname) <br><b>ssl_client_sni</b> hostname - SNI hostname to send to upstream server (overrides the requested hostname)
<br><b>ssl_client_alpn</b> protocol1 protocol2 ... - ALPN protocols to negotiate with upstream server (e.g., ssl_client_alpn h2 http/1.1) <br><b>ssl_client_alpn</b> protocol1 protocol2 ... - ALPN protocols to negotiate with upstream server (e.g., ssl_client_alpn h2 http/1.1)
<br><b>ssl_client_mode</b> mode - when to establish TLS connection: 0 - on connect (default), 1 - after authentication, 2 - before data <br><b>ssl_client_mode</b> mode - when to establish TLS connection: 0 - on connect (default), 1 - after authentication, 2 - before data, 3 - only for secure parent types (ending with 's')
<br><b>ssl_certcache</b> /path/to/cache/ - location for the generated MITM certificates cache, optional if ssl_server_ca_file / ssl_server_ca_key are configured. <br><b>ssl_certcache</b> /path/to/cache/ - location for the generated MITM certificates cache, optional if ssl_server_ca_file / ssl_server_ca_key are configured.
The cache may contain 3 files: 3proxy.pem - public The cache may contain 3 files: 3proxy.pem - public
self-signed certificates (used if ssl_server_ca_file is not configured), self-signed certificates (used if ssl_server_ca_file is not configured),
@ -55,7 +60,6 @@ Generated certificates are placed in the same path.
<h4>MITM example:</h4> <h4>MITM example:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_ca_file /path/to/cafile ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
@ -67,7 +71,6 @@ MITM's traffic with a spoofed certificate for the port 3128 proxy.
<h4>https:// proxy example:</h4> <h4>https:// proxy example:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert path_to_cert ssl_server_cert path_to_cert
ssl_server_key path_to_key ssl_server_key path_to_key
ssl_serv ssl_serv
@ -79,7 +82,6 @@ Creates an https:// proxy on port 33128 and an http:// proxy on port 3128
<h4>TLS client example (connect to upstream via TLS):</h4> <h4>TLS client example (connect to upstream via TLS):</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_client_cert /path/to/client.crt ssl_client_cert /path/to/client.crt
ssl_client_key /path/to/client.key ssl_client_key /path/to/client.key
ssl_client_verify ssl_client_verify
@ -89,9 +91,27 @@ proxy -p3128
</pre> </pre>
Creates an HTTP proxy that connects to upstream servers via TLS with client certificate authentication. Creates an HTTP proxy that connects to upstream servers via TLS with client certificate authentication.
<h4>Conditional TLS for parent proxy (ssl_client_mode 3):</h4>
<pre>
ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/key
ssl_client_mode 3
auth strong
allow user1
parent 1000 https parent1.example.com 443
allow user2
parent 1000 socks5 parent2.example.com 1080
ssl_serv
ssl_cli
proxy -p3128
ssl_noserv
ssl_nocli
</pre>
Creates an HTTP proxy on port 3128 that uses TLS for client connections (ssl_serv). With ssl_client_mode 3, TLS handshake to parent proxy is performed only if the parent type ends with 's' (secure types). In this example, user1's traffic goes through an https parent proxy with TLS encryption, while user2's traffic goes through a regular socks5 parent without TLS. Secure parent types include: tcps, https, connects, connect+s, socks4s, socks5s, socks4+s, socks5+s, pop3s, smtps, ftps.
<h4>mTLS example (require client certificate):</h4> <h4>mTLS example (require client certificate):</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert /path/to/server.crt ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/server.key ssl_server_key /path/to/server.key
ssl_server_ca_file /path/to/ca.crt ssl_server_ca_file /path/to/ca.crt

View File

@ -1,6 +1,10 @@
<h3>3proxy SSL/TLS плагин</h3> <h3>3proxy SSL/TLS поддержка</h3>
Плагин можно использовать для перехвата и дешифровки SSL/TLS трафика, для шифрования трафика прокси-сервера и аутентификации с помощью клиентских сертификатов. <p><b>Примечание:</b> Начиная с версии 0.9.7 поддержка SSL/TLS встроена в 3proxy и не требует
отдельного плагина. Все команды ssl_* доступны напрямую при компиляции 3proxy с поддержкой
OpenSSL (WITH_SSL). Строка plugin больше не нужна.</p>
<p>Плагин можно использовать для перехвата и дешифровки SSL/TLS трафика, для шифрования трафика прокси-сервера и аутентификации с помощью клиентских сертификатов.</p>
<h4>Для прозрачного перехвата трафика (MITM):</h4> <h4>Для прозрачного перехвата трафика (MITM):</h4>
@ -44,7 +48,7 @@ ssl_cli (или ssl_client) - устанавливать TLS-соединени
<br><b>ssl_client_ca_store</b> /path/to/castore - хранилище CA-сертификатов для ssl_client_verify (OpenSSL 3.0+) <br><b>ssl_client_ca_store</b> /path/to/castore - хранилище CA-сертификатов для ssl_client_verify (OpenSSL 3.0+)
<br><b>ssl_client_sni</b> hostname - SNI-имя хоста для отправки вышестоящему серверу (переопределяет запрошенное имя хоста) <br><b>ssl_client_sni</b> hostname - SNI-имя хоста для отправки вышестоящему серверу (переопределяет запрошенное имя хоста)
<br><b>ssl_client_alpn</b> протокол1 протокол2 ... - ALPN-протоколы для согласования с вышестоящим сервером (например, ssl_client_alpn h2 http/1.1) <br><b>ssl_client_alpn</b> протокол1 протокол2 ... - ALPN-протоколы для согласования с вышестоящим сервером (например, ssl_client_alpn h2 http/1.1)
<br><b>ssl_client_mode</b> режим - когда устанавливать TLS-соединение: 0 - при подключении (по умолчанию), 1 - после аутентификации, 2 - перед передачей данных <br><b>ssl_client_mode</b> режим - когда устанавливать TLS-соединение: 0 - при подключении (по умолчанию), 1 - после аутентификации, 2 - перед передачей данных, 3 - только для защищённых типов parent прокси (заканчивающихся на 's')
<br><b>ssl_certcache</b> /path/to/cache/ - расположение кеша сгенерированных MITM-сертификатов. Кеш может содержать <br><b>ssl_certcache</b> /path/to/cache/ - расположение кеша сгенерированных MITM-сертификатов. Кеш может содержать
файлы 3proxy.pem, 3proxy.key, server.key, которые используются как ssl_server_ca_file, файлы 3proxy.pem, 3proxy.key, server.key, которые используются как ssl_server_ca_file,
ssl_server_ca_key и ssl_server_key соответственно, если они не заданы. Если server.key не задан, ssl_server_ca_key и ssl_server_key соответственно, если они не заданы. Если server.key не задан,
@ -52,7 +56,6 @@ ssl_server_ca_key и ssl_server_key соответственно, если он
<h4>Пример MITM:</h4> <h4>Пример MITM:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_ca_file /path/to/cafile ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
@ -64,7 +67,6 @@ proxy -p3129
<h4>Пример конфигурации https:// прокси:</h4> <h4>Пример конфигурации https:// прокси:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert path_to_cert ssl_server_cert path_to_cert
ssl_server_key path_to_key ssl_server_key path_to_key
ssl_serv ssl_serv
@ -76,7 +78,6 @@ proxy -p3128
<h4>Пример TLS-клиента (соединение к вышестоящему серверу через TLS):</h4> <h4>Пример TLS-клиента (соединение к вышестоящему серверу через TLS):</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_client_cert /path/to/client.crt ssl_client_cert /path/to/client.crt
ssl_client_key /path/to/client.key ssl_client_key /path/to/client.key
ssl_client_verify ssl_client_verify
@ -86,9 +87,27 @@ proxy -p3128
</pre> </pre>
Создается HTTP-прокси, который соединяется с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату. Создается HTTP-прокси, который соединяется с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату.
<h4>Условное TLS для parent прокси (ssl_client_mode 3):</h4>
<pre>
ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/key
ssl_client_mode 3
auth strong
allow user1
parent 1000 https parent1.example.com 443
allow user2
parent 1000 socks5 parent2.example.com 1080
ssl_serv
ssl_cli
proxy -p3128
ssl_noserv
ssl_nocli
</pre>
Создается HTTP-прокси на порту 3128, использующий TLS для клиентских соединений (ssl_serv). При ssl_client_mode 3 TLS-рукопожатие с родительским прокси выполняется только если тип parent прокси заканчивается на 's' (защищённые типы). В данном примере трафик user1 идёт через https родительский прокси с TLS-шифрованием, а трафик user2 — через обычный socks5 родитель без TLS. Защищённые типы parent прокси: tcps, https, connects, connect+s, socks4s, socks5s, socks4+s, socks5+s, pop3s, smtps, ftps.
<h4>Пример mTLS (требование клиентского сертификата):</h4> <h4>Пример mTLS (требование клиентского сертификата):</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert /path/to/server.crt ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/server.key ssl_server_key /path/to/server.key
ssl_server_ca_file /path/to/ca.crt ssl_server_ca_file /path/to/ca.crt

View File

@ -140,7 +140,7 @@ configuration file
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.org .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy.cfg(3), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), 3proxy.cfg(5), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8),
kill(1), syslogd(8), kill(1), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/

File diff suppressed because it is too large Load Diff

81
man/3proxy_crypt.8 Normal file
View File

@ -0,0 +1,81 @@
.TH 3proxy_crypt "8" "April 2026" "3proxy 0.9" "Universal proxy server"
.SH NAME
.B 3proxy_crypt
\- utility to generate encrypted passwords for 3proxy
.SH SYNOPSIS
.B 3proxy_crypt
.I password
.br
.B 3proxy_crypt
.I salt password
.SH DESCRIPTION
.B 3proxy_crypt
is a utility to generate encrypted password hashes for use with 3proxy
configuration. Encrypted passwords allow the system to avoid storing
passwords in cleartext in configuration files.
.PP
When invoked with a single argument, it produces an NT password hash
(MD4-based, suitable for NTLM authentication). The output is prefixed with
.BR NT: .
.PP
When invoked with two arguments (salt and password), it produces a BLAKE2b
password hash. The salt length is limited to 64 characters. The output is
prefixed with
.BR CR: .
.PP
The resulting hash can be used in the 3proxy configuration file with the
.B users
directive instead of a cleartext password.
.SH OPTIONS
.TP
.I password
Cleartext password to encrypt.
.TP
.I salt
Salt string for BLAKE2b hashing (max 64 characters).
.SH EXAMPLE
.TP
Generate NT password hash:
.RS
3proxy_crypt MySecretPassword
.RE
.TP
Result:
.RS
NT:3F7E6D8D96E8E7A9B0C1D2E3F4A5B6C7
.RE
.TP
Generate BLAKE2b password hash with salt:
.RS
3proxy_crypt MySalt MySecretPassword
.RE
.TP
Result:
.RS
CR:$3$MySalt$...
.RE
.TP
Using in 3proxy.cfg:
.RS
users user1:CR:$3$MySalt$...
.RE
.SH NOTES
The NT hash uses the RSA MD4 Message-Digest Algorithm. The BLAKE2b hash
uses the BLAKE2 cryptographic hash function.
.PP
When a password hash is prefixed with
.B NT:
or
.BR CR: ,
3proxy uses the corresponding algorithm to verify passwords instead of
comparing cleartext strings.
.SH BUGS
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy(8), 3proxy.cfg(5),
.br
https://3proxy.org/
.SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.org )

View File

@ -36,6 +36,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/ftppr.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -h .B -h
Default destination. It's used if the target address is not specified by the user. Default destination. It's used if the target address is not specified by the user.
@ -68,7 +73,7 @@ and
.IR port .IR port
as the FTP server. The address of the real FTP server must be configured as a part of as the FTP server. The address of the real FTP server must be configured as a part of
the FTP username. The format for the username is the FTP username. The format for the username is
.IR username \fB@ server , .IR username @ server ,
where where
.I server .I server
is the address of the FTP server and is the address of the FTP server and

View File

@ -36,6 +36,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/pop3p.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 110. Port. Port proxy listens for incoming connections. Default is 110.
@ -62,7 +67,7 @@ and
.IR port .IR port
as a POP3 server. The address of the real POP3 server must be configured as a part of as a POP3 server. The address of the real POP3 server must be configured as a part of
the POP3 username. The format for the username is the POP3 username. The format for the username is
.IR username \fB@ server , .IR username @ server ,
where where
.I server .I server
is the address of the POP3 server and is the address of the POP3 server and

View File

@ -34,6 +34,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/proxy.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -a .B -a
Anonymous. Hide information about client. Anonymous. Hide information about client.

View File

@ -36,6 +36,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/smtpp.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 25. Port. Port proxy listens for incoming connections. Default is 25.
@ -63,7 +68,7 @@ and
.IR port .IR port
as an SMTP server. The address of the real SMTP server must be configured as a part of as an SMTP server. The address of the real SMTP server must be configured as a part of
the SMTP username. The format for the username is the SMTP username. The format for the username is
.IR username \fB@ server , .IR username @ server ,
where where
.I server .I server
is the address of the SMTP server and is the address of the SMTP server and

View File

@ -49,6 +49,11 @@ of IP-IP NAT and does not work with port translation.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/socks.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 1080. Port. Port proxy listens for incoming connections. Default is 1080.

View File

@ -31,6 +31,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/tcppm.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
@ -50,10 +55,18 @@ crashes.
- port tcppm accepts connections on - port tcppm accepts connections on
.TP .TP
.I remote_host .I remote_host
- IP address of the host the connection is forwarded to - IP address of the host the connection is forwarded to. Unix domain sockets
can be specified with the syntax
.I unix:/path/to/socket
(e.g., unix:/var/run/app.sock). On Linux, abstract (fileless) Unix sockets
use the syntax
.I unix:@socketname
(e.g., unix:@app.socket).
.TP .TP
.I remote_port .I remote_port
- remote port the connection is forwarded to - remote port the connection is forwarded to. Ignored when using Unix socket
destination, but must be specified (use any positive value) for syntax
compatibility.
.SH CLIENTS .SH CLIENTS
Any TCP-based application can be used as a client. Use Any TCP-based application can be used as a client. Use
.I internal_ip .I internal_ip

View File

@ -36,6 +36,11 @@ with the routing table.
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default, connections to any interface are accepted. It\'s usually unsafe.
Unix domain sockets can be specified with
.I -iunix:/path/to/socket
syntax (e.g., -iunix:/var/run/tlspr.sock). On Linux, abstract sockets use
.I -iunix:@socketname
syntax.
.TP .TP
.B -a .B -a
Anonymous. Hide information about client. Anonymous. Hide information about client.

View File

@ -6,10 +6,10 @@ if [ $3 ]; then
echo countin \"`wc -l /etc/3proxy/conf/counters|awk '{print $1}'`/$1\" D $3 $1 >> /etc/3proxy/conf/counters echo countin \"`wc -l /etc/3proxy/conf/counters|awk '{print $1}'`/$1\" D $3 $1 >> /etc/3proxy/conf/counters
fi fi
if [ $2 ]; then if [ $2 ]; then
echo $1:`/bin/mycrypt $$ $2` >> /etc/3proxy/conf/passwd echo $1:`/bin/3proxy_crypt $$ $2` >> /etc/3proxy/conf/passwd
else else
echo usage: $0 username password [day_limit] [bandwidth] echo usage: $0 username password [day_limit] [bandwidth]
echo " "day_limit - traffic limit in MB per day echo " "day_limit - traffic limit in MB per day
echo " "bandwidth - bandwith in bits per second 1048576 = 1Mbps echo " "bandwidth - bandwidth in bits per second 1048576 = 1Mbps
fi fi

View File

@ -32,14 +32,15 @@ make clean
%files %files
/bin/3proxy /bin/3proxy
/bin/ftppr /bin/3proxy_crypt
/bin/mycrypt /bin/3proxy_ftppr
/bin/pop3p /bin/3proxy_pop3p
/bin/proxy /bin/3proxy_proxy
/bin/socks /bin/3proxy_smtpp
/bin/tcppm /bin/3proxy_socks
/bin/udppm /bin/3proxy_tcppm
/bin/tlspr /bin/3proxy_tlspr
/bin/3proxy_udppm
%config(noreplace) /etc/3proxy/3proxy.cfg %config(noreplace) /etc/3proxy/3proxy.cfg
/etc/3proxy/conf /etc/3proxy/conf
/etc/init.d/3proxy /etc/init.d/3proxy
@ -49,7 +50,7 @@ make clean
%config(noreplace) /usr/local/3proxy/conf/bandlimiters %config(noreplace) /usr/local/3proxy/conf/bandlimiters
%config(noreplace) /usr/local/3proxy/conf/counters %config(noreplace) /usr/local/3proxy/conf/counters
/usr/local/3proxy/libexec/*.ld.so /usr/local/3proxy/libexec/*.ld.so
/usr/share/man/man3/* /usr/share/man/man5/3proxy.cfg.5
/usr/share/man/man8/* /usr/share/man/man8/*
/var/log/3proxy /var/log/3proxy

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -7,6 +7,12 @@
*/ */
#include "proxy.h" #include "proxy.h"
#ifdef WITH_SSL
void ssl_install(void);
#endif
#ifdef WITH_PCRE
void pcre_install(void);
#endif
#ifndef _WIN32 #ifndef _WIN32
#include <sys/resource.h> #include <sys/resource.h>
#ifndef NOPLUGINS #ifndef NOPLUGINS
@ -66,9 +72,9 @@ void __stdcall CommandHandler( DWORD dwCommand )
Sleep(2000); Sleep(2000);
SetStatus( SERVICE_STOPPED, 0, 0 ); SetStatus( SERVICE_STOPPED, 0, 0 );
#ifndef NOODBC #ifndef NOODBC
pthread_mutex_lock(&log_mutex); _3proxy_mutex_lock(&log_mutex);
close_sql(); close_sql();
pthread_mutex_unlock(&log_mutex); _3proxy_mutex_unlock(&log_mutex);
#endif #endif
break; break;
case SERVICE_CONTROL_PAUSE: case SERVICE_CONTROL_PAUSE:
@ -118,13 +124,6 @@ void mysigpause (int sig){
void mysigterm (int sig){ void mysigterm (int sig){
conf.paused++; conf.paused++;
usleep(999*SLEEPTIME);
usleep(999*SLEEPTIME);
#ifndef NOODBC
pthread_mutex_lock(&log_mutex);
close_sql();
pthread_mutex_unlock(&log_mutex);
#endif
conf.timetoexit = 1; conf.timetoexit = 1;
} }
@ -141,8 +140,10 @@ int timechanged (time_t oldtime, time_t newtime, ROTATION lt){
struct tm tmold; struct tm tmold;
struct tm *tm; struct tm *tm;
tm = localtime(&oldtime); tm = localtime(&oldtime);
if(!tm) return 0;
tmold = *tm; tmold = *tm;
tm = localtime(&newtime); tm = localtime(&newtime);
if(!tm) return 0;
switch(lt){ switch(lt){
case MINUTELY: case MINUTELY:
if(tm->tm_min != tmold.tm_min)return 1; if(tm->tm_min != tmold.tm_min)return 1;
@ -214,17 +215,17 @@ void dumpcounters(struct trafcount *tlin, int counterd){
cheader.updated = conf.time; cheader.updated = conf.time;
lseek(counterd, 0, SEEK_SET); if(lseek(counterd, 0, SEEK_SET) >= 0 && write(counterd, &cheader, sizeof(struct counter_header))){}
if(write(counterd, &cheader, sizeof(struct counter_header))){}
for(tl=tlin; tl; tl = tl->next){ for(tl=tlin; tl; tl = tl->next){
if(tl->number){ if(tl->number){
lseek(counterd, if(lseek(counterd,
sizeof(struct counter_header) + (tl->number - 1) * sizeof(struct counter_record), sizeof(struct counter_header) + (tl->number - 1) * sizeof(struct counter_record),
SEEK_SET); SEEK_SET) >= 0){
crecord.traf64 = tl->traf64; crecord.traf64 = tl->traf64;
crecord.cleared = tl->cleared; crecord.cleared = tl->cleared;
crecord.updated = tl->updated; crecord.updated = tl->updated;
if(write(counterd, &crecord, sizeof(struct counter_record))){} if(write(counterd, &crecord, sizeof(struct counter_record))){}
}
} }
if(tl->type!=NEVER && timechanged(tl->cleared, conf.time, tl->type)){ if(tl->type!=NEVER && timechanged(tl->cleared, conf.time, tl->type)){
tl->cleared = conf.time; tl->cleared = conf.time;
@ -267,9 +268,11 @@ void cyclestep(void){
} }
if(timechanged(basetime, conf.time, DAILY)) { if(timechanged(basetime, conf.time, DAILY)) {
tm = localtime(&conf.time); tm = localtime(&conf.time);
wday = (1 << tm->tm_wday); if(tm){
tm->tm_hour = tm->tm_min = tm->tm_sec = 0; wday = (1 << tm->tm_wday);
basetime = mktime(tm); tm->tm_hour = tm->tm_min = tm->tm_sec = 0;
basetime = mktime(tm);
}
} }
if(conf.logname) { if(conf.logname) {
if(timechanged(conf.logtime, conf.time, conf.logtype)) { if(timechanged(conf.logtime, conf.time, conf.logtype)) {
@ -508,31 +511,37 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
return 1; return 1;
} }
pthread_mutex_init(&config_mutex, NULL); _3proxy_mutex_init(&config_mutex);
pthread_mutex_init(&bandlim_mutex, NULL); _3proxy_mutex_init(&bandlim_mutex);
pthread_mutex_init(&connlim_mutex, NULL); _3proxy_mutex_init(&connlim_mutex);
pthread_mutex_init(&hash_mutex, NULL); _3proxy_mutex_init(&tc_mutex);
pthread_mutex_init(&tc_mutex, NULL); _3proxy_mutex_init(&log_mutex);
pthread_mutex_init(&pwl_mutex, NULL);
pthread_mutex_init(&log_mutex, NULL);
#ifndef NORADIUS #ifndef NORADIUS
pthread_mutex_init(&rad_mutex, NULL); _3proxy_mutex_init(&rad_mutex);
#endif #endif
#ifdef _WIN32 #ifdef _WIN32
if(!CreatePipe(&conf.threadinit[0], &conf.threadinit[1], NULL, 1)){ conf.threadinit = CreateSemaphore(NULL, 1, 1, NULL);
#else if(!conf.threadinit){
if(pipe(conf.threadinit)) { fprintf(stderr, "semaphore init failed\n");
#endif
fprintf(stderr, "CreatePipe failed\n");
return 1; return 1;
}; }
#else
_3proxy_mutex_init(&conf.threadinit);
#endif
#ifdef WITH_SSL
ssl_install();
#endif
#ifdef WITH_PCRE
pcre_install();
#endif
freeconf(&conf); freeconf(&conf);
res = readconfig(fp); res = readconfig(fp);
conf.version++; conf.version++;
if(res) RETURN(res); if(res) RETURN(res);
if(!writable)fclose(fp); if(!writable){fclose(fp); fp = NULL;}
#ifdef _WIN32 #ifdef _WIN32
@ -563,6 +572,7 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
CLEARRETURN: CLEARRETURN:
if(fp && fp != stdin) {fclose(fp); fp = NULL;}
return 0; return 0;
} }

270
src/3proxy_crypt.c Normal file
View File

@ -0,0 +1,270 @@
/*
3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement
*/
#include "blake2_compat.h"
#ifdef WITH_SSL
#include <openssl/evp.h>
#ifndef WITHMAIN
/* MD5 needed for $1$ crypt */
#endif
#endif
#include <string.h>
#define MD5_SIZE 16
#ifdef _WIN32
#pragma warning (disable : 4996)
#endif
void tohex(unsigned char *in, unsigned char *out, int len);
static unsigned char itoa64[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#if defined(WITH_SSL)
EVP_MD *md4 = NULL;
EVP_MD *md5 = NULL;
#endif
void
_crypt_to64(unsigned char *s, unsigned long v, int n)
{
while (--n >= 0) {
*s++ = itoa64[v&0x3f];
v >>= 6;
}
}
#ifdef WITH_SSL
unsigned char * ntpwdhash (unsigned char *szHash, const unsigned char *szPassword, int ctohex)
{
unsigned char szUnicodePass[513];
unsigned int nPasswordLen;
EVP_MD_CTX *ctx;
unsigned int len=sizeof(szUnicodePass);
unsigned int i;
/*
* NT passwords are unicode. Convert plain text password
* to unicode by inserting a zero every other byte
*/
nPasswordLen = (int)strlen((char *)szPassword);
if(nPasswordLen > 255)nPasswordLen = 255;
for (i = 0; i < nPasswordLen; i++) {
szUnicodePass[i << 1] = szPassword[i];
szUnicodePass[(i << 1) + 1] = 0;
}
/* Encrypt Unicode password to a 16-byte MD4 hash */
ctx = EVP_MD_CTX_new();
if(!EVP_DigestInit_ex(ctx, md4, NULL)){
fprintf(stderr, "Failed to init MD4 digest\n");
}
EVP_DigestUpdate(ctx, szUnicodePass, (nPasswordLen<<1));
EVP_DigestFinal_ex(ctx, szUnicodePass, &len);
EVP_MD_CTX_free(ctx);
if (ctohex){
tohex(szUnicodePass, szHash, 16);
}
else memcpy(szHash, szUnicodePass, 16);
return szHash;
}
#endif
unsigned char * mycrypt(const unsigned char *pw, const unsigned char *salt, unsigned char *passwd){
const unsigned char *ep;
unsigned char *magic;
unsigned char *p;
const unsigned char *sp;
unsigned char final[MD5_SIZE];
int sl;
unsigned long l;
#if defined(WITH_SSL)
if(salt[0] == '$' && salt[1] == '1' && salt[2] == '$' && (ep = (unsigned char *)strchr((char *)salt+3, '$'))) {
EVP_MD_CTX *ctx, *ctx1;
unsigned int len;
int pl, i;
sp = salt +3;
sl = (int)(ep - sp);
magic = (unsigned char *)"$1$";
ctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx, md5, NULL);
/* The password first, since that is what is most unknown */
EVP_DigestUpdate(ctx,pw,strlen((char *)pw));
/* Then our magic string */
EVP_DigestUpdate(ctx,magic,strlen((char *)magic));
/* Then the raw salt */
EVP_DigestUpdate(ctx,sp,sl);
/* Then just as many unsigned characters of the MD5(pw,salt,pw) */
ctx1 = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx1, EVP_md5(), NULL);
EVP_DigestUpdate(ctx1,pw,strlen((char *)pw));
EVP_DigestUpdate(ctx1,sp,sl);
EVP_DigestUpdate(ctx1,pw,strlen((char *)pw));
EVP_DigestFinal_ex(ctx1,final,&len);
EVP_MD_CTX_free(ctx1);
for(pl = (int)strlen((char *)pw); pl > 0; pl -= MD5_SIZE)
EVP_DigestUpdate(ctx,final,pl>MD5_SIZE ? MD5_SIZE : pl);
/* Don't leave anything around in vm they could use. */
memset(final,0,sizeof final);
/* Then something really weird... */
for (i = (int)strlen((char *)pw); i ; i >>= 1)
if(i&1)
EVP_DigestUpdate(ctx, final, 1);
else
EVP_DigestUpdate(ctx, pw, 1);
EVP_DigestFinal_ex(ctx,final,&len);
EVP_MD_CTX_free(ctx);
/*
* and now, just to make sure things don't run too fast
* On a 60 Mhz Pentium this takes 34 msec, so you would
* need 30 seconds to build a 1000 entry dictionary...
*/
for(i=0;i<1000;i++) {
ctx1 = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx1, md5, NULL);
if(i & 1)
EVP_DigestUpdate(ctx1,pw,strlen((char *)pw));
else
EVP_DigestUpdate(ctx1,final,MD5_SIZE);
if(i % 3)
EVP_DigestUpdate(ctx1,sp,sl);
if(i % 7)
EVP_DigestUpdate(ctx1,pw,strlen((char *)pw));
if(i & 1)
EVP_DigestUpdate(ctx1,final,MD5_SIZE);
else
EVP_DigestUpdate(ctx1,pw,strlen((char *)pw));
EVP_DigestFinal_ex(ctx1,final,&len);
EVP_MD_CTX_free(ctx1);
}
/* Don't leave anything around in vm they could use. */
memset(final,0,sizeof final);
}
else
#endif
if(salt[0] == '$' && salt[1] == '3' && salt[2] == '$' && (ep = (unsigned char *)strchr((char *)salt+3, '$'))) {
sp = salt +3;
sl = (int)(ep - sp);
magic = (unsigned char *)"$3$";
{
blake2b_state S;
blake2b_init(&S, MD5_SIZE);
blake2b_update(&S, pw, strlen((char *)pw) + 1);
blake2b_update(&S, sp, sl);
blake2b_final(&S, final, MD5_SIZE);
}
}
else {
*passwd = 0;
return passwd;
}
strcpy((char *)passwd,(char *)magic);
strncat((char *)passwd,(char *)sp,sl);
strcat((char *)passwd,"$");
p = passwd + strlen((char *)passwd);
l = (final[ 0]<<16) | (final[ 6]<<8) | final[12];
_crypt_to64(p,l,4); p += 4;
l = (final[ 1]<<16) | (final[ 7]<<8) | final[13];
_crypt_to64(p,l,4); p += 4;
l = (final[ 2]<<16) | (final[ 8]<<8) | final[14];
_crypt_to64(p,l,4); p += 4;
l = (final[ 3]<<16) | (final[ 9]<<8) | final[15];
_crypt_to64(p,l,4); p += 4;
l = (final[ 4]<<16) | (final[10]<<8) | final[ 5];
_crypt_to64(p,l,4); p += 4;
l = final[11] ;
_crypt_to64(p,l,2); p += 2;
*p = '\0';
return passwd;
}
#ifdef WITHMAIN
#ifdef WITH_SSL
OSSL_LIB_CTX *library_ctx = NULL;
#include <openssl/provider.h>
#endif
#include <stdio.h>
int main(int argc, char* argv[]){
unsigned char buf[1024];
unsigned i;
if(argc < 2 || argc > 3) {
fprintf(stderr, "usage: \n"
#ifdef WITH_SSL
"\t%s <password>\n"
#endif
"\t%s <salt> <password>\n"
#ifdef WITH_SSL
"Performs NT crypt if no salt specified, BLAKE2 crypt with salt\n"
#else
"Performs BLAKE2 crypt with salt\n"
#endif
"This software uses:\n"
#ifdef WITH_SSL
" OpenSSL EVP (MD4, MD5, BLAKE2b)\n"
#else
" BLAKE2 reference implementation\n"
#endif
,
argv[0],
argv[0]);
return 1;
}
#ifdef WITH_SSL
library_ctx = OSSL_LIB_CTX_new();
OSSL_PROVIDER_load(library_ctx, "legacy");
OSSL_PROVIDER_load(library_ctx, "default");
md4 = EVP_MD_fetch(library_ctx, "MD4", NULL);
if (md4 == NULL) {
fprintf(stderr, "Error fetching MD4\n");
}
md5 = EVP_MD_fetch(library_ctx, "MD5", NULL);
if (md5 == NULL) {
fprintf(stderr, "Error fetching MD5\n");
}
#endif
if(argc == 2) {
#ifdef WITH_SSL
printf("NT:%s\n", ntpwdhash(buf, (unsigned char *)argv[1], 1));
#else
fprintf(stderr, "NT crypt not available (compiled without OpenSSL)\n");
#endif
}
else {
i = (int)strlen((char *)argv[1]);
if (i > 64) argv[1][64] = 0;
sprintf((char *)buf, "$3$%s$", argv[1]);
printf("CR:%s\n", mycrypt((unsigned char *)argv[2], buf, buf+256));
}
return 0;
}
#endif

View File

@ -2,8 +2,7 @@
# 3 proxy common Makefile # 3 proxy common Makefile
# #
all: $(BUILDDIR)3proxy$(EXESUFFICS) $(BUILDDIR)mycrypt$(EXESUFFICS) $(BUILDDIR)pop3p$(EXESUFFICS) $(BUILDDIR)smtpp$(EXESUFFICS) $(BUILDDIR)ftppr$(EXESUFFICS) $(BUILDDIR)tcppm$(EXESUFFICS) $(BUILDDIR)tlspr$(EXESUFFICS) $(BUILDDIR)udppm$(EXESUFFICS) $(BUILDDIR)socks$(EXESUFFICS) $(BUILDDIR)proxy$(EXESUFFICS) allplugins all: $(BUILDDIR)3proxy$(EXESUFFICS) $(BUILDDIR)$(CRYPT_PREFIX)crypt$(EXESUFFICS) $(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS) $(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS) $(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS) $(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) allplugins
sockmap$(OBJSUFFICS): sockmap.c proxy.h structures.h sockmap$(OBJSUFFICS): sockmap.c proxy.h structures.h
$(CC) $(CFLAGS) sockmap.c $(CC) $(CFLAGS) sockmap.c
@ -27,62 +26,60 @@ sockgetchar$(OBJSUFFICS): sockgetchar.c proxy.h structures.h
$(CC) $(CFLAGS) sockgetchar.c $(CC) $(CFLAGS) sockgetchar.c
proxy$(OBJSUFFICS): proxy.c proxy.h structures.h proxymain.c proxy$(OBJSUFFICS): proxy.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)ANONYMOUS proxy.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)ANONYMOUS $(DEFINEOPTION)NOUDPMAIN proxy.c
pop3p$(OBJSUFFICS): pop3p.c proxy.h structures.h proxymain.c pop3p$(OBJSUFFICS): pop3p.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP pop3p.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)NOUDPMAIN pop3p.c
smtpp$(OBJSUFFICS): smtpp.c proxy.h structures.h proxymain.c smtpp$(OBJSUFFICS): smtpp.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP smtpp.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)NOUDPMAIN smtpp.c
ftppr$(OBJSUFFICS): ftppr.c proxy.h structures.h proxymain.c ftppr$(OBJSUFFICS): ftppr.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP ftppr.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)NOUDPMAIN ftppr.c
tcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h proxymain.c tcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP tcppm.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tcppm.c
tlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP tlspr.c
socks$(OBJSUFFICS): socks.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP socks.c
udppm$(OBJSUFFICS): udppm.c proxy.h structures.h proxymain.c udppm$(OBJSUFFICS): udppm.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP udppm.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP udppm.c
tlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tlspr.c
socks$(OBJSUFFICS): socks.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP $(DEFINEOPTION)NOUDPMAIN socks.c
3proxy$(OBJSUFFICS): 3proxy.c proxy.h structures.h 3proxy$(OBJSUFFICS): 3proxy.c proxy.h structures.h
$(CC) $(CFLAGS) 3proxy.c $(CC) $(CFLAGS) 3proxy.c
$(BUILDDIR)proxy$(EXESUFFICS): sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS): sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS)
$(LN) $(LNOUT)$(BUILDDIR)proxy$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
$(BUILDDIR)pop3p$(EXESUFFICS): sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS) $(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS): sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
$(LN) $(LNOUT)$(BUILDDIR)pop3p$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
$(BUILDDIR)smtpp$(EXESUFFICS): sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS) $(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS): sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS)
$(LN) $(LNOUT)$(BUILDDIR)smtpp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) base64$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) base64$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
$(BUILDDIR)ftppr$(EXESUFFICS): sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) ftp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS) $(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS): sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) ftp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
$(LN) $(LNOUT)$(BUILDDIR)ftppr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
$(BUILDDIR)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)$(PREFIX)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)socks$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)tcppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) hash$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS) $(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
mainfunc$(OBJSUFFICS): proxy.h structures.h proxymain.c mainfunc$(OBJSUFFICS): proxy.h structures.h proxymain.c
$(CC) $(COUT)mainfunc$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)MODULEMAINFUNC=mainfunc proxymain.c $(CC) $(COUT)mainfunc$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)MODULEMAINFUNC=mainfunc proxymain.c
srvproxy$(OBJSUFFICS): proxy.c proxy.h structures.h srvproxy$(OBJSUFFICS): proxy.c proxy.h structures.h
$(CC) $(COUT)srvproxy$(OBJSUFFICS) $(CFLAGS) proxy.c $(CC) $(COUT)srvproxy$(OBJSUFFICS) $(CFLAGS) proxy.c
@ -119,6 +116,24 @@ srvdnspr$(OBJSUFFICS): dnspr.c proxy.h structures.h
auth$(OBJSUFFICS): auth.c proxy.h structures.h auth$(OBJSUFFICS): auth.c proxy.h structures.h
$(CC) $(COUT)auth$(OBJSUFFICS) $(CFLAGS) auth.c $(CC) $(COUT)auth$(OBJSUFFICS) $(CFLAGS) auth.c
acl$(OBJSUFFICS): acl.c proxy.h structures.h
$(CC) $(COUT)acl$(OBJSUFFICS) $(CFLAGS) acl.c
limiter$(OBJSUFFICS): limiter.c proxy.h structures.h
$(CC) $(COUT)limiter$(OBJSUFFICS) $(CFLAGS) limiter.c
redirect$(OBJSUFFICS): redirect.c proxy.h structures.h
$(CC) $(COUT)redirect$(OBJSUFFICS) $(CFLAGS) redirect.c
hash$(OBJSUFFICS): hash.c proxy.h structures.h
$(CC) $(COUT)hash$(OBJSUFFICS) $(CFLAGS) hash.c
hashtables$(OBJSUFFICS): hashtables.c proxy.h structures.h
$(CC) $(COUT)hashtables$(OBJSUFFICS) $(CFLAGS) hashtables.c
resolve$(OBJSUFFICS): resolve.c proxy.h structures.h
$(CC) $(COUT)resolve$(OBJSUFFICS) $(CFLAGS) resolve.c
authradius$(OBJSUFFICS): authradius.c proxy.h structures.h authradius$(OBJSUFFICS): authradius.c proxy.h structures.h
$(CC) $(COUT)authradius$(OBJSUFFICS) $(CFLAGS) authradius.c $(CC) $(COUT)authradius$(OBJSUFFICS) $(CFLAGS) authradius.c
@ -131,25 +146,30 @@ log$(OBJSUFFICS): log.c proxy.h structures.h
datatypes$(OBJSUFFICS): datatypes.c proxy.h structures.h datatypes$(OBJSUFFICS): datatypes.c proxy.h structures.h
$(CC) $(COUT)datatypes$(OBJSUFFICS) $(CFLAGS) datatypes.c $(CC) $(COUT)datatypes$(OBJSUFFICS) $(CFLAGS) datatypes.c
mycrypt$(OBJSUFFICS): mycrypt.c 3proxy_crypt$(OBJSUFFICS): 3proxy_crypt.c
$(CC) $(COUT)mycrypt$(OBJSUFFICS) $(CFLAGS) mycrypt.c $(CC) $(COUT)3proxy_crypt$(OBJSUFFICS) $(CFLAGS) 3proxy_crypt.c
mycryptmain$(OBJSUFFICS): mycrypt.c 3proxy_cryptmain$(OBJSUFFICS): 3proxy_crypt.c
$(CC) $(COUT)mycryptmain$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITHMAIN mycrypt.c $(CC) $(COUT)3proxy_cryptmain$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITHMAIN 3proxy_crypt.c
$(BUILDDIR)mycrypt$(EXESUFFICS): md4$(OBJSUFFICS) md5$(OBJSUFFICS) mycryptmain$(OBJSUFFICS) base64$(OBJSUFFICS) blake2$(OBJSUFFICS): libs/blake2.h libs/blake2-impl.h libs/blake2b-ref.c
$(LN) $(LNOUT)$(BUILDDIR)mycrypt$(EXESUFFICS) $(LDFLAGS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) base64$(OBJSUFFICS) mycryptmain$(OBJSUFFICS) $(CC) $(COUT)blake2$(OBJSUFFICS) $(CFLAGS) libs/blake2b-ref.c
$(BUILDDIR)$(CRYPT_PREFIX)crypt$(EXESUFFICS): blake2$(OBJSUFFICS) 3proxy_cryptmain$(OBJSUFFICS) base64$(OBJSUFFICS)
md4$(OBJSUFFICS): libs/md4.h libs/md4.c $(LN) $(LNOUT)$(BUILDDIR)$(CRYPT_PREFIX)crypt$(EXESUFFICS) $(LDFLAGS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) 3proxy_cryptmain$(OBJSUFFICS) $(LIBS)
$(CC) $(COUT)md4$(OBJSUFFICS) $(CFLAGS) libs/md4.c
md5$(OBJSUFFICS): libs/md5.h libs/md5.c
$(CC) $(COUT)md5$(OBJSUFFICS) $(CFLAGS) libs/md5.c
stringtable$(OBJSUFFICS): stringtable.c stringtable$(OBJSUFFICS): stringtable.c
$(CC) $(COUT)stringtable$(OBJSUFFICS) $(CFLAGS) stringtable.c $(CC) $(COUT)stringtable$(OBJSUFFICS) $(CFLAGS) stringtable.c
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) auth$(OBJSUFFICS) authradius$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) mycrypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(COMPATLIBS) $(VERSIONDEP) ssllib$(OBJSUFFICS): ssllib.c
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) authradius$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) mycrypt$(OBJSUFFICS) md5$(OBJSUFFICS) md4$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(CC) $(COUT)ssllib$(OBJSUFFICS) $(CFLAGS) ssllib.c
ssl$(OBJSUFFICS): ssl.c
$(CC) $(COUT)ssl$(OBJSUFFICS) $(CFLAGS) ssl.c
pcre$(OBJSUFFICS): pcre.c
$(CC) $(COUT)pcre$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITH_PCRE pcre.c
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) blake2$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(COMPATLIBS) $(VERSIONDEP)
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(COMPATLIBS) $(LIBS) $(PCRE_LIBS)

168
src/acl.c Normal file
View File

@ -0,0 +1,168 @@
/*
3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement
*/
#include "proxy.h"
int IPInentry(struct sockaddr *sa, struct iplist *ipentry){
int addrlen;
unsigned char *ip, *ipf, *ipt;
if(!sa || ! ipentry || *SAFAMILY(sa) != ipentry->family) return 0;
ip = (unsigned char *)SAADDR(sa);
ipf = (unsigned char *)&ipentry->ip_from;
ipt = (unsigned char *)&ipentry->ip_to;
addrlen = SAADDRLEN(sa);
if(memcmp(ip,ipf,addrlen) < 0 || memcmp(ip,ipt,addrlen) > 0) return 0;
return 1;
}
int ACLmatches(struct ace* acentry, struct clientparam * param){
struct userlist * userentry;
struct iplist *ipentry;
struct portlist *portentry;
struct period *periodentry;
unsigned char * username;
struct hostname * hstentry=NULL;
int i;
int match = 0;
username = param->username?param->username:(unsigned char *)"-";
if(acentry->src) {
for(ipentry = acentry->src; ipentry; ipentry = ipentry->next)
if(IPInentry((struct sockaddr *)&param->sincr, ipentry)) {
break;
}
if(!ipentry) return 0;
}
if((acentry->dst && (!SAISNULL(&param->req) || param->operation == UDPASSOC || param->operation==BIND)) || (acentry->dstnames && param->hostname)) {
for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next)
if(IPInentry((struct sockaddr *)&param->req, ipentry)) {
break;
}
if(!ipentry) {
if(acentry->dstnames && param->hostname){
for(i=0; param->hostname[i]; i++){
param->hostname[i] = tolower(param->hostname[i]);
}
while(i > 5 && param->hostname[i-1] == '.') param->hostname[i-1] = 0;
for(hstentry = acentry->dstnames; hstentry; hstentry = hstentry->next){
int lname, lhost;
switch(hstentry->matchtype){
case 0:
#ifndef _WIN32
if(strcasestr((char *)param->hostname, (char *)hstentry->name)) match = 1;
#else
if(strstr((char *)param->hostname, (char *)hstentry->name)) match = 1;
#endif
break;
case 1:
if(!strncasecmp((char *)param->hostname, (char *)hstentry->name, strlen((char *)hstentry->name)))
match = 1;
break;
case 2:
lname = strlen((char *)hstentry->name);
lhost = strlen((char *)param->hostname);
if(lhost > lname){
if(!strncasecmp((char *)param->hostname + (lhost - lname),
(char *)hstentry->name,
lname))
match = 1;
}
break;
default:
if(!strcasecmp((char *)param->hostname, (char *)hstentry->name)) match = 1;
break;
}
if(match) break;
}
}
}
if(!ipentry && !hstentry) return 0;
}
if(acentry->ports && (*SAPORT(&param->req) || param->operation == UDPASSOC || param->operation == BIND)) {
for (portentry = acentry->ports; portentry; portentry = portentry->next)
if(ntohs(*SAPORT(&param->req)) >= portentry->startport &&
ntohs(*SAPORT(&param->req)) <= portentry->endport) {
break;
}
if(!portentry) return 0;
}
if(acentry->wdays){
if(!(acentry -> wdays & wday)) return 0;
}
if(acentry->periods){
int start_time = (int)(param->time_start - basetime);
for(periodentry = acentry->periods; periodentry; periodentry = periodentry -> next)
if(start_time >= periodentry->fromtime && start_time < periodentry->totime){
break;
}
if(!periodentry) return 0;
}
if(acentry->users){
for(userentry = acentry->users; userentry; userentry = userentry->next)
if(!strcmp((char *)username, (char *)userentry->user)){
break;
}
if(!userentry) return 0;
}
if(acentry->operation) {
if((acentry->operation & param->operation) != param->operation){
return 0;
}
}
if(acentry->weight && (acentry->weight < param->weight)) return 0;
return 1;
}
int checkACL(struct clientparam * param){
struct ace* acentry;
if(!param->srv->acl) {
return 0;
}
for(acentry = param->srv->acl; acentry; acentry = acentry->next) {
if(ACLmatches(acentry, param)) {
param->nolog = acentry->nolog;
param->weight = acentry->weight;
if(acentry->action == 2) {
struct ace dup;
int res=60,i=0;
if(param->operation < 256 && !(param->operation & CONNECT)){
continue;
}
if(param->redirected && acentry->chains && SAISNULL(&acentry->chains->addr) && !*SAPORT(&acentry->chains->addr)) {
continue;
}
if(param->remsock != INVALID_SOCKET) {
return 0;
}
for(; i < conf.parentretries; i++){
dup = *acentry;
res = handleredirect(param, &dup);
if(!res) break;
if(param->remsock != INVALID_SOCKET) param->srv->so._closesocket(param->sostate, param->remsock);
param->remsock = INVALID_SOCKET;
}
return res;
}
return acentry->action;
}
}
return 3;
}

1439
src/auth.c

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2000-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2000-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -8,7 +8,7 @@
#ifndef NORADIUS #ifndef NORADIUS
#include "proxy.h" #include "proxy.h"
#include "libs/md5.h" #include <openssl/evp.h>
#define AUTH_VECTOR_LEN 16 #define AUTH_VECTOR_LEN 16
#define MAX_STRING_LEN 254 #define MAX_STRING_LEN 254
@ -166,7 +166,7 @@ static int ntry = 0;
int nradservers = 0; int nradservers = 0;
char radiussecret[64]=""; char radiussecret[64]="";
pthread_mutex_t rad_mutex; _3proxy_mutex_t rad_mutex;
void md5_calc(unsigned char *output, unsigned char *input, void md5_calc(unsigned char *output, unsigned char *input,
unsigned int inputlen); unsigned int inputlen);
@ -183,14 +183,19 @@ char *strNcpy(char *dest, const char *src, int n)
return dest; return dest;
} }
extern EVP_MD *md4;
extern EVP_MD *md5;
void md5_calc(unsigned char *output, unsigned char *input, void md5_calc(unsigned char *output, unsigned char *input,
unsigned int inlen) unsigned int inlen)
{ {
MD5_CTX context; EVP_MD_CTX *ctx = EVP_MD_CTX_new();
unsigned int len = 0;
MD5Init(&context); EVP_DigestInit_ex(ctx, md5, NULL);
MD5Update(&context, input, inlen); EVP_DigestUpdate(ctx, input, inlen);
MD5Final(output, &context); EVP_DigestFinal_ex(ctx, output, &len);
EVP_MD_CTX_free(ctx);
} }
@ -306,11 +311,7 @@ int radsend(struct clientparam * param, int auth, int stop){
int total_length; int total_length;
int len; int len;
int op; int op;
#ifdef NOIPV6 PROXYSOCKADDRTYPE saremote;
struct sockaddr_in saremote;
#else
struct sockaddr_in6 saremote;
#endif
struct pollfd fds[1]; struct pollfd fds[1];
char vector[AUTH_VECTOR_LEN]; char vector[AUTH_VECTOR_LEN];
radius_packet_t packet, rpacket; radius_packet_t packet, rpacket;
@ -331,11 +332,11 @@ int radsend(struct clientparam * param, int auth, int stop){
memset(&packet, 0, sizeof(packet)); memset(&packet, 0, sizeof(packet));
pthread_mutex_lock(&rad_mutex); _3proxy_mutex_lock(&rad_mutex);
if(auth)random_vector(packet.vector, param); if(auth)random_vector(packet.vector, param);
id = ((ntry++) & 0xff); id = ((ntry++) & 0xff);
pthread_mutex_unlock(&rad_mutex); _3proxy_mutex_unlock(&rad_mutex);
packet.code = auth?PW_AUTHENTICATION_REQUEST:PW_ACCOUNTING_REQUEST; packet.code = auth?PW_AUTHENTICATION_REQUEST:PW_ACCOUNTING_REQUEST;
packet.id=id; packet.id=id;

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement

76
src/blake2_compat.h Normal file
View File

@ -0,0 +1,76 @@
#ifndef BLAKE2_COMPAT_H
#define BLAKE2_COMPAT_H
#if defined(WITH_SSL)
#include <openssl/opensslv.h>
#endif
#if defined(WITH_SSL) && OPENSSL_VERSION_NUMBER >= 0x10100000L
#include <openssl/evp.h>
#include <string.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/params.h>
#include <openssl/core_names.h>
#endif
/*
* OpenSSL 1.1.0+ BLAKE2b implementation.
* Provides the same streaming API as libs/blake2.h but uses EVP internally.
*
* OpenSSL 3.0+: uses OSSL_DIGEST_PARAM_SIZE for proper custom output sizes.
* OpenSSL 1.1.x: computes full 64-byte output and truncates in blake2b_final.
*/
typedef EVP_MD_CTX *blake2b_state;
static int blake2b_init(blake2b_state *S, size_t outlen) {
*S = EVP_MD_CTX_new();
if (!*S) return -1;
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
size_t sz = outlen;
OSSL_PARAM params[2];
params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &sz);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_DigestInit_ex2(*S, EVP_blake2b512(), params)) {
#else
(void)outlen;
if (!EVP_DigestInit_ex(*S, EVP_blake2b512(), NULL)) {
#endif
EVP_MD_CTX_free(*S);
*S = NULL;
return -1;
}
return 0;
}
static int blake2b_update(blake2b_state *S, const void *in, size_t inlen) {
if (inlen == 0) return 0;
return EVP_DigestUpdate(*S, in, inlen) ? 0 : -1;
}
static int blake2b_final(blake2b_state *S, void *out, size_t outlen) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
unsigned int len = 0;
int ret = EVP_DigestFinal_ex(*S, out, &len) ? 0 : -1;
#else
unsigned char tmp[64];
unsigned int len = 0;
int ret = EVP_DigestFinal_ex(*S, tmp, &len) ? 0 : -1;
if (ret == 0) memcpy(out, tmp, outlen);
#endif
EVP_MD_CTX_free(*S);
*S = NULL;
return ret;
}
#else
#include "libs/blake2.h"
#endif
#endif /* BLAKE2_COMPAT_H */

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -22,10 +22,15 @@ int randomizer = 1;
void daemonize(void){ void daemonize(void){
if(fork() > 0) { pid_t pid = fork();
if(pid > 0) {
usleep(SLEEPTIME); usleep(SLEEPTIME);
_exit(0); _exit(0);
} }
if(pid < 0) {
perror("fork()");
return;
}
setsid(); setsid();
} }
@ -33,36 +38,38 @@ int randomizer = 1;
unsigned char **stringtable = NULL; unsigned char **stringtable = NULL;
#ifdef WITH_LINUX_FUTEX #ifdef WITH_UN
int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3) void make_un(const unsigned char *path, struct sockaddr_un * sun){
{ memset(sun, 0, sizeof(*sun));
return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3); sun->sun_family = AF_UNIX;
} strncpy(sun->sun_path, (char *)path, sizeof(sun->sun_path) - 1);
int mutex_lock(int *val) if(*path == '@')*sun->sun_path = 0;
{
int c;
if ((c = __sync_val_compare_and_swap(val, 0, 1)) != 0)
do {
if(c == 2 || __sync_val_compare_and_swap(val, 1, 2) != 0)
sys_futex(val, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
} while ((c = __sync_val_compare_and_swap(val, 0, 2)) != 0);
return 0;
}
int mutex_unlock(int *val)
{
if(__sync_fetch_and_sub (val, 1) != 1){
*val = 0;
sys_futex(val, FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
}
return 0;
} }
#endif #endif
int myinet_ntop(int af, void *src, char *dst, socklen_t size){ int myinet_ntop(int af, void *src, char *dst, socklen_t size){
#ifdef WITH_UN
if(af == AF_UNIX){
struct sockaddr_un *sun = (struct sockaddr_un *)src;
int ephemeral = 0;
char *path = sun->sun_path;
char *basename;
if(!path[0] && path[1]){
ephemeral = 1;
*dst++ = '@';
path++;
}
basename = strrchr(path, '/');
if(basename) basename++;
else basename = path;
if(size > 0){
strncpy(dst, basename, (size > 40) ? 40 : size - (ephemeral + 1));
dst[((size > 40) ? 40 : size - (ephemeral + 1))] = 0;
}
return (int)strlen(dst);
}
#endif
#ifndef NOIPV6 #ifndef NOIPV6
if(af != AF_INET6){ if(af != AF_INET6){
#endif #endif
@ -108,7 +115,11 @@ int timeouts[12] = {
}; };
struct extparam conf = { struct extparam conf = {
.threadinit = {0, 0}, #ifdef _WIN32
.threadinit = NULL,
#else
.threadinit = 0,
#endif
.timeouts = timeouts, .timeouts = timeouts,
.acl = NULL, .acl = NULL,
.conffile = NULL, .conffile = NULL,
@ -213,6 +224,7 @@ int
FD_ZERO(&writefd); FD_ZERO(&writefd);
FD_ZERO(&oobfd); FD_ZERO(&oobfd);
for(i=0; i<nfds; i++){ for(i=0; i<nfds; i++){
if(fds[i].fd >= FD_SETSIZE) continue;
if((fds[i].events&POLLIN))FD_SET(fds[i].fd, &readfd); if((fds[i].events&POLLIN))FD_SET(fds[i].fd, &readfd);
if((fds[i].events&POLLOUT))FD_SET(fds[i].fd, &writefd); if((fds[i].events&POLLOUT))FD_SET(fds[i].fd, &writefd);
if((fds[i].events&POLLPRI))FD_SET(fds[i].fd, &oobfd); if((fds[i].events&POLLPRI))FD_SET(fds[i].fd, &oobfd);
@ -221,6 +233,7 @@ int
} }
if((num = select(((int)(maxfd))+1, &readfd, &writefd, &oobfd, &tv)) < 1) return num; if((num = select(((int)(maxfd))+1, &readfd, &writefd, &oobfd, &tv)) < 1) return num;
for(i=0; i<nfds; i++){ for(i=0; i<nfds; i++){
if(fds[i].fd >= FD_SETSIZE) continue;
if(FD_ISSET(fds[i].fd, &readfd)) fds[i].revents |= POLLIN; if(FD_ISSET(fds[i].fd, &readfd)) fds[i].revents |= POLLIN;
if(FD_ISSET(fds[i].fd, &writefd)) fds[i].revents |= POLLOUT; if(FD_ISSET(fds[i].fd, &writefd)) fds[i].revents |= POLLOUT;
if(FD_ISSET(fds[i].fd, &oobfd)) fds[i].revents |= POLLPRI; if(FD_ISSET(fds[i].fd, &oobfd)) fds[i].revents |= POLLPRI;
@ -524,14 +537,14 @@ int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa,
fcntl(sock,F_SETFL, O_NONBLOCK | fcntl(sock,F_GETFL)); fcntl(sock,F_SETFL, O_NONBLOCK | fcntl(sock,F_GETFL));
#endif #endif
if(param?param->srv->so._connect(param->sostate, sock,sa,size) : so._connect(so.state, sock,sa,size)) { if(param?param->srv->so._connect(param->sostate, sock,sa,size) : so._connect(so.state, sock,sa,size)) {
if(errno != EAGAIN && errno != EINPROGRESS) return (13); if(errno != EAGAIN && errno != EINPROGRESS) return 13;
} }
if(!errno) return 0; if(!errno) return 0;
memset(fds, 0, sizeof(fds)); memset(fds, 0, sizeof(fds));
fds[0].fd = sock; fds[0].fd = sock;
fds[0].events = POLLOUT; fds[0].events = POLLOUT;
if((param?param->srv->so._poll(param->sostate, fds, 1, to*1000):so._poll(so.state, fds, 1, to*1000)) <= 0 || !(fds[0].revents & POLLOUT) || (fds[0].revents & (POLLERR|POLLHUP))) { if((param?param->srv->so._poll(param->sostate, fds, 1, to*1000):so._poll(so.state, fds, 1, to*1000)) <= 0 || !(fds[0].revents & POLLOUT) || (fds[0].revents & (POLLERR|POLLHUP))) {
return (13); return 13;
} }
return 0; return 0;
} }
@ -561,8 +574,17 @@ int doconnect(struct clientparam * param){
memcpy(SAADDR(&param->sinsr), SAADDR(&param->req), SAADDRLEN(&param->req)); memcpy(SAADDR(&param->sinsr), SAADDR(&param->req), SAADDRLEN(&param->req));
} }
if(!*SAPORT(&param->sinsr))*SAPORT(&param->sinsr) = *SAPORT(&param->req); if(!*SAPORT(&param->sinsr))*SAPORT(&param->sinsr) = *SAPORT(&param->req);
if ((param->remsock=param->srv->so._socket(param->sostate, SASOCK(&param->sinsr), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {return (11);} if ((param->remsock=param->srv->so._socket(param->sostate, SASOCK(&param->sinsr), SOCK_STREAM,
#ifdef WITH_UN
*SAFAMILY(&param->sinsr) == AF_UNIX? 0 :
#endif
IPPROTO_TCP
)) == INVALID_SOCKET) {return (11);}
if(SAISNULL(&param->sinsl)){ if(SAISNULL(&param->sinsl)){
#ifdef WITH_UN
if(*SAFAMILY(&param->sinsr) == AF_UNIX) param->sinsl = param->sinsr;
else
#endif
#ifndef NOIPV6 #ifndef NOIPV6
if(*SAFAMILY(&param->sinsr) == AF_INET6) param->sinsl = param->srv->extsa6; if(*SAFAMILY(&param->sinsr) == AF_INET6) param->sinsl = param->srv->extsa6;
else else
@ -602,6 +624,9 @@ int doconnect(struct clientparam * param){
if(*SAFAMILY(&param->sinsl) == AF_INET6 && param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IPV6, IPV6_BOUND_IF, &idx, sizeof(idx))) return 12; if(*SAFAMILY(&param->sinsl) == AF_INET6 && param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IPV6, IPV6_BOUND_IF, &idx, sizeof(idx))) return 12;
#endif #endif
} }
#endif
#ifdef WITH_UN
if(*SAFAMILY(&param->sinsl) != AF_UNIX)
#endif #endif
if(param->srv->so._bind(param->sostate, param->remsock, (struct sockaddr*)&param->sinsl, SASIZE(&param->sinsl))==-1) { if(param->srv->so._bind(param->sostate, param->remsock, (struct sockaddr*)&param->sinsl, SASIZE(&param->sinsl))==-1) {
return 12; return 12;
@ -637,7 +662,7 @@ int scanaddr(const unsigned char *s, uint32_t * ip, uint32_t * mask) {
RESOLVFUNC resolvfunc = NULL; RESOLVFUNC resolvfunc = NULL;
#ifndef _WIN32 #ifndef _WIN32
pthread_mutex_t gethostbyname_mutex; _3proxy_mutex_t gethostbyname_mutex;
int ghbn_init = 0; int ghbn_init = 0;
#endif #endif
@ -693,10 +718,10 @@ uint32_t getip(unsigned char *name){
#ifndef NOSTDRESOLVE #ifndef NOSTDRESOLVE
#if !defined(_WIN32) && !defined(GETHOSTBYNAME_R) #if !defined(_WIN32) && !defined(GETHOSTBYNAME_R)
if(!ghbn_init){ if(!ghbn_init){
pthread_mutex_init(&gethostbyname_mutex, NULL); _3proxy_mutex_init(&gethostbyname_mutex);
ghbn_init++; ghbn_init++;
} }
pthread_mutex_lock(&gethostbyname_mutex); _3proxy_mutex_lock(&gethostbyname_mutex);
#endif #endif
hp=gethostbyname((char *)name); hp=gethostbyname((char *)name);
if (!hp && conf.demanddialprog) { if (!hp && conf.demanddialprog) {
@ -705,7 +730,7 @@ uint32_t getip(unsigned char *name){
} }
retval = hp?*(uint32_t *)hp->h_addr:0; retval = hp?*(uint32_t *)hp->h_addr:0;
#if !defined(_WIN32) && !defined(GETHOSTBYNAME_R) #if !defined(_WIN32) && !defined(GETHOSTBYNAME_R)
pthread_mutex_unlock(&gethostbyname_mutex); _3proxy_mutex_unlock(&gethostbyname_mutex);
#endif #endif
#ifdef GETHOSTBYNAME_R #ifdef GETHOSTBYNAME_R
#undef gethostbyname #undef gethostbyname

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -7,6 +7,12 @@
*/ */
#include "proxy.h" #include "proxy.h"
#ifdef WITH_SSL
void ssl_install(void);
#endif
#ifdef WITH_PCRE
void pcre_install(void);
#endif
#ifndef _WIN32 #ifndef _WIN32
#include <sys/resource.h> #include <sys/resource.h>
#include <pwd.h> #include <pwd.h>
@ -20,12 +26,10 @@
#define DEFAULTCONFIG conf.stringtable[25] #define DEFAULTCONFIG conf.stringtable[25]
#endif #endif
pthread_mutex_t bandlim_mutex; _3proxy_mutex_t bandlim_mutex;
pthread_mutex_t connlim_mutex; _3proxy_mutex_t connlim_mutex;
pthread_mutex_t tc_mutex; _3proxy_mutex_t tc_mutex;
pthread_mutex_t pwl_mutex; _3proxy_mutex_t config_mutex;
pthread_mutex_t hash_mutex;
pthread_mutex_t config_mutex;
int haveerror = 0; int haveerror = 0;
int linenum = 0; int linenum = 0;
@ -154,8 +158,8 @@ int start_proxy_thread(struct child * chp){
#ifdef _WIN32 #ifdef _WIN32
HANDLE h; HANDLE h;
#endif #endif
char r[1];
_3proxy_sem_lock(conf.threadinit);
#ifdef _WIN32 #ifdef _WIN32
#ifndef _WINCE #ifndef _WINCE
h = (HANDLE)_beginthreadex((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, (void *) chp, (DWORD)0, &thread); h = (HANDLE)_beginthreadex((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, (void *) chp, (DWORD)0, &thread);
@ -170,14 +174,8 @@ int start_proxy_thread(struct child * chp){
pthread_create(&thread, &pa, startsrv, (void *)chp); pthread_create(&thread, &pa, startsrv, (void *)chp);
pthread_attr_destroy(&pa); pthread_attr_destroy(&pa);
#endif #endif
#ifdef _WIN32 _3proxy_sem_lock(conf.threadinit);
ReadFile(conf.threadinit[0], r, 1, NULL, NULL); _3proxy_sem_unlock(conf.threadinit);
#else
while(read(conf.threadinit[0], r, 1) !=1) if(errno != EINTR) {
fprintf(stderr, "pipe failed\n");
return 40;
}
#endif
if(haveerror) { if(haveerror) {
fprintf(stderr, "Service not started on line: %d%s\n", linenum, haveerror == 2? ": insufficient memory":""); fprintf(stderr, "Service not started on line: %d%s\n", linenum, haveerror == 2? ": insufficient memory":"");
return(40); return(40);
@ -197,7 +195,7 @@ static int h_proxy(int argc, unsigned char ** argv){
childdef.service = S_PROXY; childdef.service = S_PROXY;
childdef.helpmessage = " -n - no NTLM support\n"; childdef.helpmessage = " -n - no NTLM support\n";
#ifdef NOIPV6 #ifdef NOIPV6
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.hashsize)){ if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize)){
fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, proxy may run very slow\n", linenum); fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, proxy may run very slow\n", linenum);
} }
#endif #endif
@ -230,7 +228,7 @@ static int h_proxy(int argc, unsigned char ** argv){
childdef.service = S_SOCKS; childdef.service = S_SOCKS;
childdef.helpmessage = " -n - no NTLM support\n"; childdef.helpmessage = " -n - no NTLM support\n";
#ifdef NOIPV6 #ifdef NOIPV6
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.hashsize)){ if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize)){
fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, socks may run very slow\n", linenum); fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, socks may run very slow\n", linenum);
} }
#endif #endif
@ -276,7 +274,7 @@ static int h_proxy(int argc, unsigned char ** argv){
childdef.service = S_DNSPR; childdef.service = S_DNSPR;
childdef.helpmessage = " -s - simple DNS forwarding - do not use 3proxy resolver / name cache\n"; childdef.helpmessage = " -s - simple DNS forwarding - do not use 3proxy resolver / name cache\n";
#ifndef NOIPV6 #ifndef NOIPV6
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.hashsize) || resolvfunc == fakeresolver){ if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize) || resolvfunc == fakeresolver){
fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, dnspr will not work as expected\n", linenum); fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, dnspr will not work as expected\n", linenum);
} }
#endif #endif
@ -285,14 +283,20 @@ static int h_proxy(int argc, unsigned char ** argv){
} }
static int h_internal(int argc, unsigned char ** argv){ static int h_internal(int argc, unsigned char ** argv){
getip46(46, argv[1], (struct sockaddr *)&conf.intsa); #ifdef WITH_UN
if(!strncmp((char *)argv[1], "unix:", 5)){
make_un(argv[1] +5, (struct sockaddr_un *)&conf.intsa);
}
else
#endif
getip46(46, argv[1], (struct sockaddr *)&conf.intsa);
return 0; return 0;
} }
static int h_external(int argc, unsigned char ** argv){ static int h_external(int argc, unsigned char ** argv){
int res; int res;
#ifndef NOIPV6 #ifndef NOIPV6
struct sockaddr_in6 sa6; PROXYSOCKADDRTYPE sa6;
memset(&sa6, 0, sizeof(sa6)); memset(&sa6, 0, sizeof(sa6));
res = getip46(46, argv[1], (struct sockaddr *)&sa6); res = getip46(46, argv[1], (struct sockaddr *)&sa6);
if(!res) return 1; if(!res) return 1;
@ -335,10 +339,10 @@ static int h_log(int argc, unsigned char ** argv){
else if(*argv[1]=='&'){ else if(*argv[1]=='&'){
conf.logfunc = logsql; conf.logfunc = logsql;
if(notchanged) return 0; if(notchanged) return 0;
pthread_mutex_lock(&log_mutex); _3proxy_mutex_lock(&log_mutex);
close_sql(); close_sql();
init_sql((char *)argv[1]+1); init_sql((char *)argv[1]+1);
pthread_mutex_unlock(&log_mutex); _3proxy_mutex_unlock(&log_mutex);
} }
#endif #endif
#ifndef NORADIUS #ifndef NORADIUS
@ -439,18 +443,6 @@ static int h_counter(int argc, unsigned char **argv){
fprintf(stderr, "Not a counter file %s, line %d\n", argv[1], linenum); fprintf(stderr, "Not a counter file %s, line %d\n", argv[1], linenum);
return 2; return 2;
} }
#ifdef _TIME64_T_DEFINED
#ifdef _MAX__TIME64_T
#define MAX_COUNTER_TIME (_MAX__TIME64_T)
#elif defined (MAX__TIME64_T)
#define MAX_COUNTER_TIME (MAX__TIME64_T)
#else
#define MAX_COUNTER_TIME (0x793406fff)
#endif
#else
#define MAX_COUNTER_TIME ((sizeof(time_t)>4)?(time_t)0x793406fff:(time_t)0x7fffffff)
#endif
if(ch1.updated < 0 || ch1.updated >= MAX_COUNTER_TIME){ if(ch1.updated < 0 || ch1.updated >= MAX_COUNTER_TIME){
fprintf(stderr, "Invalid or corrupted counter file %s. Use countersutil utility to convert from older version\n", argv[1]); fprintf(stderr, "Invalid or corrupted counter file %s. Use countersutil utility to convert from older version\n", argv[1]);
return 3; return 3;
@ -526,46 +518,47 @@ static int h_auth(int argc, unsigned char **argv){
} }
static int h_users(int argc, unsigned char **argv){ static int h_users(int argc, unsigned char **argv){
int j; static char dummy;
unsigned char *arg; int j;
struct passwords *pwl = NULL; unsigned char *arg;
char *pw[2];
for (j = 1; j<argc; j++) { for (j = 1; j < argc; j++) {
if(!(pwl = myalloc(sizeof(struct passwords)))) { arg = (unsigned char *)strchr((char *)argv[j], ':');
return(21); if (!arg) continue;
} *arg = 0;
memset(pwl, 0, sizeof(struct passwords)); pw[0] = (char *)argv[j];
arg = (unsigned char *)strchr((char *)argv[j], ':'); if (arg[1] && arg[2] && arg[3] == ':') {
if(!arg||!arg[1]||!arg[2]||arg[3]!=':') { pw[1] = (char *)(arg + 4);
pwl->user = (unsigned char *)mystrdup((char *)argv[j]); if (arg[1] == 'N' && arg[2] == 'T') {
pwl->pwtype = SYS; #ifdef WITH_SSL
} if (!pwnt_table.ihashtable && inithashtable(&pwnt_table, 16, 32, 1048576))
else { return 3;
*arg = 0; hashadd(&pwnt_table, pw, &dummy, MAX_COUNTER_TIME);
pwl->user = (unsigned char *)mystrdup((char *)argv[j]); #endif
continue;
}
if (arg[1] == 'C' && arg[2] == 'R') {
if (!pwcr_table.ihashtable && inithashtable(&pwcr_table, 16, 32, 1048576))
return 3;
hashadd(&pwcr_table, pw[0], pw[1], MAX_COUNTER_TIME);
continue;
}
if (arg[1] == 'C' && arg[2] == 'L') {
/* fall through to CL handling below */
} else {
continue;
}
} else {
pw[1] = (char *)(arg + 1);
}
if((arg[1] == 'C' && arg[2] == 'L' && (pwl->pwtype = CL)) || if (!pw_table.ihashtable && inithashtable(&pw_table, 16, 32, 1048576))
(arg[1] == 'C' && arg[2] == 'R' && (pwl->pwtype = CR)) || return 3;
(arg[1] == 'N' && arg[2] == 'T' && (pwl->pwtype = NT)) || hashadd(&pw_table, pw, &dummy, MAX_COUNTER_TIME);
(arg[1] == 'L' && arg[2] == 'M' && (pwl->pwtype = LM))){ }
pwl->password = (unsigned char *)mystrdup((char *)arg+4); return 0;
}
else {
pwl->password = (unsigned char *) mystrdup((char *)arg + 1);
pwl->pwtype = UN;
}
if(!pwl->password) return 3;
}
if(!pwl->user) return 21;
pthread_mutex_lock(&pwl_mutex);
pwl->next = conf.pwl;
conf.pwl = pwl;
pthread_mutex_unlock(&pwl_mutex);
}
return 0;
} }
static int h_maxconn(int argc, unsigned char **argv){ static int h_maxconn(int argc, unsigned char **argv){
@ -590,7 +583,7 @@ static int h_maxconn(int argc, unsigned char **argv){
static int h_backlog(int argc, unsigned char **argv){ static int h_backlog(int argc, unsigned char **argv){
conf.backlog = atoi((char *)argv[1]); conf.backlog = atoi((char *)argv[1]);
if(conf.maxchild < 0) { if(conf.backlog < 0) {
return(1); return(1);
} }
return 0; return 0;
@ -649,14 +642,14 @@ static int h_fakeresolve(int argc, unsigned char **argv){
} }
static int h_nscache(int argc, unsigned char **argv){ static int h_nscache(int argc, unsigned char **argv){
int res; unsigned res;
res = atoi((char *)argv[1]); res = (unsigned)atoi((char *)argv[1]);
if(res < 256) { if(res < 256) {
fprintf(stderr, "Invalid NS cache size: %d\n", res); fprintf(stderr, "Invalid NS cache size: %d\n", res);
return 1; return 1;
} }
if(inithashtable(&dns_table, (unsigned)res)){ if(dns_table.growlimit != res && inithashtable(&dns_table, (res >> 2), (res >> 2), res)){
fprintf(stderr, "Failed to initialize NS cache\n"); fprintf(stderr, "Failed to initialize NS cache\n");
return 2; return 2;
} }
@ -672,14 +665,14 @@ static int h_parentretries(int argc, unsigned char **argv){
} }
static int h_nscache6(int argc, unsigned char **argv){ static int h_nscache6(int argc, unsigned char **argv){
int res; unsigned res;
res = atoi((char *)argv[1]); res = (unsigned)atoi((char *)argv[1]);
if(res < 256) { if(res < 256) {
fprintf(stderr, "Invalid NS cache size: %d\n", res); fprintf(stderr, "Invalid NS cache size: %d\n", res);
return 1; return 1;
} }
if(inithashtable(&dns6_table, (unsigned)res)){ if(dns6_table.growlimit != res &&inithashtable(&dns6_table, (res>>2), (res>>2), res)){
fprintf(stderr, "Failed to initialize NS cache\n"); fprintf(stderr, "Failed to initialize NS cache\n");
return 2; return 2;
} }
@ -687,11 +680,7 @@ static int h_nscache6(int argc, unsigned char **argv){
} }
static int h_nsrecord(int argc, unsigned char **argv){ static int h_nsrecord(int argc, unsigned char **argv){
#ifndef NOIPV6 PROXYSOCKADDRTYPE sa;
struct sockaddr_in6 sa;
#else
struct sockaddr_in sa;
#endif
memset(&sa, 0, sizeof(sa)); memset(&sa, 0, sizeof(sa));
if(!getip46(46, argv[2], (struct sockaddr *)&sa)) return 1; if(!getip46(46, argv[2], (struct sockaddr *)&sa)) return 1;
@ -771,7 +760,7 @@ struct redirdesc redirs[] = {
static int h_parent(int argc, unsigned char **argv){ static int h_parent(int argc, unsigned char **argv){
struct ace *acl = NULL; struct ace *acl = NULL;
struct chain *chains; struct chain *chains;
char * cidr; char * cidr = NULL;
int i; int i;
acl = conf.acl; acl = conf.acl;
@ -790,23 +779,45 @@ static int h_parent(int argc, unsigned char **argv){
chains->weight = (unsigned)atoi((char *)argv[1]); chains->weight = (unsigned)atoi((char *)argv[1]);
if(chains->weight == 0 || chains->weight >1000) { if(chains->weight == 0 || chains->weight >1000) {
fprintf(stderr, "Chaining error: bad chain weight %u line %d\n", chains->weight, linenum); fprintf(stderr, "Chaining error: bad chain weight %u line %d\n", chains->weight, linenum);
myfree(chains);
return(3); return(3);
} }
for(i = 0; redirs[i].name ; i++){ for(i = 0; redirs[i].name ; i++){
if(!strcmp((char *)argv[2], redirs[i].name)) { int len;
len = strlen(redirs[i].name);
if(!strncmp((char *)argv[2], redirs[i].name, len)
&& (argv[2][len] == 0 || (argv[2][len] == 's' && argv[2][len+1] == 0))
) {
chains->type = redirs[i].redir; chains->type = redirs[i].redir;
if(argv[2][len] == 's') chains->secure = 1;
break; break;
} }
} }
if(!redirs[i].name) { if(!redirs[i].name) {
fprintf(stderr, "Chaining error: bad chain type (%s)\n", argv[2]); fprintf(stderr, "Chaining error: bad chain type (%s)\n", argv[2]);
myfree(chains);
return(4); return(4);
} }
#ifdef WITH_UN
if(!strncmp((char *)argv[3], "unix:", 5)){
make_un(argv[3] + 5, (struct sockaddr_un*)&chains->addr);
}
else {
#endif
cidr = strchr((char *)argv[3], '/'); cidr = strchr((char *)argv[3], '/');
if(cidr) *cidr = 0; if(cidr) *cidr = 0;
if(!getip46(46, argv[3], (struct sockaddr *)&chains->addr)) return (5); if(!getip46(46, argv[3], (struct sockaddr *)&chains->addr)) {
myfree(chains);
return (5);
}
#ifdef WITH_UN
}
#endif
chains->exthost = (unsigned char *)mystrdup((char *)argv[3]); chains->exthost = (unsigned char *)mystrdup((char *)argv[3]);
if(!chains->exthost) return 21; if(!chains->exthost) {
myfree(chains);
return 21;
}
if(cidr){ if(cidr){
*cidr = '/'; *cidr = '/';
chains->cidr = atoi(cidr + 1); chains->cidr = atoi(cidr + 1);
@ -842,11 +853,7 @@ static int h_nolog(int argc, unsigned char **argv){
} }
int scanipl(unsigned char *arg, struct iplist *dst){ int scanipl(unsigned char *arg, struct iplist *dst){
#ifndef NOIPV6 PROXYSOCKADDRTYPE sa;
struct sockaddr_in6 sa;
#else
struct sockaddr_in sa;
#endif
char * slash, *dash; char * slash, *dash;
int masklen, addrlen; int masklen, addrlen;
int res; int res;
@ -1223,7 +1230,10 @@ static int h_ace(int argc, unsigned char **argv){
} }
memset(acl->chains, 0, sizeof(struct chain)); memset(acl->chains, 0, sizeof(struct chain));
acl->chains->type = R_HTTP; acl->chains->type = R_HTTP;
if(!getip46(46, argv[1], (struct sockaddr *)&acl->chains->addr)) return 5; if(!getip46(46, argv[1], (struct sockaddr *)&acl->chains->addr)) {
freeacl(acl);
return 5;
}
*SAPORT(&acl->chains->addr) = htons((uint16_t)atoi((char *)argv[2])); *SAPORT(&acl->chains->addr) = htons((uint16_t)atoi((char *)argv[2]));
acl->chains->weight = 1000; acl->chains->weight = 1000;
case ALLOW: case ALLOW:
@ -1251,7 +1261,7 @@ static int h_ace(int argc, unsigned char **argv){
sscanf((char *)argv[1], "%u", &ncl->rate); sscanf((char *)argv[1], "%u", &ncl->rate);
sscanf((char *)argv[2], "%u", &ncl->period); sscanf((char *)argv[2], "%u", &ncl->period);
} }
pthread_mutex_lock(&connlim_mutex); _3proxy_mutex_lock(&connlim_mutex);
if(!conf.connlimiter){ if(!conf.connlimiter){
conf.connlimiter = ncl; conf.connlimiter = ncl;
} }
@ -1261,7 +1271,7 @@ static int h_ace(int argc, unsigned char **argv){
for(cli = conf.connlimiter; cli->next; cli = cli->next); for(cli = conf.connlimiter; cli->next; cli = cli->next);
cli->next = ncl; cli->next = ncl;
} }
pthread_mutex_unlock(&connlim_mutex); _3proxy_mutex_unlock(&connlim_mutex);
break; break;
case BANDLIM: case BANDLIM:
@ -1283,7 +1293,7 @@ static int h_ace(int argc, unsigned char **argv){
return(4); return(4);
} }
} }
pthread_mutex_lock(&bandlim_mutex); _3proxy_mutex_lock(&bandlim_mutex);
if(!strcmp((char *)argv[0], "bandlimin") || !strcmp((char *)argv[0], "nobandlimin")){ if(!strcmp((char *)argv[0], "bandlimin") || !strcmp((char *)argv[0], "nobandlimin")){
if(!conf.bandlimiter){ if(!conf.bandlimiter){
conf.bandlimiter = nbl; conf.bandlimiter = nbl;
@ -1307,7 +1317,7 @@ static int h_ace(int argc, unsigned char **argv){
} }
} }
conf.bandlimver++; conf.bandlimver++;
pthread_mutex_unlock(&bandlim_mutex); _3proxy_mutex_unlock(&bandlim_mutex);
break; break;
case COUNTIN: case COUNTIN:
@ -1359,7 +1369,7 @@ static int h_ace(int argc, unsigned char **argv){
} }
} }
} }
pthread_mutex_lock(&tc_mutex); _3proxy_mutex_lock(&tc_mutex);
if(!conf.trafcounter){ if(!conf.trafcounter){
conf.trafcounter = tl; conf.trafcounter = tl;
} }
@ -1369,7 +1379,7 @@ static int h_ace(int argc, unsigned char **argv){
for(ntl = conf.trafcounter; ntl->next; ntl = ntl->next); for(ntl = conf.trafcounter; ntl->next; ntl = ntl->next);
ntl->next = tl; ntl->next = tl;
} }
pthread_mutex_unlock(&tc_mutex); _3proxy_mutex_unlock(&tc_mutex);
} }
return 0; return 0;
@ -1397,21 +1407,6 @@ static int h_delimchar(int argc, unsigned char **argv){
static int h_radius(int argc, unsigned char **argv){ static int h_radius(int argc, unsigned char **argv){
uint16_t port; uint16_t port;
/*
int oldrad;
#ifdef NOIPV6
struct sockaddr_in bindaddr;
#else
struct sockaddr_in6 bindaddr;
#endif
oldrad = nradservers;
nradservers = 0;
for(; oldrad; oldrad--){
if(radiuslist[oldrad].logsock >= 0) so._closesocket(radiuslist[oldrad].logsock);
radiuslist[oldrad].logsock = -1;
}
*/
memset(radiuslist, 0, sizeof(radiuslist)); memset(radiuslist, 0, sizeof(radiuslist));
if(strlen((char *)argv[1]) > 63) argv[1][63] = 0; if(strlen((char *)argv[1]) > 63) argv[1][63] = 0;
strcpy(radiussecret, (char *)argv[1]); strcpy(radiussecret, (char *)argv[1]);
@ -1422,21 +1417,18 @@ static int h_radius(int argc, unsigned char **argv){
s++; s++;
} }
if( !getip46(46, argv[nradservers + 2], (struct sockaddr *)&radiuslist[nradservers].authaddr)) return 1; if( !getip46(46, argv[nradservers + 2], (struct sockaddr *)&radiuslist[nradservers].authaddr)) return 1;
if( s && !getip46(46, (unsigned char *)s+1, (struct sockaddr *)&radiuslist[nradservers].localaddr)) return 2; if( s && !getip46(46, (unsigned char *)s, (struct sockaddr *)&radiuslist[nradservers].localaddr)) return 2;
if(!*SAPORT(&radiuslist[nradservers].authaddr))*SAPORT(&radiuslist[nradservers].authaddr) = htons(1812); if(!*SAPORT(&radiuslist[nradservers].authaddr))*SAPORT(&radiuslist[nradservers].authaddr) = htons(1812);
port = ntohs(*SAPORT(&radiuslist[nradservers].authaddr)); port = ntohs(*SAPORT(&radiuslist[nradservers].authaddr));
radiuslist[nradservers].logaddr = radiuslist[nradservers].authaddr; radiuslist[nradservers].logaddr = radiuslist[nradservers].authaddr;
*SAPORT(&radiuslist[nradservers].logaddr) = htons(port+1); *SAPORT(&radiuslist[nradservers].logaddr) = htons(port+1);
/*
bindaddr = radiuslist[nradservers].localaddr;
if ((radiuslist[nradservers].logsock = so._socket(SASOCK(&radiuslist[nradservers].logaddr), SOCK_DGRAM, 0)) < 0) return 2;
if (so._bind(radiuslist[nradservers].logsock, (struct sockaddr *)&bindaddr, SASIZE(&bindaddr))) return 3;
*/
} }
return 0; return 0;
} }
#endif #endif
static int h_authcache(int argc, unsigned char **argv){ static int h_authcache(int argc, unsigned char **argv){
int authcachesize = 0;
conf.authcachetype = 0; conf.authcachetype = 0;
if(strstr((char *) *(argv + 1), "ip")) conf.authcachetype |= 1; if(strstr((char *) *(argv + 1), "ip")) conf.authcachetype |= 1;
if(strstr((char *) *(argv + 1), "user")) conf.authcachetype |= 2; if(strstr((char *) *(argv + 1), "user")) conf.authcachetype |= 2;
@ -1444,13 +1436,35 @@ static int h_authcache(int argc, unsigned char **argv){
if(strstr((char *) *(argv + 1), "limit")) conf.authcachetype |= 8; if(strstr((char *) *(argv + 1), "limit")) conf.authcachetype |= 8;
if(strstr((char *) *(argv + 1), "acl")) conf.authcachetype |= 16; if(strstr((char *) *(argv + 1), "acl")) conf.authcachetype |= 16;
if(strstr((char *) *(argv + 1), "ext")) conf.authcachetype |= 32; if(strstr((char *) *(argv + 1), "ext")) conf.authcachetype |= 32;
if(strstr((char *) *(argv + 1), "dstaddr")) conf.authcachetype |= 64;
if(strstr((char *) *(argv + 1), "dstport")) conf.authcachetype |= 128;
if(strstr((char *) *(argv + 1), "dsthost")) conf.authcachetype |= 256;
if(strstr((char *) *(argv + 1), "dstoper")) conf.authcachetype |= 512;
if(strstr((char *) *(argv + 1), "srvaddr")) conf.authcachetype |= 1024;
if(strstr((char *) *(argv + 1), "srvport")) conf.authcachetype |= 2048;
if(argc > 2) conf.authcachetime = (unsigned) atoi((char *) *(argv + 2)); if(argc > 2) conf.authcachetime = (unsigned) atoi((char *) *(argv + 2));
if(argc > 3) authcachesize = (unsigned) atoi((char *) *(argv + 3));
if(!conf.authcachetype) conf.authcachetype = 6; if(!conf.authcachetype) conf.authcachetype = 6;
if(!conf.authcachetime) conf.authcachetime = 600; if(!conf.authcachetime) conf.authcachetime = 600;
if(!authcachesize) authcachesize = 65536*4;
if(auth_table.growlimit != authcachesize && inithashtable(&auth_table, authcachesize < 1024? authcachesize:1024, authcachesize < 1024? authcachesize:1024, authcachesize)){
fprintf(stderr, "Failed to initialize auth cache\n");
return 2;
}
return 0; return 0;
} }
static int h_plugin(int argc, unsigned char **argv){ static int h_plugin(int argc, unsigned char **argv){
#ifdef WITH_SSL
if(argc >= 3 && !strcmp((char *)argv[2], "ssl_plugin")){
return 0;
}
#endif
#ifdef WITH_PCRE
if(argc >= 3 && !strcmp((char *)argv[2], "pcre_plugin")){
return 0;
}
#endif
#ifdef NOPLUGINS #ifdef NOPLUGINS
return 999; return 999;
#else #else
@ -1653,7 +1667,7 @@ struct commands commandhandlers[]={
{commandhandlers+53, "filtermaxsize", h_filtermaxsize, 2, 2}, {commandhandlers+53, "filtermaxsize", h_filtermaxsize, 2, 2},
{commandhandlers+54, "nolog", h_nolog, 1, 1}, {commandhandlers+54, "nolog", h_nolog, 1, 1},
{commandhandlers+55, "weight", h_nolog, 2, 2}, {commandhandlers+55, "weight", h_nolog, 2, 2},
{commandhandlers+56, "authcache", h_authcache, 2, 3}, {commandhandlers+56, "authcache", h_authcache, 2, 4},
{commandhandlers+57, "smtpp", h_proxy, 1, 0}, {commandhandlers+57, "smtpp", h_proxy, 1, 0},
{commandhandlers+58, "delimchar",h_delimchar, 2, 2}, {commandhandlers+58, "delimchar",h_delimchar, 2, 2},
{commandhandlers+59, "authnserver", h_authnserver, 2, 2}, {commandhandlers+59, "authnserver", h_authnserver, 2, 2},
@ -1717,8 +1731,8 @@ int parsestr (unsigned char *str, unsigned char **argm, int nitems, unsigned cha
*str = 0; *str = 0;
space = 1; space = 1;
if(incbegin){ if(incbegin){
argc--; if(argc) argc--;
if((fd = open((char *)incbegin+1, O_RDONLY)) <= 0){ if((fd = open((char *)incbegin+1, O_RDONLY)) < 0){
fprintf(stderr, "Failed to open %s\n", incbegin+1); fprintf(stderr, "Failed to open %s\n", incbegin+1);
return -1; return -1;
} }
@ -1731,7 +1745,7 @@ int parsestr (unsigned char *str, unsigned char **argm, int nitems, unsigned cha
} }
} }
len = 0; len = 0;
if(argm[argc]!=(incbegin+1)) { if(argc > 0 && argm[argc]!=(incbegin+1)) {
len = (int)strlen((char *)argm[argc]); len = (int)strlen((char *)argm[argc]);
memmove(buf+*inbuf, argm[argc], len); memmove(buf+*inbuf, argm[argc], len);
} }
@ -1807,13 +1821,17 @@ int readconfig(FILE * fp){
res = 1; res = 1;
for(cm = commandhandlers; cm; cm = cm->next){ for(cm = commandhandlers; cm; cm = cm->next){
if(!strcmp((char *)argv[0], (char *)cm->command) && argc >= cm->minargs && (!cm->maxargs || argc <= cm->maxargs)){ if(!strcmp((char *)argv[0], (char *)cm->command)){
res = (*cm->handler)(argc, argv); if(argc < cm->minargs || (cm->maxargs && argc > cm->maxargs)){
if(res > 0){ fprintf(stderr, "Command: '%s' wrong number of arguments , line %d\n", argv[0], linenum);
fprintf(stderr, "Command: '%s' failed with code %d, line %d\n", argv[0], res, linenum); return(linenum);
return(linenum); }
} res = (*cm->handler)(argc, argv);
if(!res) break; if(res > 0){
fprintf(stderr, "Command: '%s' failed with code %d, line %d\n", argv[0], res, linenum);
return(linenum);
}
if(!res) break;
} }
} }
if(res != 1)continue; if(res != 1)continue;
@ -1841,7 +1859,6 @@ void freeconf(struct extparam *confp){
struct bandlim * blout; struct bandlim * blout;
struct connlim * cl; struct connlim * cl;
struct trafcount * tc; struct trafcount * tc;
struct passwords *pw;
struct ace *acl; struct ace *acl;
struct filemon *fm; struct filemon *fm;
int counterd, archiverc; int counterd, archiverc;
@ -1853,33 +1870,33 @@ void freeconf(struct extparam *confp){
pthread_mutex_lock(&tc_mutex); _3proxy_mutex_lock(&tc_mutex);
confp->trafcountfunc = NULL; confp->trafcountfunc = NULL;
tc = confp->trafcounter; tc = confp->trafcounter;
confp->trafcounter = NULL; confp->trafcounter = NULL;
counterd = confp->counterd; counterd = confp->counterd;
confp->counterd = -1; confp->counterd = -1;
confp->countertype = NONE; confp->countertype = NONE;
pthread_mutex_unlock(&tc_mutex); _3proxy_mutex_unlock(&tc_mutex);
pthread_mutex_lock(&bandlim_mutex); _3proxy_mutex_lock(&bandlim_mutex);
bl = confp->bandlimiter; bl = confp->bandlimiter;
blout = confp->bandlimiterout; blout = confp->bandlimiterout;
confp->bandlimiter = NULL; confp->bandlimiter = NULL;
confp->bandlimiterout = NULL; confp->bandlimiterout = NULL;
confp->bandlimfunc = NULL; confp->bandlimfunc = NULL;
confp->bandlimver++; confp->bandlimver++;
pthread_mutex_unlock(&bandlim_mutex); _3proxy_mutex_unlock(&bandlim_mutex);
pthread_mutex_lock(&connlim_mutex); _3proxy_mutex_lock(&connlim_mutex);
cl = confp->connlimiter; cl = confp->connlimiter;
confp->connlimiter = NULL; confp->connlimiter = NULL;
pthread_mutex_unlock(&connlim_mutex); _3proxy_mutex_unlock(&connlim_mutex);
pthread_mutex_lock(&pwl_mutex);
pw = confp->pwl;
confp->pwl = NULL;
pthread_mutex_unlock(&pwl_mutex);
destroyhashtable(&pw_table);
#ifdef WITH_SSL
destroyhashtable(&pwnt_table);
#endif
destroyhashtable(&pwcr_table);
confp->logfunc = lognone; confp->logfunc = lognone;
logformat = confp->logformat; logformat = confp->logformat;
@ -1924,7 +1941,6 @@ void freeconf(struct extparam *confp){
freeacl(acl); freeacl(acl);
freepwl(pw);
for(; bl; bl = (struct bandlim *) itfree(bl, bl->next)) freeacl(bl->ace); for(; bl; bl = (struct bandlim *) itfree(bl, bl->next)) freeacl(bl->ace);
for(; blout; blout = (struct bandlim *) itfree(blout, blout->next))freeacl(blout->ace); for(; blout; blout = (struct bandlim *) itfree(blout, blout->next))freeacl(blout->ace);
for(; cl; cl = (struct connlim *) itfree(cl, cl->next)) freeacl(cl->ace); for(; cl; cl = (struct connlim *) itfree(cl, cl->next)) freeacl(cl->ace);
@ -1949,7 +1965,13 @@ int reload (void){
FILE *fp; FILE *fp;
int error = -2; int error = -2;
pthread_mutex_lock(&config_mutex); _3proxy_mutex_lock(&config_mutex);
#ifdef WITH_SSL
ssl_install();
#endif
#ifdef WITH_PCRE
pcre_install();
#endif
conf.paused++; conf.paused++;
freeconf(&conf); freeconf(&conf);
conf.paused++; conf.paused++;
@ -1963,6 +1985,6 @@ int reload (void){
} }
if(!writable)fclose(fp); if(!writable)fclose(fp);
} }
pthread_mutex_unlock(&config_mutex); _3proxy_mutex_unlock(&config_mutex);
return error; return error;
} }

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement

View File

@ -1,5 +1,5 @@
/* /*
3APA3A simpliest proxy server 3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement

316
src/hash.c Normal file
View File

@ -0,0 +1,316 @@
#include "proxy.h"
struct hashentry {
time_t expires;
uint32_t inext;
char value[4];
};
static uint32_t hashindex(unsigned tablesize, const uint8_t* hash){
return (*(unsigned *)hash) % tablesize;
}
void destroyhashtable(struct hashtable *ht){
_3proxy_mutex_lock(&ht->hash_mutex);
if(ht->ihashtable){
myfree(ht->ihashtable);
ht->ihashtable = NULL;
}
if(ht->hashvalues){
myfree(ht->hashvalues);
ht->hashvalues = NULL;
}
if(ht->hashhashvalues){
myfree(ht->hashhashvalues);
ht->hashhashvalues = NULL;
}
ht->poolsize = 0;
ht->tablesize = 0;
ht->ihashempty = 0;
_3proxy_mutex_unlock(&ht->hash_mutex);
_3proxy_mutex_destroy(&ht->hash_mutex);
}
#define hvalue(ht,I) ((struct hashentry *)(ht->hashvalues + (I-1)*(sizeof(struct hashentry) + ht->recsize - 4)))
#define hhash(ht,I) ((ht->hashhashvalues + (I-1)*(ht->hash_size)))
int inithashtable(struct hashtable *ht, unsigned tablesize, unsigned poolsize, unsigned growlimit){
unsigned i;
clock_t c;
#ifdef _WIN32
struct timeb tb;
ftime(&tb);
#else
struct timeval tb;
struct timezone tz;
gettimeofday(&tb, &tz);
#endif
c = clock();
if(tablesize < 2 || poolsize < tablesize || growlimit < poolsize) return 1;
if(ht->ihashtable){
_3proxy_mutex_lock(&ht->hash_mutex);
if(ht->ihashtable){
myfree(ht->ihashtable);
ht->ihashtable = NULL;
}
if(ht->hashvalues){
myfree(ht->hashvalues);
ht->hashvalues = NULL;
}
if(ht->hashhashvalues){
myfree(ht->hashhashvalues);
ht->hashhashvalues = NULL;
}
ht->poolsize = 0;
ht->tablesize = 0;
}
else {
_3proxy_mutex_init(&ht->hash_mutex);
_3proxy_mutex_lock(&ht->hash_mutex);
}
if(!(ht->ihashtable = myalloc(tablesize * sizeof(uint32_t)))
|| !(ht->hashvalues = myalloc(poolsize * (sizeof(struct hashentry) + ht->recsize - 4)))
|| !(ht->hashhashvalues = myalloc(poolsize * ht->hash_size))
){
myfree(ht->ihashtable);
ht->ihashtable = NULL;
myfree(ht->hashvalues);
ht->hashvalues = NULL;
_3proxy_mutex_unlock(&ht->hash_mutex);
return 3;
}
ht->poolsize = poolsize;
ht->tablesize = tablesize;
ht->growlimit = growlimit;
memset(ht->ihashtable, 0, ht->tablesize * sizeof(uint32_t));
memset(ht->hashvalues, 0, ht->poolsize * (sizeof(struct hashentry) + ht->recsize - 4));
for(i = 1; i < ht->poolsize; i++) {
hvalue(ht,i)->inext = i+1;
}
ht->ihashempty = 1;
_3proxy_mutex_unlock(&ht->hash_mutex);
return 0;
}
static void hashcompact(struct hashtable *ht){
int i;
uint32_t he, *hep;
if((conf.time - ht->compacted) < 300 || !ht->tablesize || !ht->poolsize || ht->ihashempty) return;
for(i = 0; i < ht->tablesize; i++){
for(hep = ht->ihashtable + i; (he = *hep) != 0; ){
if(hvalue(ht,he)->expires < conf.time ) {
(*hep) = hvalue(ht,he)->inext;
hvalue(ht,he)->expires = 0;
hvalue(ht,he)->inext = ht->ihashempty;
ht->ihashempty = he;
}
else hep=&(hvalue(ht,he)->inext);
}
}
ht->compacted = conf.time;
if(ht->ihashempty) return;
}
static void hashgrow(struct hashtable *ht){
unsigned newsize = (ht->poolsize + (ht->poolsize >> 1));
unsigned i;
void * newvalues;
if(!ht->tablesize || !ht->poolsize) return;
if(ht->poolsize / ht->tablesize < 4) hashcompact(ht);
if(ht->ihashempty) return;
if(ht->poolsize >= ht->growlimit) return;
if(newsize > ht->growlimit) newsize = ht->growlimit;
newvalues = myrealloc(ht->hashvalues, newsize * (sizeof(struct hashentry) + ht->recsize - 4));
if(!newvalues) return;
ht->hashvalues = newvalues;
newvalues = myrealloc(ht->hashhashvalues, 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));
for(i = ht->poolsize + 1; i < newsize; i++) {
hvalue(ht,i)->inext = i+1;
}
hvalue(ht,newsize)->inext = ht->ihashempty;
ht->ihashempty = ht->poolsize + 1;
ht->poolsize = newsize;
if (ht->poolsize / ht->tablesize > 10) {
unsigned newtablesize = ht->poolsize / 3;
uint32_t *newitable = myalloc(newtablesize * sizeof(uint32_t));
if (newitable) {
unsigned j;
memset(newitable, 0, newtablesize * sizeof(uint32_t));
for (j = 0; j < ht->tablesize; j++) {
uint32_t he = ht->ihashtable[j];
while (he) {
uint32_t next = hvalue(ht, he)->inext;
unsigned idx = hashindex(newtablesize, hhash(ht, he));
hvalue(ht, he)->inext = newitable[idx];
newitable[idx] = he;
he = next;
}
}
myfree(ht->ihashtable);
ht->ihashtable = newitable;
ht->tablesize = newtablesize;
}
}
}
void hashadd(struct hashtable *ht, void* name, void* value, time_t expires){
uint32_t hen, he;
uint32_t *hep;
int overwrite = 0;
uint8_t hash[MAX_HASH_SIZE];
uint32_t index;
uint32_t last = 0;
if(!ht||!value||!name||!ht->ihashtable) {
return;
}
ht->index2hash_add(ht, name, hash);
_3proxy_mutex_lock(&ht->hash_mutex);
index = hashindex(ht->tablesize, hash);
for(hep = ht->ihashtable + index; (he = *hep)!=0; ){
if(hvalue(ht,he)->expires < conf.time || !memcmp(hash, hhash(ht,he), ht->hash_size)) {
(*hep) = hvalue(ht,he)->inext;
hvalue(ht,he)->expires = 0;
hvalue(ht,he)->inext = ht->ihashempty;
ht->ihashempty = he;
}
else {
hep=&(hvalue(ht,he)->inext);
last = he;
}
}
if(!ht->ihashempty){
hashgrow(ht);
}
if(ht->ihashempty){
hen = ht->ihashempty;
ht->ihashempty = hvalue(ht,ht->ihashempty)->inext;
hvalue(ht,hen)->inext = ht->ihashtable[index];
ht->ihashtable[index] = hen;
}
else {
hen = last;
}
if(hen){
memcpy(hhash(ht,hen), hash, ht->hash_size);
memcpy(hvalue(ht,hen)->value, value, ht->recsize);
hvalue(ht,hen)->expires = expires;
}
_3proxy_mutex_unlock(&ht->hash_mutex);
}
int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl){
uint8_t hash[MAX_HASH_SIZE];
uint32_t *hep;
uint32_t he;
uint32_t index;
if(!ht || !ht->ihashtable || !name) {
return 0;
}
ht->index2hash_search(ht,name, hash);
_3proxy_mutex_lock(&ht->hash_mutex);
index = hashindex(ht->tablesize, hash);
for(hep = ht->ihashtable + index; (he = *hep)!=0; ){
if(hvalue(ht, he)->expires < conf.time) {
(*hep) = hvalue(ht,he)->inext;
hvalue(ht,he)->expires = 0;
hvalue(ht,he)->inext = ht->ihashempty;
ht->ihashempty = he;
}
else if(!memcmp(hash, hhash(ht,he), ht->hash_size)){
if(ttl) *ttl = (uint32_t)(hvalue(ht,he)->expires - conf.time);
memcpy(value, hvalue(ht,he)->value, ht->recsize);
_3proxy_mutex_unlock(&ht->hash_mutex);
return 1;
}
else hep=&(hvalue(ht,he)->inext);
}
_3proxy_mutex_unlock(&ht->hash_mutex);
return 0;
}
void hashdelete(struct hashtable *ht, void *name){
uint8_t hash[MAX_HASH_SIZE];
uint32_t *hep;
uint32_t he;
uint32_t index;
if(!ht || !ht->ihashtable || !name) {
return;
}
ht->index2hash_search(ht, name, hash);
_3proxy_mutex_lock(&ht->hash_mutex);
index = hashindex(ht->tablesize, hash);
for(hep = ht->ihashtable + index; (he = *hep) != 0; ){
if((hvalue(ht, he)->expires && hvalue(ht, he)->expires < conf.time) || !memcmp(hash, hhash(ht, he), ht->hash_size)) {
(*hep) = hvalue(ht, he)->inext;
hvalue(ht, he)->expires = 0;
hvalue(ht, he)->inext = ht->ihashempty;
ht->ihashempty = he;
}
else hep = &(hvalue(ht, he)->inext);
}
_3proxy_mutex_unlock(&ht->hash_mutex);
}
#define MURMUR_C1 0xcc9e2d51u
#define MURMUR_C2 0x1b873593u
uint32_t murmurhash3(const void *key, int len, uint32_t seed) {
const uint8_t *data = (const uint8_t *)key;
const int nblocks = len / 4;
uint32_t h = seed;
int i;
const uint32_t *blocks = (const uint32_t *)(data);
const uint8_t *tail = data + nblocks * 4;
uint32_t k;
for (i = 0; i < nblocks; i++) {
memcpy(&k, blocks + i, sizeof(k));
k *= MURMUR_C1;
k = (k << 15) | (k >> 17);
k *= MURMUR_C2;
h ^= k;
h = (h << 13) | (h >> 19);
h = h * 5 + 0xe6546b64u;
}
k = 0;
switch (len & 3) {
case 3: k ^= (uint32_t)tail[2] << 16; /* fall through */
case 2: k ^= (uint32_t)tail[1] << 8; /* fall through */
case 1: k ^= (uint32_t)tail[0];
k *= MURMUR_C1;
k = (k << 15) | (k >> 17);
k *= MURMUR_C2;
h ^= k;
}
h ^= (uint32_t)len;
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
h *= 0xc2b2ae35u;
h ^= h >> 16;
return h;
}

109
src/hashtables.c Normal file
View File

@ -0,0 +1,109 @@
#include "proxy.h"
#include "blake2_compat.h"
static void char_index2hash(const struct hashtable *ht, void *index, uint8_t *hash){
blake2b_state S;
blake2b_init(&S, ht->hash_size);
blake2b_update(&S, index, strlen((const char*)index) + 1);
blake2b_final(&S, hash, ht->hash_size);
}
static void param2hash_add(const struct hashtable *ht, void *index, uint8_t *hash){
blake2b_state S;
struct clientparam *param = (struct clientparam *)index;
unsigned type = param->srv->authcachetype;
blake2b_init(&S, ht->hash_size);
if((type & 2) && param->username)blake2b_update(&S, param->username, strlen((const char *)param->username) + 1);
if((type & 4) && param->password)blake2b_update(&S, param->password, strlen((const char *)param->password) + 1);
if((type & 1) && !(type & 8))blake2b_update(&S, SAADDR(&param->sincr), SAADDRLEN(&param->sincr));
if((type & 16))blake2b_update(&S, &param->srv->acl, sizeof(param->srv->acl));
if((type & 64))blake2b_update(&S, SAADDR(&param->req), SAADDRLEN(&param->req));
if((type & 128))blake2b_update(&S, SAPORT(&param->req), 2);
if((type & 256) && param->hostname)blake2b_update(&S, param->hostname, strlen((const char *)param->hostname) + 1);
if((type & 512))blake2b_update(&S, &param->operation, sizeof(param->operation));
if((type & 1024))blake2b_update(&S, SAADDR(&param->srv->intsa), SAADDRLEN(&param->srv->intsa));
if((type & 2048))blake2b_update(&S, SAPORT(&param->srv->intsa), 2);
blake2b_final(&S, hash, ht->hash_size);
memcpy(param->hash, hash, ht->hash_size);
}
void param2hash_search(const struct hashtable *ht, void *index, uint8_t *hash){
struct clientparam *param = (struct clientparam *)index;
memcpy(hash, param->hash, ht->hash_size);
}
static void user2hash_search(const struct hashtable *ht, void *index, uint8_t *hash){
struct clientparam *param = (struct clientparam *)index;
blake2b_state S;
blake2b_init(&S, ht->hash_size);
blake2b_update(&S, param->username, strlen((const char *)param->username) + 1);
blake2b_final(&S, hash, ht->hash_size);
}
static void udpparam2hash(const struct hashtable *ht, void *index, uint8_t *hash){
struct clientparam *param = (struct clientparam *)index;
blake2b_state S;
blake2b_init(&S, ht->hash_size);
blake2b_update(&S, SAADDR(&param->srv->intsa), SAADDRLEN(&param->srv->intsa));
blake2b_update(&S, SAPORT(&param->srv->intsa), 2);
blake2b_update(&S, SAADDR(&param->sincr), SAADDRLEN(&param->sincr));
blake2b_update(&S, SAPORT(&param->sincr), 2);
blake2b_final(&S, hash, ht->hash_size);
}
static void pw2hash_add(const struct hashtable *ht, void *index, uint8_t *hash){
char ** pw = (char **)index;
blake2b_state S;
blake2b_init(&S, ht->hash_size);
if(pw[0])blake2b_update(&S, pw[0], strlen(pw[0]) + 1);
if(pw[1])blake2b_update(&S, pw[1], strlen(pw[1]) + 1);
blake2b_final(&S, hash, ht->hash_size);
}
static void pw2hash_search(const struct hashtable *ht, void *index, uint8_t *hash){
struct clientparam *param = (struct clientparam *)index;
char *pw[2] = {(char *)param->username, (char *)param->password};
pw2hash_add(ht, pw, hash);
}
static void pwnt2hash_add(const struct hashtable *ht, void *index, uint8_t *hash){
char ** pw = (char **)index;
blake2b_state S;
blake2b_init(&S, ht->hash_size);
if(pw[0])blake2b_update(&S, pw[0], strlen(pw[0]) + 1);
if(pw[1])blake2b_update(&S, pw[1], strlen(pw[1]) + 1);
blake2b_final(&S, hash, ht->hash_size);
}
#ifdef WITH_SSL
static void pwnt2hash_search(const struct hashtable *ht, void *index, uint8_t *hash){
struct clientparam *param = (struct clientparam *)index;
unsigned char pass[40];
char *pw[2] = {(char *)param->username, (char *)pass};
ntpwdhash(pass, param->password, 1);
pwnt2hash_add(ht, pw, hash);
}
#endif
struct hashtable dns_table = {char_index2hash, char_index2hash, 4, 12};
struct hashtable dns6_table = {char_index2hash, char_index2hash, 16, 12};
struct hashtable auth_table = {param2hash_add, param2hash_search, sizeof(struct authcache), 12};
struct hashtable pw_table = {pw2hash_add, pw2hash_search, 0, 12};
#ifdef WITH_SSL
struct hashtable pwnt_table = {pwnt2hash_add, pwnt2hash_search, 0, 12};
#endif
struct hashtable pwcr_table = {char_index2hash, user2hash_search, 64, 12};

160
src/libs/blake2-impl.h Normal file
View File

@ -0,0 +1,160 @@
/*
BLAKE2 reference source code package - reference C implementations
Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the
terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at
your option. The terms of these licenses can be found at:
- CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
- OpenSSL license : https://www.openssl.org/source/license.html
- Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
More information about the BLAKE2 hash function can be found at
https://blake2.net.
*/
#ifndef BLAKE2_IMPL_H
#define BLAKE2_IMPL_H
#include <stdint.h>
#include <string.h>
#if !defined(__cplusplus) && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L)
#if defined(_MSC_VER)
#define BLAKE2_INLINE __inline
#elif defined(__GNUC__)
#define BLAKE2_INLINE __inline__
#else
#define BLAKE2_INLINE
#endif
#else
#define BLAKE2_INLINE inline
#endif
static BLAKE2_INLINE uint32_t load32( const void *src )
{
#if defined(NATIVE_LITTLE_ENDIAN)
uint32_t w;
memcpy(&w, src, sizeof w);
return w;
#else
const uint8_t *p = ( const uint8_t * )src;
return (( uint32_t )( p[0] ) << 0) |
(( uint32_t )( p[1] ) << 8) |
(( uint32_t )( p[2] ) << 16) |
(( uint32_t )( p[3] ) << 24) ;
#endif
}
static BLAKE2_INLINE uint64_t load64( const void *src )
{
#if defined(NATIVE_LITTLE_ENDIAN)
uint64_t w;
memcpy(&w, src, sizeof w);
return w;
#else
const uint8_t *p = ( const uint8_t * )src;
return (( uint64_t )( p[0] ) << 0) |
(( uint64_t )( p[1] ) << 8) |
(( uint64_t )( p[2] ) << 16) |
(( uint64_t )( p[3] ) << 24) |
(( uint64_t )( p[4] ) << 32) |
(( uint64_t )( p[5] ) << 40) |
(( uint64_t )( p[6] ) << 48) |
(( uint64_t )( p[7] ) << 56) ;
#endif
}
static BLAKE2_INLINE uint16_t load16( const void *src )
{
#if defined(NATIVE_LITTLE_ENDIAN)
uint16_t w;
memcpy(&w, src, sizeof w);
return w;
#else
const uint8_t *p = ( const uint8_t * )src;
return ( uint16_t )((( uint32_t )( p[0] ) << 0) |
(( uint32_t )( p[1] ) << 8));
#endif
}
static BLAKE2_INLINE void store16( void *dst, uint16_t w )
{
#if defined(NATIVE_LITTLE_ENDIAN)
memcpy(dst, &w, sizeof w);
#else
uint8_t *p = ( uint8_t * )dst;
*p++ = ( uint8_t )w; w >>= 8;
*p++ = ( uint8_t )w;
#endif
}
static BLAKE2_INLINE void store32( void *dst, uint32_t w )
{
#if defined(NATIVE_LITTLE_ENDIAN)
memcpy(dst, &w, sizeof w);
#else
uint8_t *p = ( uint8_t * )dst;
p[0] = (uint8_t)(w >> 0);
p[1] = (uint8_t)(w >> 8);
p[2] = (uint8_t)(w >> 16);
p[3] = (uint8_t)(w >> 24);
#endif
}
static BLAKE2_INLINE void store64( void *dst, uint64_t w )
{
#if defined(NATIVE_LITTLE_ENDIAN)
memcpy(dst, &w, sizeof w);
#else
uint8_t *p = ( uint8_t * )dst;
p[0] = (uint8_t)(w >> 0);
p[1] = (uint8_t)(w >> 8);
p[2] = (uint8_t)(w >> 16);
p[3] = (uint8_t)(w >> 24);
p[4] = (uint8_t)(w >> 32);
p[5] = (uint8_t)(w >> 40);
p[6] = (uint8_t)(w >> 48);
p[7] = (uint8_t)(w >> 56);
#endif
}
static BLAKE2_INLINE uint64_t load48( const void *src )
{
const uint8_t *p = ( const uint8_t * )src;
return (( uint64_t )( p[0] ) << 0) |
(( uint64_t )( p[1] ) << 8) |
(( uint64_t )( p[2] ) << 16) |
(( uint64_t )( p[3] ) << 24) |
(( uint64_t )( p[4] ) << 32) |
(( uint64_t )( p[5] ) << 40) ;
}
static BLAKE2_INLINE void store48( void *dst, uint64_t w )
{
uint8_t *p = ( uint8_t * )dst;
p[0] = (uint8_t)(w >> 0);
p[1] = (uint8_t)(w >> 8);
p[2] = (uint8_t)(w >> 16);
p[3] = (uint8_t)(w >> 24);
p[4] = (uint8_t)(w >> 32);
p[5] = (uint8_t)(w >> 40);
}
static BLAKE2_INLINE uint32_t rotr32( const uint32_t w, const unsigned c )
{
return ( w >> c ) | ( w << ( 32 - c ) );
}
static BLAKE2_INLINE uint64_t rotr64( const uint64_t w, const unsigned c )
{
return ( w >> c ) | ( w << ( 64 - c ) );
}
/* prevents compiler optimizing out memset() */
static BLAKE2_INLINE void secure_zero_memory(void *v, size_t n)
{
static void *(*const volatile memset_v)(void *, int, size_t) = &memset;
memset_v(v, 0, n);
}
#endif

197
src/libs/blake2.h Normal file
View File

@ -0,0 +1,197 @@
/*
BLAKE2 reference source code package - reference C implementations
Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the
terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at
your option. The terms of these licenses can be found at:
- CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
- OpenSSL license : https://www.openssl.org/source/license.html
- Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
More information about the BLAKE2 hash function can be found at
https://blake2.net.
*/
#ifndef BLAKE2_H
#define BLAKE2_H
#include <stddef.h>
#include <stdint.h>
#if defined(WATCOM)
#define BLAKE2_PACKED(x) _Packed x
#elif defined(_MSC_VER)
#define BLAKE2_PACKED(x) __pragma(pack(push, 1)) x __pragma(pack(pop))
#else
#define BLAKE2_PACKED(x) x __attribute__((packed))
#endif
#if defined(__cplusplus)
extern "C" {
#endif
enum blake2s_constant
{
BLAKE2S_BLOCKBYTES = 64,
BLAKE2S_OUTBYTES = 32,
BLAKE2S_KEYBYTES = 32,
BLAKE2S_SALTBYTES = 8,
BLAKE2S_PERSONALBYTES = 8
};
enum blake2b_constant
{
BLAKE2B_BLOCKBYTES = 128,
BLAKE2B_OUTBYTES = 64,
BLAKE2B_KEYBYTES = 64,
BLAKE2B_SALTBYTES = 16,
BLAKE2B_PERSONALBYTES = 16
};
typedef struct blake2s_state__
{
uint32_t h[8];
uint32_t t[2];
uint32_t f[2];
uint8_t buf[BLAKE2S_BLOCKBYTES];
size_t buflen;
size_t outlen;
uint8_t last_node;
} blake2s_state;
typedef struct blake2b_state__
{
uint64_t h[8];
uint64_t t[2];
uint64_t f[2];
uint8_t buf[BLAKE2B_BLOCKBYTES];
size_t buflen;
size_t outlen;
uint8_t last_node;
} blake2b_state;
typedef struct blake2sp_state__
{
blake2s_state S[8][1];
blake2s_state R[1];
uint8_t buf[8 * BLAKE2S_BLOCKBYTES];
size_t buflen;
size_t outlen;
} blake2sp_state;
typedef struct blake2bp_state__
{
blake2b_state S[4][1];
blake2b_state R[1];
uint8_t buf[4 * BLAKE2B_BLOCKBYTES];
size_t buflen;
size_t outlen;
} blake2bp_state;
BLAKE2_PACKED(struct blake2s_param__
{
uint8_t digest_length; /* 1 */
uint8_t key_length; /* 2 */
uint8_t fanout; /* 3 */
uint8_t depth; /* 4 */
uint32_t leaf_length; /* 8 */
uint32_t node_offset; /* 12 */
uint16_t xof_length; /* 14 */
uint8_t node_depth; /* 15 */
uint8_t inner_length; /* 16 */
/* uint8_t reserved[0]; */
uint8_t salt[BLAKE2S_SALTBYTES]; /* 24 */
uint8_t personal[BLAKE2S_PERSONALBYTES]; /* 32 */
});
typedef struct blake2s_param__ blake2s_param;
BLAKE2_PACKED(struct blake2b_param__
{
uint8_t digest_length; /* 1 */
uint8_t key_length; /* 2 */
uint8_t fanout; /* 3 */
uint8_t depth; /* 4 */
uint32_t leaf_length; /* 8 */
uint32_t node_offset; /* 12 */
uint32_t xof_length; /* 16 */
uint8_t node_depth; /* 17 */
uint8_t inner_length; /* 18 */
uint8_t reserved[14]; /* 32 */
uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */
uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */
});
typedef struct blake2b_param__ blake2b_param;
typedef struct blake2xs_state__
{
blake2s_state S[1];
blake2s_param P[1];
} blake2xs_state;
typedef struct blake2xb_state__
{
blake2b_state S[1];
blake2b_param P[1];
} blake2xb_state;
/* Padded structs result in a compile-time error */
enum {
BLAKE2_DUMMY_1 = 1/(int)(sizeof(blake2s_param) == BLAKE2S_OUTBYTES),
BLAKE2_DUMMY_2 = 1/(int)(sizeof(blake2b_param) == BLAKE2B_OUTBYTES)
};
/* Streaming API */
int blake2s_init( blake2s_state *S, size_t outlen );
int blake2s_init_key( blake2s_state *S, size_t outlen, const void *key, size_t keylen );
int blake2s_init_param( blake2s_state *S, const blake2s_param *P );
int blake2s_update( blake2s_state *S, const void *in, size_t inlen );
int blake2s_final( blake2s_state *S, void *out, size_t outlen );
int blake2b_init( blake2b_state *S, size_t outlen );
int blake2b_init_key( blake2b_state *S, size_t outlen, const void *key, size_t keylen );
int blake2b_init_param( blake2b_state *S, const blake2b_param *P );
int blake2b_update( blake2b_state *S, const void *in, size_t inlen );
int blake2b_final( blake2b_state *S, void *out, size_t outlen );
int blake2sp_init( blake2sp_state *S, size_t outlen );
int blake2sp_init_key( blake2sp_state *S, size_t outlen, const void *key, size_t keylen );
int blake2sp_update( blake2sp_state *S, const void *in, size_t inlen );
int blake2sp_final( blake2sp_state *S, void *out, size_t outlen );
int blake2bp_init( blake2bp_state *S, size_t outlen );
int blake2bp_init_key( blake2bp_state *S, size_t outlen, const void *key, size_t keylen );
int blake2bp_update( blake2bp_state *S, const void *in, size_t inlen );
int blake2bp_final( blake2bp_state *S, void *out, size_t outlen );
/* Variable output length API */
int blake2xs_init( blake2xs_state *S, const size_t outlen );
int blake2xs_init_key( blake2xs_state *S, const size_t outlen, const void *key, size_t keylen );
int blake2xs_update( blake2xs_state *S, const void *in, size_t inlen );
int blake2xs_final(blake2xs_state *S, void *out, size_t outlen);
int blake2xb_init( blake2xb_state *S, const size_t outlen );
int blake2xb_init_key( blake2xb_state *S, const size_t outlen, const void *key, size_t keylen );
int blake2xb_update( blake2xb_state *S, const void *in, size_t inlen );
int blake2xb_final(blake2xb_state *S, void *out, size_t outlen);
/* Simple API */
int blake2s( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
int blake2b( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
int blake2sp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
int blake2bp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
int blake2xs( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
int blake2xb( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
/* This is simply an alias for blake2b */
int blake2( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen );
#if defined(__cplusplus)
}
#endif
#endif

379
src/libs/blake2b-ref.c Normal file
View File

@ -0,0 +1,379 @@
/*
BLAKE2 reference source code package - reference C implementations
Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the
terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at
your option. The terms of these licenses can be found at:
- CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
- OpenSSL license : https://www.openssl.org/source/license.html
- Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
More information about the BLAKE2 hash function can be found at
https://blake2.net.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "blake2.h"
#include "blake2-impl.h"
static const uint64_t blake2b_IV[8] =
{
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL
};
static const uint8_t blake2b_sigma[12][16] =
{
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } ,
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } ,
{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 } ,
{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 } ,
{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 } ,
{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 } ,
{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 } ,
{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 } ,
{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 } ,
{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 } ,
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } ,
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }
};
static void blake2b_set_lastnode( blake2b_state *S )
{
S->f[1] = (uint64_t)-1;
}
/* Some helper functions, not necessarily useful */
static int blake2b_is_lastblock( const blake2b_state *S )
{
return S->f[0] != 0;
}
static void blake2b_set_lastblock( blake2b_state *S )
{
if( S->last_node ) blake2b_set_lastnode( S );
S->f[0] = (uint64_t)-1;
}
static void blake2b_increment_counter( blake2b_state *S, const uint64_t inc )
{
S->t[0] += inc;
S->t[1] += ( S->t[0] < inc );
}
static void blake2b_init0( blake2b_state *S )
{
size_t i;
memset( S, 0, sizeof( blake2b_state ) );
for( i = 0; i < 8; ++i ) S->h[i] = blake2b_IV[i];
}
/* init xors IV with input parameter block */
int blake2b_init_param( blake2b_state *S, const blake2b_param *P )
{
const uint8_t *p = ( const uint8_t * )( P );
size_t i;
blake2b_init0( S );
/* IV XOR ParamBlock */
for( i = 0; i < 8; ++i )
S->h[i] ^= load64( p + sizeof( S->h[i] ) * i );
S->outlen = P->digest_length;
return 0;
}
int blake2b_init( blake2b_state *S, size_t outlen )
{
blake2b_param P[1];
if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return -1;
P->digest_length = (uint8_t)outlen;
P->key_length = 0;
P->fanout = 1;
P->depth = 1;
store32( &P->leaf_length, 0 );
store32( &P->node_offset, 0 );
store32( &P->xof_length, 0 );
P->node_depth = 0;
P->inner_length = 0;
memset( P->reserved, 0, sizeof( P->reserved ) );
memset( P->salt, 0, sizeof( P->salt ) );
memset( P->personal, 0, sizeof( P->personal ) );
return blake2b_init_param( S, P );
}
int blake2b_init_key( blake2b_state *S, size_t outlen, const void *key, size_t keylen )
{
blake2b_param P[1];
if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return -1;
if ( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return -1;
P->digest_length = (uint8_t)outlen;
P->key_length = (uint8_t)keylen;
P->fanout = 1;
P->depth = 1;
store32( &P->leaf_length, 0 );
store32( &P->node_offset, 0 );
store32( &P->xof_length, 0 );
P->node_depth = 0;
P->inner_length = 0;
memset( P->reserved, 0, sizeof( P->reserved ) );
memset( P->salt, 0, sizeof( P->salt ) );
memset( P->personal, 0, sizeof( P->personal ) );
if( blake2b_init_param( S, P ) < 0 ) return -1;
{
uint8_t block[BLAKE2B_BLOCKBYTES];
memset( block, 0, BLAKE2B_BLOCKBYTES );
memcpy( block, key, keylen );
blake2b_update( S, block, BLAKE2B_BLOCKBYTES );
secure_zero_memory( block, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */
}
return 0;
}
#define G(r,i,a,b,c,d) \
do { \
a = a + b + m[blake2b_sigma[r][2*i+0]]; \
d = rotr64(d ^ a, 32); \
c = c + d; \
b = rotr64(b ^ c, 24); \
a = a + b + m[blake2b_sigma[r][2*i+1]]; \
d = rotr64(d ^ a, 16); \
c = c + d; \
b = rotr64(b ^ c, 63); \
} while(0)
#define ROUND(r) \
do { \
G(r,0,v[ 0],v[ 4],v[ 8],v[12]); \
G(r,1,v[ 1],v[ 5],v[ 9],v[13]); \
G(r,2,v[ 2],v[ 6],v[10],v[14]); \
G(r,3,v[ 3],v[ 7],v[11],v[15]); \
G(r,4,v[ 0],v[ 5],v[10],v[15]); \
G(r,5,v[ 1],v[ 6],v[11],v[12]); \
G(r,6,v[ 2],v[ 7],v[ 8],v[13]); \
G(r,7,v[ 3],v[ 4],v[ 9],v[14]); \
} while(0)
static void blake2b_compress( blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES] )
{
uint64_t m[16];
uint64_t v[16];
size_t i;
for( i = 0; i < 16; ++i ) {
m[i] = load64( block + i * sizeof( m[i] ) );
}
for( i = 0; i < 8; ++i ) {
v[i] = S->h[i];
}
v[ 8] = blake2b_IV[0];
v[ 9] = blake2b_IV[1];
v[10] = blake2b_IV[2];
v[11] = blake2b_IV[3];
v[12] = blake2b_IV[4] ^ S->t[0];
v[13] = blake2b_IV[5] ^ S->t[1];
v[14] = blake2b_IV[6] ^ S->f[0];
v[15] = blake2b_IV[7] ^ S->f[1];
ROUND( 0 );
ROUND( 1 );
ROUND( 2 );
ROUND( 3 );
ROUND( 4 );
ROUND( 5 );
ROUND( 6 );
ROUND( 7 );
ROUND( 8 );
ROUND( 9 );
ROUND( 10 );
ROUND( 11 );
for( i = 0; i < 8; ++i ) {
S->h[i] = S->h[i] ^ v[i] ^ v[i + 8];
}
}
#undef G
#undef ROUND
int blake2b_update( blake2b_state *S, const void *pin, size_t inlen )
{
const unsigned char * in = (const unsigned char *)pin;
if( inlen > 0 )
{
size_t left = S->buflen;
size_t fill = BLAKE2B_BLOCKBYTES - left;
if( inlen > fill )
{
S->buflen = 0;
memcpy( S->buf + left, in, fill ); /* Fill buffer */
blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
blake2b_compress( S, S->buf ); /* Compress */
in += fill; inlen -= fill;
while(inlen > BLAKE2B_BLOCKBYTES) {
blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES);
blake2b_compress( S, in );
in += BLAKE2B_BLOCKBYTES;
inlen -= BLAKE2B_BLOCKBYTES;
}
}
memcpy( S->buf + S->buflen, in, inlen );
S->buflen += inlen;
}
return 0;
}
int blake2b_final( blake2b_state *S, void *out, size_t outlen )
{
uint8_t buffer[BLAKE2B_OUTBYTES] = {0};
size_t i;
if( out == NULL || outlen < S->outlen )
return -1;
if( blake2b_is_lastblock( S ) )
return -1;
blake2b_increment_counter( S, S->buflen );
blake2b_set_lastblock( S );
memset( S->buf + S->buflen, 0, BLAKE2B_BLOCKBYTES - S->buflen ); /* Padding */
blake2b_compress( S, S->buf );
for( i = 0; i < 8; ++i ) /* Output full hash to temp buffer */
store64( buffer + sizeof( S->h[i] ) * i, S->h[i] );
memcpy( out, buffer, S->outlen );
secure_zero_memory(buffer, sizeof(buffer));
return 0;
}
/* inlen, at least, should be uint64_t. Others can be size_t. */
int blake2b( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen )
{
blake2b_state S[1];
/* Verify parameters */
if ( NULL == in && inlen > 0 ) return -1;
if ( NULL == out ) return -1;
if( NULL == key && keylen > 0 ) return -1;
if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1;
if( keylen > BLAKE2B_KEYBYTES ) return -1;
if( keylen > 0 )
{
if( blake2b_init_key( S, outlen, key, keylen ) < 0 ) return -1;
}
else
{
if( blake2b_init( S, outlen ) < 0 ) return -1;
}
blake2b_update( S, ( const uint8_t * )in, inlen );
blake2b_final( S, out, outlen );
return 0;
}
int blake2( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ) {
return blake2b(out, outlen, in, inlen, key, keylen);
}
#if defined(SUPERCOP)
int crypto_hash( unsigned char *out, unsigned char *in, unsigned long long inlen )
{
return blake2b( out, BLAKE2B_OUTBYTES, in, inlen, NULL, 0 );
}
#endif
#if defined(BLAKE2B_SELFTEST)
#include <string.h>
#include "blake2-kat.h"
int main( void )
{
uint8_t key[BLAKE2B_KEYBYTES];
uint8_t buf[BLAKE2_KAT_LENGTH];
size_t i, step;
for( i = 0; i < BLAKE2B_KEYBYTES; ++i )
key[i] = ( uint8_t )i;
for( i = 0; i < BLAKE2_KAT_LENGTH; ++i )
buf[i] = ( uint8_t )i;
/* Test simple API */
for( i = 0; i < BLAKE2_KAT_LENGTH; ++i )
{
uint8_t hash[BLAKE2B_OUTBYTES];
blake2b( hash, BLAKE2B_OUTBYTES, buf, i, key, BLAKE2B_KEYBYTES );
if( 0 != memcmp( hash, blake2b_keyed_kat[i], BLAKE2B_OUTBYTES ) )
{
goto fail;
}
}
/* Test streaming API */
for(step = 1; step < BLAKE2B_BLOCKBYTES; ++step) {
for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) {
uint8_t hash[BLAKE2B_OUTBYTES];
blake2b_state S;
uint8_t * p = buf;
size_t mlen = i;
int err = 0;
if( (err = blake2b_init_key(&S, BLAKE2B_OUTBYTES, key, BLAKE2B_KEYBYTES)) < 0 ) {
goto fail;
}
while (mlen >= step) {
if ( (err = blake2b_update(&S, p, step)) < 0 ) {
goto fail;
}
mlen -= step;
p += step;
}
if ( (err = blake2b_update(&S, p, mlen)) < 0) {
goto fail;
}
if ( (err = blake2b_final(&S, hash, BLAKE2B_OUTBYTES)) < 0) {
goto fail;
}
if (0 != memcmp(hash, blake2b_keyed_kat[i], BLAKE2B_OUTBYTES)) {
goto fail;
}
}
}
puts( "ok" );
return 0;
fail:
puts("error");
return -1;
}
#endif

View File

@ -1,290 +0,0 @@
/*
* md4c.c MD4 message-digest algorithm
*
* License to copy and use this software is granted provided that it
* is identified as the "RSA Data Security, Inc. MD4 Message-Digest
* Algorithm" in all material mentioning or referencing this software
* or this function.
*
* License is also granted to make and use derivative works provided
* that such works are identified as "derived from the RSA Data
* Security, Inc. MD4 Message-Digest Algorithm" in all material
* mentioning or referencing the derived work.
*
* RSA Data Security, Inc. makes no representations concerning either
* the merchantability of this software or the suitability of this
* software for any particular purpose. It is provided "as is"
* without express or implied warranty of any kind.
*
* These notices must be retained in any copies of any part of this
* documentation and/or software.
*
* Copyright 1990,1991,1992 RSA Data Security, Inc.
*/
#include "md4.h"
/* Constants for MD4Transform routine.
*/
#define S11 3
#define S12 7
#define S13 11
#define S14 19
#define S21 3
#define S22 5
#define S23 9
#define S24 13
#define S31 3
#define S32 9
#define S33 11
#define S34 15
static void MD4Transform PROTO_LIST ((UINT4 [4], unsigned char [64]));
static void Encode PROTO_LIST
((unsigned char *, UINT4 *, unsigned int));
static void Decode PROTO_LIST
((UINT4 *, unsigned char *, unsigned int));
static void MD4_memcpy PROTO_LIST ((POINTER, POINTER, unsigned int));
static void MD4_memset PROTO_LIST ((POINTER, int, unsigned int));
static unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G and H are basic MD4 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
/* Rotation is separate from addition to prevent recomputation */
#define FF(a, b, c, d, x, s) { \
(a) += F ((b), (c), (d)) + (x); \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define GG(a, b, c, d, x, s) { \
(a) += G ((b), (c), (d)) + (x) + (UINT4)0x5a827999; \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define HH(a, b, c, d, x, s) { \
(a) += H ((b), (c), (d)) + (x) + (UINT4)0x6ed9eba1; \
(a) = ROTATE_LEFT ((a), (s)); \
}
void md4_calc(unsigned char *output, unsigned char *input, unsigned inlen)
{
MD4_CTX context;
MD4Init(&context);
MD4Update(&context, input, inlen);
MD4Final(output, &context);
}
/* MD4 initialization. Begins an MD4 operation, writing a new context.
*/
void MD4Init ( MD4_CTX *context)
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* MD4 block update operation. Continues an MD4 message-digest
operation, processing another message block, and updating the
context.
*/
void MD4Update (MD4_CTX *context, unsigned char *input, unsigned inputLen)
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int)((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((UINT4)inputLen << 3))
< ((UINT4)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT4)inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
MD4_memcpy
((POINTER)&context->buffer[index], (POINTER)input, partLen);
MD4Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD4Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
/* Buffer remaining input */
MD4_memcpy
((POINTER)&context->buffer[index], (POINTER)&input[i],
inputLen-i);
}
/* MD4 finalization. Ends an MD4 message-digest operation, writing the
the message digest and zeroizing the context.
*/
void MD4Final (unsigned char digest[16], MD4_CTX *context)
{
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
Encode (bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD4Update (context, PADDING, padLen);
/* Append length (before padding) */
MD4Update (context, bits, 8);
/* Store state in digest */
Encode (digest, context->state, 16);
/* Zeroize sensitive information.
*/
MD4_memset ((POINTER)context, 0, sizeof (*context));
}
/* MD4 basic transformation. Transforms state based on block.
*/
static void MD4Transform (UINT4 state[4], unsigned char block[64])
{
UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11); /* 1 */
FF (d, a, b, c, x[ 1], S12); /* 2 */
FF (c, d, a, b, x[ 2], S13); /* 3 */
FF (b, c, d, a, x[ 3], S14); /* 4 */
FF (a, b, c, d, x[ 4], S11); /* 5 */
FF (d, a, b, c, x[ 5], S12); /* 6 */
FF (c, d, a, b, x[ 6], S13); /* 7 */
FF (b, c, d, a, x[ 7], S14); /* 8 */
FF (a, b, c, d, x[ 8], S11); /* 9 */
FF (d, a, b, c, x[ 9], S12); /* 10 */
FF (c, d, a, b, x[10], S13); /* 11 */
FF (b, c, d, a, x[11], S14); /* 12 */
FF (a, b, c, d, x[12], S11); /* 13 */
FF (d, a, b, c, x[13], S12); /* 14 */
FF (c, d, a, b, x[14], S13); /* 15 */
FF (b, c, d, a, x[15], S14); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 0], S21); /* 17 */
GG (d, a, b, c, x[ 4], S22); /* 18 */
GG (c, d, a, b, x[ 8], S23); /* 19 */
GG (b, c, d, a, x[12], S24); /* 20 */
GG (a, b, c, d, x[ 1], S21); /* 21 */
GG (d, a, b, c, x[ 5], S22); /* 22 */
GG (c, d, a, b, x[ 9], S23); /* 23 */
GG (b, c, d, a, x[13], S24); /* 24 */
GG (a, b, c, d, x[ 2], S21); /* 25 */
GG (d, a, b, c, x[ 6], S22); /* 26 */
GG (c, d, a, b, x[10], S23); /* 27 */
GG (b, c, d, a, x[14], S24); /* 28 */
GG (a, b, c, d, x[ 3], S21); /* 29 */
GG (d, a, b, c, x[ 7], S22); /* 30 */
GG (c, d, a, b, x[11], S23); /* 31 */
GG (b, c, d, a, x[15], S24); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 0], S31); /* 33 */
HH (d, a, b, c, x[ 8], S32); /* 34 */
HH (c, d, a, b, x[ 4], S33); /* 35 */
HH (b, c, d, a, x[12], S34); /* 36 */
HH (a, b, c, d, x[ 2], S31); /* 37 */
HH (d, a, b, c, x[10], S32); /* 38 */
HH (c, d, a, b, x[ 6], S33); /* 39 */
HH (b, c, d, a, x[14], S34); /* 40 */
HH (a, b, c, d, x[ 1], S31); /* 41 */
HH (d, a, b, c, x[ 9], S32); /* 42 */
HH (c, d, a, b, x[ 5], S33); /* 43 */
HH (b, c, d, a, x[13], S34); /* 44 */
HH (a, b, c, d, x[ 3], S31); /* 45 */
HH (d, a, b, c, x[11], S32); /* 46 */
HH (c, d, a, b, x[ 7], S33); /* 47 */
HH (b, c, d, a, x[15], S34); /* 48 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information.
*/
MD4_memset ((POINTER)x, 0, sizeof (x));
}
/* Encodes input (UINT4) into output (unsigned char). Assumes len is
a multiple of 4.
*/
static void Encode (unsigned char *output, UINT4 *input, unsigned len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char)(input[i] & 0xff);
output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (unsigned char) into output (UINT4). Assumes len is
a multiple of 4.
*/
static void Decode (UINT4 *output, unsigned char *input, unsigned len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
(((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
}
/* Note: Replace "for loop" with standard memcpy if possible.
*/
static void MD4_memcpy (POINTER output, POINTER input, unsigned len)
{
unsigned int i;
for (i = 0; i < len; i++)
output[i] = input[i];
}
/* Note: Replace "for loop" with standard memset if possible.
*/
static void MD4_memset (POINTER output, int value, unsigned len)
{
unsigned int i;
for (i = 0; i < len; i++)
((char *)output)[i] = (char)value;
}

View File

@ -1,83 +0,0 @@
#ifndef _LRAD_MD4_H
#define _LRAD_MD4_H
#ifndef _LRAD_PROTO_H
#define _LRAD_PROTO_H
/* GLOBAL.H - RSAREF types and constants
*/
/* PROTOTYPES should be set to one if and only if the compiler supports
function argument prototyping.
The following makes PROTOTYPES default to 0 if it has not already
been defined with C compiler flags.
*/
#ifndef PROTOTYPES
# if __STDC__
# define PROTOTYPES 1
# else
# define PROTOTYPES 0
# endif
#endif
/* POINTER defines a generic pointer type */
typedef unsigned char *POINTER;
#define _POINTER_T
/* UINT2 defines a two byte word */
typedef unsigned short int UINT2;
#define _UINT2_T
/* UINT4 defines a four byte word */
typedef unsigned int UINT4;
#define _UINT4_T
/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
returns an empty list.
*/
#if PROTOTYPES
#define PROTO_LIST(list) list
#else
#define PROTO_LIST(list) ()
#endif
#endif /* _LRAD_PROTO_H */
/* MD4.H - header file for MD4C.C
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD4 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD4 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* MD4 context. */
typedef struct {
UINT4 state[4]; /* state (ABCD) */
UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD4_CTX;
void md4_calc (unsigned char *, unsigned char *, unsigned int);
void MD4Init PROTO_LIST ((MD4_CTX *));
void MD4Update PROTO_LIST
((MD4_CTX *, unsigned char *, unsigned int));
void MD4Final PROTO_LIST ((unsigned char [16], MD4_CTX *));
#endif /* _LRAD_MD4_H */

View File

@ -1,325 +0,0 @@
/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
#include "md5.h"
/* Constants for MD5Transform routine.
*/
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
void librad_md5_calc(unsigned char *output, unsigned char *input,
unsigned int inputlen);
static void MD5Transform PROTO_LIST ((UINT4 [4], const unsigned char [64]));
static void Encode PROTO_LIST
((unsigned char *, UINT4 *, unsigned int));
static void Decode PROTO_LIST
((UINT4 *, const unsigned char *, unsigned int));
static void MD5_memcpy PROTO_LIST ((POINTER, CONSTPOINTER, unsigned int));
static void MD5_memset PROTO_LIST ((POINTER, int, unsigned int));
static const unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
void librad_md5_calc(unsigned char *output, unsigned char *input,
unsigned int inlen)
{
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, input, inlen);
MD5Final(output, &context);
}
/* MD5 initialization. Begins an MD5 operation, writing a new context.
*/
void MD5Init (MD5_CTX *context)
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
void MD5Update (MD5_CTX *context, const unsigned char *input, unsigned inputLen)
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int)((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((UINT4)inputLen << 3))
< ((UINT4)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT4)inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
MD5_memcpy
((POINTER)&context->buffer[index], (CONSTPOINTER)input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
/* Buffer remaining input */
MD5_memcpy
((POINTER)&context->buffer[index], (CONSTPOINTER)&input[i],
inputLen-i);
}
/* MD5 finalization. Ends an MD5 message-digest operation, writing the
the message digest and zeroizing the context.
*/
void MD5Final (unsigned char digest[16], MD5_CTX *context)
{
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
Encode (bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update (context, PADDING, padLen);
/* Append length (before padding) */
MD5Update (context, bits, 8);
/* Store state in digest */
Encode (digest, context->state, 16);
/* Zeroize sensitive information.
*/
MD5_memset ((POINTER)context, 0, sizeof (*context));
}
/* MD5 basic transformation. Transforms state based on block.
*/
static void MD5Transform (UINT4 state[4], const unsigned char block[64])
{
UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information.
*/
MD5_memset ((POINTER)x, 0, sizeof (x));
}
/* Encodes input (UINT4) into output (unsigned char). Assumes len is
a multiple of 4.
*/
static void Encode (unsigned char *output, UINT4 *input, unsigned len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char)(input[i] & 0xff);
output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
}
}
/* Decodes input (unsigned char) into output (UINT4). Assumes len is
a multiple of 4.
*/
static void Decode (UINT4 *output, const unsigned char *input, unsigned len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
(((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
}
/* Note: Replace "for loop" with standard memcpy if possible.
*/
static void MD5_memcpy (POINTER output, CONSTPOINTER input, unsigned len)
{
unsigned int i;
for (i = 0; i < len; i++)
output[i] = input[i];
}
/* Note: Replace "for loop" with standard memset if possible.
*/
static void MD5_memset (POINTER output, int value, unsigned len)
{
unsigned int i;
for (i = 0; i < len; i++)
((char *)output)[i] = (char)value;
}

View File

@ -1,94 +0,0 @@
#ifndef _LRAD_MD5_H
#define _LRAD_MD5_H
#ifndef _LRAD_PROTO_H
#define _LRAD_PROTO_H
/* GLOBAL.H - RSAREF types and constants
*/
/* PROTOTYPES should be set to one if and only if the compiler supports
function argument prototyping.
The following makes PROTOTYPES default to 0 if it has not already
been defined with C compiler flags.
*/
#ifndef PROTOTYPES
# if __STDC__
# define PROTOTYPES 1
# else
# define PROTOTYPES 0
# endif
#endif
/* POINTER defines a generic pointer type */
#ifndef _POINTER_T
typedef unsigned char *POINTER;
#endif
typedef const unsigned char *CONSTPOINTER;
/* UINT2 defines a two byte word */
#ifndef _UINT2_T
typedef unsigned short int UINT2;
#endif
/* UINT4 defines a four byte word */
#ifndef _UINT4_T
typedef unsigned int UINT4;
#endif
/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
returns an empty list.
*/
#if PROTOTYPES
#define PROTO_LIST(list) list
#else
#define PROTO_LIST(list) ()
#endif
#endif /* _LRAD_PROTO_H */
/*
* FreeRADIUS defines to ensure globally unique MD5 function names,
* so that we don't pick up vendor-specific broken MD5 libraries.
*/
#define MD5_CTX librad_MD5_CTX
#define MD5Init librad_MD5Init
#define MD5Update librad_MD5Update
#define MD5Final librad_MD5Final
/* MD5.H - header file for MD5C.C
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* MD5 context. */
typedef struct {
UINT4 state[4]; /* state (ABCD) */
UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
void MD5Init PROTO_LIST ((MD5_CTX *));
void MD5Update PROTO_LIST
((MD5_CTX *, const unsigned char *, unsigned int));
void MD5Final PROTO_LIST ((unsigned char [16], MD5_CTX *));
#endif /* _LRAD_MD5_H */

204
src/limiter.c Normal file
View File

@ -0,0 +1,204 @@
/*
3APA3A simplest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement
*/
#include "proxy.h"
int startconnlims (struct clientparam *param){
struct connlim * ce;
time_t delta;
uint64_t rating;
int ret = 0;
param->connlim = 1;
_3proxy_mutex_lock(&connlim_mutex);
for(ce = conf.connlimiter; ce; ce = ce->next) {
if(ACLmatches(ce->ace, param)){
if(ce->ace->action == NOCONNLIM)break;
if(!ce->period){
if(ce->rate <= ce->rating) {
ret = 1;
break;
}
ce->rating++;
continue;
}
delta = conf.time - ce->basetime;
if(ce->period <= delta || ce->basetime > conf.time){
ce->basetime = conf.time;
ce->rating = 0x100000;
continue;
}
rating = delta? ((ce->rating * (ce->period - delta)) / ce->period) + 0x100000 : ce->rating + 0x100000;
if (rating > (ce->rate<<20)) {
ret = 2;
break;
}
ce->rating = rating;
ce->basetime = conf.time;
}
}
if(ret) {
struct connlim * cee;
for(cee = conf.connlimiter; cee != ce; cee = cee->next) {
if(ACLmatches(cee->ace, param) && !cee->period && cee->rating) {
cee->rating--;
}
}
param->connlim = 0;
}
_3proxy_mutex_unlock(&connlim_mutex);
return ret;
}
void stopconnlims (struct clientparam *param){
struct connlim * ce;
_3proxy_mutex_lock(&connlim_mutex);
for(ce = conf.connlimiter; ce; ce = ce->next) {
if(ACLmatches(ce->ace, param)){
if(ce->ace->action == NOCONNLIM)break;
if(!ce->period && ce->rating){
ce->rating--;
continue;
}
}
}
_3proxy_mutex_unlock(&connlim_mutex);
}
void initbandlims (struct clientparam *param){
struct bandlim * be;
int i;
param->bandlimfunc = NULL;
param->bandlims[0] = NULL;
param->bandlimsout[0] = NULL;
if(!conf.bandlimfunc || (!conf.bandlimiter && !conf.bandlimiterout)) return;
for(i=0, be = conf.bandlimiter; be && i<MAXBANDLIMS; be = be->next) {
if(ACLmatches(be->ace, param)){
if(be->ace->action == NOBANDLIM) {
break;
}
param->bandlims[i++] = be;
param->bandlimfunc = conf.bandlimfunc;
}
}
if(i<MAXBANDLIMS)param->bandlims[i] = NULL;
for(i=0, be = conf.bandlimiterout; be && i<MAXBANDLIMS; be = be->next) {
if(ACLmatches(be->ace, param)){
if(be->ace->action == NOBANDLIM) {
break;
}
param->bandlimsout[i++] = be;
param->bandlimfunc = conf.bandlimfunc;
}
}
if(i<MAXBANDLIMS)param->bandlimsout[i] = NULL;
param->bandlimver = conf.bandlimver;
}
unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout){
unsigned sleeptime = 0, nsleeptime;
time_t sec;
unsigned msec;
unsigned now;
int i;
#ifdef _WIN32
struct timeb tb;
ftime(&tb);
sec = (unsigned)tb.time;
msec = (unsigned)tb.millitm*1000;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
sec = tv.tv_sec;
msec = tv.tv_usec;
#endif
if(!nbytesin && !nbytesout) return 0;
_3proxy_mutex_lock(&bandlim_mutex);
if(param->bandlimver != conf.bandlimver){
initbandlims(param);
param->bandlimver = conf.bandlimver;
}
for(i=0; nbytesin&& i<MAXBANDLIMS && param->bandlims[i]; i++){
if( !param->bandlims[i]->basetime ||
param->bandlims[i]->basetime > sec ||
param->bandlims[i]->basetime < (sec - 120)
)
{
param->bandlims[i]->basetime = sec;
param->bandlims[i]->nexttime = 0;
continue;
}
now = (unsigned)((sec - param->bandlims[i]->basetime) * 1000000) + msec;
nsleeptime = (param->bandlims[i]->nexttime > now)?
param->bandlims[i]->nexttime - now : 0;
sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
param->bandlims[i]->basetime = sec;
param->bandlims[i]->nexttime = msec + nsleeptime + (((uint64_t)nbytesin * 8 * 1000000) / param->bandlims[i]->rate);
}
for(i=0; nbytesout && i<MAXBANDLIMS && param->bandlimsout[i]; i++){
if( !param->bandlimsout[i]->basetime ||
param->bandlimsout[i]->basetime > sec ||
param->bandlimsout[i]->basetime < (sec - 120)
)
{
param->bandlimsout[i]->basetime = sec;
param->bandlimsout[i]->nexttime = 0;
continue;
}
now = (unsigned)((sec - param->bandlimsout[i]->basetime) * 1000000) + msec;
nsleeptime = (param->bandlimsout[i]->nexttime > now)?
param->bandlimsout[i]->nexttime - now : 0;
sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
param->bandlimsout[i]->basetime = sec;
param->bandlimsout[i]->nexttime = msec + nsleeptime + ((nbytesout > 512)? ((nbytesout+32)/64)*((64*8*1000000)/param->bandlimsout[i]->rate) : ((nbytesout+1)* (8*1000000))/param->bandlimsout[i]->rate);
}
_3proxy_mutex_unlock(&bandlim_mutex);
return sleeptime/1000;
}
void trafcountfunc(struct clientparam *param){
struct trafcount * tc;
int countout = 0;
_3proxy_mutex_lock(&tc_mutex);
for(tc = conf.trafcounter; tc; tc = tc->next) {
if(ACLmatches(tc->ace, param)){
if(tc->ace->action == NOCOUNTIN) {
countout = 1;
break;
}
if(tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTIN && tc->ace->action != COUNTALL) {
countout = 1;
continue;
}
tc->traf64 += param->statssrv64;
tc->updated = conf.time;
}
}
if(countout) for(tc = conf.trafcounter; tc; tc = tc->next) {
if(ACLmatches(tc->ace, param)){
if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTOUT && tc->ace->action != COUNTALL ) {
continue;
}
tc->traf64 += param->statscli64;
tc->updated = conf.time;
}
}
_3proxy_mutex_unlock(&tc_mutex);
}

Some files were not shown because too many files have changed in this diff Show More