Compare commits

...

215 Commits

Author SHA1 Message Date
Vladimir Dubrovin
57841074b9 Avoid sleep on service thread sync
Some checks failed
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2025-04-16 21:29:48 +03:00
Vladimir Dubrovin
7320094c11 SOCKSTRACE fixed
Some checks failed
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2025-04-15 19:51:01 +03:00
Vladimir Dubrovin
43d48adeb9 ssl_server_verify, ssl_server_ca_dir, ssl_server_ca_store added, ssl_server / ssl_client aliases added to ssl_serv / ssl_cli 2025-04-15 19:18:14 +03:00
Vladimir Dubrovin
6355f9659b ssl_noserv fixed, ssl_cli/ssl_nocli/ssl_client_cert/ssl_client_key added
Some checks are pending
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2025-04-14 21:40:59 +03:00
Vladimir Dubrovin
7aad0205e1 Remove legacy NTLMv1 code
Some checks failed
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
2025-03-17 19:44:48 +03:00
Vladimir Dubrovin
89b45b1b2a Support HAProxy proxy v1 protocol
Some checks failed
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
Added:
-H option - expect HAProxy proxy v1 header, e.g. `proxy -H`

parent ha type - send HAProxy proxy v1 header (must be last in redirection), e.g.

allow *
parent 1000 ha
parent 1000 proxy 1.2.3.4 3128
socks
2025-03-15 15:54:29 +03:00
Vladimir Dubrovin
27c9e62faa Merge branch 'master' of https://github.com/3proxy/3proxy
Some checks are pending
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2025-03-15 13:03:25 +03:00
Vladimir Dubrovin
7888502cd5 Support tlspr in auto 2025-03-15 13:02:46 +03:00
z3apa3a
9429421314 Fix Makefile.llvm 2025-03-15 11:52:33 +03:00
z3apa3a
00b3e02e05 Add 3proxy.rc to Makefile.llvm 2025-03-15 11:50:51 +03:00
z3apa3a
08177f2161 Fix Makefile.win 2025-03-15 11:21:08 +03:00
z3apa3a
188b0a2841 Add resources compilation to Makefile.win 2025-03-15 11:17:59 +03:00
Vladimir Dubrovin
a37e6e5a81 Fix Makefile.win
Some checks are pending
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2025-03-14 22:25:26 +03:00
Vladimir Dubrovin
8fc31a7336 return lost tabs into Makefiles 2025-03-14 22:23:15 +03:00
Vladimir Dubrovin
4eb0ca60b7
Update Makefile.win 2025-03-14 21:02:08 +03:00
Vladimir Dubrovin
584fdfd51f
Update Makefile.win 2025-03-14 21:00:22 +03:00
Vladimir Dubrovin
5a6e9c92e3
Update Makefile.win 2025-03-14 20:59:28 +03:00
Vladimir Dubrovin
eaf66dc8d1 Update git workflow
Some checks are pending
C/C++ CI / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI / ${{ matrix.target }} (windows-2022) (push) Waiting to run
2025-03-14 20:44:43 +03:00
Vladimir Dubrovin
e6f5f7b5e0 make compatible with openssl 1.x 2025-03-14 20:14:57 +03:00
Vladimir Dubrovin
d48f24ac84 rsa.h not required 2025-03-14 19:56:58 +03:00
Vladimir Dubrovin
4de45ff3a8
Use PCRE_STATIC pcre_plugin.c 2025-03-14 18:03:26 +03:00
Vladimir Dubrovin
74081c8146
use PCRE_STATIC 2025-03-14 17:55:09 +03:00
Vladimir Dubrovin
c71370ec03
Update c-cpp.yml
Do not try to install on mac
2025-03-14 17:04:42 +03:00
Vladimir Dubrovin
b1b64972c5
Update c-cpp.yml
add more targets
2025-03-14 17:02:05 +03:00
Vladimir Dubrovin
db7ef4ba2f
Update c-cpp.yml 2025-03-14 16:52:11 +03:00
Vladimir Dubrovin
51fc2f6dcb
Update c-cpp.yml 2025-03-14 16:38:47 +03:00
Vladimir Dubrovin
16bd55a074
Update c-cpp.yml 2025-03-14 16:28:40 +03:00
Vladimir Dubrovin
0ca9030520
Update c-cpp.yml 2025-03-14 16:27:16 +03:00
Vladimir Dubrovin
87255a8201
Create c-cpp.yml 2025-03-14 16:22:13 +03:00
Vladimir Dubrovin
d80889474b
Update README 2025-03-10 14:07:43 +03:00
Vladimir Dubrovin
8133480b11
Update README 2025-03-10 14:06:29 +03:00
z3apa3a
f23fc4fc44 mention https:// proxy in README 2025-03-10 00:51:43 +03:00
z3apa3a
3668634781 Update readme for 0.9.5 2025-03-10 00:46:46 +03:00
Vladimir Dubrovin
46a230ebd3 Merge branch 'master' of https://github.com/3proxy/3proxy 2025-03-10 00:37:18 +03:00
z3apa3a
e8e1bdfbf1 switch windows / arm to DLL version of OpenSSL 2025-03-10 00:36:05 +03:00
Vladimir Dubrovin
a5f1f08b60 Use non-static openssl libs for windows arm64 2025-03-09 20:55:23 +03:00
z3apa3a
926ef71ba0 Fix Makefile.Linux 2025-03-09 19:51:17 +03:00
z3apa3a
bc92819572 Fix tlspr for compatibility with older compileres 2025-03-09 19:16:35 +03:00
z3apa3a
a76dd93e86 Add tlspr to install section 2025-03-09 18:38:04 +03:00
z3apa3a
2900b80d88 Prepare for 0.9.5 release 2025-03-09 17:29:17 +03:00
z3apa3a
d7b0061626 Fix ssl_plugin for windows building 2025-03-09 17:26:50 +03:00
z3apa3a
74134db09e Fix ssl_plugin for Windows 2025-03-09 17:22:18 +03:00
Vladimir Dubrovin
878025598b tlspr (SNI proxy) documented 2025-03-09 15:03:06 +03:00
Vladimir Dubrovin
6387bed4f2 Replace strcpy with memmove for overlapping regions 2024-12-20 14:38:58 +03:00
Vladimir Dubrovin
cb6a4166b7 Use -fPIC instead of -fPIE 2024-09-11 18:34:40 +03:00
Vladimir Dubrovin
cf6946cc8b Fix: IPv6 address may be invalid on some plafrorms for SOCKSv5 UDP ASSOCIATE 2024-07-18 12:50:59 +03:00
Vladimir Dubrovin
ab8db00b1f Fix type for ssl_poll 2024-06-04 19:26:34 +03:00
Vladimir Dubrovin
94dfa195db char * / unsigned char * conversions fixed 2024-05-31 19:53:28 +03:00
Vladimir Dubrovin
fb4ab5d07f Remove accidentely added binary 2024-05-20 13:44:50 +03:00
Vladimir Dubrovin
57f11d8a0f Add tlspr binary to git ignore 2024-05-20 13:41:55 +03:00
Vladimir Dubrovin
013d4bc333 tlspr (SNI proxy) implemented
Options -cN - level of TLS check
default - allow non-TLS traffic
1 - require TLS, only check client HELLO packet
2 - require TLS, check both client and server HELLO
3 - require TLS, check server send certificate (not compatible with TLS 1.3)
4 - require mutual TLS, check server send certificate request and client sends certificate (not compatible with TLS 1.3)
-P - default port

examples:

1.
tlspr -p1443 -P443 -c1
(port 1443 may be used to redirect traffic to destination port 143). SNI is used to find destination host

2.
allow * * * 80
parent 1000 http 0.0.0.0 0
allow * * * * CONNECT
parent 1000 tls 0.0.0.0 0
deny * * some.not.allowed.host
allow *
socks

attempts to take destination hostname from SNI in SOCKS
2024-05-20 13:01:38 +03:00
Vladimir Dubrovin
29ef226b3c Обновлена документация 2024-03-10 17:01:54 +03:00
Vladimir Dubrovin
d347f0a058 More TLS commands added, ssl_srvkey / ssl_srvfile renamed
ssl_server_cert - certificate for SSL server (rename from ssl_srvkey)
ssl_server_key - key for ssl_server_cert of generated mirm certificate (renamed from ssl_srvkey)
ssl_server_ca_file - CA file for mitm
ssl_server_ca_key - key for mitm CA
ssl_client_ca_file, ssl_client_ca_dir, ssl_client_ca_store - locations for root CAs used with ssl_client_verify for TLS client
ssl_certcache is not optional, if ssl_server_ca_file / ssl_server_ca_key are configured
2024-03-10 16:20:42 +03:00
Vladimir Dubrovin
a316622a85 Added multiple TLS configuration parameters for SSLPlugin
ssl_client_ciphersuites - TLS client ciphers for TLS 1.3, e.g. ssl_client_ciphersuites TLS_AES_128_GCM_SHA256
ssl_server_ciphersuites - TLS server ciphers for TLS 1.3
ssl_client_cipher_list - TLS client ciphers for TLS 1.2 and below , e.g. ssl_client_cipher_list ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305
ssl_server_cipher_list - TLS server ciphers for TLS 1.2 and below
ssl_client_min_proto_version - TLS client min TLS version (e.g. TLSv1.2)
ssl_server_min_proto_version - TLS server min TLS version (e.g. TLSv1.2)
ssl_client_max_proto_version - TLS client max TLS version (e.g. TLSv1.2)
ssl_server_max_proto_version - TLS server max TLS version (e.g. TLSv1.2)
ssl_client_verify - verify certificate for upstream server in TLS client functionality
ssl_client_no_verify - do not verify certificate for upstream server in TLS client functionality (default)
2024-03-10 13:36:40 +03:00
Vladimir Dubrovin
d87241c487 Keep TLS server context 2024-03-09 18:37:44 +03:00
Vladimir Dubrovin
144af547fb Keep TLS client context between requests 2024-03-09 16:23:03 +03:00
Vladimir Dubrovin
35d1de6f5e Ffix use-after-free in freeparam 2024-02-22 17:30:50 +03:00
Vladimir Dubrovin
a592f07783 Update SSLPlugin documentation 2024-02-19 00:13:08 +03:00
Vladimir Dubrovin
161cbbd452 fix crash on insufficient memory 2024-02-18 23:54:31 +03:00
Vladimir Dubrovin
067fdd7f95 support ssl_serv / ssl_noserv commands
example:
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_srvcert path_to_cert
ssl_srvkey path_to_key
ssl_serv
proxy -p33128
ssl_noserv
proxy -p3128
2024-02-18 23:42:09 +03:00
Vladimir Dubrovin
d77e528847 minor fixes 2024-02-18 20:18:31 +03:00
Vladimir Dubrovin
2b4d8e67e4 Do not store CA cert subject 2024-02-18 19:53:35 +03:00
Vladimir Dubrovin
375e3a74d0 call local socket function 2024-02-18 19:41:45 +03:00
Vladimir Dubrovin
6dc145b16b initial commit to TLS refactoring 2024-02-18 19:07:09 +03:00
Vladimir Dubrovin
d162ad5c38 Fix windows issues 2024-02-17 18:53:58 +03:00
Vladimir Dubrovin
8198db8617 adding state to socket functions 2024-02-17 17:31:25 +03:00
Vladimir Dubrovin
d83c1f47f8 Rollback commit in the wrong branch 2024-02-17 13:18:14 +03:00
Vladimir Dubrovin
20a929ca53 Add per-service sockfuncs 2024-02-17 12:57:36 +03:00
Vladimir Dubrovin
a80bef9ecf
Merge pull request #978 from tautschnig/fix-decls
Fix plugin declarations of hashindex and nametohash
2023-10-11 17:00:48 +03:00
Michael Tautschnig
687ebafb1b Fix plugin declarations of hashindex and nametohash
Plugins using these would fail to provide the required arguments.
2023-10-11 10:00:47 +00:00
Vladimir Dubrovin
5e2b2a399e clean up warnings 2023-07-13 15:29:26 +03:00
Vladimir Dubrovin
5f341806b7 Deadloc on traffcount fixed 2023-07-13 13:13:36 +03:00
Vladimir Dubrovin
00513a7d28 eliminate redundant code in previous fix 2023-07-12 17:21:46 +03:00
Vladimir Dubrovin
dc7e098e6b Support request filters for SOCKS, support broken BIND request from some clients 2023-07-12 15:55:50 +03:00
Vladimir Dubrovin
8b57982a09 Fix FreeBSD install 2023-06-10 12:22:59 +03:00
Vladimir Dubrovin
cebb45c095 Fix FreeBSD install secrion 2023-06-01 11:42:16 +03:00
Vladimir Dubrovin
13979b5df4 Allow hostnames in parent 2023-04-26 15:05:47 +03:00
Vladimir Dubrovin
782878b5b4 Fix github links 2023-04-26 15:04:24 +03:00
Vladimir Dubrovin
6532163f01 Fix connlim issues 2023-04-26 15:04:00 +03:00
Vladimir Dubrovin
862405bdfd set linger close to setsockopt 2022-12-23 17:58:15 +03:00
Vladimir Dubrovin
c716c67da2
Merge pull request #840 from DanWin/increase-listen-backlog
Add backlog configuration
2022-11-08 19:51:40 +03:00
Daniel Winzen
b94e1fc01f
Few more changes 2022-11-08 16:02:47 +01:00
Daniel Winzen
cc0fd518bd
Incorporate feedback from z3APA3A 2022-11-08 15:42:04 +01:00
Daniel Winzen
9a6908e623
Add backlog config option 2022-11-08 15:04:19 +01:00
Daniel Winzen
65e57a251d
Clarify use of maxconn in man page 2022-11-08 13:25:05 +01:00
Daniel Winzen
25c375a78a
Increase backlog of listening sockets to match maxconn 2022-11-03 23:24:25 +01:00
Vladimir Dubrovin
a22e2be77b
Merge pull request #838 from DanWin/linux-tcp-fastopen
Add support for TCP_FASTOPEN_CONNECT and TCP_FASTOPEN socket options
2022-11-02 10:57:40 +03:00
Daniel Winzen
8a160dd188
Add support for TCP_FASTOPEN_CONNECT and TCP_FASTOPEN socket options (linux) 2022-11-01 20:11:26 +01:00
Vladimir Dubrovin
fb56b7d307 "auto" command added 2022-10-18 17:58:52 +03:00
Vladimir Dubrovin
5165a4d5bd prevent use-after-free in smtpp 2022-08-31 14:34:48 +03:00
Vladimir Dubrovin
bac19c9ae6 Close service only after config mutex unlocked on reload 2022-08-12 19:18:52 +03:00
Vladimir Dubrovin
c98621aeef Always select between IPV6_BOUND_IF and IP_BOUND_IF 2022-06-29 10:35:17 +03:00
Vladimir Dubrovin
3dc698eccd Fix compilation issues 2022-06-29 10:18:36 +03:00
Vladimir Dubrovin
c1beceb24b Support IP_BOUND_IF on MacOS 2022-06-28 12:50:48 +03:00
Vladimir Dubrovin
4ad05d1565 add handleredirect() to symbols 2022-06-24 10:44:28 +03:00
Vladimir Dubrovin
55d1bbe155 Grace delay feature added
`proxy -g8000,3,10`

First parameter is average read size we want to keep, second parameter is
minimal number of packets in the same direction to apply algorythm,
last value is delay added after polling and prior to reading data.
An example above adds 10 millisecond delay before reading data if average
polling size is below 8000 bytes and 3 read operations are made in the same
direction. It's specially usefule with splice. `logdump 1 1` is useful
to see how grace delays work, choose delay value to avoid filling the read
pipe/buffer (typically 64K) but keep the request sizes close to chosen average
on large file upload/download.
2022-05-19 18:51:02 +03:00
Vladimir Dubrovin
8a8622b30f FIX: SSLPlugin for tcppm 2022-05-19 15:42:18 +03:00
Vladimir Dubrovin
1cf169b7ae FIX: SSLPlugin with SOCKS 2022-05-19 13:26:52 +03:00
Vladimir Dubrovin
d20e76bbc9 FIX: SSLPlugin with http proxy 2022-05-19 11:49:19 +03:00
Vladimir Dubrovin
468124f55c Fix SSLPlugin with HTTP proxy 2022-05-18 18:14:24 +03:00
Vladimir Dubrovin
17f07f2053 Update udppm.c 2022-04-25 16:45:49 +03:00
Vladimir Dubrovin
6d77141ecc Update socks.c 2022-04-25 13:09:55 +03:00
Vladimir Dubrovin
7e681bbacd Update common.c
Process failed connect more correcly
2022-04-07 20:19:49 +03:00
Vladimir Dubrovin
266e62644c Fix RADIUS Login-Service/Login-TCP-Port length 2022-02-22 15:45:23 +03:00
Vladimir Dubrovin
f53b0eb985 fix invalid length in previous commit 2021-11-25 12:21:06 +03:00
Vladimir Dubrovin
bd1dcacf73 Fix domain name reply processing on connect request for parent proxy 2021-11-24 22:53:14 +03:00
Vladimir Dubrovin
e1448b9eb1 connlim error code corrected (should return 10) 2021-11-24 18:22:04 +03:00
Vladimir Dubrovin
70b14394b0 Change minumum DNS cache time to 1 sec 2021-10-30 13:43:20 +03:00
Vladimir Dubrovin
6c1b711fc9 do not ignore Makefile from plugins 2021-10-29 19:26:20 +03:00
Vladimir Dubrovin
34c4162cea Update Makefile.FreeBSD 2021-10-29 19:25:58 +03:00
Vladimir Dubrovin
461fae12e7 set logfunc after configuration reload 2021-10-29 19:12:03 +03:00
Vladimir Dubrovin
e8203ac3a5 Merge branch 'master' of https://github.com/3proxy/3proxy 2021-10-29 18:56:25 +03:00
Vladimir Dubrovin
beaa8777bb Add RuntimeDirectory for systemd 2021-10-29 18:56:23 +03:00
Vladimir Dubrovin
9254688d07
Merge pull request #684 from victor-rds/arm_docker
Add support to Docker images for ARM platforms
2021-10-29 17:43:56 +03:00
Vladimir Dubrovin
daa2b74354 Merge branch 'master' of https://github.com/3proxy/3proxy 2021-10-21 19:57:06 +03:00
Vladimir Dubrovin
bec6e589fb extNat implemented incorrectly, removing current support 2021-10-21 19:57:02 +03:00
Vladimir Dubrovin
f9347c2f8b Allow all-zero IP and port for BIND and UDP ASSOC 2021-10-21 19:56:09 +03:00
Victor R. Santos
0d47a1eee3
Update Dockerfiles, fix builds on ARM plaforms
- Add support to ARM64, ARM/v7 and ARM/v6 devices
- Remove hardcoded "/lib/x86_64-linux-gnu" path
- Move libdl.so.* to a common location
- Format code to keep consistency between dockerfiles
2021-10-04 16:41:44 -03:00
Vladimir Dubrovin
58cf0d8def do not create pid file in default configuration 2021-10-01 15:56:56 +03:00
z3apa3a
5fa261e91e Send accounting start packet if log radius is enabled 2021-07-02 18:38:21 +03:00
z3apa3a
b15d5bf681 Commit as 0.9.4 2021-07-02 12:01:43 +03:00
z3apa3a
e1b4e50242 Copyright update 2021-07-02 11:50:33 +03:00
z3apa3a
346880eb2e debian files 2021-07-01 19:59:57 +03:00
z3apa3a
e607c8b5d0 remove icqpr references from specs 2021-07-01 19:58:12 +03:00
z3apa3a
1fca6ada82 Use self-built openssl for Windows 2021-07-01 19:55:20 +03:00
z3apa3a
d7eb9fb82f better error handling on splice() 2021-05-18 11:34:57 +03:00
z3apa3a
1bd6eff0e6 Update sockmap.c 2021-05-17 18:12:50 +03:00
z3apa3a
e642100271 Merge branch 'master' of https://github.com/3proxy/3proxy 2021-05-15 18:42:30 +03:00
z3apa3a
aac5c9fff9 More accurate error handling on socket mapping 2021-05-15 18:42:17 +03:00
Vladimir Dubrovin
e235ada0de Make SSLPlugin to compile under *nix 2021-05-11 13:53:41 +03:00
Vladimir Dubrovin
7335bc2fb6 Do not change error code >10 on redirection 2021-04-29 14:01:07 +03:00
z3apa3a
3f4c267a25 Use logic operation instead of binary where appropriate 2021-04-22 17:59:10 +03:00
z3apa3a
6279e86086 Do not terminate connection on POLLHUP if there is a data to read 2021-04-22 16:59:07 +03:00
z3apa3a
cc2979ee5b use uint16 instead of char 2021-04-22 11:26:18 +03:00
z3apa3a
bad85a3d51 Support IPv6 subnets in parent extip 2021-04-21 20:39:57 +03:00
z3apa3a
36f16fb899 Better connection error handling in 'proxy' 2021-04-21 17:35:17 +03:00
z3apa3a
5f550c9107 change code for getpeername() error 2021-04-21 16:36:34 +03:00
z3apa3a
47c1640223 remove icqpr man 2021-04-15 17:52:24 +03:00
Vladimir Dubrovin
681182b1e5 Fix: '-' sign incorrectly parsed in hostname ACL, bandlim race condition on configuration reload 2021-04-15 12:26:34 +03:00
Vladimir Dubrovin
9fae0082a3 Change clean command for BSD 2021-01-22 18:17:09 +03:00
z3APA3A
c30065256f Use so._closesocket instead of socket (compilation issues on non-Windows) 2021-01-20 17:55:09 +03:00
z3APA3A
cbe0c2f511 parentretries command added 2021-01-19 14:40:18 +03:00
z3APA3A
1f2bdd7b80 Update version.h
version year update
2021-01-19 14:37:36 +03:00
z3APA3A
0c902525e5 commit as 0.9.3 2020-12-03 21:14:59 +03:00
z3APA3A
129d26475e Fixed: counters incorectly shown in webadmin, contall/nocountall are not applied 2020-12-02 20:08:03 +03:00
z3APA3A
29f8867a9e fix the compilation warning 2020-12-02 11:13:55 +03:00
z3APA3A
252c4cb36b set 1 for release in specs 2020-12-01 18:20:13 +03:00
z3APA3A
07603ceea7 & is not required for systemd 2020-12-01 11:19:43 +03:00
z3APA3A
8ec14c131d Do not fail on clean 2020-11-29 14:00:19 +03:00
z3APA3A
1225dbced7 hostname (%n) may by incomlete in log on long record 2020-11-29 12:47:58 +03:00
z3APA3A
3cd9bdffcb Update README for docker images 2020-11-28 03:18:11 +03:00
z3APA3A
336a4acd46 Update dockerfiles 2020-11-28 02:45:36 +03:00
z3APA3A
c5abe51e26 fix adding proxy account 2020-11-27 19:36:21 +03:00
z3APA3A
31062bdc3c Create Dockerfile.minimal 2020-11-27 15:49:13 +03:00
z3APA3A
8943099dfb extip parent type documented 2020-11-27 15:48:59 +03:00
z3APA3A
09f007e741 http supported in parent name resolution 2020-11-25 17:09:54 +03:00
z3APA3A
4487fd4a73 typo corrected 2020-11-25 17:06:06 +03:00
z3APA3A
5498a79115 add builddate (if defined) to rc 2020-11-24 20:43:30 +03:00
z3APA3A
9c7fc9fddc correct clean 2020-11-24 20:05:49 +03:00
z3APA3A
4d63f957c2 Fix for connect back 2020-11-23 18:58:33 +03:00
z3APA3A
828e00e668 correct afterclean 2020-11-22 02:15:42 +03:00
z3APA3A
3ba16310c5 del res files in afterclean 2020-11-22 02:15:24 +03:00
z3APA3A
7aaa9c18dd build rc file from res 2020-11-22 02:14:53 +03:00
z3APA3A
72923879a3 Make rc file non-version specific 2020-11-21 18:36:39 +03:00
z3APA3A
b1cc2c7c70 Label as 0.9.2 2020-11-21 11:27:43 +03:00
z3APA3A
d88c927ba9 allow overwrite CC for linking 2020-11-20 14:19:47 +03:00
z3APA3A
cf58e62baa rm makefile on clean 2020-11-20 13:49:17 +03:00
z3APA3A
daf4a56665 Remove .o and binaries after clean 2020-11-20 13:30:38 +03:00
z3APA3A
05bc297ea7 Fixed SSLPlugin handling 2020-11-19 23:22:15 +03:00
z3APA3A
7ea9ec89be update changelog and spec for 0.9.2 2020-11-19 10:39:37 +03:00
z3APA3A
f23b6b0d96 export pcre_options 2020-11-19 02:52:47 +03:00
z3APA3A
d2dcf4bb69 better dat filters handling 2020-11-19 02:30:19 +03:00
z3APA3A
1ff0fabf15 switching version to 0.9.2 2020-11-18 18:45:32 +03:00
z3APA3A
e013cc2ab8 remove unneeded fseek 2020-11-18 17:55:23 +03:00
z3APA3A
99a744abda Few bugfixes 2020-11-18 16:10:07 +03:00
z3APA3A
062d60e9d6 README updated 2020-11-17 12:45:44 +03:00
z3APA3A
b777ffec66 RH man handling is arch dependant 2020-11-13 21:00:28 +03:00
z3APA3A
8a2050e7fa remove FAQ from index 2020-11-13 19:58:55 +03:00
z3APA3A
9fbb88238e support cross building 2020-11-13 19:50:39 +03:00
z3APA3A
36f8cde2fb remove unused float variable 2020-11-13 11:39:13 +03:00
z3APA3A
f64cd475af Do not set sigmask for thread in standalone service 2020-11-13 11:01:14 +03:00
z3APA3A
a29d2ab66b readme update 2020-11-13 03:20:37 +03:00
z3APA3A
fd1b7ce2a2 Commit as 0.9.1 2020-11-13 02:56:03 +03:00
z3APA3A
e0ccb34c10 Add LimitNOFILE/LimitNPROC for systemd 2020-11-13 02:09:43 +03:00
z3APA3A
ba29f38959 update gitignore 2020-11-13 02:09:26 +03:00
z3APA3A
a6dfc81e98 debian files corrected 2020-11-12 17:43:18 +03:00
z3APA3A
fe05526472 do not ingore changelog 2020-11-12 16:30:05 +03:00
z3APA3A
a6445334e2 initial implementation of debian building rules 2020-11-12 16:24:00 +03:00
z3APA3A
e5db29d1cb spec file added for rpm build 2020-11-12 03:20:15 +03:00
z3APA3A
7bf7de53b2 start 3proxy without daemon to keep pid 2020-11-12 03:00:34 +03:00
z3APA3A
312c40359c make Makefile.Linux more suitable for packaging + support systemd 2020-11-12 01:57:25 +03:00
z3APA3A
021314d6f5 Fix bandlim handling 2020-11-11 17:40:46 +03:00
z3APA3A
ff67464aa1 Do not fail users without argument 2020-11-11 17:35:06 +03:00
z3APA3A
c113f236e4 FAQ moved to HowTo 2020-11-10 14:40:44 +03:00
z3APA3A
596dee0c5b typo corrected 2020-11-05 17:43:03 +03:00
z3APA3A
32d5dc05c3 More accurate bandlim hangling 2020-11-05 16:09:13 +03:00
z3APA3A
3a31da9b3d fixed error in previous commit 2020-11-03 14:48:55 +03:00
z3APA3A
9356db8de6 Minor memory handling changes 2020-11-03 13:39:56 +03:00
z3APA3A
dbbbe59ef2 Fix acl copy / auth copy out-of-memory error 2020-11-03 11:16:04 +03:00
z3APA3A
c1c5875356 better memory allocation errors handling, countall/nocountall corrected 2020-11-03 02:05:18 +03:00
z3APA3A
b81089f22e More correct handling of insufficient memory 2020-11-02 18:59:13 +03:00
z3APA3A
ee0eac51d6 Remove RDHUP processing
Do not actually need it, may lead to connection closed before all data
read
2020-11-02 16:10:04 +03:00
z3APA3A
6ecb4993fd readme update 2020-10-31 02:31:18 +03:00
z3APA3A
285a7e6765 Commit as 0.9.0 2020-10-22 11:38:44 +03:00
z3APA3A
b2f82ed04f More accurate conditions in sockmap's main event loop 2020-10-19 13:11:44 +03:00
z3APA3A
01ec2f12d5 fail portmapping if name can not be resolved 2020-10-16 23:13:07 +03:00
z3APA3A
624c3e6ae1 correct IPv6 parsing where hostname is expected 2020-10-16 22:51:02 +03:00
z3APA3A
0d713dacc1 README updated 2020-10-16 02:35:01 +03:00
z3APA3A
582f9d7be4 Minor documentation update 2020-10-15 18:39:47 +03:00
z3APA3A
3f2659cb0f Use MAXFAILATTEMPT to limit socket failuers 2020-10-15 16:44:32 +03:00
z3APA3A
aeb0f4caa5 Better handle socket closing 2020-10-15 16:27:39 +03:00
z3APA3A
22555b58ec Do not sigmask main thread for standalone services 2020-10-15 16:00:43 +03:00
z3APA3A
5448329c8a Document RADIUS support 2020-10-15 12:25:33 +03:00
z3APA3A
a8b000b7f1 Allow to specify binding address for RADIUS 2020-10-15 12:21:46 +03:00
z3APA3A
edaee895e6 Merged from devel as 0.9.0-rc 2020-10-15 02:16:20 +03:00
117 changed files with 4351 additions and 6438 deletions

50
.github/workflows/c-cpp.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: C/C++ CI
on:
push:
branches: [ "master" ]
paths: [ '**.c', '**.h', 'Makefile.**', '.github/configs', '.github/workflows/c-cpp.yml' ]
pull_request:
branches: [ "master" ]
paths: [ '**.c', '**.h', 'Makefile.**', '.github/configs', '.github/workflows/c-cpp.yml' ]
jobs:
ci:
name: "${{ matrix.target }}"
strategy:
matrix:
target:
- ubuntu-latest
- ubuntu-24.04-arm
- macos-15
- windows-2022
runs-on: ${{ matrix.target }}
steps:
- uses: actions/checkout@v4
# - name: configure
# run: ./configure
- name: ln Linux
if: ${{ startsWith(matrix.target, 'ubuntu') }}
run: ln -s Makefile.Linux Makefile
- name: ln Mac
if: ${{ startsWith(matrix.target, 'macos') }}
run: ln -s Makefile.FreeBSD Makefile
- name: ln Windows
if: ${{ startsWith(matrix.target, 'windows') }}
run: copy Makefile.win Makefile
- name: dirs Windows
if: ${{ startsWith(matrix.target, 'windows') }}
run: cmd /C 'echo LIBS := -L "c:/program files/openssl/lib" $(LIBS) >>Makefile.win && echo CFLAGS := -I "c:/program files/openssl/include" $(CFLAGS) >>Makefile.win && type Makefile.win'
- name: SSLPlugin Linux
if: ${{ startsWith(matrix.target, 'ubuntu') }}
run: 'echo PLUGINS := $(PLUGINS) SSLPlugin >>Makefile & echo LIBS := $(LIBS) -lcrypto -lssl >>Makefile'
- name: make
run: make
- name: mkdir
if: ${{ startsWith(matrix.target, 'ubuntu') }}
run: mkdir ~/3proxy
- name: make install
if: ${{ startsWith(matrix.target, 'ubuntu') }}
run: make DESTDIR=~/3proxy install
- name: make clean
run: make clean

16
.gitignore vendored
View File

@ -11,6 +11,17 @@
*.lib *.lib
*.key *.key
*.pem *.pem
*.so
bin/3proxy
bin/proxy
bin/socks
bin/tcppm
bin/udppm
bin/pop3p
bin/smtpp
bin/ftppr
bin/mycrypt
bin/tlspr
bin64/ bin64/
dll/ dll/
tmp/ tmp/
@ -24,6 +35,8 @@ tmp/
res res
version.c version.c
version version
version.sh
buildlinux.sh
3proxy.res 3proxy.res
src/3proxy src/3proxy
@ -43,8 +56,7 @@ doc/html/man3/
doc/html/man8/ doc/html/man8/
*.var *.var
verfile.sh verfile.sh
Makefile /Makefile
Changelog
copytgz.sh copytgz.sh
*~.nib *~.nib
local.properties local.properties

55
Dockerfile.full Normal file
View File

@ -0,0 +1,55 @@
# 3proxy.full is fully functional 3proxy build based on busibox:glibc
#
#to build:
# docker build -f Dockerfile.full -t 3proxy.full .
#to run:
# by default 3proxy uses safe chroot environment with chroot to /usr/local/3proxy with uid/gid 65535/65535 and expects
# configuration file to be placed in /usr/local/etc/3proxy.
# Paths in configuration file must be relative to /usr/local/3proxy, that is use /logs instead of
# /usr/local/3proxy/logs. nserver in chroot is required for DNS resolution. An example:
#
# echo nserver 8.8.8.8 >/path/to/local/config/directory/3proxy.cfg
# echo proxy -p3129 >>/path/to/local/config/directory/3proxy.cfg
# docker run -p 3129:3129 -v /path/to/local/config/directory:/usr/local/3proxy/conf -name 3proxy.full 3proxy.full
#
# /path/to/local/config/directory in this example must conrain 3proxy.cfg
# if you need 3proxy to be executed without chroot with root permissions, replace /etc/3proxy/3proxy.cfg by e.g. mounting config
# dir to /etc/3proxy ot by providing config file /etc/3proxy/3proxy.cfg
# docker run -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.
# plugins are located in /usr/local/3proxy/libexec (/libexec for chroot config).
FROM gcc AS buildenv
COPY . 3proxy
RUN cd 3proxy &&\
echo "">> Makefile.Linux &&\
echo PLUGINS = StringsPlugin TrafficPlugin PCREPlugin TransparentPlugin SSLPlugin>>Makefile.Linux &&\
echo LIBS = -l:libcrypto.a -l:libssl.a -ldl >>Makefile.Linux &&\
make -f Makefile.Linux &&\
strip bin/3proxy &&\
strip bin/StringsPlugin.ld.so &&\
strip bin/TrafficPlugin.ld.so &&\
strip bin/PCREPlugin.ld.so &&\
strip bin/TransparentPlugin.ld.so &&\
strip bin/SSLPlugin.ld.so &&\
mkdir /usr/local/lib/3proxy &&\
cp "/lib/`gcc -dumpmachine`"/libdl.so.* /usr/local/lib/3proxy/
FROM busybox:glibc
COPY --from=buildenv /usr/local/lib/3proxy/libdl.so.* /lib/
COPY --from=buildenv 3proxy/bin/3proxy /bin/
COPY --from=buildenv 3proxy/bin/*.ld.so /usr/local/3proxy/libexec/
RUN mkdir /usr/local/3proxy/logs &&\
mkdir /usr/local/3proxy/conf &&\
chown -R 65535:65535 /usr/local/3proxy &&\
chmod -R 550 /usr/local/3proxy &&\
chmod 750 /usr/local/3proxy/logs &&\
chmod -R 555 /usr/local/3proxy/libexec &&\
chown -R root /usr/local/3proxy/libexec &&\
mkdir /etc/3proxy/ &&\
echo chroot /usr/local/3proxy 65535 65535 >/etc/3proxy/3proxy.cfg &&\
echo include /conf/3proxy.cfg >>/etc/3proxy/3proxy.cfg &&\
chmod 440 /etc/3proxy/3proxy.cfg
CMD ["/bin/3proxy", "/etc/3proxy/3proxy.cfg"]

41
Dockerfile.minimal Normal file
View File

@ -0,0 +1,41 @@
# dockerfile for "interactive" minimal 3proxy execution, no configuration mounting is required, configuration
# is accepted from stdin. Use "end" command to indicate the end of configuration. Use "log" for stdout logging.
#
# This is busybox based docker with only 3proxy static executable and empty non-writable "run" directory.
#
# "plugin" is not supported
#
# Build:
#
# docker build -f Dockerfile.minimal -t 3proxy.minimal .
#
# Run example:
#
# docker run -i -p 3129:3129 --name 3proxy 3proxy.minimal
#or
# docker start -i 3proxy
#<chroot run 65535 65535
#<nserver 8.8.8.8
#<nscache 65535
#<log
#<proxy -p3129
#<end
#
# use "chroot run 65536 65536" in config for safe chroot environment. nserver is required for DNS resolutions in chroot.
FROM gcc AS buildenv
COPY . 3proxy
RUN cd 3proxy &&\
echo "">>Makefile.Linux &&\
echo LDFLAGS = -fPIC -O2 -fno-strict-aliasing -pthread >>Makefile.Linux &&\
echo PLUGINS = >>Makefile.Linux &&\
echo LIBS = >>Makefile.Linux &&\
echo CFLAGS = -g -fPIC -O2 -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER -DNOPLUGINS >>Makefile.Linux &&\
make -f Makefile.Linux &&\
strip bin/3proxy
FROM busybox:glibc
COPY --from=buildenv 3proxy/bin/3proxy /bin/3proxy
RUN mkdir /run && chmod 555 /run
CMD ["/bin/3proxy"]

View File

@ -1,20 +1,17 @@
# #
# 3 proxy Makefile for GCC/Unix # 3 proxy Makefile for GCC/Unix
# #
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# remove -DNOODBC from CFLAGS and add -lodbc to LDFLAGS to compile with ODBC # remove -DNOODBC from CFLAGS and add -lodbc to LDFLAGS to compile with ODBC
# 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 ?= gcc CC ?= cc
CFLAGS = -c -O -fno-strict-aliasing -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL CFLAGS += -c -fno-strict-aliasing -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o COUT = -o
LN ?= ${CC} LN ?= ${CC}
LDFLAGS = -pthread -O -fno-strict-aliasing LDFLAGS += -pthread -fno-strict-aliasing
# -lpthreads may be reuqired on some platforms instead of -pthreads # -lpthreads may be reuiured on some platforms instead of -pthreads
# -ldl or -lld may be required for some platforms # -ldl or -lld may be required for some platforms
DCFLAGS = -fPIC DCFLAGS = -fPIC
DLFLAGS = -shared DLFLAGS = -shared
@ -28,6 +25,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f REMOVECOMMAND = rm -f
AFTERCLEAN = (find . -type f -name "*.o" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -perm +111 -delete) || true
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.FreeBSD MAKEFILE = Makefile.FreeBSD
@ -36,22 +34,16 @@ PLUGINS = StringsPlugin TrafficPlugin PCREPlugin PamAuth TransparentPlugin
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/mycrypt /usr/local/3proxy/bin/mycrypt
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 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
echo /usr/local/3proxy/3proxy.cfg already exists if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi
else
install scripts/3proxy.cfg /usr/local/etc/3proxy/
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
echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user
fi
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

@ -12,9 +12,9 @@ CC = gcc
CFLAGS = -g -fPIC -O2 -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER CFLAGS = -g -fPIC -O2 -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER
COUT = -o COUT = -o
LN = gcc LN = $(CC)
DCFLAGS = DCFLAGS =
LDFLAGS = -fPIE -O2 -fno-strict-aliasing -pthread LDFLAGS = -fPIC -O2 -fno-strict-aliasing -pthread
DLFLAGS = -shared DLFLAGS = -shared
DLSUFFICS = .ld.so DLSUFFICS = .ld.so
# -lpthreads may be reuqired on some platforms instead of -pthreads # -lpthreads may be reuqired on some platforms instead of -pthreads
@ -26,6 +26,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f 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 TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.Linux MAKEFILE = Makefile.Linux
@ -45,6 +46,7 @@ DESTDIR =
prefix = prefix =
exec_prefix = $(prefix) exec_prefix = $(prefix)
man_prefix = /usr/share man_prefix = /usr/share
chroot_prefix = /usr/local
INSTALL = /usr/bin/install INSTALL = /usr/bin/install
INSTALL_BIN = $(INSTALL) -m 755 INSTALL_BIN = $(INSTALL) -m 755
@ -56,7 +58,8 @@ INSTALL_OBJS = bin/3proxy \
bin/proxy \ bin/proxy \
bin/socks \ bin/socks \
bin/tcppm \ bin/tcppm \
bin/udppm bin/udppm \
bin/tlspr
INSTALL_CFG = scripts/3proxy.cfg.chroot INSTALL_CFG = scripts/3proxy.cfg.chroot
@ -66,19 +69,22 @@ INSTALL_CFG_OBJS = scripts/3proxy.cfg \
INSTALL_CFG_OBJS2 = counters bandlimiters INSTALL_CFG_OBJS2 = counters bandlimiters
INSTALL_INITD_SCRIPT = scripts/init.d/3proxy.sh INSTALL_INITD_SCRIPT = scripts/init.d/3proxy.sh
INSTALL_SYSTEMD_SCRIPT = scripts/3proxy.service
CHROOTDIR = $(DESTDIR)/usr/local/3proxy CHROOTDIR = $(DESTDIR)$(chroot_prefix)/3proxy
CHROOTREL = ../..$(chroot_prefix)/3proxy
MANDIR1 = $(DESTDIR)$(man_prefix)/man/man1 MANDIR1 = $(DESTDIR)$(man_prefix)/man/man1
MANDIR3 = $(DESTDIR)$(man_prefix)/man/man3 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)$(prefix)/etc/3proxy ETCDIR = $(DESTDIR)/etc/3proxy
INITDDIR = $(DESTDIR)$(prefix)/etc/init.d INITDDIR = $(DESTDIR)/etc/init.d
RUNBASE = $(DESTDIR)$(prefix)/var/run RUNBASE = $(DESTDIR)/var/run
RUNDIR = $(RUNBASE)/3proxy RUNDIR = $(RUNBASE)/3proxy
LOGBASE = $(DESTDIR)$(prefix)/var/log LOGBASE = $(DESTDIR)/var/log
LOGDIR = $(LOGBASE)/3proxy LOGDIR = $(LOGBASE)/3proxy
INSTALL_CFG_DEST = $(ETCDIR)/conf INSTALL_CFG_DEST = $(ETCDIR)/conf
SYSTEMDDIR = $(DESTDIR)/usr/lib/systemd/system/
install-bin: install-bin:
$(INSTALL_BIN) -d $(BINDIR) $(INSTALL_BIN) -d $(BINDIR)
@ -99,7 +105,7 @@ install-chroot-dir:
install-etc-default-config: install-etc-default-config:
if [ ! -d $(INSTALL_CFG_DEST) ]; then \ if [ ! -d $(INSTALL_CFG_DEST) ]; then \
ln -s $(CHROOTDIR)/conf $(INSTALL_CFG_DEST); \ ln -s $(CHROOTREL)/conf $(INSTALL_CFG_DEST); \
$(INSTALL_BIN) $(INSTALL_CFG) $(ETCDIR)/3proxy.cfg; \ $(INSTALL_BIN) $(INSTALL_CFG) $(ETCDIR)/3proxy.cfg; \
$(INSTALL_BIN) $(INSTALL_CFG_OBJS) $(INSTALL_CFG_DEST); \ $(INSTALL_BIN) $(INSTALL_CFG_OBJS) $(INSTALL_CFG_DEST); \
fi fi
@ -117,46 +123,22 @@ install-man:
$(INSTALL_DATA) man/*.8 $(MANDIR8) $(INSTALL_DATA) man/*.8 $(MANDIR8)
install-init: install-init:
if [ -d $(INITDIR) ]; then \ $(INSTALL_BIN) -d $(INITDDIR)
$(INSTALL_BIN) $(INSTALL_INITD_SCRIPT) $(INITDDIR)/3proxy; \ $(INSTALL_BIN) $(INSTALL_INITD_SCRIPT) $(INITDDIR)/3proxy
fi $(INSTALL_BIN) -d $(SYSTEMDDIR)
if [ -f /usr/sbin/update-rc.d ]; then \ $(INSTALL_DATA) $(INSTALL_SYSTEMD_SCRIPT) $(SYSTEMDDIR)
/usr/sbin/update-rc.d 3proxy defaults; \
/usr/sbin/update-rc.d 3proxy enable; \
fi
install-run: install-run:
$(INSTALL_BIN) -d $(RUNDIR) $(INSTALL_BIN) -d $(RUNDIR)
install-log: install-log:
@if [ -d $(LOGBASE) ] && [ ! -d $(LOGDIR) ]; then \ $(INSTALL_BIN) -d $(LOGBASE)
ln -s $(CHROOTDIR)/logs $(LOGDIR);\ @if [ ! -d $(LOGDIR) ]; then \
ln -s $(CHROOTREL)/logs $(LOGDIR);\
fi fi
install: install-chroot-dir install-bin install-etc install-log install-man install-run install-init install: install-chroot-dir install-bin install-etc install-log install-man install-run install-init
@getent passwd proxy || useradd -UMr -s /bin/false -c 3proxy proxy @if [ "$(DESTDIR)" = "" ]; then \
@if [ ! -f $(INSTALL_CFG_DEST)/passwd ]; then \ sh scripts/debian/preinst; \
touch $(INSTALL_CFG_DEST)/passwd;\ sh scripts/debian/postinst; \
fi
@chown -R proxy:proxy $(CHROOTDIR)
@chmod 550 $(CHROOTDIR)/
@chmod 550 $(CHROOTDIR)/conf/
@chmod 440 $(CHROOTDIR)/conf/*
@echo ""
@echo 3proxy installed.
@echo use
@echo " "service 3proxy start
@echo to start proxy
@echo " "service 3proxy stop
@echo to stop proxy
@echo " "$(INSTALL_CFG_DEST)/add3proxyuser.sh
@echo to add users
@echo ""
@echo Default config uses Google\'s DNS.
@echo It\'s recommended to use provider supplied DNS or install local recursor, e.g. pdns-recursor.
@echo Configure preferred DNS in $(INSTALL_CFG_DEST)/3proxy.cfg.
@echo run \'$(INSTALL_CFG_DEST)/add3proxyuser.sh admin password\' to configure \'admin\' user
@if [ -f /usr/sbin/service ]; then \
/usr/sbin/service 3proxy stop ;\
/usr/sbin/service 3proxy start ;\
fi fi

View File

@ -11,7 +11,7 @@ BUILDDIR = ../bin/
CC = cc CC = cc
CFLAGS = -xO3 -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL CFLAGS = -xO3 -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o ./ COUT = -o ./
LN = cc LN = $(CC)
LDFLAGS = -xO3 LDFLAGS = -xO3
DCFLAGS = -fPIC DCFLAGS = -fPIC
DLFLAGS = -shared DLFLAGS = -shared
@ -25,6 +25,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f 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 TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.Solaris MAKEFILE = Makefile.Solaris

View File

@ -12,7 +12,7 @@ BUILDDIR = ../bin/
CC = gcc CC = gcc
CFLAGS = -O2 -fno-strict-aliasing -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL CFLAGS = -O2 -fno-strict-aliasing -c -D_SOLARIS -D_THREAD_SAFE -DGETHOSTBYNAME_R -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o ./ COUT = -o ./
LN = gcc LN = $(CC)
LDFLAGS = -O3 LDFLAGS = -O3
DCFLAGS = -fPIC DCFLAGS = -fPIC
DLFLAGS = -shared DLFLAGS = -shared
@ -26,6 +26,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f 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 TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.Solaris-gcc MAKEFILE = Makefile.Solaris-gcc

View File

@ -3,10 +3,11 @@
# #
all: all:
$(TYPECOMMAND) $(MAKEFILE) > src/Makefile.var @$(TYPECOMMAND) $(MAKEFILE) > src/Makefile.var
@cd src && $(MAKE) @cd src && $(MAKE)
clean: clean:
@$(REMOVECOMMAND) *$(OBJSUFFICS) $(COMPFILES) @cd src && $(REMOVECOMMAND) *$(OBJSUFFICS) $(COMPFILES) && cd ..
@cd src && $(MAKE) clean @$(AFTERCLEAN)

View File

@ -10,13 +10,13 @@
BUILDDIR = ../bin/ BUILDDIR = ../bin/
CC = clang CC = clang
CFLAGS = -O2 -fno-strict-aliasing -c -pthread -static -DWITH_STD_MALLOC -DNOIPV6 CFLAGS = -O2 -fno-strict-aliasing -c -pthread -DWITH_STD_MALLOC -DWITH_WSAPOLL
COUT = -o COUT = -o
LN = clang LN = $(CC)
LDFLAGS = -O2 -fno-strict-aliasing -static -s LDFLAGS = -O2 -fno-strict-aliasing -s
DLFLAGS = -shared DLFLAGS = -shared
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = -lws2_32 -lodbc32 -ladvapi32 LIBS = -lws2_32 -lodbc32 -ladvapi32 -luser32 -lcrypto -lssl
LIBSPREFIX = -l LIBSPREFIX = -l
LIBSSUFFIX = LIBSSUFFIX =
LNOUT = -o LNOUT = -o
@ -25,12 +25,22 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *.tmp COMPFILES = *.tmp
REMOVECOMMAND = rm -f REMOVECOMMAND = rm -f
AFTERCLEAN = find src/ -type f -name "*.o" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -executable -delete
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.win MAKEFILE = Makefile.llvm
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin SSLPlugin
VERFILE := 3proxy.res $(VERFILE)
VERSION := $(VERSION)
VERSIONDEP := 3proxy.res $(VERSIONDEP)
BUILDDATE := $(BUILDDATE)
AFTERCLEAN = (find . -type f -name "*.o" -delete && find . -type f -name "*.res" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -executable -delete) || true
include Makefile.inc include Makefile.inc
3proxy.res:
llvm-rc 3proxy.rc
allplugins: allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.o &&cd ..\..) @list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done

View File

@ -8,13 +8,13 @@
BUILDDIR = ../bin/ BUILDDIR = ../bin/
CC = cl CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE) CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "WITH_SSL" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE)
COUT = /Fo COUT = /Fo
LN = link LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386 LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL DLFLAGS = /DLL
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32.lib ssleay32.lib LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib Crypt32.lib libcrypto.lib libssl.lib
LIBSOLD = libeay32MT.lib ssleay32MT.lib LIBSOLD = libeay32MT.lib ssleay32MT.lib
LIBSPREFIX = LIBSPREFIX =
LIBSSUFFIX = .lib LIBSSUFFIX = .lib
@ -24,23 +24,21 @@ EXESUFFICS = .exe
OBJSUFFICS = .obj OBJSUFFICS = .obj
DEFINEOPTION = /D DEFINEOPTION = /D
COMPFILES = *.pch *.idb COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL REMOVECOMMAND = del
TYPECOMMAND = type TYPECOMMAND = type
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.msvc MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin SSLPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin SSLPlugin
VERFILE = $(VERFILE) VERFILE = 3proxy.res $(VERFILE)
VERSION = $(VERSION) VERSION = $(VERSION)
VERSIONDEP = 3proxy.res $(VERSIONDEP)
BUILDDATE = $(BUILDDATE) BUILDDATE = $(BUILDDATE)
AFTERCLEAN = if exist src\*.res (del src\*.res) && if exist src\*.err (del src\*.err)
include Makefile.inc include Makefile.inc
../3proxy.res: 3proxy.res:
rc /fo../3proxy.res ../3proxy.rc $(VERSION) $(BUILDDATE) rc 3proxy.rc
3proxyres.obj: ../3proxy.res
cvtres /out:3proxyres.obj /MACHINE:I386 ../3proxy.res
allplugins: allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..) for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)

View File

@ -8,13 +8,13 @@
BUILDDIR = ../bin64/ BUILDDIR = ../bin64/
CC = cl CC = cl
CFLAGS = /nologo /MT /W3 /Ox /EHs- /GS /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE) CFLAGS = /nologo /MT /W3 /Ox /EHs- /GS /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_SSL" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE)
COUT = /Fo COUT = /Fo
LN = link LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:x64 LDFLAGS = /nologo /subsystem:console /incremental:no /machine:x64
DLFLAGS = /DLL DLFLAGS = /DLL
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32.lib ssleay32.lib LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib Crypt32.lib libcrypto.lib libssl.lib
LIBSOLD = libeay32.lib ssleay32.lib LIBSOLD = libeay32.lib ssleay32.lib
LIBSPREFIX = LIBSPREFIX =
LIBSSUFFIX = .lib LIBSSUFFIX = .lib
@ -27,20 +27,15 @@ COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type TYPECOMMAND = type
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.msvc64 VERFILE = 3proxy.res $(VERFILE)
VERSIONDEP = 3proxy.res $(VERSIONDEP)
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin SSLPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin SSLPlugin
VERFILE = $(VERFILE) AFTERCLEAN = del src\*.res
#../3proxy.res:
# rc /fo../3proxy.res ../3proxy.rc
#3proxyres.obj: ../3proxy.res
# cvtres /out:3proxyres.obj /MACHINE:X64 ../3proxy.res
include Makefile.inc include Makefile.inc
../3proxy.res: 3proxy.res:
rc /fo../3proxy.res ../3proxy.rc $(VERSION) $(BUILDDATE) rc 3proxy.rc
3proxyres.obj: ../3proxy.res 3proxyres.obj: ../3proxy.res
cvtres /out:3proxyres.obj /machine:x64 ../3proxy.res cvtres /out:3proxyres.obj /machine:x64 ../3proxy.res

View File

@ -8,13 +8,13 @@
BUILDDIR = ../bin64/ BUILDDIR = ../bin64/
CC = cl CC = cl
CFLAGS = /nologo /MT /W3 /Ox /EHs- /GS /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_WSAPOLL" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE) CFLAGS = /nologo /MT /W3 /Ox /EHs- /GS /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "WITH_WSAPOLL" /D "WITH_SSL" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "PRINTF_INT64_MODIFIER=\"I64\"" /Fp"proxy.pch" /FD /c $(VERSION) $(BUILDDATE)
COUT = /Fo COUT = /Fo
LN = link LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:arm64 LDFLAGS = /nologo /subsystem:console /incremental:no /machine:arm64
DLFLAGS = /DLL DLFLAGS = /DLL
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libcrypto.lib libssl.lib
LIBSOLD = LIBSOLD =
LIBSPREFIX = LIBSPREFIX =
LIBSSUFFIX = .lib LIBSSUFFIX = .lib
@ -28,19 +28,16 @@ REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type TYPECOMMAND = type
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.msvcARM64 MAKEFILE = Makefile.msvcARM64
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin FilePlugin SSLPlugin
VERFILE = $(VERFILE) VERFILE = 3proxy.res $(VERFILE)
VERSIONDEP = 3proxy.res $(VERSIONDEP)
AFTERCLEAN = del src\*.res
#../3proxy.res:
# rc /fo../3proxy.res ../3proxy.rc
#3proxyres.obj: ../3proxy.res
# cvtres /out:3proxyres.obj /MACHINE:X64 ../3proxy.res
include Makefile.inc include Makefile.inc
../3proxy.res: 3proxy.res:
rc /fo../3proxy.res ../3proxy.rc $(VERSION) $(BUILDDATE) rc 3proxy.rc
3proxyres.obj: ../3proxy.res 3proxyres.obj: ../3proxy.res
cvtres /out:3proxyres.obj /machine:x64 ../3proxy.res cvtres /out:3proxyres.obj /machine:x64 ../3proxy.res

View File

@ -12,7 +12,7 @@ CC = mips-openwrt-linux-gcc
CFLAGS = -g -O2 -fno-strict-aliasing -c -pthread -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER CFLAGS = -g -O2 -fno-strict-aliasing -c -pthread -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER
COUT = -o COUT = -o
LN = mips-openwrt-linux-gcc LN = $(CC)
DCFLAGS = -fPIC DCFLAGS = -fPIC
LDFLAGS = -O2 -fno-strict-aliasing -pthread -s LDFLAGS = -O2 -fno-strict-aliasing -pthread -s
DLFLAGS = -shared DLFLAGS = -shared
@ -26,6 +26,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f 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 TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.openwrt-mips MAKEFILE = Makefile.openwrt-mips

View File

@ -13,7 +13,7 @@ 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 -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL CFLAGS = -g -O2 -fno-strict-aliasing -c -pthread -D_THREAD_SAFE -D_REENTRANT -DNOODBC -DWITH_STD_MALLOC -DFD_SETSIZE=4096 -DWITH_POLL
COUT = -o COUT = -o
LN = gcc LN = $(CC)
LDFLAGS = -O2 -fno-strict-aliasing -pthread LDFLAGS = -O2 -fno-strict-aliasing -pthread
# -lpthreads may be reuqired on some platforms instead of -pthreads # -lpthreads may be reuqired on some platforms instead of -pthreads
# -ldl or -lld may be required for some platforms # -ldl or -lld may be required for some platforms
@ -29,6 +29,7 @@ OBJSUFFICS = .o
DEFINEOPTION = -D DEFINEOPTION = -D
COMPFILES = *~ COMPFILES = *~
REMOVECOMMAND = rm -f 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 TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.unix MAKEFILE = Makefile.unix

View File

@ -30,14 +30,43 @@ COMPATLIBS =
MAKEFILE = Makefile.watcom MAKEFILE = Makefile.watcom
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin
VERFILE = $(VERFILE) VERFILE = $(VERFILE)
VERSION = $(VERSION)
VERSIONDEP = 3proxy.res $(VERSIONDEP)
BUILDDATE = $(BUILDDATE)
include Makefile.inc include Makefile.inc
../3proxy.res: 3proxy.res:
rc /fo../3proxy.res ../3proxy.rc $(VERSION) $(BUILDDATE) rc 3proxy.rc
3proxyres.obj: ../3proxy.res
cvtres /out:3proxyres.obj ../3proxy.res
allplugins: allplugins:
call ../makeplugins.bat copy Makefile plugins\utf8tocp1251
copy Makefile.var plugins\utf8tocp1251
cd plugins\utf8tocp1251
nmake
del *.obj *.idb
cd ../../
copy Makefile plugins\WindowsAuthentication
copy Makefile.var plugins\WindowsAuthentication
cd plugins\WindowsAuthentication
nmake
del *.obj *.idb
cd ../../
copy Makefile plugins\TrafficPlugin
copy Makefile.var plugins\TrafficPlugin
cd plugins\TrafficPlugin
nmake
del *.obj *.idb
cd ../../
copy Makefile plugins\StringsPlugin
copy Makefile.var plugins\StringsPlugin
cd plugins\StringsPlugin
nmake
del *.obj *.idb
cd ../../
copy Makefile plugins\PCREPlugin
copy Makefile.var plugins\PCREPlugin
cd plugins\PCREPlugin
nmake
del *.obj *.idb
cd ../../

View File

@ -10,13 +10,13 @@
BUILDDIR = ../bin/ BUILDDIR = ../bin/
CC = gcc CC = gcc
CFLAGS = -O2 -s -c -mthreads -DWITH_STD_MALLOC -DNOIPV6 -DNORADIUS CFLAGS = -O2 -s -c -mthreads -DWITH_STD_MALLOC -DWITH_WSAPOLL
COUT = -o COUT = -o
LN = gcc LN = gcc
LDFLAGS = -O2 -s -mthreads LDFLAGS = -O2 -s -mthreads
DLFLAGS = -shared DLFLAGS = -shared
DLSUFFICS = .dll DLSUFFICS = .dll
LIBS = -lws2_32 -lodbc32 -ladvapi32 LIBS = -lws2_32 -lodbc32 -ladvapi32 -luser32 -lcrypto -lssl
LIBSPREFIX = -l LIBSPREFIX = -l
LIBSSUFFIX = LIBSSUFFIX =
LNOUT = -o LNOUT = -o
@ -28,9 +28,18 @@ REMOVECOMMAND = rm -f
TYPECOMMAND = cat TYPECOMMAND = cat
COMPATLIBS = COMPATLIBS =
MAKEFILE = Makefile.win MAKEFILE = Makefile.win
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin SSLPLugin
VERFILE := 3proxyres.o $(VERFILE)
VERSION := $(VERSION)
VERSIONDEP := 3proxyres.o $(VERSIONDEP)
BUILDDATE := $(BUILDDATE)
AFTERCLEAN = (find . -type f -name "*.o" -delete && find . -type f -name "*.res" -delete && find src/ -type f -name "Makefile.var" -delete && find bin/ -type f -executable -delete) || true
include Makefile.inc include Makefile.inc
3proxyres.o:
windres 3proxy.rc -o 3proxyres.o
allplugins: allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; rm *.o ; cd ../.. ; done @list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; cd ../.. ; done

66
README
View File

@ -1,12 +1,25 @@
# 3APA3A 3proxy tiny proxy server # 3APA3A 3proxy tiny proxy server
(c) 2002-2019 by Vladimir '3APA3A' Dubrovin <3proxy@3proxy.ru> (c) 2002-2025 by Vladimir '3APA3A' Dubrovin <3proxy@3proxy.org>
Download:
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 https://github.com/z3APA3A/3proxy/releases
or
https://3proxy.org/download/ Docker images:
https://hub.docker.com/repository/docker/3proxy/3proxy
Archive of old versions: https://github.com/z3APA3A/3proxy-archive 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 --install 3proxy --install
@ -18,7 +31,9 @@ Archive of old versions: https://github.com/z3APA3A/3proxy-archive
removes the service (should be stopped before via removes the service (should be stopped before via
'net stop 3proxy'). 'net stop 3proxy').
To build in Linux install git and build-essential packages, use * To build in Linux
install git and build-essential packages, use
git clone https://github.com/z3apa3a/3proxy git clone https://github.com/z3apa3a/3proxy
cd 3proxy cd 3proxy
@ -26,10 +41,31 @@ ln -s Makefile.Linux Makefile
make make
sudo make install sudo make install
use /etc/3proxy/add3proxyuser.sh script to add users. 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.
Please read doc/html/index.html and man pages. 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.
* For MacOS X / FreeBSD / *BSD
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
ln -s Makefile.FreeBSD Makefile
make
(binaries are in bin/ directory)
Features: Features:
1. General 1. General
@ -50,6 +86,8 @@ Please read doc/html/index.html and man pages.
+ SOCKSv5 UDP and BIND support (fully compatible with + SOCKSv5 UDP and BIND support (fully compatible with
SocksCAP/FreeCAP for UDP) SocksCAP/FreeCAP for UDP)
+ Transparent SOCKS redirection for HTTP, POP3, FTP, SMTP + 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 + POP3 Proxy
+ FTP proxy + FTP proxy
+ TCP port mapper (port forwarding) + TCP port mapper (port forwarding)
@ -58,7 +96,7 @@ Please read doc/html/index.html and man pages.
+ Threaded application (no child process). + Threaded application (no child process).
+ Web administration and statistics + Web administration and statistics
+ Plugins for functionality extension + Plugins for functionality extension
+ Native 64 bit application + Native 32/64 bit application
2. Proxy chaining and network connections 2. Proxy chaining and network connections
+ Can be used as a bridge between client and different proxy type + Can be used as a bridge between client and different proxy type
(e.g. convert incoming HTTP proxy request from client to SOCKSv5 (e.g. convert incoming HTTP proxy request from client to SOCKSv5
@ -78,9 +116,8 @@ Please read doc/html/index.html and man pages.
+ syslog logging (Unix) + syslog logging (Unix)
+ ODBC logging + ODBC logging
+ RADIUS accounting + RADIUS accounting
+ log file rotation (hourly, daily, weekly, monthly) + log file rotation
+ automatic log file comperssion with external archiver (for files) + automatic log file processing with external archiver (for files)
+ automatic removal of older log files
+ Character filtering for log files + Character filtering for log files
+ different log files for different servces are supported + different log files for different servces are supported
4. Access control 4. Access control
@ -89,12 +126,13 @@ Please read doc/html/index.html and man pages.
(POST, PUT, GET, etc), weekday and daytime. (POST, PUT, GET, etc), weekday and daytime.
+ ACL-driven (user/source/destination/protocol/weekday/daytime or + ACL-driven (user/source/destination/protocol/weekday/daytime or
combined) bandwith limitation for incoming and (!)outgoing trafic. combined) bandwith limitation for incoming and (!)outgoing trafic.
+ ACL-driven (user/source/destination/protocol/weekday/daytime or + ACL-driven traffic limitation per day, week or month for incoming and
combined) traffic limitation per day, week or month for incoming and
outgoing traffic outgoing traffic
+ Connection limitation and ratelimting
+ User authentication by username / password + User authentication by username / password
+ RADIUS Authentication and Authorization + RADIUS Authentication and Authorization
+ User authentication by DNS hostname + 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 + Access control by username/password for SOCKSv5 and HTTP/HTTPS/FTP
+ Cleartext or encrypted (crypt/MD5 or NT) passwords. + Cleartext or encrypted (crypt/MD5 or NT) passwords.
+ Connection redirection + Connection redirection
@ -170,6 +208,7 @@ smtpp SMTP proxy server, binds to port 25. You must specify
via mail.somehost.ru via proxy. via mail.somehost.ru via proxy.
tcppm TCP port mapping. Maps some TCP port on local machine to tcppm TCP port mapping. Maps some TCP port on local machine to
TCP port on remote host. 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 udppm UDP port mapping. Maps some UDP port on local machine to
UDP port on remote machine. Only one user simulationeously UDP port on remote machine. Only one user simulationeously
can use UDP mapping, so it cann't be used for public service can use UDP mapping, so it cann't be used for public service
@ -183,7 +222,6 @@ mycrypt Program to obtain crypted password fro cleartext. Supports
produces NT password produces NT password
mycrypt salt password mycrypt salt password
produces MD5/crypt password with salt "salt". produces MD5/crypt password with salt "salt".
dighosts Utility for building networks list from web page.
Run utility with --help option for command line reference. Run utility with --help option for command line reference.

1
RELEASE Normal file
View File

@ -0,0 +1 @@
0.9.5

View File

@ -1 +1 @@
(c) 2002-2019 by Vladimir '3APA3A' Dubrovin <vlad@3proxy.ru> (c) 2002-2025 by Vladimir '3APA3A' Dubrovin <vlad@3proxy.org>

16
copying
View File

@ -1,12 +1,8 @@
3proxy 0.9 Public License Agreement 3proxy 0.9 Public License Agreement
(c) 2000-2019 by 3APA3A (3APA3A@3proxy.ru) (c) 2000-2025 by 3APA3A (3APA3A@3proxy.ru)
(c) 2000-2019 by 3proxy.org (http://3proxy.org/) (c) 2000-2025 by 3proxy.org (https://3proxy.org/)
(c) 2000-2019 by Vladimir Dubrovin (vlad@3proxy.ru) (c) 2000-2025 by Vladimir Dubrovin (vlad@3proxy.org)
This software uses:
RSA Data Security, Inc. MD4 Message-Digest Algorithm
RSA Data Security, Inc. MD5 Message-Digest Algorithm
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@ -42,20 +38,20 @@ terms of compatible license, including:
1. Apache License, Version 2.0 or (at your option) any later version 1. Apache License, Version 2.0 or (at your option) any later version
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 https://www.apache.org/licenses/LICENSE-2.0
2. GNU General Public License as published by 2. GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.gnu.org/licenses/gpl.txt https://www.gnu.org/licenses/gpl.txt
3. GNU Lesser General Public License as published by the 3. GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. (at your option) any later version.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.gnu.org/licenses/lgpl.txt https://www.gnu.org/licenses/lgpl.txt

10
debian/3proxy.manpages vendored Normal file
View File

@ -0,0 +1,10 @@
man/3proxy.8
man/3proxy.cfg.3
man/ftppr.8
man/tlspr.8
man/pop3p.8
man/proxy.8
man/smtpp.8
man/socks.8
man/tcppm.8
man/udppm.8

18
debian/changelog vendored Normal file
View File

@ -0,0 +1,18 @@
3proxy (0.9.3-210629140419) buster; urgency=medium
*3proxy 0.9.3 build
-- z3APA3A <3apa3a@3proxy.org> Thu, 01 Jul 2021 19:48:44 +0300
3proxy (0.9.3-1) buster; urgency=medium
*3proxy 0.9.3 initial build
-- z3APA3A <3apa3a@3proxy.org> Thu, 03 Dec 2020 21:13:58 +0300
3proxy (0.9.2-1) buster; urgency=medium
*3proxy 0.9.2 initial build
-- z3APA3A <3apa3a@3proxy.org> Thu, 19 Nov 2020 19:19:19 +0300

1
debian/compat vendored Normal file
View File

@ -0,0 +1 @@
9

4
debian/conffiles vendored Normal file
View File

@ -0,0 +1,4 @@
/usr/local/3proxy/conf/3proxy.cfg
/usr/local/3proxy/conf/add3proxyuser.sh
/usr/local/3proxy/conf/bandlimiters
/usr/local/3proxy/conf/counters

18
debian/control vendored Normal file
View File

@ -0,0 +1,18 @@
Source: 3proxy
Maintainer: z3APA3A <3apa3a@3proxy.org>
Section: net
Priority: optional
Standards-Version: 4.0.0
Build-Depends: debhelper (>=10)
Homepage: https://3proxy.org/
Vcs-Git: https://github.com/z3APA3A/3proxy
Vcs-Browser: https://github.com/z3APA3A/3proxy
Package: 3proxy
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: tiny free proxy server
3Proxy tiny free proxy server is really tiny freeware proxy servers set.
It includes HTTP proxy with HTTPS and FTP support, SOCKSv4/SOCKSv4.5/SOCKSv5 proxy (socks/socks.exe), POP3 proxy, SMTP proxy, FTP proxy, caching DNS proxy, TCP and UDP portmappers.
You can use every proxy as a standalone program (socks, proxy, tcppm, udppm, pop3p) or use combined program (3proxy). Combined proxy additionally supports features like access control, bandwidth limiting, limiting daily/weekly/monthly traffic amount, proxy chaining, log rotation, syslog and ODBC logging, etc.
It's created to be small, simple and yet very functional.

20
debian/copyright vendored Normal file
View File

@ -0,0 +1,20 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: 3proxy
Upstream-Contact: 3proxy@3proxy.org
Source: https://3proxy.org/
Files: *
Copyright: 2000-2020 3APA3A, Vladimir Dubrovin, 3proxy.org
License: BSD-3-clause or Apache or GPL-2+ or LGPL-2+
Files: src/libs/md*.*
Copyright: 1990,1991,1992 RSA Data Security, Inc
License: public-domain
Files: src/libs/regex.*
Copyright: Henry Spencer
License: public-domain
Files: src/libs/smbdes.c
Copyright: Andrew Tridgell 1998
License: GPL-2+

43
debian/postinst vendored Normal file
View File

@ -0,0 +1,43 @@
if [ ! -f /usr/local/3proxy/conf/passwd ]; then \
touch /usr/local/3proxy/conf/passwd;\
fi
chown -R proxy:proxy /usr/local/3proxy
chmod 550 /usr/local/3proxy/
chmod 550 /usr/local/3proxy/conf/
chmod 440 /usr/local/3proxy/conf/*
if /bin/systemctl >/dev/null 2>&1; then \
/usr/sbin/update-rc.d 3proxy disable || true; \
/usr/sbin/chkconfig 3proxy off || true; \
/bin/systemctl enable 3proxy.service; \
elif [ -x /usr/sbin/update-rc.d ]; then \
/usr/sbin/update-rc.d 3proxy defaults; \
/usr/sbin/update-rc.d 3proxy enable; \
elif [ -x /usr/sbin/chkconfig ]; then \
/usr/sbin/chkconfig 3proxy on; \
fi
echo ""
echo 3proxy installed.
if /bin/systemctl >/dev/null 2>&1; then \
/bin/systemctl stop 3proxy.service \
/bin/systemctl start 3proxy.service \
echo use ;\
echo " "systemctl start 3proxy.service ;\
echo to start proxy ;\
echo " "systemctl stop 3proxy.service ;\
echo to stop proxy ;\
elif [ -x /usr/sbin/service ]; then \
/usr/sbin/service 3proxy stop || true;\
/usr/sbin/service 3proxy start || true;\
echo " "service 3proxy start ;\
echo to start proxy ;\
echo " "service 3proxy stop ;\
echo to stop proxy ;\
fi
echo " "/usr/local/3proxy/conf/add3proxyuser.sh
echo to add users
echo ""
echo Default config uses Google\'s DNS.
echo It\'s recommended to use provider supplied DNS or install local recursor, e.g. pdns-recursor.
echo Configure preferred DNS in /usr/local/3proxy/conf/3proxy.cfg.
echo run \'/usr/local/3proxy/conf/add3proxyuser.sh admin password\' to configure \'admin\' user

4
debian/preinst vendored Normal file
View File

@ -0,0 +1,4 @@
if [ -x /usr/sbin/useradd ]; then \
/usr/bin/getent group proxy >/dev/null || (/usr/sbin/groupadd -f -r proxy || true); \
/usr/bin/getent passwd proxy >/dev/null || (/usr/sbin/useradd -Mr -s /bin/false -g proxy -c 3proxy proxy || true); \
fi

16
debian/rules vendored Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/make -f
%:
dh $@
override_dh_auto_build:
ln -s Makefile.Linux Makefile || true
dh_auto_build
override_dh_auto_clean:
find src/ -type f -name "*.o" -delete
find src/ -type f -name "Makefile.var" -delete
find bin/ -type f -executable -delete
rm -f Makefile
override_dh_usrlocal:

1
debian/source/format vendored Normal file
View File

@ -0,0 +1 @@
3.0 (quilt)

View File

@ -1,165 +1,2 @@
<h3>Why ... doesn't work?</h3>
<p><i>Q: Why does nothing work?</i></p> <H2><A href="hotoe.html">See HowTo:</a></H2>
A: Valid configuration file is required.
<p><i>Q: Why restrictions (redirections, limits, etc) do not work?</i></p>
A: Most probable reasons: 'auth none' or no auth is used. For any ACL based feature one of 'iponly', 'nbname' or 'strong' auths required. Sequence of commands may be invalid. Commands are executed one-by-one and 'proxy', 'tcppm', 'socks' or another service commands must follow valid configuration. Invalid sequence of ACLs. First matching ACL is used (except of internal redirections, see below). If ACL contains at least one records last record is assumed to be 'deny *'.
<p><i>Q: Why doesn't 3proxy work as service under Windows?</i></p>
Possible reasons:
<ul>
<li>there are relative paths in configuration file for included files,
log files, etc. Always use absolute paths. For example
$"c:\3proxy\networks.local" instead of $networks.local. For debugging remove
'service' and 'daemon', log to stdout an try to execute 3proxy from command
line from some different directory (for example from disk root).
<li>SYSTEM account doesn't have access to executable file, configuration files,
log files, etc.
<li>configuration files is not located in default path (3proxy.cfg in same
location with 3proxy.exe). For alternative configuration file location use
<pre>
3proxy --install full_path_to_configuration_file
</pre>
<li>user has no rights to install or start service
<li>service is already installed and/or started
</ul>
<p><A NAME="INTEXT"><i>Q: Why doesn't internal and external commands work as expected</i></A></li></p>
A: Check your expectations first.
Both internal and external IPs are IPs of the host running 3proxy itself.
This configuration option is usefull in situation 3proxy is running on the
border host with 2 (or more) connections: e.g. LAN and WAN with different IPs
<pre>
LAN connection +-------------+ Internet connection
LAN <-------------->| 3proxy host |<-------------------> INTERNET
^+-------------+^
| |
Internal IP External IP
</pre>
If 3proxy is used on the host with single connection, both internal and
external are usually same IP.
<br>Internal should exist and be UP on the moment 3proxy is started and
should never be disconnected/DOWN. If this interface is periodically
disconnected (e.g. direct link between 2 hosts), do not specify internal
address or use 0.0.0.0 instead. In this case, if you have 2 or more
interfaces you must use firewall (preferably) or 3proxy ACLs to avoid open
proxy situation.
<br>
External IP (if specified) must exist in the momet 3proxy
serves client request. If external interface is no specified (or 0.0.0.0),
system select external IP. It may be possible to access resources of internal
network, to prevent this use ACLs. In addition, SOCKSv5 will not support BIND
operation, required for incoming connections (this operation is quite rarely
implemented in SOCKSv5 clients and usually is not required). In case of
dynamic address, do not specify external or use external 0.0.0.0 or, if
external address is required, create a script to determine current external
IP and save it to file, and use external "$path_to_file" with "monitor" command
to automatically reload configuration on address change.
<p><i>Q: Why doesn't ODBC loggind work?</i></p>
A: Check you use system DSN.
Check SQL request is valid.
The best way to check is to make file or stdout logging, get SQL request from log file or console and execute this request manually.
Under Unix, you may also want to adjust 'stacksize' parameter.
<p><i>Q: Why doesn't IPv6 work?</i></p>
A: Proxy can not access destination directly over IPv6 if client requests IPv4 address.
To access IPv6 destination, either IPv6 address or hostname must be used in request.
Best solution is to enable option to resolve hostnames via proxy on client side.
<p><i>Q: Why proxy crash on request processing?</a></i></p>
<i>A:</i> default stacksize may be insufficient, if some non-default plugins
are used (e.g. PAM and ODBC on Linux) or if compiled on some platforms with
invalid system defined values (few versionds of FreeBSD on amd64).
Problem can be resolved with 'stacksize' command or '-S' option starting 3proxy 0.8.4.
<p><i>Q: Why doesn't APOP/CRAM-MD5 authentication work with POP3 proxy?</i></p>
A: Any Challenge-response authentication require challenge to be transmitted from server. Pop3p doesn't know which server to use before authentication, it makes it impossible to obtain challenge. You can encrypt your POP3 communications with TLS (i.e. stunnel) or IPSec.
<h3>Redirection to local proxy</h3>
<p><i>Q: What is it for?</i></p>
A: To have control based on request and to have URLs and another protocol specific parameters to be logged.
<p><i>Q: What are restrictions?</i></p>
A: It's hard to redirect services for non-default ports; Internet Explorer supports only SOCKSv4 with no password authentication (Internet Explorer sends username, but not password), for SOCKSv5 only cleartext password authentication is supported.
<p><i>Q: What are advantages?</i></p>
A: You need only to setup SOCKS proxy in browser settings. You can use socksifier, i.e. FreeCAP or SocksCAP with application which is not proxy aware.
<p><i>Q: How to setup?</i></p>
A: You should specify parent proxy with IP of 0.0.0.0 and port 0. Examples:
<pre>
auth iponly
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
allow * * * 80,8080-8088
#redirect ports 80 and 8080-8088 to local HTTP proxy
#Second allow is required, because ACLs are checked
#twice: first time by socks and second by http proxy.
allow * * * 21,2121
parent 1000 ftp 0.0.0.0 0
allow * * * 21,2121
#redirect ports 21 and 2121 to local
#ftp proxy
allow *
#allow rest of connections directly
socks
#now let socks server to start
</pre>
<p><i>Q: How it affects different ACL rules?</i></p>
A: After local redirections rules are applied again to protocol-level request. Redirection rule itself is skipped. It makes it possible to redirect request again on the external proxy depending on request itself.
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
#redirect http traffic to internal proxy
allow * * $c:\3proxy\local.nets 80,8080-8088
#allow direct access to local.nets networks
allow * * * 80,8080-8088
parent 1000 http proxy.3proxy.org 3128
#use parent caching proxy for rest of the networks
allow *
#allow direct connections for rest of socks
#requests
</pre>
<h3>Can I ...?</h3>
<p><i>Q: Is it possible to resolve names through parent proxy?</i></p>
A: Yes, use 'proxy', 'connect+', 'socks4+' or 'socks5+' as parent proxy type.
3proxy itself requires name resolutions for ACL checks, so, if it's impossible
to resolve names from 3proxy host, use
<pre>
fakeresolve
</pre>
command. Fakeresolve resolves any name to 127.0.0.2.
<p><i>Q: Can I use 3proxy as FTP proxy?</i></p>
A: There are two kinds of FTP proxy supported: FTP over HTTP support (known as FTP proxy inside Internet Explorer, Mozilla and another browsers) and real FTP proxy (usable in Far and different FTP clients). Both are supported in 3proxy: first one as a part of HTTP 'proxy' and second one as 'ftppr'.
<p><i>Q: Can I bind any 3proxy service to non-default port?</i></p>
A: proxy -p8080
<h3>Why so ...?</h3>
<p><i>Q: Why traffic accounting is incomplete? It differs for what my provider (or another accounting application) shows to me?</i></p>
A: 3proxy accounts protocol level traffic. Provider counts channel or IP-level traffic with network and transport headers. In additions, 3proxy doesn't counts DNS resolutions, pings, floods, scans, etc. It makes approx. 10% of difference. That's why you should have 15% reserve if you use 3proxy to limit your traffic. If difference with your provider is significantly above 10% you should look for traffic avoiding proxy server, for example connections through NAT, traffic originated from the host with proxy installed, traffic from server applications, etc.
<p><i>Q: Why configuration is so difficult and non-intuitive?</i></p>
A: Configuration format is created in a way it's easy to parse and matches to internal 3proxy structures. In addition, there are some older things left for compatibility to be cleaned in 3proxy release. And last, I think it's easy and intuitive.
<p><i>Q: Why the code is so difficult and non-intuitive?</i></p>
A: First, I'm not programmer. Second, 3proxy was 'proof of concept' in reply for some conference post. Request was to write proxy server in 100 lines of code. First version of 3proxy had less, with HTTP and SOCKS support and portmappers. Third, there are peoples who want to use 3proxy code in trojans. I don't want to help them. Fourth, the aim is to support different platforms. It's well known - the worse code is, the better it compiles.
<p><i>Q: Why do you use insecure strcpy, sprintf, etc?</i></p>
A: Why not? I try to use insecure function in secure manner. You're welcome to look for vulnerabilities.

View File

@ -1,295 +1,2 @@
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
3APA3A 3proxy tiny proxy server Frequently Asked Questions (FAQ) <H2><A href="hotoe.html">См. HowTo</a></H2>
<ul>
<li><a href="#TROUBLE">Почему не работает...</a></li>
<ul>
<li><a href="#NOTHING">Q: Почему ничего не работает?</a></li>
<li><a href="#LIMITS">Q: Почему не работают ограничения доступа (перенаправления, ограничения по скорости, трафику и т.д.)?</a></li>
<li><a href="#SERVICE">Q: Почему 3proxy не запускается как служба?</a></li>
<li><a href="#INTEXT">Q: Почему не получается указать internal и external?</a></li>
<li><a href="#ODBC">Q: Почему не работает ведение журналов в ODBC?</a></li>
<li><a href="#IPV6">Q: Почему не работает IPv6?</a></li>
<li><a href="#CHAP">Q: Почему не поддерживаются APOP и CRAM-MD5 в POP3 прокси?</a></li>
<li><a href="#CRASH">Q: Почему прокси крэшится при обработке запроса?</a></li>
</ul>
<li><a href="#SOCKSREDIR">Перенаправление socks соединений в локальный прокси</a></li>
<ul>
<li><a href="#REDIR">Q: Для чего это надо?</a></li>
<li><a href="#REDIRLIMIT">Q: Какие недостатки?</a></li>
<li><a href="#REDIRADV">Q: Какие преимущества?</a></li>
<li><a href="#REDIRHOW">Q: Как настраивается?</a></li>
<li><a href="#REDIINTER">Q: Как взаимодействует с другими правилами в ACL?</a></li>
</ul>
<li><a href="#ISIT">А есть ли...</a></li>
<ul>
<li><a href="#NAMES">Можно ли разрешать имена на родительском прокси?</a></li>
<li><a href="#ISFTP">Существует ли сейчас поддержка FTP прокси в продукте?</a></li>
<li><a href="#PORT">Каким образом можно прибиндить сервисы на свой порт, к примеру, HTTP прокси к 8080, а не 3128 как по-умолчанию?</a></li>
<li><a href="#BANDLIM">Как ограничить ширину канала?</a></li>
</ul>
<li><a href="#BRRR">Почему так криво...</a></li>
<ul>
<li><a href="#TRAF">Почему так криво считается трафик? Не совпадает с ...</a></li>
<li><a href="#CONFIG">Почему такая кривая конфигурация и ничерта не понятно?</a></li>
<li><a href="#CODE">Почему так криво написан код?</a>
<li><a href="#UNSAFE">Почему так много strcpy, sprintf и т.д., это ж дыры!</a>
</ul>
</ul>
<hr>
<li><b><a name="TROUBLE">Почему не работает...<a></b></li>
<ul>
<li><a name="NOTHING"><i>Q: Почему ничего не работает?</i></a></li>
<p>
<i>A:</i> Потому что для работы нужен правильный файл конфигурации.
</p>
<li><a name="LIMITS"><i>Q: Почему не работают ограничения доступа (перенаправления, ограничения по скорости,
трафику и т.д.)?</i></a></li>
<p>
<i>A:</i> Обычные ошибки - использование auth none (для работы любых
функций, основанных на ACL, требуется auth iponly, nbname или strong),
нарушение порядка ввода команд (команды выполняются последовательно,
запуск сервиса proxy, socks, tcppm и т.д. должен осуществляться после
того, как указана его конфигурация), неправильный порядок записей в ACL
(записи просматриваются последовательно до первой, удовлетворяющей
критериям). Если в ACL имеется хотя бы одна запись, то считается, что
последняя запись в ACL - это неявная deny *.
</p>
<li><a name="SERVICE"><i>Q: Почему 3proxy не запускается как служба?</i></a></li>
<p>
<i>A:</i> Наиболее вероятные причины:
<ul>
<li>Использование относительных (неполных) путей файлов в файле конфигурации
При использовании файлов журналов, файлов вставок ($filename) используйте
полные пути, например, $"c:\3proxy\include files\networks.local". Тоже самое
относится к файлам журналов и любым другим.
Для отладки лучше запускать 3proxy с ведением журнала на стандартный вывод.
Не забудьте в таком случае отключить daemon и service в файле конфигурации.
Для чистоты эксперимента запускать 3proxy из коммандной строки в таком случае
следует, находясь в другой папке.
<li>Отсутствие у системной записи прав на доступ к исполняемому файлу, каким-либо файлам конфигурации, журнала и т.п.
<li>Отсутствие файла конфигурации по стандартному расположению -
3proxy.cfg в одном каталоге с исполняемым файлом. Если файл расположен по
другому пути, необходимо использовать команду
<pre>
3proxy --install path_to_configuration_file</pre>
<li>Отсутствие у пользователя прав на установку или запуск службы
<li>Служба уже установлена или запущена
</ul>
</p>
<li><a name="INTEXT"><i>Q: Почему не получается указать internal и external?</i></a></li></li>
<p>
<i>A:</i> Убедитесь, что выправильно понимаете что такое internal и external адреса.
Оба адреса - это адреса, принадлежищие хосту, на котором установлен 3proxy.
Эта опция конфигурации необходима в классической ситуации, когда 3proxy
установлен на граничном компьютере с двумя (или более) подключениями:
<pre>
LAN connection +-------------+ Internet connection
LAN <-------------->| 3proxy host |<-------------------> INTERNET
^+-------------+^
| |
Internal IP External IP</pre>
Если 3proxy работает на хосте с одним интерфейсом, то его адрес будет и
internal и external.
<br>Интерфейс с адресом internal должен существовать и быть рабочим на момент
запуска 3proxy, и не должен отключаться. Если internal интерфейс
периодически отключается, то не следует его указывать, или можно указать адрес
0.0.0.0. При этом прокси будет принимать запросы на всех интерфейсах, поэтому
при наличии нескольких интерфейсов для ограничения доступа следует использовать
фаервол или хотя бы ACL.
</p>
<p>
Интерфейс с адресом external, если он указан, должен быть рабочим на момент
получения запроса клиента. При отсутствии external или адресе 0.0.0.0 внешний
адрес будет выбираться системой при установке соединения. При этом, может быть
возможность доступа через прокси к ресурсам локальной сети, поэтому для
предотвращения несанкционированного доступа следует использовать ACL. Кроме
того, могут быть проблемы с приемом входящих соединений через SOCKSv5
(SOCKSv5 используется в клиентах исключительно редко).
В случае, если адрес динамический, можно либо не
указывать external, либо использовать адрес 0.0.0.0, либо, если необходима
поддержка входящих соединений в SOCKSv5, использовать скрипт,
который будет получать текущий адрес и сохранять его в файл, который будет
отслуживаться через команду monitor.
</p>
<li><a name="ODBC"><i>Q: Почему не работает ведение журналов в ODBC?</i></a></li>
<p>
<i>A:</i> Убедитесь, что используется системный, а не
пользовательский DSN. Убедитесь, что выполняется правильный SQL запрос. Наиболее
распространенная проблема связана с отсутствием кавычек или неправильным
форматом данных. Самый простой способ - сделать ведение журнала в файл или
на стандартный вывод, просмотреть выдаваемые SQL запросы и попробовать
дать такой запрос вручную.
</p>
<li><a name="IPv6"><i>Q: Почему не работает IPv6?</i></a></li>
<p>
<i>A:</i> Прокси не может обращаться напрямую к IPv6 сети если в запросе от клиента
указан IPv4. В запросе от клиента должен быть IPv6 адрес или имя хоста, чаще
всего это решается включением опции разрешения имен через прокси-сервер на стороне
клиента.
</p>
<li><a name="CHAP"><i>Q: Почему не поддерживаются APOP и CRAM-MD5 в POP3 прокси?</i></a></li>
<p>
<i>A:</i> Любая challenge-response аутентификация, к которым относятся APOP
и CRAM-MD5, требует, чтобы со стороны сервера был передан уникальный challenge.
До начала аутентификации POP3 прокси не знает, к какому серверу следует
подключаться для получения Challenge, поэтому challenge-response в принципе
невозможен. Защитить соединение можно с помощью TLS (например, stunnel) или
IPSec.
</p>
<li><a name="CRASH"><i>Q: Почему прокси крэшится при обработке запроса?</a></i></li>
<p>
<i>A:</i> Возможно, недостаточен размер стека потока по-умолчанию, это может
быть при использовани каких-либо сторонних плагинов (PAM, ODBC) или на
некоторых платформах (некоторые версии FreeBSD на amd64). Можно решить
проблему с помощью опции 'stacksize' или '-S', поддерживаемых в 0.8.4 и выше.
</p>
</ul>
<hr>
<li><b><a name="SOCKSREDIR">Перенаправление socks соединений в локальный прокси</a></b></li>
<ul>
<li><a name="REDIR"><i>Q: Для чего это надо?</i></a></li>
<p>
<i>A:</i> Чтобы иметь в логах URL запросов, если пользователь SOCKS пользуется
Web, FTP или POP3.
</p>
<li><a name="REDIRLIMIT"><i>Q: Какие недостатки?</i></a></li>
<p>
<i>A:</i> Перенапраление невозможно для web-серверов или FTP, висящих на
нестандартных портах, для SOCKSv4 не поддрживается авторизация с
паролем (IE поддерживает только SOCKSv4), но при этом IE передает
имя пользователя по SOCKSv4 (имя, с которым пользователь вошел в систему).
Для SOCKSv5 не поддерживается NTLM авторизация, пароли передаются в открытом
тексте.
</p>
<li><a name="REDIRADV"><i>Q: Какие преимущества?</i></a></li>
<p>
<i>A:</i> Достаточно в настройках IE только указать адрес SOCKS прокси. В
больших сетях можно для этого использовать WPAD (автоматическое
обнаружение прокси). В 3proxy достаточно запускать только одну службу
(socks). Если используется только Internet Explorer, то можно
автоматически получать имя пользователя в логах, не запрашивая
логин/пароль.
</p>
<li><a name="REDIRHOW"><i>Q: Как настраивается?</i></a></li>
<p>
<i>A:</i> Указывается parent http proxy со специальным адресом 0.0.0.0 и портом
0. Пример:
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
allow * * * 80,8080-8088
#перенаправить соединения по портам 80 и 8080-8088 в локальный
#http прокси. Вторая команда allow необходима, т.к. контроль доступа
#осуществляется 2 раза - на уровне socks и на уровне HTTP прокси
allow * * * 21,2121
parent 1000 ftp 0.0.0.0 0
allow * * * 21,2121
#перенаправить соединения по портам 21 и 2121 в локальный
#ftp прокси
allow *
#пустить все соединения напрямую
socks</pre>
</p>
<li><a name="REDIINTER"><i>Q: Как взаимодействует с другими правилами в ACL?</i></a></li>
<p>
<i>A:</i> После внутреннего перенаправления правила рассматриваются еще раз за
исключением самого правила с перенаправлением (т.е. обработка правил не
прекращается). Это позволяет сделать дальнейшие перенаправления на
внешний прокси. По этой же причине локальное перенаправление не должно
быть последним правилом (т.е. должно быть еще хотя бы правило allow,
чтобы разрешить внешние соединения через HTTP прокси).
Например,
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
#перенаправить во внутренний прокси
allow * * $c:\3proxy\local.nets 80,8080-8088
#разрешить прямой web-доступ к сетям из local.nets
allow * * * 80,8080-8088
parent 1000 http proxy.3proxy.ru 3128
#все остальные веб-запросы перенаправить на внешний прокси-сервер
allow *
#разрешить socks-запросы по другим портам</pre>
</p>
</ul>
<hr>
<li><b><a name="ISIT">А есть ли...</a></b></li>
<ul>
<li><a name="NAMES"><i>Q: Можно ли разрешать имена на родительском прокси?</i></a></li>
<p>
<i>A:</i> Можно. Для этого надо использовать тип родительского прокси http,
connect+, socks4+ и socks5+. Однако, при это надо помнить, что самому 3proxy
требуется разрешение имени для управления ACL. Поэтому, если с прокси-хоста
не работают разрешения имени, необходимо в конфигурации дать команду
<pre>
fakeresolve</pre>
которая разрешает любое имя в адрес 127.0.0.2.
</p>
<li><a name="ISFTP"><i>Q: Существует ли сейчас поддержка FTP прокси в продукте?</i></a></li>
<p>
Есть поддержка как FTP через HTTP (то, что называется FTP прокси в Internet
Explorer, Netscape, Opera) так и настоящего FTP прокси (то, что называется
FTP proxy в FAR и FTP клиентах).
</p>
<li><a name="PORT"><i>Q: Каким образом можно прибиндить сервисы на свой порт, к примеру, HTTP прокси к 8080, а не 3128 как по-умолчанию?</i></a></li>
<p>
А:
<pre>
proxy -p8080</pre>
</p>
<li><a name="BANDLIM"><i>Q: Как ограничить ширину канала?</i></a></li>
<p>
<i>A:</i> Читайте HowTo <a href="https://3proxy.ru/howtor.asp#BANDLIM">https://3proxy.ru/howtor.asp#BANDLIM</a>
</p>
</ul>
<hr>
<li><b><a name="BRRR">Почему так криво...</a></b></li>
<ul>
<li><a name="TRAF"><i>Q: Почему так криво считается трафик? Не совпадает с ...</i></a></li>
<p>
<i>A:</i> Следует учитывать, что 3proxy считает трафик только на прикладном уровне и
только проходящий через прокси-сервер. Провайдеры и другие средства учета
трафика считают трафик на сетевом уровне, что уже дает расхождение порядка 10%
за счет информации из заголовков пакетов. Кроме того, часть трафика, как
минимум DNS-разрешения, различный флудовый трафик и т.д. идут мимо прокси.
Уровень "шумового" трафика в Internet сейчас составляет порядка 50KB/день на
каждый реальный IP адрес, но может сильно варьироваться в зависимости от сети,
наличия открытых портов, реакции на ping-запросы и текущего уровня вирусной
активности. По этим причинам, если 3proxy используется чтобы не "выжрать"
трафик, выделенный провайдером, всегда следует делать некий запас порядка
15%.
</p>
<p>
Если на одной с 3proxy машине имеются какие-либо сервисы или
работает пользователь, то их трафик не проходит через proxy-сервер и так же
не будет учтен. Если где-то есть NAT, то клиенты, выходящие через NAT мимо
прокси, так же останутся неучтенными. Если расхождение с провайдером превышает
10% - нужно искать причину именно в этом.
</p>
<li><a name="CONFIG"><i>Q: Почему такая кривая конфигурация и ничерта не понятно?</i></a></li>
<p>
<i>A:</i> Есть несколько причин. Во-первых, до выхода релиза (т.е. версии 1.0) я буду изо
всех сил добиваться совместимости конфигурации между версиями. Во-вторых,
конфигурация сделана так, чтобы ее можно было легко разбирать программно.
В-третьих, все там понятно. При желании. Если знать как все работает.
</p>
<li><a name="CODE"><i>Q: Почему так криво написан код?</i></a></li>
<p>
<i>A:</i> Есть несколько причин. Во-первых, я не программист. Во-вторых, 3proxy изначально
писался на коленке (в отет на &quot;слабо&quot; в одной из конференций). Никто
не мог предположить, что им кто-то реально будет пользоваться. В-третьих, у многих
возникает желание разобраться в коде 3proxy чтобы внедрить его в какой-нибудь
троян. Очень не хочется облегчать эту задачу. В-четвертых, мне надо добиться
компиляции кода в как можно большем числе систем. Замечено, что чем кривее код в
C, тем он лучше переносится.
</p>
<li><a name="UNSAFE"><i>Q: Почему так много strcpy, sprintf и т.д., это ж дыры!</i></a><li>
<p>
<i>A:</i> Есть несколько причин. Во-первых, несмотря на дурной тон использования этих
функций, они наиболее совместимы между разными системами и компиляторами.
Во-вторых, само по себе их использование не означает присутствие дыры, если их
параметры должным образом контролируются. Найдете дыру - обязательно сообщите.
В третьих, может быть я уберу их перед конечным релизом, чтобы никого не
пугать.
</p>
</ul>

View File

@ -285,3 +285,16 @@ requirements.
system bus are bottlenecks. system bus are bottlenecks.
<p>TCP_NODELAY and splice are not contrary to each over and should be combined on <p>TCP_NODELAY and splice are not contrary to each over and should be combined on
high-speed connections. high-speed connections.
<h4>Add grace delay to reduce system calls<h4>
<pre>proxy -g8000,3,10</pre>
First parameter is average read size we want to keep, second parameter is
minimal number of packets in the same direction to apply algorythm,
last value is delay added after polling and prior to reading data.
An example above adds 10 millisecond delay before reading data if average
polling size is below 8000 bytes and 3 read operations are made in the same
direction. It's specially usefule with splice. <pre>logdump 1 1</pre> is useful
to see how grace delays work, choose delay value to avoid filling the read
pipe/buffer (typically 64K) but keep the request sizes close to chosen average
on large file upload/download.

View File

@ -8,7 +8,6 @@
<li><A HREF="#INTL">How to compile 3proxy with Intel C Compiler under Windows</A> <li><A HREF="#INTL">How to compile 3proxy with Intel C Compiler under Windows</A>
<li><A HREF="#GCCWIN">How to compile 3proxy with GCC under Windows</A> <li><A HREF="#GCCWIN">How to compile 3proxy with GCC under Windows</A>
<li><A HREF="#GCCUNIX">How to compile 3proxy with GCC under Unix/Linux</A> <li><A HREF="#GCCUNIX">How to compile 3proxy with GCC under Unix/Linux</A>
<li><A HREF="#CCCUNIX">How to compile 3proxy with Compaq C Compiler under Unix/Linux</A>
</ul> </ul>
<li><A HREF="#INSTALL">Proxy server installation and removal</A> <li><A HREF="#INSTALL">Proxy server installation and removal</A>
<ul> <ul>
@ -18,20 +17,32 @@
</ul> </ul>
<li><A HREF="#SERVER">Server configuration</A> <li><A HREF="#SERVER">Server configuration</A>
<ul> <ul>
<li><a href="#NOTHING">How to make 3proxy start</a></li>
<li><a href="#LIMITS">How to make limitation (access, bandwidth, traffic, connections) work</a></li>
<li><a href="#SERVICE">How to make 3proxy to run as a service</a></li>
<li><a href="#INTEXT">How to understand internal and external</a></li>
<li><a href="#ODBC">How to make ODBC logging work?</a></li>
<li><a href="#IPV6">How to make IPv6 work</a></li>
<li><a href="#CRASH">How to fix 3proxy crashes</a></li>
<li><A HREF="#SAMPLE">Where to find configuration example</A> <li><A HREF="#SAMPLE">Where to find configuration example</A>
<li><A HREF="#LOGGING">How to set up logging</A> <li><A HREF="#LOGGING">How to set up logging</A>
<li><A HREF="#LOGFORMAT">How to setup logging format</A> <li><A HREF="#LOGFORMAT">How to setup logging format</A>
<li><A HREF="#LOGANALIZERS">How to use log analizers with 3proxy</A> <li><A HREF="#LOGANALIZERS">How to use log analizers with 3proxy</A>
<li><A HREF="#LAUNCH">How to start any of proxy services (HTTP, SOCKS etc)</A> <li><A HREF="#LAUNCH">How to start any of proxy services (HTTP, SOCKS etc)</A>
<li><A HREF="#BIND">How to bind service to specific interface and port?</A> <li><a href="#BIND">How to bind service to specific interface or port</a>
<li><a href="#NAMES">How to resolve names through a parent proxy</a></li>
<li><a href="#ISFTP">How to setup FTP proxy</a></li>
<li><a href="#TLSPR">How to setup SNI proxy (tlspr)</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 user list</A> <li><A HREF="#USERS">How to create 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>
<li><A HREF="#REDIR">How to manage redirections</A> <li><A HREF="#REDIR">How to manage redirections</A>
<li><a href="#SOCKSREDIR">How to manage local redirections</a>
<li><A HREF="#ROUNDROBIN">How to balance traffic between few external channgels?</A> <li><A HREF="#ROUNDROBIN">How to balance traffic between few external channgels?</A>
<li><A HREF="#CHAIN">How to manage proxy chains</A> <li><A HREF="#CHAIN">How to manage proxy chains</A>
<li><A HREF="#BANDLIM">How to limit bandwidth</A> <li><A HREF="#BANDLIM">How to limit bandwidth</A>
<li><A HREF="#TRAFLIM">How to limit traffic amount</A> <li><A HREF="#TRAFLIM">How to limit traffic amount</A>
<li><a href="#TRAF">How to fix incorrect traffic accounting</a>
<li><A HREF="#NETLIST">How to build network lists</A> <li><A HREF="#NETLIST">How to build network lists</A>
<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>
@ -84,12 +95,6 @@ shouldn't have problems under different Solaris, BSD or linux compatible systems
For different systems you may be required to patch Makefile or even source codes. For different systems you may be required to patch Makefile or even source codes.
If you want to use ODBC support, make sure to install ODBC for unix, remove -DNOODBC If you want to use ODBC support, make sure to install ODBC for unix, remove -DNOODBC
option from makefile compiler options and add ODBC library to linker variable. option from makefile compiler options and add ODBC library to linker variable.
</p>
</ul>
<hr>
<li><A NAME="CCCUNIX">How to compile 3proxy with Compaq C Compiler under Unix/Linux</A></li>
<p>
See <A HREF="#GCCUNIX">How to compile 3proxy with GCC under Unix/Linux</A>, use Makefile.ccc instead of Makefile.unix.
</p> </p>
</ul> </ul>
<hr> <hr>
@ -164,6 +169,83 @@ Add 3proxy to system startup scripts.
<li><A NAME="SERVER">Server configuration</A> <li><A NAME="SERVER">Server configuration</A>
<p> <p>
<ul> <ul>
<li><a name="NOTHING">How to make 3proxy start</a>
<p>Valid configuration file is required.
<li><a name="IMITS">How to make limitation (access, bandwidth, traffic, connections) work</a>
<p> Most probable reasons for non-working limitations: 'auth none' or no auth is used. For any ACL based feature one of 'iponly', 'nbname' or 'strong' auths required. Sequence of commands may be invalid. Commands are executed one-by-one and 'proxy', 'tcppm', 'socks' or another service commands must follow valid configuration. Invalid sequence of ACLs. First matching ACL is used (except of internal redirections, see below). If ACL contains at least one records last record is assumed to be 'deny *'.
<li><a name="SERVICE">How to make 3proxy to run as a service</a>
<p>Possible reasons for 3proxy starts manually but fails to start as a service:
<ul>
<li>there are relative paths in configuration file for included files,
log files, etc. Always use absolute paths. For example
$"c:\3proxy\networks.local" instead of $networks.local. For debugging remove
'service' and 'daemon', log to stdout an try to execute 3proxy from command
line from some different directory (for example from disk root).
<li>SYSTEM account doesn't have access to executable file, configuration files,
log files, etc.
<li>configuration files is not located in default path (3proxy.cfg in same
location with 3proxy.exe). For alternative configuration file location use
<pre>
3proxy --install full_path_to_configuration_file
</pre>
<li>user has no rights to install or start service
<li>service is already installed and/or started
</ul>
<p><A NAME="INTEXT">How to understant internal and external</A>
<p>
Both internal and external IPs are IPs of the host running 3proxy itself.
This configuration option is usefull in situation 3proxy is running on the
border host with 2 (or more) connections: e.g. LAN and WAN with different IPs
<pre>
LAN connection +-------------+ Internet connection
LAN <-------------->| 3proxy host |<-------------------> INTERNET
^+-------------+^
| |
Internal IP External IP
</pre>
If 3proxy is used on the host with single connection, both internal and
external are usually same IP.
<br>Internal should exist and be UP on the moment 3proxy is started and
should never be disconnected/DOWN. If this interface is periodically
disconnected (e.g. direct link between 2 hosts), do not specify internal
address or use 0.0.0.0 instead. In this case, if you have 2 or more
interfaces you must use firewall (preferably) or 3proxy ACLs to avoid open
proxy situation.
<br>
External IP (if specified) must exist in the momet 3proxy
serves client request. If external interface is no specified (or 0.0.0.0),
system select external IP. It may be possible to access resources of internal
network, to prevent this use ACLs. In addition, SOCKSv5 will not support BIND
operation, required for incoming connections (this operation is quite rarely
implemented in SOCKSv5 clients and usually is not required). In case of
dynamic address, do not specify external or use external 0.0.0.0 or, if
external address is required, create a script to determine current external
IP and save it to file, and use external "$path_to_file" with "monitor" command
to automatically reload configuration on address change.
<li><a name="ODBC">How to make ODBC logging work?</a>
<p>
Check you use system DSN.
Check SQL request is valid.
The best way to check is to make file or stdout logging, get SQL request from log file or console and execute this request manually.
Under Unix, you may also want to adjust 'stacksize' parameter.
<li><a name="IPV6">How to make IPv6 work</a>
<p> Proxy can not access destination directly over IPv6 if client requests IPv4 address.
To access IPv6 destination, either IPv6 address or hostname must be used in request.
Best solution is to enable option to resolve hostnames via proxy on client side.
<li><a name="CRASH">How to fix 3proxy crashes</a>
<p> default stacksize may be insufficient, if some non-default plugins
are used (e.g. PAM and ODBC on Linux) or if compiled on some platforms with
invalid system defined values (few versionds of FreeBSD on amd64).
Problem can be resolved with 'stacksize' command or '-S' option starting 3proxy 0.8.4.
<li><A NAME="SAMPLE">Where to find configuration example</A> <li><A NAME="SAMPLE">Where to find configuration example</A>
<p> <p>
Server configuration example 3proxy.cfg.sample is in any 3proxy distribution. Server configuration example 3proxy.cfg.sample is in any 3proxy distribution.
@ -380,6 +462,53 @@ and 192.168.2.1 use
<pre> <pre>
proxy -p8080 -i192.168.1.1 proxy -p8080 -i192.168.1.1
proxy -p8080 -i192.168.2.1 proxy -p8080 -i192.168.2.1
</pre>
</p>
<li><a name="NAMES">How to resolve names through a parent proxy</a></li>
<p>
<i>A:</i> Use one of proxy, connect+, socks4+ or socks5+ as a parent type. 3proxy
itself still performs a name resolution, it's required e.g. to ACLs matching.
So, if no name resolution must be performed by 3proxy itself add a command
<pre>
fakeresolve</pre>
this command resolves any name to 127.0.0.2 address.
</p>
<li><a name="ISFTP"><i>How to setup FTP proxy</i></a></li>
<p>
There is FTP over HTTP (what is called FTP proxy in browsers) and FTP over FTP ¯à®ªá¨
(what is called FTP proxy in file managers and FTP clients). For browsers, there is no need to start additional
proxy service, 'proxy' supports FTP over HTTP, configure 'proxy' port as an FTP proxy. For ftp clients and file
managers use ftppr. FTP proxy supports both active and passive mode with client, but always use passive mode with FTP servers.
</p>
<li><a name="TLSPR"><i>How to setup SNI proxy (tlspr)</i></a></li>
<p>
SNI proxy can be used to transparently redirect any TLS traffic with external router or local redirection rules. It can also be used
to extract hostnames from TLS to use in ACLs in combination with SOCKS or HTTP(s) proxy and/or Transparent plugin. It can also be used to require TLS or mTLS between services. TLS hadshake contains no
port information, if tlspr is used as a standalone service, destination port may be either detected with Transparent plugin or configured with -P option (default 443).
</p><p>
-c option is used to specify level of TLS check:
</p><pre>
0 (default) - allow non-TLS traffic
1 - require TLS, only check client HELLO packet
2 - require TLS, check both client and server HELLO
3 - require TLS, check server send certificate (not compatible with TLS 1.3)
4 - require mutual TLS, check server send certificate request and client sends certificate (not compatible with TLS 1.3)
</pre>
<p>
configuration examples:
1. port 1443 may be used to redirect traffic to destination port 143). SNI is used to find destination host
<pre>
tlspr -p1443 -P443 -c1
</pre>
2. used as parent tls to detect destination hostname from TLS in socks
<pre>
allow * * * 80
parent 1000 http 0.0.0.0 0
allow * * * * CONNECT
parent 1000 tls 0.0.0.0 0
deny * * some.not.allowed.host
allow *
socks
</pre> </pre>
</p> </p>
<li><A NAME="AUTH">How to limit service access</A> <li><A NAME="AUTH">How to limit service access</A>
@ -518,7 +647,7 @@ allow &lt;userlist&gt; &lt;sourcelist&gt; &lt;targetlist&gt; &lt;targetportlist&
'flush' command is used to finish with existing ACL and to start new one. 'flush' command is used to finish with existing ACL and to start new one.
It's required to have different ACLs for different services. It's required to have different ACLs for different services.
'allow' is used to allow connection and 'deny' to deny connection. 'allow' 'allow' is used to allow connection and 'deny' to deny connection. 'allow'
command can be extended by 'parent' command to manage redirections (see <A NAME="REDIR">How to manage redirections</A>)). If ACL command can be extended by 'parent' command to manage redirections (see <A href="#REDIR">How to manage redirections</A>)). If ACL
is empty it allow everything. If ACL is not empty, first matching ACL entry is empty it allow everything. If ACL is not empty, first matching ACL entry
is searched for user request and ACL action (allow or deny) performed. If is searched for user request and ACL action (allow or deny) performed. If
no matching record found, connection is denied and user will be asked to no matching record found, connection is denied and user will be asked to
@ -607,6 +736,60 @@ no need to run these services expicitly. Local redirections are usefull if
you want to see and control via ACLs protocol specific parameters, e.g. you want to see and control via ACLs protocol specific parameters, e.g.
filenames requests thorugh FTP while clients are using SOCKS. filenames requests thorugh FTP while clients are using SOCKS.
</p> </p>
<li><a name="SOCKSREDIR">Š ª ã¯à ¢«ïâì «®ª «ì­ë¬¨ ¯¥à¥­ ¯à ¢«¥­¨ï¬¨</a>
<p>
<p><i>Q: What is it for?</i></p>
A: To have control based on request and to have URLs and another protocol specific parameters to be logged.
<p><i>Q: What are restrictions?</i></p>
A: It's hard to redirect services for non-default ports; Internet Explorer supports only SOCKSv4 with no password authentication (Internet Explorer sends username, but not password), for SOCKSv5 only cleartext password authentication is supported.
<p><i>Q: What are advantages?</i></p>
A: You need only to setup SOCKS proxy in browser settings. You can use socksifier, i.e. FreeCAP or SocksCAP with application which is not proxy aware.
<p><i>Q: How to setup?</i></p>
A: You should specify parent proxy with IP of 0.0.0.0 and port 0. Examples:
<pre>
auth iponly
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
allow * * * 80,8080-8088
#redirect ports 80 and 8080-8088 to local HTTP proxy
#Second allow is required, because ACLs are checked
#twice: first time by socks and second by http proxy.
allow * * * 21,2121
parent 1000 ftp 0.0.0.0 0
allow * * * 21,2121
#redirect ports 21 and 2121 to local
#ftp proxy
allow *
#allow rest of connections directly
socks
#now let socks server to start
</pre>
<p><i>Q: How it affects different ACL rules</i></p>
A: After local redirections rules are applied again to protocol-level request. Redirection rule itself is skipped. It makes it possible to redirect request again on the external proxy depending on request itself.
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
#redirect http traffic to internal proxy
allow * * $c:\3proxy\local.nets 80,8080-8088
#allow direct access to local.nets networks
allow * * * 80,8080-8088
parent 1000 http proxy.3proxy.org 3128
#use parent caching proxy for rest of the networks
allow *
#allow direct connections for rest of socks
#requests
</pre>
<li><A NAME="ROUNDROBIN">How to balance traffic between few external channgels?</A> <li><A NAME="ROUNDROBIN">How to balance traffic between few external channgels?</A>
<p> <p>
Proxy itself doesn't manage network level routing. The only way to control Proxy itself doesn't manage network level routing. The only way to control
@ -722,30 +905,9 @@ reportpath specifies location of text reports, type parameter of 'counter'
command controls how often text reports are created. amount is amount of command controls how often text reports are created. amount is amount of
allowed traffic in Megabytes (MB). nocountin allows you to set exclusions. allowed traffic in Megabytes (MB). nocountin allows you to set exclusions.
</p> </p>
<li><A NAME="NETLIST">How to build network lists</A> <li><a name="TRAF"><i>How to fix incorrect traffic accounting</i></a>
<p>Networks or users lists are often very huge. 3proxy doesn't currently
supports user groups, but ones can be created by the means of include files. <p>3proxy accounts protocol level traffic. Provider counts channel or IP-level traffic with network and transport headers. In additions, 3proxy doesn't counts DNS resolutions, pings, floods, scans, etc. It makes approx. 10% of difference. That's why you should have 15% reserve if you use 3proxy to limit your traffic. If difference with your provider is significantly above 10% you should look for traffic avoiding proxy server, for example connections through NAT, traffic originated from the host with proxy installed, traffic from server applications, etc.
You can store comma-delimited lists of networks or users in the separate
file and use $ macro to insert this list into 3proxy.cfg.
3proxy comes with 'dighosts'
utility. This utility helps to grab the list of the network from HTTP page.
It may be usefull to e.g. obtain a regullary updated list of local networks
from ISP's server. A network list can be either in form of NETWORK MASK,
e.g. 192.168.1.0 255.255.255.0 or NETWORK/LENGTH, e.g. 192.168.1.0/24. You can
launch dighosts from 3proxy.cfg to be executed on every 3proxy startup or
configuration reload:
<pre>
system "dighosts http://provider/network.html local.networks"
allow * * $local.networks
allow *
parent 1000 proxy.provider 3128 *
proxy
flush
</pre>
In this example we obtain list of local networks from provider's page to
local.networks file, allow direct access to these networks and redirect all
connection to external networks to provider's proxy.
</p>
<li><a name="NSCACHING"><i>How to configure name resolution and DNS caching</i></a> <li><a name="NSCACHING"><i>How to configure name resolution and DNS caching</i></a>
<p> <p>
For name resolution and caching use commands nserver, nscache / nscache6 and nsrecord. For name resolution and caching use commands nserver, nscache / nscache6 and nsrecord.
@ -817,7 +979,7 @@ connection to external networks to provider's proxy.
<li><A NAME="NEWVERSION">How to obtain latest 3proxy version</A> <li><A NAME="NEWVERSION">How to obtain latest 3proxy version</A>
<p> <p>
Latest version of 3proxy may be obtained Latest version of 3proxy may be obtained
<A HREF="http://3proxy.org/">here</A>. <A HREF="https://3proxy.org/">here</A>.
New version may have changes and incompatibilities with previous one in files New version may have changes and incompatibilities with previous one in files
format or commands. Please, read CHANGELOG file and another documentation format or commands. Please, read CHANGELOG file and another documentation
before installing new version. before installing new version.
@ -874,7 +1036,7 @@ You can control 3proxy service via "Services" administration ot via "net" comman
<li>90 - unexpected system error (should not happen) <li>90 - unexpected system error (should not happen)
<li>91 - unexpected poll error (should not happen) <li>91 - unexpected poll error (should not happen)
<li>92 - connection terminated by timeout (see timeouts) <li>92 - connection terminated by timeout (see timeouts)
<li>93 - connection terminated by ratelimit-related timeout <li>93 - connection terminated by ratelimit-related timeout or due to errors limit
<li>94 - connection termination by server or client with unsent data <li>94 - connection termination by server or client with unsent data
<li>95 - dirty connection termination by client (or networking issue) <li>95 - dirty connection termination by client (or networking issue)
<li>96 - dirty connection termination by server (or networking issue) <li>96 - dirty connection termination by server (or networking issue)

View File

@ -18,25 +18,35 @@
</ul> </ul>
<li><a href="#SERVER">Конфигурация сервера</a> <li><a href="#SERVER">Конфигурация сервера</a>
<ul> <ul>
<li><a href="#NOTHING">Как заставить 3proxy запускаться</a></li>
<li><a href="#LIMITS">Как заставить ограничения (по ширине канала, трафику, ACL и. т.п.) работать</a></li>
<li><a href="#SERVICE">Как заставить 3proxy запускаться как службу</a></li>
<li><a href="#INTEXT">Как разобраться с internal и external</a></li>
<li><a href="#ODBC">Как починить ведение журналов в ODBC?</a></li>
<li><a href="#IPV6">Как заставить IPv6 работать</a></li>
<li><a href="#CRASH">Как сделать чтобы 3proxy не крешился</a></li>
<li><a href="#SAMPLE">Как посмотреть пример файла конфигурации</a> <li><a href="#SAMPLE">Как посмотреть пример файла конфигурации</a>
<li><a href="#LOGGING">Как настроить ведение журнала</a> <li><a href="#LOGGING">Как настроить ведение журнала</a>
<li><a href="#LOGFORMAT">Как настроить формат журнала</a> <li><a href="#LOGFORMAT">Как настроить формат журнала</a>
<li><a href="#LOGANALIZERS">Как использовать лог-анализаторы с 3proxy</a> <li><a href="#LOGANALIZERS">Как использовать лог-анализаторы с 3proxy</a>
<li><a href="#LAUNCH">Как запустить конкретную службу (HTTP, SOCKS и т.д)</a> <li><a href="#LAUNCH">Как запустить конкретную службу (HTTP, SOCKS и т.д)</a>
<li><a href="#BIND">Как повесить службу на определенный интерфейс или порт</a> <li><a href="#BIND">Как повесить службу на определенный интерфейс или порт</a>
<li><a href="#NAMES">Как разрешать имена на родительском прокси?</a></li>
<li><a href="#ISFTP">Как настроить FTP прокси?</a></li>
<li><a href="#TLSPR">Как настроить SNI proxy (tlspr)</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>
<li><a href="#REDIR">Как управлять перенаправлениями</a> <li><a href="#REDIR">Как управлять перенаправлениями</a>
<li><a href="#SOCKSREDIR">Как управлять локальными перенаправлениями</a>
<li><a href="#ROUNDROBIN">Как организовать балансировку между несколькими каналами</a> <li><a href="#ROUNDROBIN">Как организовать балансировку между несколькими каналами</a>
<li><a href="#CHAIN">Как составлять цепочки прокси</a> <li><a href="#CHAIN">Как составлять цепочки прокси</a>
<li><a href="#BANDLIM">Как ограничивать скорости приема</a> <li><a href="#BANDLIM">Как ограничивать скорости приема</a>
<li><a href="#TRAFLIM">Как ограничивать объем принимаемого трафика</a> <li><a href="#TRAFLIM">Как ограничивать объем принимаемого трафика</a>
<li><a href="#NETLIST">Как строить списки сетей</a> <li><a href="#TRAF">Как пофиксить некорректный подсчет трафика</a></li>
<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="#DEMANDDIAL">Как устанавливать соединение по требованию</a>
</ul> </ul>
<li><a href="#CLIENT">Конфигурация и настройка клиентов</a> <li><a href="#CLIENT">Конфигурация и настройка клиентов</a>
<ul> <ul>
@ -172,6 +182,101 @@
<li><a name="SERVER"><b>Конфигурация сервера</b></a> <li><a name="SERVER"><b>Конфигурация сервера</b></a>
<p> <p>
<ul> <ul>
<li><a name="NOTHING">Как заставить прокси работать</a></li>
<p>
Для работы требуется корректный файл конфигурации. Если прокси не запускается, значит в конфигурации есть ошибка.
</p>
<li><a name="LIMITS">Как заставить работать ограничения (контроль доступа, ограничения ширины канала, счетчики и т.п.)</a></li>
<p>
<i>A:</i> Обычные ошибки - использование auth none (для работы любых
функций, основанных на ACL, требуется auth iponly, nbname или strong),
нарушение порядка ввода команд (команды выполняются последовательно,
запуск сервиса proxy, socks, tcppm и т.д. должен осуществляться после
того, как указана его конфигурация), неправильный порядок записей в ACL
(записи просматриваются последовательно до первой, удовлетворяющей
критериям). Если в ACL имеется хотя бы одна запись, то считается, что
последняя запись в ACL - это неявная deny *.
</p>
<li><a name="SERVICE">Как починить запуск 3proxy службой</a></li>
<p>
Чаще всего 3proxy не запускается службой (но запускается вручную) по одной из следующих причин:
<ul>
<li>Использование относительных (неполных) путей файлов в файле конфигурации
При использовании файлов журналов, файлов вставок ($filename) используйте
полные пути, например, $"c:\3proxy\include files\networks.local". Тоже самое
относится к файлам журналов и любым другим.
Для отладки лучше запускать 3proxy с ведением журнала на стандартный вывод.
Не забудьте в таком случае отключить daemon и service в файле конфигурации.
Для чистоты эксперимента запускать 3proxy из коммандной строки в таком случае
следует, находясь в другой папке.
<li>Отсутствие у системной записи прав на доступ к исполняемому файлу, каким-либо файлам конфигурации, журнала и т.п.
<li>Отсутствие файла конфигурации по стандартному расположению -
3proxy.cfg в одном каталоге с исполняемым файлом. Если файл расположен по
другому пути, необходимо использовать команду
<pre>
3proxy --install path_to_configuration_file</pre>
<li>Отсутствие у пользователя прав на установку или запуск службы
<li>Служба уже установлена или запущена
</ul>
</p>
<li><a name="INTEXT">Как разобраться с internal и external</a></li></li>
<p>
Убедитесь, что выправильно понимаете что такое internal и external адреса.
Оба адреса - это адреса, принадлежищие хосту, на котором установлен 3proxy.
Эта опция конфигурации необходима в классической ситуации, когда 3proxy
установлен на граничном компьютере с двумя (или более) подключениями:
<pre>
LAN connection +-------------+ Internet connection
LAN <-------------->| 3proxy host |<-------------------> INTERNET
^+-------------+^
| |
Internal IP External IP</pre>
Если 3proxy работает на хосте с одним интерфейсом, то его адрес будет и
internal и external.
<br>Интерфейс с адресом internal должен существовать и быть рабочим на момент
запуска 3proxy, и не должен отключаться. Если internal интерфейс
периодически отключается, то не следует его указывать, или можно указать адрес
0.0.0.0. При этом прокси будет принимать запросы на всех интерфейсах, поэтому
при наличии нескольких интерфейсов для ограничения доступа следует использовать
фаервол или хотя бы ACL.
</p>
<p>
Интерфейс с адресом external, если он указан, должен быть рабочим на момент
получения запроса клиента. При отсутствии external или адресе 0.0.0.0 внешний
адрес будет выбираться системой при установке соединения. При этом, может быть
возможность доступа через прокси к ресурсам локальной сети, поэтому для
предотвращения несанкционированного доступа следует использовать ACL. Кроме
того, могут быть проблемы с приемом входящих соединений через SOCKSv5
(SOCKSv5 используется в клиентах исключительно редко).
В случае, если адрес динамический, можно либо не
указывать external, либо использовать адрес 0.0.0.0, либо, если необходима
поддержка входящих соединений в SOCKSv5, использовать скрипт,
который будет получать текущий адрес и сохранять его в файл, который будет
отслуживаться через команду monitor.
</p>
<li><a name="ODBC">Как починить ведение журналов в ODBC</a></li>
<p>
Убедитесь, что используется системный, а не
пользовательский DSN. Убедитесь, что выполняется правильный SQL запрос. Наиболее
распространенная проблема связана с отсутствием кавычек или неправильным
форматом данных. Самый простой способ - сделать ведение журнала в файл или
на стандартный вывод, просмотреть выдаваемые SQL запросы и попробовать
дать такой запрос вручную.
</p>
<li><a name="IPv6">Как починить IPv6</a></li>
<p>
Прокси не может обращаться напрямую к IPv6 сети если в запросе от клиента
указан IPv4. В запросе от клиента должен быть IPv6 адрес или имя хоста, чаще
всего это решается включением опции разрешения имен через прокси-сервер на стороне
клиента.
</p>
<li><a name="CRASH">Как починить падения 3proxy</a></li>
<p>
Возможно, недостаточен размер стека потока по-умолчанию, это может
быть при использовани каких-либо сторонних плагинов (PAM, ODBC) или на
некоторых платформах (некоторые версии FreeBSD на amd64). Можно решить
проблему с помощью опции 'stacksize' или '-S', поддерживаемых в 0.8.4 и выше.
</p>
<li><a name="SAMPLE"><i>Как посмотреть пример файла конфигурации</i></a> <li><a name="SAMPLE"><i>Как посмотреть пример файла конфигурации</i></a>
<p> <p>
Пример файла конфигурации 3proxy.cfg.sample поставляется с любым дистрибутивом Пример файла конфигурации 3proxy.cfg.sample поставляется с любым дистрибутивом
@ -386,6 +491,59 @@
<pre> <pre>
proxy -p8080 -i192.168.1.1 proxy -p8080 -i192.168.1.1
proxy -p8080 -i192.168.2.1</pre> proxy -p8080 -i192.168.2.1</pre>
<li><a name="NAMES"><i>Как разрешать имена на родительском прокси?</i></a></li>
<p>
<i>A:</i> Для этого надо использовать тип родительского прокси http,
connect+, socks4+ и socks5+. Однако, при это надо помнить, что самому 3proxy
требуется разрешение имени для управления ACL. Поэтому, если с прокси-хоста
не работают разрешения имени, необходимо в конфигурации дать команду
<pre>
fakeresolve</pre>
которая разрешает любое имя в адрес 127.0.0.2.
</p>
<li><a name="ISFTP"><i>Как настроить FTP прокси?</i></a></li>
<p>
Есть поддержка как FTP через HTTP (то, что называется FTP прокси в браузерах) так и настоящего FTP прокси (то, что называется
FTP proxy в командных оболочках и FTP клиентах). В браузерах в качестве FTP прокси следует прописывать порт службы proxy,
т.е. FTP организован
через http прокси, дополнительного прокси поднимать не надо. Для FTP-клиентов необходимо поднять ftppr. FTP прокси всегда работает
с FTP сервером в пассивном режиме.
</p>
<li><a name="TLSPR"><i>Как настроить SNI proxy (tlspr)</i></a></li>
<p>
SNI proxy может быть использовать для транспарентного перенаправления любого TLS трафика (например HTTPS) на внешнем маршрутизаторе
или локальными правилами. Так же можно использовать его для извлечения имени хоста из TLS хендшейка с целью логгирования или использования в ACL.
Еще одна задача которую может решать модуль - требование наличия TLS или mTLS (mutual TLS).
Если tlspr используется как отдельный сервис без исползования плагина Transparent, то необходимо задать порт назначения через опцию -T (по умолчанию 443),
т.к. TLS хендшейк не содержит информации о порте назначения.
</p><p>
-c контролирует уровень требования к TLS:
</p><pre>
0 (по умолчанию) - пропустить трафик без TLS
1 - требовать TLS, проверять наличие client HELLO
2 - требовать TLS, проверять наличие client и server HELLO
3 - требовать TLS, проверять наличие серверного сертификата (не совместим с TLS 1.3+)
4 - требовать взаимный (mutual) TLS, проверять что сервер запрашивает сертификат и клиент его отправляет (не совместим с TLS 1.3+)
</pre>
<p>
примеры конфигурации:
1. Порт 1443 можно использовать для перенаправления в него HTTPS трафика по порту 443 (например с внешнего маршрутизатора)
<pre>
tlspr -p1443 -P443 -c1
</pre>
2. tlspr используется как родительский прокси в SOCKS чтобы обнаруживать реальный hostname назначения (даже если запрашивается подклюение по IP адресу)
<pre>
allow * * * 80
parent 1000 http 0.0.0.0 0
allow * * * * CONNECT
parent 1000 tls 0.0.0.0 0
deny * * some.not.allowed.host
allow *
socks
</pre>
</p>
<li><a name="AUTH"><i>Как ограничить доступ к службе</i></a> <li><a name="AUTH"><i>Как ограничить доступ к службе</i></a>
<p> <p>
Во-первых, для ограничения доступа необходимо указать внутренний интерфейс, Во-первых, для ограничения доступа необходимо указать внутренний интерфейс,
@ -614,6 +772,74 @@
того, чтобы видеть в логах записи о посещаемых пользвоателем ресурсах и того, чтобы видеть в логах записи о посещаемых пользвоателем ресурсах и
загружаемых файлах даже в том случае, если он подключается через SOCKS. загружаемых файлах даже в том случае, если он подключается через SOCKS.
</p> </p>
<li><a name="SOCKSREDIR">Как управлять локальными перенаправлениями</a>
<p>
<ul>
<li><a name="REDIR"><i>Q: Для чего это надо?</i></a></li>
<p>
<i>A:</i> Чтобы иметь в логах URL запросов, если пользователь SOCKS пользуется
Web, FTP или POP3.
</p>
<li><a name="REDIRLIMIT"><i>Q: Какие недостатки?</i></a></li>
<p>
<i>A:</i> Перенапраление невозможно для web-серверов или FTP, висящих на
нестандартных портах, для SOCKSv4 не поддрживается авторизация с
паролем (IE поддерживает только SOCKSv4), но при этом IE передает
имя пользователя по SOCKSv4 (имя, с которым пользователь вошел в систему).
Для SOCKSv5 не поддерживается NTLM авторизация, пароли передаются в открытом
тексте.
</p>
<li><a name="REDIRADV"><i>Q: Какие преимущества?</i></a></li>
<p>
<i>A:</i> Достаточно в настройках IE только указать адрес SOCKS прокси. В
больших сетях можно для этого использовать WPAD (автоматическое
обнаружение прокси). В 3proxy достаточно запускать только одну службу
(socks). Если используется только Internet Explorer, то можно
автоматически получать имя пользователя в логах, не запрашивая
логин/пароль.
</p>
<li><a name="REDIRHOW"><i>Q: Как настраивается?</i></a></li>
<p>
<i>A:</i> Указывается parent http proxy со специальным адресом 0.0.0.0 и портом
0. Пример:
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
allow * * * 80,8080-8088
#перенаправить соединения по портам 80 и 8080-8088 в локальный
#http прокси. Вторая команда allow необходима, т.к. контроль доступа
#осуществляется 2 раза - на уровне socks и на уровне HTTP прокси
allow * * * 21,2121
parent 1000 ftp 0.0.0.0 0
allow * * * 21,2121
#перенаправить соединения по портам 21 и 2121 в локальный
#ftp прокси
allow *
#пустить все соединения напрямую
socks</pre>
</p>
<li><a name="REDIINTER"><i>Q: Как взаимодействует с другими правилами в ACL?</i></a></li>
<p>
<i>A:</i> После внутреннего перенаправления правила рассматриваются еще раз за
исключением самого правила с перенаправлением (т.е. обработка правил не
прекращается). Это позволяет сделать дальнейшие перенаправления на
внешний прокси. По этой же причине локальное перенаправление не должно
быть последним правилом (т.е. должно быть еще хотя бы правило allow,
чтобы разрешить внешние соединения через HTTP прокси).
Например,
<pre>
allow * * * 80,8080-8088
parent 1000 http 0.0.0.0 0
#перенаправить во внутренний прокси
allow * * $c:\3proxy\local.nets 80,8080-8088
#разрешить прямой web-доступ к сетям из local.nets
allow * * * 80,8080-8088
parent 1000 http proxy.3proxy.ru 3128
#все остальные веб-запросы перенаправить на внешний прокси-сервер
allow *
#разрешить socks-запросы по другим портам</pre>
</p>
</ul>
<li><a name="ROUNDROBIN"><i>Как организовать балансировку между несоклькими каналами</i></a> <li><a name="ROUNDROBIN"><i>Как организовать балансировку между несоклькими каналами</i></a>
<p> <p>
Сам по себе прокси не может управлять маршрутизацией пакетов сетевого уровня. Сам по себе прокси не может управлять маршрутизацией пакетов сетевого уровня.
@ -742,33 +968,26 @@
<br> <br>
amount - объем трафика на указанный период в мегабайтах. amount - объем трафика на указанный период в мегабайтах.
</p> </p>
<li><a name="NETLIST"><i>Как строить списки сетей</i></a> <li><a name="TRAF">Как пофиксить некорректный подсчет трафика</a>
<p> <p>
Очень часто списки сетей и пользователей бывают достаточно громоздкими. Следует учитывать, что 3proxy считает трафик только на прикладном уровне и
3proxy не поддерживает создание групп, но позволяет включение файлов. Это только проходящий через прокси-сервер. Провайдеры и другие средства учета
означает, что для удобства администрирования выгодно хранить списки трафика считают трафик на сетевом уровне, что уже дает расхождение порядка 10%
пользователей и списки сетей в отдельных файлах и при необходимости дать за счет информации из заголовков пакетов. Кроме того, часть трафика, как
пользователю доступ к тому или иному ресурсу, править файл со списком минимум DNS-разрешения, различный флудовый трафик и т.д. идут мимо прокси.
пользователей или сетей вместо того, чтобы править сам файл 3proxy.cfg. В файле Уровень "шумового" трафика в Internet сейчас составляет порядка 50KB/день на
3proxy.cfg файл со списком можно включить с помощью макроса $. каждый реальный IP адрес, но может сильно варьироваться в зависимости от сети,
Поскольку в 3proxy есть ограничения на максимальный размер элемента наличия открытых портов, реакции на ping-запросы и текущего уровня вирусной
конфигурации, большие списки следует разбивать на несколько файлов и активности. По этим причинам, если 3proxy используется чтобы не "выжрать"
использовать несколько записей списка контроля доступом. трафик, выделенный провайдером, всегда следует делать некий запас порядка
В комплекте с 3proxy поставляется утилита dighosts, которая позволяет построить 15%.
список сетей по странице Web. Утилита осуществляет поиск адресов на Web-странице </p>
в формате АДРЕС МАСКА или АДРЕС/ДЛИНА. Утилиту dighosts можно вызвать во время <p>
старта 3proxy, используя команду system. Например: Если на одной с 3proxy машине имеются какие-либо сервисы или
<pre> работает пользователь, то их трафик не проходит через proxy-сервер и так же
system "dighosts http://provider/network.html local.networks" не будет учтен. Если где-то есть NAT, то клиенты, выходящие через NAT мимо
allow * * $local.networks прокси, так же останутся неучтенными. Если расхождение с провайдером превышает
allow * 10% - нужно искать причину именно в этом.
parent 1000 proxy.provider 3128 *
proxy
flush</pre>
В данном случае в файле local.networks генерируется список локальных сетей по
странице networklist.html. Далее используется список контроля доступа для того,
чтобы разрешить локальному прокси-серверу доступ к локальным сетям напрямую,
а все остальные запросы перенаправить на прокси-сервер провайдера.
</p> </p>
<li><a name="NSCACHING"><i>Как управлять разрешением имен и кэшированием DNS</i></a> <li><a name="NSCACHING"><i>Как управлять разрешением имен и кэшированием DNS</i></a>
<p> <p>
@ -827,19 +1046,6 @@
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="DEMANDDIAL"><i>Как устанавливать соединение по требованию</i></a>
<p>
Команда dialer задает программу, которая будет запускаться при
невозможности разрешить имя компьютера, например:
<pre>
dialer "rasdial PROVIDER"</pre>
(описание rasdial можно найти на сервере поддержки Microsoft).
Есть два аспекта: невозможность разрешения имени еще не свидетельствует
об отсутствии соединения (это должна учитывать вызываемая программа),
при использовании nscache имя может разрешиться при отсутствии
соединения. В таких случаях полезно запрашивать заведомо несуществующий
ресурс, например, http://dial.right.now/.
</p>
</ul> </ul>
<hr> <hr>
<li><a name="CLIENT"><b>Конфигурация клиентов</b></a> <li><a name="CLIENT"><b>Конфигурация клиентов</b></a>
@ -896,9 +1102,9 @@
прокси-серверы для доступа к разным ресурсам. Эта возможность разбирается в прокси-серверы для доступа к разным ресурсам. Эта возможность разбирается в
статьях статьях
<br>Microsoft: Q296591 A Description of the Automatic Discovery Feature <br>Microsoft: Q296591 A Description of the Automatic Discovery Feature
<br><a href="http://support.microsoft.com/default.aspx?scid=kb;EN-US;296591">http://support.microsoft.com/default.aspx?scid=kb;EN-US;296591</a> <br><a href="https://support.microsoft.com/default.aspx?scid=kb;EN-US;296591">http://support.microsoft.com/default.aspx?scid=kb;EN-US;296591</a>
<br>Netscape: Navigator Proxy Auto-Config File Format <br>Netscape: Navigator Proxy Auto-Config File Format
<br><a href="http://wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html">http://wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html</a> <br><a href="https://wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html">http://wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html</a>
<li><a name="FTP"><i>Как настраивать FTP клиент</i></a> <li><a name="FTP"><i>Как настраивать FTP клиент</i></a>
<p> <p>
Настройка FTP клиента для работы через SOCKS прокси не отличается от настройки Настройка FTP клиента для работы через SOCKS прокси не отличается от настройки
@ -954,20 +1160,14 @@
</p> </p>
<li><a name="CAP"><i>Как использовать 3proxy с программой, не поддерживающей работу с прокси-сервером</i></a> <li><a name="CAP"><i>Как использовать 3proxy с программой, не поддерживающей работу с прокси-сервером</i></a>
<p> <p>
Можно использовать любую программу-редиректор, например, Можно использовать любую программу-редиректор. 3proxy поддерживает исходящие
<a href="http://www.socks.permeo.com">SocksCAP</a> или
<a href="http://www.freecap.ru">FreeCAP</a>. 3proxy поддерживает исходящие
и обратные TCP и UDP соединения, но редиректоры могут иметь свои ограничения, и обратные TCP и UDP соединения, но редиректоры могут иметь свои ограничения,
кроме того, некоторые плохо написаные приложения не поддаются "соксификации". кроме того, некоторые плохо написаные приложения не поддаются "соксификации".
Если программе требуется обращаться к небольшому набору серверов Если программе требуется обращаться к небольшому набору серверов
(например, игровых), то проблему можно решить с помощью портмаппинга. (например, игровых), то проблему можно решить с помощью портмаппинга.
<li><a name="GAMES"><i>Как использовать 3proxy с играми</i></a> <li><a name="GAMES"><i>Как использовать 3proxy с играми</i></a>
<p> <p>
Оптимальный варинт - использовать соксификатор (<a href="#CAP">Как использовать Если по каким-то причинам соксификатор не работает или недоступен,
3proxy с программой, не поддерживающей работу с прокси-сервером</a>).
<a href="http://www.freecap.ru/">FreeCap 3.13 </a> проверен с играми на движке
Unreal (включая Unreal Tournament), Half-Life (включая Counter-Strike) и
другими. Если по каким-то причинам соксификатор не работает или недоступен,
то необходимо использовать отображения портов (обычно игры, то необходимо использовать отображения портов (обычно игры,
кроме mood-подобных, работают по протоколу UDP, надо использовать udppm). кроме mood-подобных, работают по протоколу UDP, надо использовать udppm).
Нужно иметь ввиду, что для udppm требуется отдельный маппинг для каждого Нужно иметь ввиду, что для udppm требуется отдельный маппинг для каждого
@ -992,7 +1192,7 @@
<li><a name="NEWVERSION"><i>Где взять свежую версию</i></a> <li><a name="NEWVERSION"><i>Где взять свежую версию</i></a>
<p> <p>
Свежую версию всегда можно взять Свежую версию всегда можно взять
<a href="http://3proxy.ru/">здесь</a>. Обратите внимание, <a href="https://3proxy.ru/">здесь</a>. Обратите внимание,
что в новой версии может измениться порядок лицензирования или команды что в новой версии может измениться порядок лицензирования или команды
конфигурации, поэтому прежде чем устанавливать новую версии программы конфигурации, поэтому прежде чем устанавливать новую версии программы
обязательно ознакомьтесь с документацией. обязательно ознакомьтесь с документацией.
@ -1050,7 +1250,7 @@
<li>90 - неожиданная системная ошибка (не должно происходить) <li>90 - неожиданная системная ошибка (не должно происходить)
<li>91 - ошибка poll (не должно происходить) <li>91 - ошибка poll (не должно происходить)
<li>92 - соединение прервано по таймауту на сетевую операцию (см. timeouts) <li>92 - соединение прервано по таймауту на сетевую операцию (см. timeouts)
<li>93 - соединение прервано по таймауту связанному с рейтлимитом <li>93 - соединение прервано по таймауту связанному с рейтлимитом или из-за превышения числа ошибок
<li>94 - клиент или сервер закрыли соединение или произошла сетевая ошибка, остались неотправленные данные <li>94 - клиент или сервер закрыли соединение или произошла сетевая ошибка, остались неотправленные данные
<li>95 - клиент "грязно" закрыл соединение или сетевая ошибка <li>95 - клиент "грязно" закрыл соединение или сетевая ошибка
<li>96 - сервер "грязно" закрыл соединение или сетевая ошибка <li>96 - сервер "грязно" закрыл соединение или сетевая ошибка

View File

@ -3,17 +3,15 @@
<a href="highload.html">Optimizing 3proxy for high loads</a><br> <a href="highload.html">Optimizing 3proxy for high loads</a><br>
<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>
<a href="faqe.html">FAQ (English)</a><br>
<a href="faqr.html">FAQ (Russian)</a>
<h3>Man pages:</h> <h3>Man pages:</h>
<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/icqpr.8.html">icqpr.8</A>
<br><A HREF="man8/pop3p.8.html">pop3p.8</A> <br><A HREF="man8/pop3p.8.html">pop3p.8</A>
<br><A HREF="man8/proxy.8.html">proxy.8</A> <br><A HREF="man8/proxy.8.html">proxy.8</A>
<br><A HREF="man8/smtpp.8.html">smtpp.8</A> <br><A HREF="man8/smtpp.8.html">smtpp.8</A>
<br><A HREF="man8/socks.8.html">socks.8</A> <br><A HREF="man8/socks.8.html">socks.8</A>
<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/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="man3/3proxy.cfg.3.html">3proxy.cfg.3</A>
</body></html> </body></html>

View File

@ -1,34 +1,64 @@
<h3>3proxy SSL/TLS plugin</h3> <h3>3proxy SSL/TLS plugin</h3>
Plugin can be used to transparently decypher SSL/TLS data. Plugin should never be used in production environment due to Plugin can be used to transparently decypher SSL/TLS data and TLS encryption for proxy traffic.
potential securiy reasons.
<pre>
ssl_certcache PATH_TO_CACHE
ssl_mitm <h4>For transparent certificate spoofing:</h4>
ssl_nomitm
</pre> <br>ssl_mitm - spoof certificates for services started below. Usage without ssl_client_verify is insecure.
ssl_certcache - path to certificates cache. For transparent spoofing cache must contain 3 files: 3proxy.pem - public
self-signed certificates, 3proxy.key - key for public certificates, server.key - this key will be used to generates
spoofed certificates.
Generated certificates will be placed to the same path.
<br>ssl_mitm - spoof certificates for services started below
<br>ssl_nomitm - do not spoof certificates for services started below <br>ssl_nomitm - do not spoof certificates for services started below
<h4>To protect traffic to server (https:// proxy) - since 0.9.5 version</h4>
ssl_serv - require TLS connection for services below
<br>ssl_noserv - do not require TLS connection for services below
<h4>Example:</h4> Parameters:
<br>ssl_server_cert /path/to/cert - Server certificate (should not be selfsigned and must contain Alternative name) for ssl_serv
<br>ssl_server_key /path/to/key - Server ceritifacte key for ssl_server_cert or generated mitm certificate
<br>ssl_client_ciphersuites ciphersuites_list - TLS client ciphers for TLS 1.3, e.g. ssl_client_ciphersuites TLS_AES_128_GCM_SHA256
<br>ssl_server_ciphersuites ciphersuites_list - TLS server ciphers for TLS 1.3
<br>ssl_client_cipher_list ciphersuites_list - TLS client ciphers for TLS 1.2 and below , e.g. ssl_client_cipher_list ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305
<br>ssl_server_cipher_list ciphersuites_list - TLS server ciphers for TLS 1.2 and below
<br>ssl_client_min_proto_version tls_version - TLS client min TLS version (e.g. TLSv1.2)
<br>ssl_server_min_proto_version tls_version - TLS server min TLS version (e.g. TLSv1.2)
<br>ssl_client_max_proto_version tls_version - TLS client max TLS version (e.g. TLSv1.2)
<br>ssl_server_max_proto_version tls_version - TLS server max TLS version (e.g. TLSv1.2)
<br>ssl_client_verify - verify certificate for upstream server in TLS client functionality (used with ssl_mitm)
<br>ssl_client_no_verify - do not verify certificate for upstream server in TLS client functionality (default)
<br>ssl_server_ca_file /path/to/cafile - CA certificate file for mitm
<br>ssl_server_ca_key /path/to/cakey - key for ssl_server_ca_file mitm CA
<br>ssl_client_ca_file, ssl_client_ca_dir, ssl_client_ca_store - locations for root CAs used with ssl_client_verify for TLS client
<br>ssl_certcache /path/to/cache/ - location for generated mitm certificates cache, optional, if ssl_server_ca_file / ssl_server_ca_key are configured.
Cache may contain 3 files: 3proxy.pem - public
self-signed certificates (used if ssl_server_ca_file is not configured),
3proxy.key - key for public certificates, used if ssl_server_ca_keyserver.key is not configured, server.key - this key is used if ssl_server_key is not configured to generates
spoofed certificates. If server.key is absent, 3proxy.key is used to generate certificates.
Generated certificates are placed to the same path.
<h4>mitm example:</h4>
<pre> <pre>
plugin /path/to/SslPlugin.dll ssl_plugin plugin /path/to/SslPlugin.dll ssl_plugin
ssl_certcache /path/to/cache/ ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
proxy -p3128 proxy -p3128
ssl_nomitm ssl_nomitm
proxy -p3129 proxy -p3129
</pre> </pre>
mitm's traffic with spoofed ceritifacate for port 3128 proxy.
<h4>Download:</h4> <h4>https:// proxy example:</h4>
<ul> <pre>
<li>Plugin included into 3proxy 0.8 plugin /path/to/SSLPlugin.so ssl_plugin
</ul> ssl_server_cert path_to_cert
ssl_server_key path_to_key
ssl_serv
proxy -p33128
ssl_noserv
proxy -p3128
</pre>
creates https:// proxy on 33128 and http:// proxy on 3128
&copy; Vladimir Dubrovin, License: BSD style &copy; Vladimir Dubrovin, License: BSD style

View File

@ -1,32 +1,61 @@
<h3>Плагин SSL/TLS для 3proxy</h3> <h3>3proxy SSL/TLS плагин</h3>
Плагин используется для транспарентной дешифровки SSL-трафика с подменой сертификата. Плагин можно использовать для перехвата и дешифровки SSL/TLS трафика и для шифрования трафика прокси-сервера
Плагин не должен использоваться в рабочем окружении, т.к. его использование дает возможность обхода проверок SSL.
<h4>Для транспаретной перехватки трафика (mitm):</h4>
<br>ssl_mitm - подменять сертификаты для сервисов стартованных ниже. Не безопасно использовать без ssl_client_verify.
<br>ssl_nomitm - не подменять сертификаты для сервисов стартованных ниже.
<pre> <h4>Для защиты трафика прокси-сервера (например https:// proxy) - начиная с 0.9.5</h4>
ssl_certcache PATH_TO_CACHE ssl_serv - включает TLS для соединений к сервисам ниже
ssl_mitm <br>ssl_noserv - отключает TLS для соединений к сервисам ниже
ssl_nomitm
</pre>
ssl_certcache - путь к кэшу сертификатов. Для транспорентной подмены сертификатов в кэше должно находиться 3 файла: 3proxy.pem - публичный
самоподписанный сертификат, 3proxy.key - ключ от этого сертификата, server.key - ключ с которым будут генерироваться подменные сертификаты.
Сгенерированные сертификаты будут помещаться в этот же каталог.
<br>ssl_mitm - подменять сертитфикаты для запущенных ниже сервисов
<br>ssl_nomitm - не подменять сертитфикаты для запущенных ниже сервисов
Параметры:
<br>ssl_server_cert /path/to/cert - сертификат сервера, не должен быть самоподписаным, имя CN должно содержаться в альтернативных именах - используется для ssl_serv
<br>ssl_server_key /path/to/key - ключ сертификата сервера для ssl_server_cert или сгенерированного сертификата ssl_mitm
<br>ssl_client_ciphersuites ciphersuites_list - наборы шифрова TLS для TLS 1.3, пример ssl_client_ciphersuites TLS_AES_128_GCM_SHA256
<br>ssl_server_ciphersuites ciphersuites_list - наборы шифрова TLS для TLS 1.3
<br>ssl_client_cipher_list ciphersuites_list - наборы шифрова TLS для TLS 1.2 и ниже, пример ssl_client_cipher_list ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305
<br>ssl_server_cipher_list ciphersuites_list - наборы шифрова TLS для TLS 1.2 и ниже
<br>ssl_client_min_proto_version tls_version - минимальная версия TLS клиента (например ssl_client_min_proto_version TLSv1.2)
<br>ssl_server_min_proto_version tls_version - минимальная версия TLS сервера
<br>ssl_client_max_proto_version tls_version - максимальная версия TLS клиента
<br>ssl_server_max_proto_version tls_version - максимальная версия TLS сервера
<br>ssl_client_verify - проверять сертификат сервера назначения (используется с ssl_mitm)
<br>ssl_client_no_verify - не проверять сертификат сервера назначения
<br>ssl_server_ca_file /path/to/cafile - CA сертификат для ssl_mitm
<br>ssl_server_ca_key /path/to/cakey - ключ CA сертификата ssl_server_ca_file mitm
<br>ssl_client_ca_file, ssl_client_ca_dir, ssl_client_ca_store - расположения корневых сертификатов ssl_client_verify
<br>ssl_certcache /path/to/cache/ - расположение кеша сгенерированных сертификатов ssl_mitm. Кеш может содержать
файлы 3proxy.pem, 3proxy.key server.key, которые используются как ssl_server_ca_file,
ssl_server_ca_key и ssl_server_key соответственно если они не заданы. Если server.key не задан,
3proxy.key используется для генерации серверного сертификата.
<h4>Пример:</h4> <h4>Пример mitm:</h4>
<pre> <pre>
plugin /path/to/SslPlugin.dll ssl_plugin plugin /path/to/SslPlugin.dll ssl_plugin
ssl_certcache /path/to/cache/ ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
proxy -p3128 proxy -p3128
ssl_nomitm ssl_nomitm
proxy -p3129 proxy -p3129
</pre> </pre>
Перехватывается трафик в прокси на порту 3128
<h4>Загрузить:</h4> <h4>Пример конфигурации https:// прокси (curl -x https://...):</h4>
<ul> <pre>
<li>Плагин включен в дистрибутив 3proxy 0.8 plugin /path/to/SSLPlugin.so ssl_plugin
</ul> ssl_server_cert path_to_cert
ssl_server_key path_to_key
ssl_serv
proxy -p33128
ssl_noserv
proxy -p3128
</pre>
На порту 33128 создается https:// прокси (не путать с CONNECT прокси aka HTTPS over HTTP прокси), на порту 3128
создается http:// прокси (может пропуска в т.ч. и HTTPS коннекты)
&copy; Vladimir Dubrovin, License: BSD style

View File

@ -1,4 +1,4 @@
<h3>Плагин подмены строк 3proxy</h3> <h3>Плагин подмены строк 3proxy</h3>
Используется, в частности, для руссификации сообщений выдаваемых 3proxy. Используется, в частности, для руссификации сообщений выдаваемых 3proxy.
Для корректной работы требуется 0.6 версия 3proxy. Для корректной работы требуется 0.6 версия 3proxy.

View File

@ -1,4 +1,4 @@
<h3>Плагин коррекции траффика 3proxy</h3> <h3>Плагин коррекции траффика 3proxy</h3>
Как известно, 3proxy считает траффик не сетевой, а прикладной. Как известно, 3proxy считает траффик не сетевой, а прикладной.
Обычно прикладной траффик немного меньше (примерно на 10%) чем сетевой, Обычно прикладной траффик немного меньше (примерно на 10%) чем сетевой,
однако в некоторых случаях, например когда пользователи сети играют в однако в некоторых случаях, например когда пользователи сети играют в

View File

@ -1,4 +1,4 @@
<h3>Плагин аутентификации Windows для 3proxy</h3> <h3>Плагин аутентификации Windows для 3proxy</h3>
Поддерживается только аутентификация открытым текстом в домене или на локальной машине Windows. Поддерживается только аутентификация открытым текстом в домене или на локальной машине Windows.
<h4>Использование</h4> <h4>Использование</h4>
<ol> <ol>

View File

@ -138,7 +138,7 @@ wget to automate this task.
configuration file configuration file
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .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(3), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8),
kill(1), syslogd(8), kill(1), syslogd(8),
@ -148,4 +148,4 @@ https://3proxy.org/
3APA3A is pronounced as \`\`zaraza\'\'. 3APA3A is pronounced as \`\`zaraza\'\'.
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -80,9 +80,18 @@ HTTP/HTTPS proxy (default port 3128)
.B socks .B socks
SOCKS 4/4.5/5 proxy (default port 1080) SOCKS 4/4.5/5 proxy (default port 1080)
.br .br
.B tlspr
SNI proxy (destination address is taken from TLS handshake), may be used to redirect any TLS-based traffic
.br
.B auto
Proxy with protocol autoselection between proxy / socks / tlspr
.br
.B pop3p .B pop3p
POP3 proxy (default port 110) POP3 proxy (default port 110)
.br .br
.B smtpp
SMTP proxy (default port 25)
.br
.B ftppr .B ftppr
FTP proxy (default port 21) FTP proxy (default port 21)
.br .br
@ -110,6 +119,8 @@ disable NTLM authentication (required if passwords are stored in Unix crypt form
.B -n1 .B -n1
enable NTLMv1 authentication. enable NTLMv1 authentication.
.br .br
.B -g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY)
delay GRACE_DELAY milliseconds before polling if average polling size below GRACE_TRAFF bytes and GRACE_NUM read operations in single directions are detected within 1 second. Useful to minimize polling
.B -s .B -s
(for admin) secure, allow only secure operations, currently only traffic counters (for admin) secure, allow only secure operations, currently only traffic counters
view without ability to reset. view without ability to reset.
@ -240,6 +251,8 @@ alternate config file. Think twice before using it.
@ (for Unix) use syslog, filename is used as ident name @ (for Unix) use syslog, filename is used as ident name
.br .br
& use ODBC, filename consists of comma-delimited datasource,username,password (username and password are optional) & use ODBC, filename consists of comma-delimited datasource,username,password (username and password are optional)
.br
radius - use RADIUS for logging
.br .br
LOGTYPE is one of: LOGTYPE is one of:
.br .br
@ -388,6 +401,28 @@ can use %A as produced archive name and %F as filename.
.br .br
default timeouts 1 5 30 60 180 1800 15 60 15 5 default timeouts 1 5 30 60 180 1800 15 60 15 5
.br
.B radius
<NAS_SECRET> <radius_server_1[:port][/local_address_1]> <radius_server_2[:port][/local_address_2]>
.br
Configures RADIUS servers to be used for logging and authentication (log and auth types
must be set to radius). port and local address to use with given server may be specified.
.br
Attributes within request: User-Name, Password: (username and password if presented by client),
Service Type: Authenticate-Only,
NAS-Port-Type: NAS-Port-Virtual,
NAS-Port-ID: (proxy service port, e.g. 1080),
NAS-IPv6-Address / NAS-IP-Address: (proxy interface accessed by client),
NAS-Identifier: (text identifing proxy, e.g. PROXY or SOCKSv5),
Framed-IPv6-Address / Framed-IP-Address: (IP address of the client),
Called-Station-ID: (requested Hostname, if presents),
Login-Service: (type of request, e.g. 1001 - SOCKS CONNECT, 1010 - HTTP GET, 1013 - HTTP CONNECT),
Login-TCP-Port: (requested port),
Login-IPv6-Host / Login-IP-Host: (requested IP).
.br
Supported reply attributes for authentication:
Framed-IP-Address / Framed-IPv6-Address (IP to assign to user), Reply-Message.
Use authcache to speedup authentication. RADIUS feature is currently experimental.
.br .br
.B nserver .B nserver
@ -456,8 +491,18 @@ External or -e can be given twice: once with IPv4 and once with IPv6 address.
.B maxconn .B maxconn
<number> <number>
.br .br
sets maximum number of simulationeous connections to each services sets maximum number of simulationeous connections to each service
started after this command. Default is 100. started after this command on network level. Default is 100.
.br
To limit clients, use connlim instead. maxconn will silently ignore
new connections, while connlim will report back to the client that
the connection limit has been reached.
.br
.B backlog
.br
sets the listening socket backlog of new connections. Default is
1 + maxconn/8. Maximum value is capped by kernel tunable somaxconn.
.br .br
.B service .B service
@ -503,6 +548,8 @@ NB: there is no any password check, name may be spoofed.
SOCKSv5, FTP, POP3 and HTTP proxy. SOCKSv5, FTP, POP3 and HTTP proxy.
.br .br
cache - cached authentication, may be used with \'authcache\'. cache - cached authentication, may be used with \'authcache\'.
.br
radius - authentication with RADIUS.
.br .br
Plugins may add additional authentication types. Plugins may add additional authentication types.
@ -656,14 +703,16 @@ connections. These 2 proxies form 1 group (summarized weight is 1000).
.br .br
creates chain of 3 proxies: 192.168.10.1, 192.168.20.1 and third creates chain of 3 proxies: 192.168.10.1, 192.168.20.1 and third
is (192.168.30.1 with probability of 0.3 or 192.168.40.1 is (192.168.30.1 with probability of 0.3 or 192.168.40.1
with probability of 0.7) for outgoing web connections. with probability of 0.7) for outgoing web connections. Chains are only applied to new connections, pipelined (keep-alive) requests in the same connection use the same chain.
.br .br
type is one of: type is one of:
.br
extip does not actully redirect request, it sets external address for this request to <ip>. It can be chained with another parent types. It's usefaul to set external IP based on ACL or make it random.
.br .br
tcp simply redirect connection. TCP is always last in chain. This type of proxy is a simple TCP redirection, it does not support parent authentication. tcp simply redirect connection. TCP is always last in chain. This type of proxy is a simple TCP redirection, it does not support parent authentication.
.br .br
http redirect to HTTP proxy. HTTP is always last chain. It should only be used with http (proxy) service, http redirect to HTTP proxy. HTTP is always the last chain. It should only be used with http (proxy) service,
if used with different service, it works as tcp redirection. if used with different service, it works as tcp redirection.
.br .br
pop3 redirect to POP3 proxy (only local redirection is supported, can only be used as a first hop in chaining) pop3 redirect to POP3 proxy (only local redirection is supported, can only be used as a first hop in chaining)
@ -1027,7 +1076,7 @@ corruption and/or Content-Length chaging. Default is 1MB (1048576).
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), syslogd(8),
.br .br
@ -1036,4 +1085,4 @@ Report all bugs to
3APA3A is pronounced as \`\`zaraza\'\'. 3APA3A is pronounced as \`\`zaraza\'\'.
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -77,11 +77,11 @@ is user\'s login on this FTP server. Login itself may contain \'@\' sign.
Only cleartext authentication is currently supported. Only cleartext authentication is currently supported.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), proxy(8), pop3p(8), socks(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), proxy(8), pop3p(8), socks(8), tcppm(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -1,80 +0,0 @@
.TH icqpr "8" "January 2019" "3proxy 0.9" "Universal proxy server"
.SH NAME
.B icqpr
\- ICQ (AOL OSCAR) proxy
.SH SYNOPSIS
.BR "icqpr " [ -d ]
.IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]]
.IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR]
.I local_port remote_host remote_port
.SH DESCRIPTION
.B icqpr
forwards ICQ connections from local to remote ICQ host. Most usual is
.B icqpr 5190 login.icq.com 5190
Also, icqpr adds UIN / AOL screen name as a username. It makes it possible
to control user's access to ICQ/AOL by UIN/screen name (use
.B auth useronly
in 3proxy).
.SH OPTIONS
.TP
.B -I
Inetd mode. Standalone service only.
.TP
.B -d
Daemonise. Detach service from console and run in the background.
.TP
.B -t
Be silenT. Do not log start/stop/accept error records.
.TP
.B -e
External address. IP address of interface proxy should initiate connections
from.
By default system will deside which address to use in accordance
with routing table.
.TP
.B -i
Internal address. IP address proxy accepts connections to.
By default connection to any interface is accepted. It\'s usually unsafe.
.TP
.B -l
Log. By default logging is to stdout. If
.I logfile
is specified logging is to file. Under Unix, if
.RI \' @ \'
preceeds
.IR logfile ,
syslog is used for logging.
.TP
.B -S
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes.
.SH ARGUMENTS
.TP
.I local_port
- port icqpr accepts connection
.TP
.I remote_host
- IP address of the host connection is forwarded to
.TP
.I remote_port
- remote port connection is forwarded to
.SH CLIENTS
You can use any ICQ/AOL client where server address configuration is supported
or spoof login server name (e.g. login.icq.com) with IP address of proxy server
via DNS record or hosts file. Transparent redirection is also possible. Use
.I internal_ip
and
.I local_port
as a destination in client application. Connection is forwarded to
.IR remote_host : remote_port
.SH BUGS
Report all bugs to
.BR 3proxy@3proxy.ru
.SH SEE ALSO
3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), udppm(8), syslogd(8),
.br
https://3proxy.org/
.SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru )

View File

@ -73,11 +73,11 @@ authentication (APOP, CRAM-MD5, etc) requires challenge from server before
we know which server to connect. we know which server to connect.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), ftppr(8), proxy(8), socks(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), ftppr(8), proxy(8), socks(8), tcppm(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -68,11 +68,11 @@ limit clients, use
instead. instead.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), ftppr(8), socks(8), pop3p(8), tcppm(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -74,11 +74,11 @@ authentication (CRAM-MD5, SPA, etc) requires challenge from server before
we know which server to connect. we know which server to connect.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), ftppr(8), proxy(8), socks(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), ftppr(8), proxy(8), socks(8), tcppm(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -74,11 +74,11 @@ sufficient privileges). If you need to control access use
instead. instead.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), proxy(8), ftppr(8), pop3p(8), tcppm(8), udppm(8), syslogd(8), 3proxy(8), proxy(8), ftppr(8), pop3p(8), tcppm(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -63,11 +63,11 @@ as a destination in client application. Connection is forwarded to
.IR remote_host : remote_port .IR remote_host : remote_port
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), udppm(8), syslogd(8), 3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

86
man/tlspr.8 Normal file
View File

@ -0,0 +1,86 @@
.TH tlspr "8" "May 2024" "3proxy 0.9" "Universal proxy server"
.SH NAME
.B tlspr
\- SNI proxy gateway service
.SH SYNOPSIS
.BR "tlspr " [ -d ][ -a ]
.IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]]
.IB \fR[ -p listening_port\fR]
.IB \fR[ -P destination_port\fR]
.IB \fR[ -c tls_check_level\fR]
.IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR]
.SH DESCRIPTION
.B proxy
is SNI gateway service (destination host is taken from TLS handshake). Destination port must be specified via -P option (or it may be detected with Transparent plugin).
.SH OPTIONS
.TP
.B -I
Inetd mode. Standalone service only.
.TP
.B -d
Daemonise. Detach service from console and run in the background.
.TP
.B -t
Be silenT. Do not log start/stop/accept error records.
.TP
.B -u
Never ask for username authentication
.TP
.B -e
External address. IP address of interface proxy should initiate connections
from.
By default system will deside which address to use in accordance
with routing table.
.TP
.B -i
Internal address. IP address proxy accepts connections to.
By default connection to any interface is accepted. It\'s usually unsafe.
.TP
.B -a
Anonymous. Hide information about client.
.TP
.B -a1
Anonymous. Show fake information about client.
.TP
.B -p
listening_port. Port proxy listens for incoming connections. Default is 1443.
.TP
.B -P
destination_port. Port to establish outgoing connections. One is required unless Transparent plugin is not used because TLS handshake does not contain port information. Default is 443.
.TP
.B -c
TLS_CHECK_LEVEL. 0 (default) - allow non-TLS traffic to pass, 1 - require TLS, only check client HELLO packet, 2 - require TLS, check both client and server HELLO, 3 - require TLS, check server send certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check server send certificate request and client sends certificate (not compatible with TLS 1.3)
.TP
.B -l
Log. By default logging is to stdout. If
.I logfile
is specified logging is to file. Under Unix, if
.RI \' @ \'
preceeds
.IR logfile ,
syslog is used for logging.
.TP
.B -S
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes.
.SH CLIENTS
You should use client with HTTP proxy support or configure router to redirect
HTTP traffic to proxy (transparent proxy). Configure client to connect to
.I internal_ip
and
.IR port .
HTTPS support allows to use almost any TCP based protocol. If you need to
limit clients, use
.BR 3proxy (8)
instead.
.SH BUGS
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy(8), ftppr(8), proxy(8), socks(8), pop3p(8), smtpp(8), tcppm(8), udppm(8), syslogd(8),
.br
https://3proxy.org/
.SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.org )

View File

@ -69,11 +69,11 @@ as a destination in client application. All datagrams are forwarded to
.IR remote_host : remote_port .IR remote_host : remote_port
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.ru .BR 3proxy@3proxy.org
.SH SEE ALSO .SH SEE ALSO
3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), udppm(8), syslogd(8), 3proxy(8), proxy(8), ftppr(8), socks(8), pop3p(8), udppm(8), syslogd(8),
.br .br
https://3proxy.org/ https://3proxy.org/
.SH AUTHORS .SH AUTHORS
3proxy is designed by Vladimir 3APA3A Dubrovin 3proxy is designed by Vladimir 3APA3A Dubrovin
.RI ( 3proxy@3proxy.ru ) .RI ( 3proxy@3proxy.org )

View File

@ -95,7 +95,7 @@ value {\n
[end] [end]
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\n <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\n
<pre><font size='-2'><b> <pre><font size='-2'><b>
(c)3APA3A, Владимир Дубровин и <A href='http://3proxy.ru/'>3proxy.ru</A>\n (c)3APA3A, Владимир Дубровин и <A href='https://3proxy.ru/'>3proxy.ru</A>\n
</b></font>\n </b></font>\n
</td></tr></table></body></html> </td></tr></table></body></html>
[end] [end]

View File

@ -83,7 +83,7 @@ GetLasestVersionInfo()
local Githublink local Githublink
local msg local msg
Githublink=`wget https://github.com/z3APA3A/3proxy/releases/latest -O /dev/stdout | Githublink=`wget https://github.com/3proxy/3proxy/releases/latest -O /dev/stdout |
awk '/<a.+href=.+\.tar\.gz/ { gsub("\"", "\n"); print; exit }' | awk '/<a.+href=.+\.tar\.gz/ { gsub("\"", "\n"); print; exit }' |
grep -e ".tar.gz"` grep -e ".tar.gz"`
if [ $? != 0 ] if [ $? != 0 ]

View File

@ -1,5 +1,4 @@
#!/bin/3proxy #!/bin/3proxy
daemon #daemon
pidfile /var/run/3proxy/3proxy.pid
chroot /usr/local/3proxy proxy proxy chroot /usr/local/3proxy proxy proxy
include /conf/3proxy.cfg include /conf/3proxy.cfg

19
scripts/3proxy.service Normal file
View File

@ -0,0 +1,19 @@
[Unit]
Description=3proxy tiny proxy server
Documentation=man:3proxy(1)
After=network.target
[Service]
Environment=CONFIGFILE=/etc/3proxy/3proxy.cfg
ExecStart=/bin/3proxy ${CONFIGFILE}
ExecReload=/bin/kill -SIGUSR1 $MAINPID
KillMode=process
Restart=on-failure
RestartSec=60s
LimitNOFILE=65536
LimitNPROC=32768
RuntimeDirectory=3proxy
[Install]
WantedBy=multi-user.target
Alias=3proxy.service

View File

@ -0,0 +1,10 @@
man/3proxy.8
man/3proxy.cfg.3
man/ftppr.8
man/pop3p.8
man/tlspr.8
man/proxy.8
man/smtpp.8
man/socks.8
man/tcppm.8
man/udppm.8

24
scripts/debian/changelog Normal file
View File

@ -0,0 +1,24 @@
3proxy (0.9.5-1) buster; urgency=medium
*3proxy 0.9.5 initial build
-- z3APA3A <3apa3a@3proxy.org> Sun, 09 Mar 2025 15:55:48 +0300
3proxy (0.9.4-1) buster; urgency=medium
*3proxy 0.9.4 initial build
-- z3APA3A <3apa3a@3proxy.org> Fri, 02 Jul 2021 00:47:00 +0300
3proxy (0.9.3-1) buster; urgency=medium
*3proxy 0.9.3 initial build
-- z3APA3A <3apa3a@3proxy.org> Thu, 03 Dec 2020 21:13:58 +0300
3proxy (0.9.2-1) buster; urgency=medium
*3proxy 0.9.2 initial build
-- z3APA3A <3apa3a@3proxy.org> Thu, 19 Nov 2020 19:19:19 +0300

1
scripts/debian/compat Normal file
View File

@ -0,0 +1 @@
9

4
scripts/debian/conffiles Normal file
View File

@ -0,0 +1,4 @@
/usr/local/3proxy/conf/3proxy.cfg
/usr/local/3proxy/conf/add3proxyuser.sh
/usr/local/3proxy/conf/bandlimiters
/usr/local/3proxy/conf/counters

18
scripts/debian/control Normal file
View File

@ -0,0 +1,18 @@
Source: 3proxy
Maintainer: z3APA3A <3apa3a@3proxy.org>
Section: net
Priority: optional
Standards-Version: 4.0.0
Build-Depends: debhelper (>=10)
Homepage: https://3proxy.org/
Vcs-Git: https://github.com/z3APA3A/3proxy
Vcs-Browser: https://github.com/z3APA3A/3proxy
Package: 3proxy
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: tiny free proxy server
3Proxy tiny free proxy server is really tiny freeware proxy servers set.
It includes HTTP proxy with HTTPS and FTP support, SOCKSv4/SOCKSv4.5/SOCKSv5 proxy (socks/socks.exe), POP3 proxy, SMTP proxy, FTP proxy, caching DNS proxy, TCP and UDP portmappers.
You can use every proxy as a standalone program (socks, proxy, tcppm, udppm, pop3p) or use combined program (3proxy). Combined proxy additionally supports features like access control, bandwidth limiting, limiting daily/weekly/monthly traffic amount, proxy chaining, log rotation, syslog and ODBC logging, etc.
It's created to be small, simple and yet very functional.

20
scripts/debian/copyright Normal file
View File

@ -0,0 +1,20 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: 3proxy
Upstream-Contact: 3proxy@3proxy.org
Source: https://3proxy.org/
Files: *
Copyright: 2000-2020 3APA3A, Vladimir Dubrovin, 3proxy.org
License: BSD-3-clause or Apache or GPL-2+ or LGPL-2+
Files: src/libs/md*.*
Copyright: 1990,1991,1992 RSA Data Security, Inc
License: public-domain
Files: src/libs/regex.*
Copyright: Henry Spencer
License: public-domain
Files: src/libs/smbdes.c
Copyright: Andrew Tridgell 1998
License: GPL-2+

43
scripts/debian/postinst Normal file
View File

@ -0,0 +1,43 @@
if [ ! -f /usr/local/3proxy/conf/passwd ]; then \
touch /usr/local/3proxy/conf/passwd;\
fi
chown -R proxy:proxy /usr/local/3proxy
chmod 550 /usr/local/3proxy/
chmod 550 /usr/local/3proxy/conf/
chmod 440 /usr/local/3proxy/conf/*
if /bin/systemctl >/dev/null 2>&1; then \
/usr/sbin/update-rc.d 3proxy disable || true; \
/usr/sbin/chkconfig 3proxy off || true; \
/bin/systemctl enable 3proxy.service; \
elif [ -x /usr/sbin/update-rc.d ]; then \
/usr/sbin/update-rc.d 3proxy defaults; \
/usr/sbin/update-rc.d 3proxy enable; \
elif [ -x /usr/sbin/chkconfig ]; then \
/usr/sbin/chkconfig 3proxy on; \
fi
echo ""
echo 3proxy installed.
if /bin/systemctl >/dev/null 2>&1; then \
/bin/systemctl stop 3proxy.service \
/bin/systemctl start 3proxy.service \
echo use ;\
echo " "systemctl start 3proxy.service ;\
echo to start proxy ;\
echo " "systemctl stop 3proxy.service ;\
echo to stop proxy ;\
elif [ -x /usr/sbin/service ]; then \
/usr/sbin/service 3proxy stop || true;\
/usr/sbin/service 3proxy start || true;\
echo " "service 3proxy start ;\
echo to start proxy ;\
echo " "service 3proxy stop ;\
echo to stop proxy ;\
fi
echo " "/usr/local/3proxy/conf/add3proxyuser.sh
echo to add users
echo ""
echo Default config uses Google\'s DNS.
echo It\'s recommended to use provider supplied DNS or install local recursor, e.g. pdns-recursor.
echo Configure preferred DNS in /usr/local/3proxy/conf/3proxy.cfg.
echo run \'/usr/local/3proxy/conf/add3proxyuser.sh admin password\' to configure \'admin\' user

4
scripts/debian/preinst Normal file
View File

@ -0,0 +1,4 @@
if [ -x /usr/sbin/useradd ]; then \
/usr/bin/getent group proxy >/dev/null || (/usr/sbin/groupadd -f -r proxy || true); \
/usr/bin/getent passwd proxy >/dev/null || (/usr/sbin/useradd -Mr -s /bin/false -g proxy -c 3proxy proxy || true); \
fi

16
scripts/debian/rules Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/make -f
%:
dh $@
override_dh_auto_build:
ln -s Makefile.Linux Makefile || true
dh_auto_build
override_dh_auto_clean:
find src/ -type f -name "*.o" -delete
find src/ -type f -name "Makefile.var" -delete
find bin/ -type f -executable -delete
rm -f Makefile
override_dh_usrlocal:

View File

@ -0,0 +1 @@
3.0 (quilt)

View File

@ -18,7 +18,7 @@ case "$1" in
echo Starting 3Proxy echo Starting 3Proxy
/bin/mkdir -p /var/run/3proxy /bin/mkdir -p /var/run/3proxy
/bin/3proxy /etc/3proxy/3proxy.cfg /bin/3proxy /etc/3proxy/3proxy.cfg &
RETVAL=$? RETVAL=$?
echo echo

127
scripts/rh/3proxy.spec Normal file
View File

@ -0,0 +1,127 @@
Name: 3proxy
Version: 0.9.5
Release: 1
Summary: 3proxy tiny proxy server
License: GPL/LGPL/Apache/BSD
URL: https://3proxy.org/
Vendor: 3proxy.org 3proxy@3proxy.org
Prefix: %{_prefix}
Packager: z3APA3A
Source: https://github.com/%{packager}/%{name}/archive/%{version}.tar.gz
%description
3proxy is lightweight yet powerful proxy server
%prep
%setup -q -n %{name}-%{version}
ln -s Makefile.Linux Makefile
%build
make
%install
make DESTDIR=%buildroot install
%clean
make clean
%files
/bin/3proxy
/bin/ftppr
/bin/mycrypt
/bin/pop3p
/bin/proxy
/bin/socks
/bin/tcppm
/bin/udppm
/bin/tlspr
%config(noreplace) /etc/3proxy/3proxy.cfg
/etc/3proxy/conf
/etc/init.d/3proxy
/usr/lib/systemd/system/3proxy.service
%config(noreplace) /usr/local/3proxy/conf/3proxy.cfg
%config(noreplace) /usr/local/3proxy/conf/add3proxyuser.sh
%config(noreplace) /usr/local/3proxy/conf/bandlimiters
%config(noreplace) /usr/local/3proxy/conf/counters
/usr/local/3proxy/libexec/PCREPlugin.ld.so
/usr/local/3proxy/libexec/StringsPlugin.ld.so
/usr/local/3proxy/libexec/TrafficPlugin.ld.so
/usr/local/3proxy/libexec/TransparentPlugin.ld.so
%if "%{_arch}" == "arm"
/usr/share/man/man3/3proxy.cfg.3
/usr/share/man/man8/3proxy.8
/usr/share/man/man8/ftppr.8
/usr/share/man/man8/pop3p.8
/usr/share/man/man8/proxy.8
/usr/share/man/man8/smtpp.8
/usr/share/man/man8/socks.8
/usr/share/man/man8/tcppm.8
/usr/share/man/man8/udppm.8
/usr/share/man/man8/tlspr.8
%else
/usr/share/man/man3/3proxy.cfg.3.gz
/usr/share/man/man8/3proxy.8.gz
/usr/share/man/man8/ftppr.8.gz
/usr/share/man/man8/pop3p.8.gz
/usr/share/man/man8/proxy.8.gz
/usr/share/man/man8/smtpp.8.gz
/usr/share/man/man8/socks.8.gz
/usr/share/man/man8/tcppm.8.gz
/usr/share/man/man8/udppm.8.gz
/usr/share/man/man8/tlspr.8.gz
%endif
/var/log/3proxy
%doc doc/*
%pre
if [ -x /usr/sbin/useradd ]; then \
/usr/bin/getent group proxy >/dev/null || (/usr/sbin/groupadd -f -r proxy || true); \
/usr/bin/getent passwd proxy >/dev/null || (/usr/sbin/useradd -Mr -s /bin/false -g proxy -c 3proxy proxy || true); \
fi
%post
if [ ! -f /usr/local/3proxy/conf/passwd ]; then \
touch /usr/local/3proxy/conf/passwd;\
fi
chown -R proxy:proxy /usr/local/3proxy
chmod 550 /usr/local/3proxy/
chmod 550 /usr/local/3proxy/conf/
chmod 440 /usr/local/3proxy/conf/*
if /bin/systemctl >/dev/null 2>&1; then \
/usr/sbin/update-rc.d 3proxy disable || true; \
/usr/sbin/chkconfig 3proxy off || true; \
/bin/systemctl enable 3proxy.service; \
elif [ -x /usr/sbin/update-rc.d ]; then \
/usr/sbin/update-rc.d 3proxy defaults; \
/usr/sbin/update-rc.d 3proxy enable; \
elif [ -x /usr/sbin/chkconfig ]; then \
/usr/sbin/chkconfig 3proxy on; \
fi
echo ""
echo 3proxy installed.
if /bin/systemctl >/dev/null 2>&1; then \
/bin/systemctl stop 3proxy.service \
/bin/systemctl start 3proxy.service \
echo use ;\
echo " "systemctl start 3proxy.service ;\
echo to start proxy ;\
echo " "systemctl stop 3proxy.service ;\
echo to stop proxy ;\
elif [ -x /usr/sbin/service ]; then \
/usr/sbin/service 3proxy stop || true;\
/usr/sbin/service 3proxy start || true;\
echo " "service 3proxy start ;\
echo to start proxy ;\
echo " "service 3proxy stop ;\
echo to stop proxy ;\
fi
echo " "/usr/local/3proxy/conf/add3proxyuser.sh
echo to add users
echo ""
echo Default config uses Google\'s DNS.
echo It\'s recommended to use provider supplied DNS or install local recursor, e.g. pdns-recursor.
echo Configure preferred DNS in /usr/local/3proxy/conf/3proxy.cfg.
echo run \'/usr/local/3proxy/conf/add3proxyuser.sh admin password\' to configure \'admin\' user

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -12,6 +12,11 @@
#ifndef NOPLUGINS #ifndef NOPLUGINS
#include <dlfcn.h> #include <dlfcn.h>
#endif #endif
#else
#ifdef WITH_SSL
#include <openssl/applink.c>
#endif
#endif #endif
#ifndef DEFAULTCONFIG #ifndef DEFAULTCONFIG
@ -516,6 +521,14 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
#ifndef NORADIUS #ifndef NORADIUS
pthread_mutex_init(&rad_mutex, NULL); pthread_mutex_init(&rad_mutex, NULL);
#endif #endif
#ifdef _WIN32
if(!CreatePipe(&conf.threadinit[0], &conf.threadinit[1], NULL, 1)){
#else
if(pipe(conf.threadinit)) {
#endif
fprintf(stderr, "CreatePipe failed\n");
return 1;
};
freeconf(&conf); freeconf(&conf);
res = readconfig(fp); res = readconfig(fp);

View File

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View File

@ -1,9 +1,8 @@
#include "src/version.h" #include "version.h"
1 VERSIONINFO 1 VERSIONINFO
FILEVERSION 0,9,0,0 FILEVERSION MAJOR3PROXY,SUBMAJOR3PROXY,MINOR3PROXY,SUBMINOR3PROXY
PRODUCTVERSION 0,9,0,0 PRODUCTVERSION MAJOR3PROXY,SUBMAJOR3PROXY,MINOR3PROXY,SUBMINOR3PROXY
FILETYPE 1 FILETYPE 1
FILESUBTYPE 0x0L FILESUBTYPE 0x0L
BEGIN BEGIN
@ -11,15 +10,15 @@ BEGIN
BEGIN BEGIN
BLOCK "040904E4" BLOCK "040904E4"
BEGIN BEGIN
VALUE "Comments", "3proxy - tiny proxy server, http://3proxy.org/\0" VALUE "Comments", "3proxy - tiny proxy server, https://3proxy.org/\0"
VALUE "CompanyName", "Vladimir Dubrovin\0" VALUE "CompanyName", "Vladimir Dubrovin\0"
VALUE "FileDescription", "3proxy - tiny proxy server\0" VALUE "FileDescription", "3proxy - tiny proxy server\0"
VALUE "FileVersion", "0.9-devel-" BUILDDATE "\0" VALUE "FileVersion", RELEASE3PROXY
VALUE "InternalName", "3proxy\0" VALUE "InternalName", "3proxy\0"
VALUE "LegalCopyright", "Copyright (C) 2002-2019 Vladimir Dubrovin\0" VALUE "LegalCopyright", "Copyright (C) 2002-" YEAR3PROXY " Vladimir Dubrovin\0"
VALUE "OriginalFilename", "3proxy.exe\0" VALUE "OriginalFilename", "3proxy.exe\0"
VALUE "ProductName", "3proxy\0" VALUE "ProductName", "3proxy\0"
VALUE "ProductVersion", "0.9-devel-" BUILDDATE "\0" VALUE "ProductVersion", RELEASE3PROXY
END END
END END
BLOCK "VarFileInfo" BLOCK "VarFileInfo"

View File

@ -2,7 +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)udppm$(EXESUFFICS) $(BUILDDIR)socks$(EXESUFFICS) $(BUILDDIR)proxy$(EXESUFFICS) allplugins 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
sockmap$(OBJSUFFICS): sockmap.c proxy.h structures.h sockmap$(OBJSUFFICS): sockmap.c proxy.h structures.h
@ -41,6 +41,10 @@ ftppr$(OBJSUFFICS): ftppr.c proxy.h structures.h proxymain.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 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 socks$(OBJSUFFICS): socks.c proxy.h structures.h proxymain.c
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP socks.c $(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)NOPORTMAP socks.c
@ -68,6 +72,9 @@ $(BUILDDIR)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetch
$(BUILDDIR)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)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)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)
$(LN) $(LNOUT)$(BUILDDIR)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(BUILDDIR)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(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)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
@ -91,6 +98,12 @@ srvftppr$(OBJSUFFICS): ftppr.c proxy.h structures.h
srvtcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h srvtcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h
$(CC) $(COUT)srvtcppm$(OBJSUFFICS) $(CFLAGS) tcppm.c $(CC) $(COUT)srvtcppm$(OBJSUFFICS) $(CFLAGS) tcppm.c
srvtlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h
$(CC) $(COUT)srvtlspr$(OBJSUFFICS) $(CFLAGS) tlspr.c
srvauto$(OBJSUFFICS): auto.c proxy.h structures.h
$(CC) $(COUT)srvauto$(OBJSUFFICS) $(CFLAGS) auto.c
srvsocks$(OBJSUFFICS): socks.c proxy.h structures.h srvsocks$(OBJSUFFICS): socks.c proxy.h structures.h
$(CC) $(COUT)srvsocks$(OBJSUFFICS) $(CFLAGS) socks.c $(CC) $(COUT)srvsocks$(OBJSUFFICS) $(CFLAGS) socks.c
@ -131,20 +144,12 @@ $(BUILDDIR)mycrypt$(EXESUFFICS): md4$(OBJSUFFICS) md5$(OBJSUFFICS) mycryptmain$(
md4$(OBJSUFFICS): libs/md4.h libs/md4.c md4$(OBJSUFFICS): libs/md4.h libs/md4.c
$(CC) $(COUT)md4$(OBJSUFFICS) $(CFLAGS) libs/md4.c $(CC) $(COUT)md4$(OBJSUFFICS) $(CFLAGS) libs/md4.c
smbdes$(OBJSUFFICS): libs/smbdes.c
$(CC) $(COUT)smbdes$(OBJSUFFICS) $(CFLAGS) libs/smbdes.c
md5$(OBJSUFFICS): libs/md5.h libs/md5.c md5$(OBJSUFFICS): libs/md5.h libs/md5.c
$(CC) $(COUT)md5$(OBJSUFFICS) $(CFLAGS) libs/md5.c $(CC) $(COUT)md5$(OBJSUFFICS) $(CFLAGS) libs/md5.c
ntlm$(OBJSUFFICS): ntlm.c
$(CC) $(COUT)ntlm$(OBJSUFFICS) $(CFLAGS) ntlm.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) 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) smbdes$(OBJSUFFICS) ntlm$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(COMPATLIBS) $(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)
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) authradius$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) mycrypt$(OBJSUFFICS) md5$(OBJSUFFICS) md4$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) smbdes$(OBJSUFFICS) ntlm$(OBJSUFFICS) stringtable$(OBJSUFFICS) srvwebadmin$(OBJSUFFICS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) $(COMPATLIBS) $(LIBS) $(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)
clean:
@$(REMOVECOMMAND) *$(OBJSUFFICS) $(COMPFILES)

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -22,6 +22,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
if (!param->srvbufsize){ if (!param->srvbufsize){
param->srvbufsize = SRVBUFSIZE; param->srvbufsize = SRVBUFSIZE;
param->srvbuf = myalloc(param->srvbufsize); param->srvbuf = myalloc(param->srvbufsize);
if(!param->srvbuf) return 21;
} }
buf = param->srvbuf; buf = param->srvbuf;
username = buf + 2048; username = buf + 2048;
@ -62,7 +63,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
len += sprintf((char *)buf + len, "\r\n"); len += sprintf((char *)buf + len, "\r\n");
} }
len += sprintf((char *)buf + len, "\r\n"); len += sprintf((char *)buf + len, "\r\n");
if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != (int)strlen((char *)buf)) if(socksend(param, param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != (int)strlen((char *)buf))
return 31; return 31;
param->statssrv64+=len; param->statssrv64+=len;
param->nwrites++; param->nwrites++;
@ -99,7 +100,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
memcpy(buf+len, hostname, hostnamelen); memcpy(buf+len, hostname, hostnamelen);
len += hostnamelen; len += hostnamelen;
} }
if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) < len){ if(socksend(param, param->remsock, buf, len, conf.timeouts[CHAIN_TO]) < len){
return 41; return 41;
} }
param->statssrv64+=len; param->statssrv64+=len;
@ -122,7 +123,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
buf[0] = 5; buf[0] = 5;
buf[1] = 1; buf[1] = 1;
buf[2] = user? 2 : 0; buf[2] = user? 2 : 0;
if(socksend(param->remsock, buf, 3, conf.timeouts[CHAIN_TO]) != 3){ if(socksend(param, param->remsock, buf, 3, conf.timeouts[CHAIN_TO]) != 3){
return 51; return 51;
} }
param->statssrv64+=len; param->statssrv64+=len;
@ -144,7 +145,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
buf[inbuf] = pass?(unsigned char)strlen((char *)pass):0; buf[inbuf] = pass?(unsigned char)strlen((char *)pass):0;
if(pass)memcpy(buf+inbuf+1, pass, buf[inbuf]); if(pass)memcpy(buf+inbuf+1, pass, buf[inbuf]);
inbuf += buf[inbuf] + 1; inbuf += buf[inbuf] + 1;
if(socksend(param->remsock, buf, inbuf, conf.timeouts[CHAIN_TO]) != inbuf){ if(socksend(param, param->remsock, buf, inbuf, conf.timeouts[CHAIN_TO]) != inbuf){
return 51; return 51;
} }
param->statssrv64+=inbuf; param->statssrv64+=inbuf;
@ -175,7 +176,7 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
} }
memcpy(buf+len, SAPORT(addr), 2); memcpy(buf+len, SAPORT(addr), 2);
len += 2; len += 2;
if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != len){ if(socksend(param, param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != len){
return 51; return 51;
} }
param->statssrv64+=len; param->statssrv64+=len;
@ -195,9 +196,10 @@ int clientnegotiate(struct chain * redir, struct clientparam * param, struct soc
break; break;
return 59; return 59;
case 3: case 3:
if (sockgetlinebuf(param, SERVER, buf, 256, 0, conf.timeouts[CHAIN_TO]) > 1) if (sockgetlinebuf(param, SERVER, buf, 1, EOF, conf.timeouts[CHAIN_TO]) != 1) return 59;
len = (unsigned char)buf[0];
if (sockgetlinebuf(param, SERVER, buf, len, EOF, conf.timeouts[CHAIN_TO]) != len) return 59;
break; break;
return 59;
case 4: case 4:
if (sockgetlinebuf(param, SERVER, buf, 18, EOF, conf.timeouts[CHAIN_TO]) == 18) if (sockgetlinebuf(param, SERVER, buf, 18, EOF, conf.timeouts[CHAIN_TO]) == 18)
break; break;
@ -220,6 +222,7 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
int weight = 1000; int weight = 1000;
int res; int res;
int done = 0; int done = 0;
int ha = 0;
struct chain * cur; struct chain * cur;
struct chain * redir = NULL; struct chain * redir = NULL;
int r2; int r2;
@ -253,10 +256,30 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
if(cur->type == R_EXTIP){ if(cur->type == R_EXTIP){
param->sinsl = cur->addr; param->sinsl = cur->addr;
if(SAISNULL(&param->sinsl))param->sinsl = param->sincr; if(SAISNULL(&param->sinsl))param->sinsl = param->sincr;
#ifndef NOIPV6
else if(cur->cidr && *SAFAMILY(&param->sinsl) == AF_INET6){
uint16_t c;
int i;
for(i = 0; i < 8; i++){
if(i==4)myrand(&param->sincr, sizeof(param->sincr));
else if(i==6) myrand(&param->req, sizeof(param->req));
if(i*16 >= cur->cidr) ((uint16_t *)SAADDR(&param->sinsl))[i] |= rand();
else if ((i+1)*16 > cur->cidr){
c = rand();
c >>= (cur->cidr - (i*16));
c |= ntohs(((uint16_t *)SAADDR(&param->sinsl))[i]);
((uint16_t *)SAADDR(&param->sinsl))[i] = htons(c);
}
}
}
#endif
if(cur->next)continue; if(cur->next)continue;
return 0; return 0;
} }
else if(SAISNULL(&cur->addr) && !*SAPORT(&cur->addr)){ else if(SAISNULL(&cur->addr) && !*SAPORT(&cur->addr)){
int i;
if(cur->extuser){ if(cur->extuser){
if(param->extusername) if(param->extusername)
myfree(param->extusername); myfree(param->extusername);
@ -268,24 +291,18 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
} }
if(*cur->extuser == '*' && !param->username) return 4; if(*cur->extuser == '*' && !param->username) return 4;
} }
switch(cur->type){
case R_POP3: for(i=0; redirs[i].name; i++){
param->redirectfunc = pop3pchild; if(cur->type == redirs[i].redir) {
param->redirectfunc = redirs[i].func;
break; break;
case R_FTP: }
param->redirectfunc = ftpprchild; }
break; if(cur->type == R_HA){
case R_ADMIN: ha = 1;
param->redirectfunc = adminchild;
break;
case R_SMTP:
param->redirectfunc = smtppchild;
break;
default:
param->redirectfunc = proxychild;
} }
if(cur->next)continue; if(cur->next)continue;
return 0; if(!ha) return 0;
} }
else if(!*SAPORT(&cur->addr) && !SAISNULL(&cur->addr)) { else if(!*SAPORT(&cur->addr) && !SAISNULL(&cur->addr)) {
unsigned short port = *SAPORT(&param->sinsr); unsigned short port = *SAPORT(&param->sinsr);
@ -298,7 +315,22 @@ int handleredirect(struct clientparam * param, struct ace * acentry){
} }
if((res = alwaysauth(param))){ if((res = alwaysauth(param))){
return (res == 10)? res : 60+res; return (res >= 10)? res : 60+res;
}
if(ha) {
char buf[128];
int len;
len = sprintf(buf, "PROXY %s ",
*SAFAMILY(&param->sincr) == AF_INET6 ? "TCP6" : "TCP4");
len += myinet_ntop(*SAFAMILY(&param->sincr), SAADDR(&param->sincr), buf+len, sizeof(param->sincr));
buf[len++] = ' ';
len += myinet_ntop(*SAFAMILY(&param->sincl), SAADDR(&param->sincl), buf+len, sizeof(param->sincl));
len += sprintf(buf + len, " %hu %hu\r\n",
ntohs(*SAPORT(&param->sincr)),
ntohs(*SAPORT(&param->sincl))
);
if(socksend(param, param->remsock, (unsigned char *)buf, len, conf.timeouts[CHAIN_TO])!=len) return 39;
return 0;
} }
} }
else { else {
@ -365,7 +397,7 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
} }
if(!ipentry) return 0; if(!ipentry) return 0;
} }
if((acentry->dst && !SAISNULL(&param->req)) || (acentry->dstnames && param->hostname)) { if((acentry->dst && (!SAISNULL(&param->req) || param->operation == UDPASSOC || param->operation==BIND)) || (acentry->dstnames && param->hostname)) {
for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next) for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next)
if(IPInentry((struct sockaddr *)&param->req, ipentry)) { if(IPInentry((struct sockaddr *)&param->req, ipentry)) {
break; break;
@ -413,7 +445,7 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
} }
if(!ipentry && !hstentry) return 0; if(!ipentry && !hstentry) return 0;
} }
if(acentry->ports && *SAPORT(&param->req)) { if(acentry->ports && (*SAPORT(&param->req) || param->operation == UDPASSOC || param->operation == BIND)) {
for (portentry = acentry->ports; portentry; portentry = portentry->next) for (portentry = acentry->ports; portentry; portentry = portentry->next)
if(ntohs(*SAPORT(&param->req)) >= portentry->startport && if(ntohs(*SAPORT(&param->req)) >= portentry->startport &&
ntohs(*SAPORT(&param->req)) <= portentry->endport) { ntohs(*SAPORT(&param->req)) <= portentry->endport) {
@ -455,6 +487,7 @@ int startconnlims (struct clientparam *param){
uint64_t rating; uint64_t rating;
int ret = 0; int ret = 0;
param->connlim = 1;
pthread_mutex_lock(&connlim_mutex); pthread_mutex_lock(&connlim_mutex);
for(ce = conf.connlimiter; ce; ce = ce->next) { for(ce = conf.connlimiter; ce; ce = ce->next) {
if(ACLmatches(ce->ace, param)){ if(ACLmatches(ce->ace, param)){
@ -505,6 +538,11 @@ void stopconnlims (struct clientparam *param){
static void initbandlims (struct clientparam *param){ static void initbandlims (struct clientparam *param){
struct bandlim * be; struct bandlim * be;
int i; 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) { for(i=0, be = conf.bandlimiter; be && i<MAXBANDLIMS; be = be->next) {
if(ACLmatches(be->ace, param)){ if(ACLmatches(be->ace, param)){
if(be->ace->action == NOBANDLIM) { if(be->ace->action == NOBANDLIM) {
@ -525,6 +563,7 @@ static void initbandlims (struct clientparam *param){
} }
} }
if(i<MAXBANDLIMS)param->bandlimsout[i] = NULL; if(i<MAXBANDLIMS)param->bandlimsout[i] = NULL;
param->bandlimver = conf.bandlimver;
} }
unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout){ unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout){
@ -550,14 +589,9 @@ unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nb
if(!nbytesin && !nbytesout) return 0; if(!nbytesin && !nbytesout) return 0;
pthread_mutex_lock(&bandlim_mutex); pthread_mutex_lock(&bandlim_mutex);
if(param->paused != conf.paused && param->bandlimver != conf.paused){ if(param->bandlimver != conf.bandlimver){
if(!conf.bandlimfunc){
param->bandlimfunc = NULL;
pthread_mutex_unlock(&bandlim_mutex);
return 0;
}
initbandlims(param); initbandlims(param);
param->bandlimver = conf.paused; param->bandlimver = conf.bandlimver;
} }
for(i=0; nbytesin&& i<MAXBANDLIMS && param->bandlims[i]; i++){ for(i=0; nbytesin&& i<MAXBANDLIMS && param->bandlims[i]; i++){
if( !param->bandlims[i]->basetime || if( !param->bandlims[i]->basetime ||
@ -574,7 +608,7 @@ unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nb
param->bandlims[i]->nexttime - now : 0; param->bandlims[i]->nexttime - now : 0;
sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime; sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
param->bandlims[i]->basetime = sec; param->bandlims[i]->basetime = sec;
param->bandlims[i]->nexttime = msec + nsleeptime + ((param->bandlims[i]->rate > 1000000)? ((nbytesin/32)*(256000000/param->bandlims[i]->rate)) : (nbytesin * (8000000/param->bandlims[i]->rate))); param->bandlims[i]->nexttime = msec + nsleeptime + ((nbytesin > 512)? ((nbytesin+32)/64)*(((64*8*1000000)/param->bandlims[i]->rate)) : ((nbytesin+1) * (8*1000000))/param->bandlims[i]->rate);
} }
for(i=0; nbytesout && i<MAXBANDLIMS && param->bandlimsout[i]; i++){ for(i=0; nbytesout && i<MAXBANDLIMS && param->bandlimsout[i]; i++){
if( !param->bandlimsout[i]->basetime || if( !param->bandlimsout[i]->basetime ||
@ -591,7 +625,7 @@ unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nb
param->bandlimsout[i]->nexttime - now : 0; param->bandlimsout[i]->nexttime - now : 0;
sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime; sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
param->bandlimsout[i]->basetime = sec; param->bandlimsout[i]->basetime = sec;
param->bandlimsout[i]->nexttime = msec + nsleeptime + ((param->bandlimsout[i]->rate > 1000000)? ((nbytesout/32)*(256000000/param->bandlimsout[i]->rate)) : (nbytesout * (8000000/param->bandlimsout[i]->rate))); 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);
} }
pthread_mutex_unlock(&bandlim_mutex); pthread_mutex_unlock(&bandlim_mutex);
return sleeptime/1000; return sleeptime/1000;
@ -604,30 +638,28 @@ void trafcountfunc(struct clientparam *param){
pthread_mutex_lock(&tc_mutex); pthread_mutex_lock(&tc_mutex);
for(tc = conf.trafcounter; tc; tc = tc->next) { for(tc = conf.trafcounter; tc; tc = tc->next) {
if(ACLmatches(tc->ace, param)){ if(ACLmatches(tc->ace, param)){
time_t t;
if(tc->ace->action == NOCOUNTIN || tc->ace->action == NOCOUNTALL) { if(tc->ace->action == NOCOUNTIN) {
countout = 1; countout = 1;
break; break;
} }
if(tc->ace->action != COUNTIN) { if(tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTIN && tc->ace->action != COUNTALL) {
countout = 1; countout = 1;
if(tc->ace->action != COUNTALL)continue; continue;
} }
tc->traf64 += param->statssrv64; tc->traf64 += param->statssrv64;
time(&t); tc->updated = conf.time;
tc->updated = t;
} }
} }
if(countout) for(tc = conf.trafcounter; tc; tc = tc->next) { if(countout) for(tc = conf.trafcounter; tc; tc = tc->next) {
if(ACLmatches(tc->ace, param)){ if(ACLmatches(tc->ace, param)){
time_t t;
if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break; if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTOUT && tc->ace->action != COUNTALL ) { if(tc->ace->action != COUNTOUT && tc->ace->action != COUNTALL ) {
continue; continue;
} }
tc->traf64 += param->statscli64; tc->traf64 += param->statscli64;
time(&t); tc->updated = conf.time;
tc->updated = t;
} }
} }
@ -640,20 +672,33 @@ int alwaysauth(struct clientparam * param){
int countout = 0; int countout = 0;
if(conf.connlimiter && param->remsock == INVALID_SOCKET && startconnlims(param)) return 95; if(conf.connlimiter && !param->connlim && startconnlims(param)) return 10;
res = doconnect(param); res = doconnect(param);
if(!res){ if(!res){
if(conf.bandlimfunc && (conf.bandlimiter||conf.bandlimiterout)){
pthread_mutex_lock(&bandlim_mutex);
initbandlims(param); initbandlims(param);
pthread_mutex_unlock(&bandlim_mutex);
}
if(conf.trafcountfunc && conf.trafcounter) {
pthread_mutex_lock(&tc_mutex);
for(tc = conf.trafcounter; tc; tc = tc->next) { for(tc = conf.trafcounter; tc; tc = tc->next) {
if(tc->disabled) continue; if(tc->disabled) continue;
if(ACLmatches(tc->ace, param)){ if(ACLmatches(tc->ace, param)){
if(tc->ace->action == NOCOUNTIN) break; if(tc->ace->action == NOCOUNTIN) {
countout = 1;
break;
}
if(tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTIN) { if(tc->ace->action != COUNTIN) {
countout = 1; countout = 1;
continue; if(tc->ace->action != COUNTALL) continue;
}
if(tc->traflim64 <= tc->traf64) {
pthread_mutex_unlock(&tc_mutex);
return 10;
} }
if(tc->traflim64 <= tc->traf64) return 10;
param->trafcountfunc = conf.trafcountfunc; param->trafcountfunc = conf.trafcountfunc;
param->maxtrafin64 = tc->traflim64 - tc->traf64; param->maxtrafin64 = tc->traflim64 - tc->traf64;
} }
@ -661,17 +706,20 @@ int alwaysauth(struct clientparam * param){
if(countout)for(tc = conf.trafcounter; tc; tc = tc->next) { if(countout)for(tc = conf.trafcounter; tc; tc = tc->next) {
if(tc->disabled) continue; if(tc->disabled) continue;
if(ACLmatches(tc->ace, param)){ if(ACLmatches(tc->ace, param)){
if(tc->ace->action == NOCOUNTOUT) break; if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break;
if(tc->ace->action != COUNTOUT) { if(tc->ace->action != COUNTOUT && tc->ace->action != COUNTALL) {
continue; continue;
} }
if(tc->traflim64 <= tc->traf64) {
if(tc->traflim64 <= tc->traf64) return 10; pthread_mutex_unlock(&tc_mutex);
return 10;
}
param->trafcountfunc = conf.trafcountfunc; param->trafcountfunc = conf.trafcountfunc;
param->maxtrafout64 = tc->traflim64 - tc->traf64; param->maxtrafout64 = tc->traflim64 - tc->traf64;
} }
} }
pthread_mutex_unlock(&tc_mutex);
}
} }
return res; return res;
} }
@ -688,6 +736,7 @@ int checkACL(struct clientparam * param){
param->weight = acentry->weight; param->weight = acentry->weight;
if(acentry->action == 2) { if(acentry->action == 2) {
struct ace dup; struct ace dup;
int res=60,i=0;
if(param->operation < 256 && !(param->operation & CONNECT)){ if(param->operation < 256 && !(param->operation & CONNECT)){
continue; continue;
@ -695,8 +744,17 @@ int checkACL(struct clientparam * param){
if(param->redirected && acentry->chains && SAISNULL(&acentry->chains->addr) && !*SAPORT(&acentry->chains->addr)) { if(param->redirected && acentry->chains && SAISNULL(&acentry->chains->addr) && !*SAPORT(&acentry->chains->addr)) {
continue; continue;
} }
if(param->remsock != INVALID_SOCKET) {
return 0;
}
for(; i < conf.parentretries; i++){
dup = *acentry; dup = *acentry;
return handleredirect(param, &dup); 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 acentry->action;
} }
@ -913,15 +971,6 @@ int strongauth(struct clientparam * param){
else if (!param->pwtype && param->password && !strcmp((char *)param->password, (char *)pwl->password)){ else if (!param->pwtype && param->password && !strcmp((char *)param->password, (char *)pwl->password)){
break; break;
} }
#ifndef NOCRYPT
else if (param->pwtype == 2 && param->password) {
ntpwdhash(buf, pwl->password, 0);
mschap(buf, param->password, buf + 16);
if(!memcmp(buf+16, param->password+8, 24)) {
break;
}
}
#endif
pthread_mutex_unlock(&pwl_mutex); pthread_mutex_unlock(&pwl_mutex);
return 6; return 6;
#ifndef NOCRYPT #ifndef NOCRYPT
@ -935,13 +984,6 @@ int strongauth(struct clientparam * param){
if(param->password && !param->pwtype && !memcmp(pwl->password, ntpwdhash(buf,param->password, 1), 32)) { if(param->password && !param->pwtype && !memcmp(pwl->password, ntpwdhash(buf,param->password, 1), 32)) {
break; break;
} }
else if (param->pwtype == 2){
fromhex(pwl->password, buf, 16);
mschap(buf, param->password, buf + 16);
if(!memcmp(buf + 16, param->password+8, 24)) {
break;
}
}
pthread_mutex_unlock(&pwl_mutex); pthread_mutex_unlock(&pwl_mutex);
return 8; return 8;
#endif #endif
@ -1186,10 +1228,10 @@ unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, un
usetcp = nservers[i].usetcp; usetcp = nservers[i].usetcp;
*SAFAMILY(sinsl) = *SAFAMILY(&nservers[i].addr); *SAFAMILY(sinsl) = *SAFAMILY(&nservers[i].addr);
} }
if((sock=so._socket(SASOCK(sinsl), usetcp?SOCK_STREAM:SOCK_DGRAM, usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) break; if((sock=so._socket(so.state, SASOCK(sinsl), usetcp?SOCK_STREAM:SOCK_DGRAM, usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) break;
if(so._bind(sock,(struct sockaddr *)sinsl,SASIZE(sinsl))){ if(so._bind(so.state, sock,(struct sockaddr *)sinsl,SASIZE(sinsl))){
so._shutdown(sock, SHUT_RDWR); so._shutdown(so.state, sock, SHUT_RDWR);
so._closesocket(sock); so._closesocket(so.state, sock);
break; break;
} }
if(makeauth && !SAISNULL(&authnserver.addr)){ if(makeauth && !SAISNULL(&authnserver.addr)){
@ -1199,9 +1241,9 @@ unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, un
*sinsr = nservers[i].addr; *sinsr = nservers[i].addr;
} }
if(usetcp){ if(usetcp){
if(connectwithpoll(sock,(struct sockaddr *)sinsr,SASIZE(sinsr),CONNECT_TO)) { if(connectwithpoll(NULL, sock,(struct sockaddr *)sinsr,SASIZE(sinsr),CONNECT_TO)) {
so._shutdown(sock, SHUT_RDWR); so._shutdown(so.state, sock, SHUT_RDWR);
so._closesocket(sock); so._closesocket(so.state, sock);
break; break;
} }
#ifdef TCP_NODELAY #ifdef TCP_NODELAY
@ -1241,15 +1283,15 @@ unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, un
len+=2; len+=2;
} }
if(socksendto(sock, (struct sockaddr *)sinsr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){ if(socksendto(NULL, sock, (struct sockaddr *)sinsr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
so._shutdown(sock, SHUT_RDWR); so._shutdown(so.state, sock, SHUT_RDWR);
so._closesocket(sock); so._closesocket(so.state, sock);
continue; continue;
} }
if(param) param->statscli64 += len; if(param) param->statscli64 += len;
len = sockrecvfrom(sock, (struct sockaddr *)sinsr, buf, 4096, conf.timeouts[DNS_TO]*1000); len = sockrecvfrom(NULL, sock, (struct sockaddr *)sinsr, buf, 4096, conf.timeouts[DNS_TO]*1000);
so._shutdown(sock, SHUT_RDWR); so._shutdown(so.state, sock, SHUT_RDWR);
so._closesocket(sock); so._closesocket(so.state, sock);
if(len <= 13) { if(len <= 13) {
continue; continue;
} }
@ -1259,7 +1301,7 @@ unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, un
us = ntohs(*(unsigned short*)buf); us = ntohs(*(unsigned short*)buf);
len-=2; len-=2;
buf+=2; buf+=2;
if(us > 4096 || us < len || (us > len && sockrecvfrom(sock, (struct sockaddr *)sinsr, buf+len, us-len, conf.timeouts[DNS_TO]*1000) != us-len)) { if(us > 4096 || us < len || (us > len && sockrecvfrom(NULL, sock, (struct sockaddr *)sinsr, buf+len, us-len, conf.timeouts[DNS_TO]*1000) != us-len)) {
continue; continue;
} }
} }
@ -1296,7 +1338,8 @@ unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, un
} }
ttl = ntohl(*(unsigned long *)(buf + k + 6)); ttl = ntohl(*(unsigned long *)(buf + k + 6));
memcpy(value, buf + k + 12, af == AF_INET6? 16:4); memcpy(value, buf + k + 12, af == AF_INET6? 16:4);
if(ttl < 60 || ttl > (3600*12)) ttl = 300; if(ttl < 0 || ttl > (3600*12)) ttl = 3600*12;
if(!ttl) ttl = 1;
hashadd(af == AF_INET6?&dns6_table:&dns_table, name, value, conf.time+ttl); hashadd(af == AF_INET6?&dns6_table:&dns_table, name, value, conf.time+ttl);
if(retttl) *retttl = ttl; if(retttl) *retttl = ttl;
return 1; return 1;

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2000-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2000-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -286,8 +286,6 @@ void random_vector(uint8_t *vector, struct clientparam *param)
} }
static float timeout = 5;
typedef struct radius_packet_t { typedef struct radius_packet_t {
uint8_t code; uint8_t code;
uint8_t id; uint8_t id;
@ -326,7 +324,7 @@ int radsend(struct clientparam * param, int auth, int stop){
char buf[64]; char buf[64];
if(!radiussecret || !nradservers) { if(!nradservers) {
return 4; return 4;
} }
@ -393,7 +391,7 @@ int radsend(struct clientparam * param, int auth, int stop){
/* NAS-Identifier */ /* NAS-Identifier */
if(conf.stringtable){ if(conf.stringtable){
*ptr++ = PW_NAS_IDENTIFIER; *ptr++ = PW_NAS_IDENTIFIER;
len = strlen(conf.stringtable[SERVICES+param->service]); len = strlen((char *)conf.stringtable[SERVICES+param->service]);
*ptr++ = (2 + len); *ptr++ = (2 + len);
memcpy(ptr, conf.stringtable[SERVICES+param->service], len); memcpy(ptr, conf.stringtable[SERVICES+param->service], len);
ptr += len; ptr += len;
@ -418,7 +416,7 @@ int radsend(struct clientparam * param, int auth, int stop){
/* Called-Station-ID */ /* Called-Station-ID */
if(param->hostname){ if(param->hostname){
*ptr++ = PW_CALLED_STATION_ID; *ptr++ = PW_CALLED_STATION_ID;
len = strlen(param->hostname); len = strlen((char *)param->hostname);
*ptr++ = (2 + len); *ptr++ = (2 + len);
memcpy(ptr, param->hostname, len); memcpy(ptr, param->hostname, len);
ptr += len; ptr += len;
@ -426,20 +424,18 @@ int radsend(struct clientparam * param, int auth, int stop){
} }
/* Login-Service */ /* Login-Service */
op = param->operation;
for(len=0; op; len++)op>>=1;
*ptr++ = PW_LOGIN_SERVICE; *ptr++ = PW_LOGIN_SERVICE;
*ptr++ = 4; *ptr++ = 6;
(*(uint16_t *)ptr)=htons((uint16_t)(len + 1000)); (*(uint32_t *)ptr)=htonl(param->operation<<8);
ptr+=2; ptr+=4;
total_length+=4; total_length+=6;
/* Login-TCP-Port */ /* Login-TCP-Port */
*ptr++ = PW_LOGIN_TCP_PORT; *ptr++ = PW_LOGIN_TCP_PORT;
*ptr++ = 4; *ptr++ = 6;
(*(uint16_t *)ptr)=*SAPORT(&param->req); (*(uint32_t *)ptr)=htonl((uint32_t)ntohs((*SAPORT(&param->req))));
ptr+=2; ptr+=4;
total_length+=4; total_length+=6;
if(*SAFAMILY(&param->req) == AF_INET6){ if(*SAFAMILY(&param->req) == AF_INET6){
@ -460,7 +456,7 @@ int radsend(struct clientparam * param, int auth, int stop){
/* Username */ /* Username */
if(param->username){ if(param->username){
len = strlen(param->username); len = strlen((char *)param->username);
if(len>128)len=128; if(len>128)len=128;
*ptr++ = PW_USER_NAME; *ptr++ = PW_USER_NAME;
*ptr++ = len + 2; *ptr++ = len + 2;
@ -503,12 +499,12 @@ int radsend(struct clientparam * param, int auth, int stop){
} }
if(auth && param->password){ if(auth && param->password){
len = strlen(param->password); len = strlen((char *)param->password);
if(len > 128) len = 128; if(len > 128) len = 128;
*ptr++ = PW_PASSWORD; *ptr++ = PW_PASSWORD;
ptr++; ptr++;
memcpy(ptr, param->password, len); memcpy(ptr, param->password, len);
rad_pwencode(ptr, rad_pwencode((char *)ptr,
&len, &len,
radiussecret, radiussecret,
(char *)packet.vector); (char *)packet.vector);
@ -545,8 +541,8 @@ int radsend(struct clientparam * param, int auth, int stop){
/* /*
if(auth) { if(auth) {
*/ */
if(sockfd >= 0) so._closesocket(sockfd); if(sockfd >= 0) so._closesocket(so.state, sockfd);
if ((sockfd = so._socket(SASOCK(&saremote), SOCK_DGRAM, 0)) < 0) { if ((sockfd = so._socket(so.state, SASOCK(&saremote), SOCK_DGRAM, 0)) < 0) {
return 4; return 4;
} }
remsock = sockfd; remsock = sockfd;
@ -554,7 +550,8 @@ int radsend(struct clientparam * param, int auth, int stop){
} }
else remsock = radiuslist[loop].logsock; else remsock = radiuslist[loop].logsock;
*/ */
len = so._sendto(remsock, (char *)&packet, total_length, 0, so._bind(so.state, remsock,(struct sockaddr *)&radiuslist[loop].localaddr,SASIZE(&radiuslist[loop].localaddr));
len = so._sendto(so.state, remsock, (char *)&packet, total_length, 0,
(struct sockaddr *)&saremote, sizeof(saremote)); (struct sockaddr *)&saremote, sizeof(saremote));
if(len != ntohs(packet.length)){ if(len != ntohs(packet.length)){
continue; continue;
@ -563,13 +560,13 @@ int radsend(struct clientparam * param, int auth, int stop){
memset(fds, 0, sizeof(fds)); memset(fds, 0, sizeof(fds));
fds[0].fd = remsock; fds[0].fd = remsock;
fds[0].events = POLLIN; fds[0].events = POLLIN;
if(so._poll(fds, 1, conf.timeouts[SINGLEBYTE_L]*1000) <= 0) { if(so._poll(so.state, fds, 1, conf.timeouts[SINGLEBYTE_L]*1000) <= 0) {
continue; continue;
} }
salen = sizeof(saremote); salen = sizeof(saremote);
data_len = so._recvfrom(remsock, (char *)&rpacket, sizeof(packet)-16, data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
0, (struct sockaddr *)&saremote, &salen); 0, (struct sockaddr *)&saremote, &salen);
@ -585,7 +582,7 @@ int radsend(struct clientparam * param, int auth, int stop){
continue; continue;
} }
if (calc_replydigest((char *)&rpacket, packet.vector, radiussecret, if (calc_replydigest((char *)&rpacket, (char *)packet.vector, radiussecret,
data_len) ){ data_len) ){
continue; continue;
} }
@ -651,13 +648,16 @@ int radsend(struct clientparam * param, int auth, int stop){
res = 4; res = 4;
} }
CLEANRET: CLEANRET:
if(sockfd >= 0) so._closesocket(sockfd); if(sockfd >= 0) so._closesocket(so.state, sockfd);
return res; return res;
} }
int radauth(struct clientparam * param){ int radauth(struct clientparam * param){
int res;
/*radsend(param, 0, 0);*/ /*radsend(param, 0, 0);*/
return radsend(param, 1, 0); res = radsend(param, 1, 0);
if(!res && param->srv->logfunc == logradius)radsend(param, 0, 0);
return res;
} }
void logradius(struct clientparam * param, const unsigned char *s) { void logradius(struct clientparam * param, const unsigned char *s) {

29
src/auto.c Normal file
View File

@ -0,0 +1,29 @@
/*
3APA3A simpliest proxy server
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement
*/
#include "proxy.h"
void * autochild(struct clientparam* param) {
int len;
if(!param->clibuf){
if(!(param->clibuf = myalloc(SRVBUFSIZE))) return 0;
param->clibufsize = SRVBUFSIZE;
param->clioffset = param->cliinbuf = 0;
}
len = sockfillbuffcli(param, 1, CONNECTION_S);
if (len != 1){
param->res = 801;
dolog(param, (unsigned char *)"");
}
if(*param->clibuf == 4 || *param->clibuf == 5) return sockschild(param);
if(*param->clibuf == 22) return tlsprchild(param);
return proxychild(param);
}

View File

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

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -93,6 +93,7 @@ char *rotations[] = {
struct extparam conf = { struct extparam conf = {
{0, 0},
{1, 5, 30, 60, 180, 1800, 15, 60, 15, 5, 0, 0}, {1, 5, 30, 60, 180, 1800, 15, 60, 15, 5, 0, 0},
NULL, NULL,
NULL, NULL,
@ -101,8 +102,9 @@ struct extparam conf = {
NULL, NULL,
NULL, NULL,
0, 0,
0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0,
0, 500, 0, 0, 0, 0, 0, 500, 0, 0, 0, 0, 0, 0, 2,
0, 0, 0,
6, 600, 6, 600,
1048576, 1048576,
NULL, NULL, NULL, NULL,
@ -137,13 +139,13 @@ char* NULLADDR="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
int myrand(void * entropy, int len){ int myrand(void * entropy, int len){
int i; int i;
unsigned short init; uint16_t init;
init = randomizer; init = randomizer;
for(i=0; i < len/2; i++){ for(i=0; i < len/2; i++){
init ^= ((unsigned short *)entropy)[i]; init ^= ((uint16_t *)entropy)[i];
} }
srand(init); srand(rand()+init);
randomizer = rand(); randomizer = rand();
return rand(); return rand();
@ -188,35 +190,141 @@ int
#endif #endif
#endif #endif
struct sockfuncs so = {
socket, #ifdef _WIN32
accept, SOCKET WINAPI def_socket(void* state, int domain, int type, int protocol){
bind, return socket(domain, type, protocol);
listen, }
connect, SOCKET WINAPI def_accept(void* state, SOCKET s, struct sockaddr * addr, int * addrlen){
getpeername, return accept(s, addr, addrlen);
getsockname, }
getsockopt, int WINAPI def_bind(void* state, SOCKET s, const struct sockaddr *addr, int addrlen){
setsockopt, return bind(s, addr, addrlen);
}
int WINAPI def_listen(void* state, SOCKET s, int backlog){
return listen(s, backlog);
}
int WINAPI def_connect(void* state, SOCKET s, const struct sockaddr *name, int namelen){
return connect(s, name, namelen);
}
int WINAPI def_getpeername(void* state, SOCKET s, struct sockaddr * name, int * namelen){
return getpeername(s, name, namelen);
}
int WINAPI def_getsockname(void* state, SOCKET s, struct sockaddr * name, int * namelen){
return getsockname(s, name, namelen);
}
int WINAPI def_getsockopt(void* state, SOCKET s, int level, int optname, char * optval, int * optlen){
return getsockopt(s, level, optname, optval, optlen);
}
int WINAPI def_setsockopt(void* state, SOCKET s, int level, int optname, const char *optval, int optlen){
return setsockopt(s, level, optname, optval, optlen);
}
int WINAPI def_poll(void* state, struct pollfd *fds, unsigned int nfds, int timeout){
#ifndef WITH_POLL #ifndef WITH_POLL
#ifndef WITH_WSAPOLL #ifndef WITH_WSAPOLL
mypoll, return mypoll(fds, nfds, timeout);
#else #else
WSAPoll, return WSAPoll(fds, nfds, timeout);
#endif #endif
#else #else
poll, return poll(fds, nfds, timeout);
#endif #endif
(void *)send, }
(void *)sendto, int WINAPI def_send(void* state, SOCKET s, const char *msg, int len, int flags){
(void *)recv, return send(s, msg, len, flags);
(void *)recvfrom, }
shutdown, int WINAPI def_sendto(void* state, SOCKET s, const char *msg, int len, int flags, const struct sockaddr *to, int tolen){
#ifdef _WIN32 return sendto(s, msg, len, flags, to, tolen);
closesocket }
int WINAPI def_recv(void* state, SOCKET s, char *buf, int len, int flags){
return recv(s, buf, len, flags);
}
int WINAPI def_recvfrom(void* state, SOCKET s, char * buf, int len, int flags, struct sockaddr * from, int * fromlen){
return recvfrom(s, buf, len, flags, from, fromlen);
}
int WINAPI def_shutdown(void* state, SOCKET s, int how){
return shutdown(s, how);
}
int WINAPI def_closesocket(void* state, SOCKET s){
return closesocket(s);
}
#else #else
close SOCKET def_socket(void* state, int domain, int type, int protocol){
return socket(domain, type, protocol);
}
SOCKET def_accept(void* state, SOCKET s, struct sockaddr * addr, socklen_t* addrlen){
return accept(s, addr, addrlen);
}
int def_bind(void* state, SOCKET s, const struct sockaddr *addr, socklen_t addrlen){
return bind(s, addr, addrlen);
}
int def_getpeername(void* state, SOCKET s, struct sockaddr * name, socklen_t* namelen){
return getpeername(s, name, namelen);
}
int def_getsockname(void* state, SOCKET s, struct sockaddr * name, socklen_t* namelen){
return getsockname(s, name, namelen);
}
int def_listen(void* state, SOCKET s, int backlog){
return listen(s, backlog);
}
int def_connect(void* state, SOCKET s, const struct sockaddr *name, socklen_t namelen){
return connect(s, name, namelen);
}
int def_getsockopt(void* state, SOCKET s, int level, int optname, void * optval, socklen_t * optlen){
return getsockopt(s, level, optname, optval, optlen);
}
int def_setsockopt(void* state, int s, int level, int optname, const void *optval, socklen_t optlen){
return setsockopt(s, level, optname, optval, optlen);
}
int def_poll(void* state, struct pollfd *fds, nfds_t nfds, int timeout){
#ifndef WITH_POLL
return mypoll(fds, nfds, timeout);
#else
return poll(fds, nfds, timeout);
#endif #endif
}
ssize_t def_send(void* state, SOCKET s, const void *msg, size_t len, int flags){
return send(s, msg, len, flags);
}
ssize_t def_sendto(void* state, SOCKET s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen){
return sendto(s, msg, len, flags, to, tolen);
}
ssize_t def_recv(void* state, SOCKET s, void *buf, size_t len, int flags){
return recv(s, buf, len, flags);
}
ssize_t def_recvfrom(void* state, SOCKET s, void * buf, size_t len, int flags, struct sockaddr * from, socklen_t* fromlen){
return recvfrom(s, buf, len, flags, from, fromlen);
}
int def_shutdown(void* state, SOCKET s, int how){
return shutdown(s, how);
}
int def_closesocket(void* state, SOCKET s){
return close(s);
}
#endif
struct sockfuncs so = {
NULL,
NULL,
def_socket,
def_accept,
def_bind,
def_listen,
def_connect,
def_getpeername,
def_getsockname,
def_getsockopt,
def_setsockopt,
def_poll,
def_send,
def_sendto,
def_recv,
def_recvfrom,
def_shutdown,
def_closesocket
}; };
#ifdef _WINCE #ifdef _WINCE
@ -293,7 +401,10 @@ int parsehostname(char *hostname, struct clientparam *param, unsigned short port
if(!hostname || !*hostname)return 2; if(!hostname || !*hostname)return 2;
if(*hostname == '[') se=strchr(hostname, ']'); if(*hostname == '[') se=strchr(hostname, ']');
if ( (sp = strchr(se?se:hostname, ':')) && !strchr(sp+1, ':')) *sp = 0; if ((sp = strchr(se?se:hostname, ':'))) {
if(strchr(sp+1, ':'))sp = NULL;
else *sp = 0;
}
if(se){ if(se){
*se = 0; *se = 0;
} }
@ -363,7 +474,7 @@ int parseconnusername(char *username, struct clientparam *param, int extpasswd,
} }
int connectwithpoll(SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){ int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
struct pollfd fds[1]; struct pollfd fds[1];
#ifdef _WIN32 #ifdef _WIN32
unsigned long ul = 1; unsigned long ul = 1;
@ -371,13 +482,14 @@ int connectwithpoll(SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
#else #else
fcntl(sock,F_SETFL, O_NONBLOCK | fcntl(sock,F_GETFL)); fcntl(sock,F_SETFL, O_NONBLOCK | fcntl(sock,F_GETFL));
#endif #endif
if(so._connect(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;
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|POLLIN;
if(so._poll(fds, 1, to*1000) <= 0) { 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)) {
return (13); return (13);
} }
return 0; return 0;
@ -395,7 +507,7 @@ int doconnect(struct clientparam * param){
return 0; return 0;
if (param->remsock != INVALID_SOCKET){ if (param->remsock != INVALID_SOCKET){
size = sizeof(param->sinsr); size = sizeof(param->sinsr);
if(so._getpeername(param->remsock, (struct sockaddr *)&param->sinsr, &size)==-1) {return (15);} if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)&param->sinsr, &size)==-1) {return (14);}
} }
else { else {
struct linger lg = {1,conf.timeouts[SINGLEBYTE_S]}; struct linger lg = {1,conf.timeouts[SINGLEBYTE_S]};
@ -408,30 +520,7 @@ 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=so._socket(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, IPPROTO_TCP)) == INVALID_SOCKET) {return (11);}
setopts(param->remsock, param->srv->srvsockopts);
so._setsockopt(param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
#ifdef REUSE
{
int opt;
#ifdef SO_REUSEADDR
opt = 1;
so._setsockopt(param->remsock, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(int));
#endif
#ifdef SO_REUSEPORT
opt = 1;
so._setsockopt(param->remsock, SOL_SOCKET, SO_REUSEPORT, (unsigned char *)&opt, sizeof(int));
#endif
}
#endif
#ifdef SO_BINDTODEVICE
if(param->srv->obindtodevice) {
if(so._setsockopt(param->remsock, SOL_SOCKET, SO_BINDTODEVICE, param->srv->obindtodevice, strlen(param->srv->obindtodevice) + 1))
return 12;
}
#endif
if(SAISNULL(&param->sinsl)){ if(SAISNULL(&param->sinsl)){
#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;
@ -440,17 +529,50 @@ int doconnect(struct clientparam * param){
param->sinsl = param->srv->extsa; param->sinsl = param->srv->extsa;
} }
*SAPORT(&param->sinsl) = 0; *SAPORT(&param->sinsl) = 0;
if(so._bind(param->remsock, (struct sockaddr*)&param->sinsl, SASIZE(&param->sinsl))==-1) { setopts(param->remsock, param->srv->srvsockopts);
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
#ifdef REUSE
{
int opt;
#ifdef SO_REUSEADDR
opt = 1;
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(int));
#endif
#ifdef SO_REUSEPORT
opt = 1;
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_REUSEPORT, (unsigned char *)&opt, sizeof(int));
#endif
}
#endif
#if defined SO_BINDTODEVICE
if(param->srv->obindtodevice) {
if(param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_BINDTODEVICE, param->srv->obindtodevice, strlen(param->srv->obindtodevice) + 1))
return 12;
}
#elif defined IP_BOUND_IF
if(param->srv->obindtodevice) {
int idx;
idx = if_nametoindex(param->srv->obindtodevice);
if(!idx || (*SAFAMILY(&param->sinsl) == AF_INET && param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IP, IP_BOUND_IF, &idx, sizeof(idx))))
return 12;
#ifndef NOIPV6
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
if(param->srv->so._bind(param->sostate, param->remsock, (struct sockaddr*)&param->sinsl, SASIZE(&param->sinsl))==-1) {
return 12; return 12;
} }
if(param->operation >= 256 || (param->operation & CONNECT)){ if(param->operation >= 256 || (param->operation & CONNECT)){
if(connectwithpoll(param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),CONNECT_TO)) { if(connectwithpoll(param, param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),CONNECT_TO)) {
return 13; return 13;
} }
} }
size = sizeof(param->sinsl); size = sizeof(param->sinsl);
if(so._getsockname(param->remsock, (struct sockaddr *)&param->sinsl, &size)==-1) {return (15);} if(param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&param->sinsl, &size)==-1) {return (15);}
} }
return 0; return 0;
} }
@ -594,7 +716,7 @@ unsigned long getip46(int family, unsigned char *name, struct sockaddr *sa){
if(detect != -1){ if(detect != -1){
if(family == 4 && detect != AF_INET) return 0; if(family == 4 && detect != AF_INET) return 0;
*SAFAMILY(sa) = (family == 6)? AF_INET6 : detect; *SAFAMILY(sa) = (family == 6)? AF_INET6 : detect;
return inet_pton(*SAFAMILY(sa), (char *)name, SAADDR(sa))? *SAFAMILY(sa) : 0; return inet_pton(*SAFAMILY(sa), (char *)name, SAADDR(sa))>0? *SAFAMILY(sa) : 0;
} }

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -150,8 +150,8 @@ int start_proxy_thread(struct child * chp){
#ifdef _WIN32 #ifdef _WIN32
HANDLE h; HANDLE h;
#endif #endif
char r[1];
conf.threadinit = 1;
#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);
@ -166,9 +166,16 @@ 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
while(conf.threadinit)usleep(SLEEPTIME); #ifdef _WIN32
ReadFile(conf.threadinit[0], r, 1, NULL, NULL);
#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\n", linenum); fprintf(stderr, "Service not started on line: %d%s\n", linenum, haveerror == 2? ": insufficient memory":"");
return(40); return(40);
} }
return 0; return 0;
@ -224,6 +231,13 @@ static int h_proxy(int argc, unsigned char ** argv){
} }
#endif #endif
} }
else if(!strcmp((char *)argv[0], "auto")) {
childdef.pf = autochild;
childdef.port = 8080;
childdef.isudp = 0;
childdef.service = S_AUTO;
childdef.helpmessage = "";
}
else if(!strcmp((char *)argv[0], "tcppm")) { else if(!strcmp((char *)argv[0], "tcppm")) {
childdef.pf = tcppmchild; childdef.pf = tcppmchild;
childdef.port = 0; childdef.port = 0;
@ -231,6 +245,13 @@ static int h_proxy(int argc, unsigned char ** argv){
childdef.service = S_TCPPM; childdef.service = S_TCPPM;
childdef.helpmessage = ""; childdef.helpmessage = "";
} }
else if(!strcmp((char *)argv[0], "tlspr")) {
childdef.pf = tlsprchild;
childdef.port = 1443;
childdef.isudp = 0;
childdef.service = S_TLSPR;
childdef.helpmessage = "";
}
else if(!strcmp((char *)argv[0], "udppm")) { else if(!strcmp((char *)argv[0], "udppm")) {
childdef.pf = udppmchild; childdef.pf = udppmchild;
childdef.port = 0; childdef.port = 0;
@ -308,8 +329,8 @@ static int h_log(int argc, unsigned char ** argv){
} }
#ifndef NOODBC #ifndef NOODBC
else if(*argv[1]=='&'){ else if(*argv[1]=='&'){
if(notchanged) return 0;
conf.logfunc = logsql; conf.logfunc = logsql;
if(notchanged) return 0;
pthread_mutex_lock(&log_mutex); pthread_mutex_lock(&log_mutex);
close_sql(); close_sql();
init_sql((char *)argv[1]+1); init_sql((char *)argv[1]+1);
@ -317,7 +338,7 @@ static int h_log(int argc, unsigned char ** argv){
} }
#endif #endif
#ifndef NORADIUS #ifndef NORADIUS
else if(!strcmp(argv[1],"radius")){ else if(!strcmp((char *)argv[1],"radius")){
conf.logfunc = logradius; conf.logfunc = logradius;
} }
#endif #endif
@ -372,6 +393,7 @@ static int h_daemon(int argc, unsigned char **argv){
static int h_config(int argc, unsigned char **argv){ static int h_config(int argc, unsigned char **argv){
if(conf.conffile)myfree(conf.conffile); if(conf.conffile)myfree(conf.conffile);
conf.conffile = mystrdup((char *)argv[1]); conf.conffile = mystrdup((char *)argv[1]);
if(!conf.conffile) return 21;
return 0; return 0;
} }
@ -403,7 +425,6 @@ static int h_archiver(int argc, unsigned char **argv){
static int h_counter(int argc, unsigned char **argv){ static int h_counter(int argc, unsigned char **argv){
struct counter_header ch1; struct counter_header ch1;
if(conf.counterd >=0)close(conf.counterd); if(conf.counterd >=0)close(conf.counterd);
if(!conf.trafcountfunc) conf.trafcountfunc = trafcountfunc;
conf.counterd = open((char *)argv[1], O_BINARY|O_RDWR|O_CREAT, 0660); conf.counterd = open((char *)argv[1], O_BINARY|O_RDWR|O_CREAT, 0660);
if(conf.counterd<0){ if(conf.counterd<0){
fprintf(stderr, "Unable to open counter file %s, line %d\n", argv[1], linenum); fprintf(stderr, "Unable to open counter file %s, line %d\n", argv[1], linenum);
@ -478,6 +499,9 @@ static int h_auth(int argc, unsigned char **argv){
for(au = authfuncs; au; au=au->next){ for(au = authfuncs; au; au=au->next){
if(!strcmp((char *)argv[argc], au->desc)){ if(!strcmp((char *)argv[argc], au->desc)){
newau = myalloc(sizeof(struct auth)); newau = myalloc(sizeof(struct auth));
if(!newau) {
return 21;
}
newau->next = conf.authfuncs; newau->next = conf.authfuncs;
conf.authfuncs = newau; conf.authfuncs = newau;
conf.authfuncs->desc = au->desc; conf.authfuncs->desc = au->desc;
@ -499,8 +523,7 @@ static int h_users(int argc, unsigned char **argv){
for (j = 1; j<argc; j++) { for (j = 1; j<argc; j++) {
if(!(pwl = myalloc(sizeof(struct passwords)))) { if(!(pwl = myalloc(sizeof(struct passwords)))) {
fprintf(stderr, "No memory for PWL entry, line %d\n", linenum); return(21);
return(1);
} }
memset(pwl, 0, sizeof(struct passwords)); memset(pwl, 0, sizeof(struct passwords));
@ -512,6 +535,7 @@ static int h_users(int argc, unsigned char **argv){
else { else {
*arg = 0; *arg = 0;
pwl->user = (unsigned char *)mystrdup((char *)argv[j]); pwl->user = (unsigned char *)mystrdup((char *)argv[j]);
if((arg[1] == 'C' && arg[2] == 'L' && (pwl->pwtype = CL)) || if((arg[1] == 'C' && arg[2] == 'L' && (pwl->pwtype = CL)) ||
(arg[1] == 'C' && arg[2] == 'R' && (pwl->pwtype = CR)) || (arg[1] == 'C' && arg[2] == 'R' && (pwl->pwtype = CR)) ||
(arg[1] == 'N' && arg[2] == 'T' && (pwl->pwtype = NT)) || (arg[1] == 'N' && arg[2] == 'T' && (pwl->pwtype = NT)) ||
@ -522,7 +546,9 @@ static int h_users(int argc, unsigned char **argv){
pwl->password = (unsigned char *) mystrdup((char *)arg + 1); pwl->password = (unsigned char *) mystrdup((char *)arg + 1);
pwl->pwtype = UN; pwl->pwtype = UN;
} }
if(!pwl->password) return 3;
} }
if(!pwl->user) return 21;
pthread_mutex_lock(&pwl_mutex); pthread_mutex_lock(&pwl_mutex);
pwl->next = conf.pwl; pwl->next = conf.pwl;
conf.pwl = pwl; conf.pwl = pwl;
@ -553,6 +579,14 @@ static int h_maxconn(int argc, unsigned char **argv){
return 0; return 0;
} }
static int h_backlog(int argc, unsigned char **argv){
conf.backlog = atoi((char *)argv[1]);
if(conf.maxchild < 0) {
return(1);
}
return 0;
}
static int h_flush(int argc, unsigned char **argv){ static int h_flush(int argc, unsigned char **argv){
freeacl(conf.acl); freeacl(conf.acl);
conf.acl = NULL; conf.acl = NULL;
@ -619,6 +653,15 @@ static int h_nscache(int argc, unsigned char **argv){
} }
return 0; return 0;
} }
static int h_parentretries(int argc, unsigned char **argv){
int res;
res = atoi((char *)argv[1]);
if(res > 0) conf.parentretries = res;
return 0;
}
static int h_nscache6(int argc, unsigned char **argv){ static int h_nscache6(int argc, unsigned char **argv){
int res; int res;
@ -679,21 +722,48 @@ static int h_monitor(int argc, unsigned char **argv){
struct filemon * fm; struct filemon * fm;
fm = myalloc(sizeof (struct filemon)); fm = myalloc(sizeof (struct filemon));
if(!fm) return 21;
if(stat((char *)argv[1], &fm->sb)){ if(stat((char *)argv[1], &fm->sb)){
myfree(fm); myfree(fm);
fprintf(stderr, "Warning: file %s doesn't exist on line %d\n", argv[1], linenum); fprintf(stderr, "Warning: file %s doesn't exist on line %d\n", argv[1], linenum);
} }
else { else {
fm->path = mystrdup((char *)argv[1]); fm->path = mystrdup((char *)argv[1]);
if(!fm->path) return 21;
fm->next = conf.fmon; fm->next = conf.fmon;
conf.fmon = fm; conf.fmon = fm;
} }
return 0; return 0;
} }
struct redirdesc redirs[] = {
{R_TCP, "tcp", tcppmchild},
{R_CONNECT, "connect", proxychild},
{R_SOCKS4, "socks4", sockschild},
{R_SOCKS5, "socks5", sockschild},
{R_HTTP, "http", proxychild},
{R_POP3, "pop3", pop3pchild},
{R_SMTP, "smtp", smtppchild},
{R_FTP, "ftp", ftpprchild},
{R_CONNECTP, "connect+", proxychild},
{R_SOCKS4P, "socks4+", sockschild},
{R_SOCKS5P, "socks5+", sockschild},
{R_SOCKS4B, "socks4b", sockschild},
{R_SOCKS5B, "socks5b", sockschild},
{R_ADMIN, "admin", adminchild},
{R_EXTIP, "extip", NULL},
{R_TLS, "tls", tlsprchild},
{R_HA, "ha", NULL},
{R_DNS, "dns", dnsprchild},
{0, NULL, NULL}
};
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;
int i;
acl = conf.acl; acl = conf.acl;
while(acl && acl->next) acl = acl->next; while(acl && acl->next) acl = acl->next;
@ -705,8 +775,7 @@ static int h_parent(int argc, unsigned char **argv){
chains = myalloc(sizeof(struct chain)); chains = myalloc(sizeof(struct chain));
if(!chains){ if(!chains){
fprintf(stderr, "Chainig error: unable to allocate memory for chain\n"); return(21);
return(2);
} }
memset(chains, 0, sizeof(struct chain)); memset(chains, 0, sizeof(struct chain));
chains->weight = (unsigned)atoi((char *)argv[1]); chains->weight = (unsigned)atoi((char *)argv[1]);
@ -714,31 +783,25 @@ static int h_parent(int argc, unsigned char **argv){
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);
return(3); return(3);
} }
if(!strcmp((char *)argv[2], "tcp"))chains->type = R_TCP; for(i = 0; redirs[i].name ; i++){
else if(!strcmp((char *)argv[2], "http"))chains->type = R_HTTP; if(!strcmp((char *)argv[2], redirs[i].name)) {
else if(!strcmp((char *)argv[2], "connect"))chains->type = R_CONNECT; chains->type = redirs[i].redir;
else if(!strcmp((char *)argv[2], "socks4"))chains->type = R_SOCKS4; break;
else if(!strcmp((char *)argv[2], "socks5"))chains->type = R_SOCKS5; }
else if(!strcmp((char *)argv[2], "connect+"))chains->type = R_CONNECTP; }
else if(!strcmp((char *)argv[2], "socks4+"))chains->type = R_SOCKS4P; if(!redirs[i].name) {
else if(!strcmp((char *)argv[2], "socks5+"))chains->type = R_SOCKS5P;
else if(!strcmp((char *)argv[2], "socks4b"))chains->type = R_SOCKS4B;
else if(!strcmp((char *)argv[2], "socks5b"))chains->type = R_SOCKS5B;
else if(!strcmp((char *)argv[2], "pop3"))chains->type = R_POP3;
else if(!strcmp((char *)argv[2], "ftp"))chains->type = R_FTP;
else if(!strcmp((char *)argv[2], "admin"))chains->type = R_ADMIN;
else if(!strcmp((char *)argv[2], "extip"))chains->type = R_EXTIP;
else if(!strcmp((char *)argv[2], "smtp"))chains->type = R_SMTP;
else {
fprintf(stderr, "Chaining error: bad chain type (%s)\n", argv[2]); fprintf(stderr, "Chaining error: bad chain type (%s)\n", argv[2]);
return(4); return(4);
} }
#ifndef NOIPV6 cidr = strchr((char *)argv[3], '/');
if(!getip46(46, argv[3], (struct sockaddr *)&chains->addr)) return 5; if(cidr) *cidr = 0;
#else if(!getip46(46, argv[3], (struct sockaddr *)&chains->addr)) return (5);
getip46(46, argv[3], (struct sockaddr *)&chains->addr);
#endif
chains->exthost = (unsigned char *)mystrdup((char *)argv[3]); chains->exthost = (unsigned char *)mystrdup((char *)argv[3]);
if(!chains->exthost) return 21;
if(cidr){
*cidr = '/';
chains->cidr = atoi(cidr + 1);
}
*SAPORT(&chains->addr) = htons((unsigned short)atoi((char *)argv[4])); *SAPORT(&chains->addr) = htons((unsigned short)atoi((char *)argv[4]));
if(argc > 5) chains->extuser = (unsigned char *)mystrdup((char *)argv[5]); if(argc > 5) chains->extuser = (unsigned char *)mystrdup((char *)argv[5]);
if(argc > 6) chains->extpass = (unsigned char *)mystrdup((char *)argv[6]); if(argc > 6) chains->extpass = (unsigned char *)mystrdup((char *)argv[6]);
@ -777,16 +840,23 @@ int scanipl(unsigned char *arg, struct iplist *dst){
#endif #endif
char * slash, *dash; char * slash, *dash;
int masklen, addrlen; int masklen, addrlen;
int res;
if((slash = strchr((char *)arg, '/'))) *slash = 0; if((slash = strchr((char *)arg, '/'))) *slash = 0;
if((dash = strchr((char *)arg,'-'))) *dash = 0; if((dash = strchr((char *)arg,'-'))) *dash = 0;
if(afdetect(arg) == -1) return 1; if(afdetect(arg) == -1) {
if(!getip46(46, arg, (struct sockaddr *)&sa)) return 1; if(slash)*slash = '/';
if(dash)*dash = '-';
return 1;
}
res = getip46(46, arg, (struct sockaddr *)&sa);
if(dash)*dash = '-';
if(!res) return 1;
memcpy(&dst->ip_from, SAADDR(&sa), SAADDRLEN(&sa)); memcpy(&dst->ip_from, SAADDR(&sa), SAADDRLEN(&sa));
dst->family = *SAFAMILY(&sa); dst->family = *SAFAMILY(&sa);
if(dash){ if(dash){
if(afdetect(dash+1) == -1) return 1; if(afdetect((unsigned char *)dash+1) == -1) return 1;
if(!getip46(46, (unsigned char *)dash+1, (struct sockaddr *)&sa)) return 2; if(!getip46(46, (unsigned char *)dash+1, (struct sockaddr *)&sa)) return 2;
memcpy(&dst->ip_to, SAADDR(&sa), SAADDRLEN(&sa)); memcpy(&dst->ip_to, SAADDR(&sa), SAADDRLEN(&sa));
if(*SAFAMILY(&sa) != dst->family || memcmp(&dst->ip_to, &dst->ip_from, SAADDRLEN(&sa)) < 0) return 3; if(*SAFAMILY(&sa) != dst->family || memcmp(&dst->ip_to, &dst->ip_from, SAADDRLEN(&sa)) < 0) return 3;
@ -794,6 +864,7 @@ int scanipl(unsigned char *arg, struct iplist *dst){
} }
memcpy(&dst->ip_to, &dst->ip_from, SAADDRLEN(&sa)); memcpy(&dst->ip_to, &dst->ip_from, SAADDRLEN(&sa));
if(slash){ if(slash){
*slash = '/';
addrlen = SAADDRLEN(&sa); addrlen = SAADDRLEN(&sa);
masklen = atoi(slash+1); masklen = atoi(slash+1);
if(masklen < 0 || masklen > (addrlen*8)) return 4; if(masklen < 0 || masklen > (addrlen*8)) return 4;
@ -843,6 +914,7 @@ struct ace * make_ace (int argc, unsigned char ** argv){
} }
memset(userl, 0, sizeof(struct userlist)); memset(userl, 0, sizeof(struct userlist));
userl->user=(unsigned char*)mystrdup((char *)arg); userl->user=(unsigned char*)mystrdup((char *)arg);
if(!userl->user) return NULL;
} while((arg = (unsigned char *)strtok((char *)NULL, ","))); } while((arg = (unsigned char *)strtok((char *)NULL, ",")));
} }
if(argc > 1 && strcmp("*", (char *)argv[1])) { if(argc > 1 && strcmp("*", (char *)argv[1])) {
@ -1136,11 +1208,11 @@ static int h_ace(int argc, unsigned char **argv){
switch(acl->action){ switch(acl->action){
case REDIRECT: case REDIRECT:
acl->chains = myalloc(sizeof(struct chain)); acl->chains = myalloc(sizeof(struct chain));
memset(acl->chains, 0, sizeof(struct chain));
if(!acl->chains) { if(!acl->chains) {
fprintf(stderr, "No memory for ACL entry, line %d\n", linenum); freeacl(acl);
return(2); return(21);
} }
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)) return 5;
*SAPORT(&acl->chains->addr) = htons((unsigned short)atoi((char *)argv[2])); *SAPORT(&acl->chains->addr) = htons((unsigned short)atoi((char *)argv[2]));
@ -1161,8 +1233,8 @@ static int h_ace(int argc, unsigned char **argv){
case NOCONNLIM: case NOCONNLIM:
ncl = myalloc(sizeof(struct connlim)); ncl = myalloc(sizeof(struct connlim));
if(!ncl) { if(!ncl) {
fprintf(stderr, "No memory to create connection limit filter\n"); freeacl(acl);
return(3); return(21);
} }
memset(ncl, 0, sizeof(struct connlim)); memset(ncl, 0, sizeof(struct connlim));
ncl->ace = acl; ncl->ace = acl;
@ -1188,14 +1260,16 @@ static int h_ace(int argc, unsigned char **argv){
nbl = myalloc(sizeof(struct bandlim)); nbl = myalloc(sizeof(struct bandlim));
if(!nbl) { if(!nbl) {
fprintf(stderr, "No memory to create band limit filter\n"); freeacl(acl);
return(3); return(21);
} }
memset(nbl, 0, sizeof(struct bandlim)); memset(nbl, 0, sizeof(struct bandlim));
nbl->ace = acl; nbl->ace = acl;
if(acl->action == BANDLIM) { if(acl->action == BANDLIM) {
sscanf((char *)argv[1], "%u", &nbl->rate); sscanf((char *)argv[1], "%u", &nbl->rate);
if(nbl->rate < 300) { if(nbl->rate < 300) {
myfree(nbl);
freeacl(acl);
fprintf(stderr, "Wrong bandwidth specified, line %d\n", linenum); fprintf(stderr, "Wrong bandwidth specified, line %d\n", linenum);
return(4); return(4);
} }
@ -1223,7 +1297,7 @@ static int h_ace(int argc, unsigned char **argv){
bli->next = nbl; bli->next = nbl;
} }
} }
conf.bandlimver++;
pthread_mutex_unlock(&bandlim_mutex); pthread_mutex_unlock(&bandlim_mutex);
break; break;
@ -1233,10 +1307,11 @@ static int h_ace(int argc, unsigned char **argv){
case NOCOUNTOUT: case NOCOUNTOUT:
case COUNTALL: case COUNTALL:
case NOCOUNTALL: case NOCOUNTALL:
if(!conf.trafcountfunc) conf.trafcountfunc = trafcountfunc;
tl = myalloc(sizeof(struct trafcount)); tl = myalloc(sizeof(struct trafcount));
if(!tl) { if(!tl) {
fprintf(stderr, "No memory to create traffic limit filter\n"); freeacl(acl);
return(5); return(21);
} }
memset(tl, 0, sizeof(struct trafcount)); memset(tl, 0, sizeof(struct trafcount));
tl->ace = acl; tl->ace = acl;
@ -1254,6 +1329,8 @@ static int h_ace(int argc, unsigned char **argv){
tl->type = getrotate(*argv[2]); tl->type = getrotate(*argv[2]);
tl->traflim64 = ((uint64_t)lim)*(1024*1024); tl->traflim64 = ((uint64_t)lim)*(1024*1024);
if(!tl->traflim64) { if(!tl->traflim64) {
myfree(tl);
freeacl(acl);
fprintf(stderr, "Wrong traffic limit specified, line %d\n", linenum); fprintf(stderr, "Wrong traffic limit specified, line %d\n", linenum);
return(6); return(6);
} }
@ -1326,16 +1403,22 @@ static int h_radius(int argc, unsigned char **argv){
} }
*/ */
memset(radiuslist, 0, sizeof(radiuslist)); memset(radiuslist, 0, sizeof(radiuslist));
if(strlen(argv[1]) > 63) argv[1][63] = 0; if(strlen((char *)argv[1]) > 63) argv[1][63] = 0;
strcpy(radiussecret, argv[1]); strcpy(radiussecret, (char *)argv[1]);
for( nradservers=0; nradservers < MAXRADIUS && nradservers < argc -2; nradservers++){ for( nradservers=0; nradservers < MAXRADIUS && nradservers < argc -2; nradservers++){
char *s = 0;
if((s=strchr((char *)argv[nradservers + 2], '/'))){
*s = 0;
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(!*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 = conf.intsa; bindaddr = radiuslist[nradservers].localaddr;
if ((radiuslist[nradservers].logsock = so._socket(SASOCK(&radiuslist[nradservers].logaddr), SOCK_DGRAM, 0)) < 0) return 2; 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; if (so._bind(radiuslist[nradservers].logsock, (struct sockaddr *)&bindaddr, SASIZE(&bindaddr))) return 3;
*/ */
@ -1473,6 +1556,7 @@ static int h_chroot(int argc, unsigned char **argv){
*p = 0; *p = 0;
} }
chrootp = mystrdup((char *)argv[1]); chrootp = mystrdup((char *)argv[1]);
if(!chrootp) return 21;
} }
if (gid && setregid(gid,gid)) { if (gid && setregid(gid,gid)) {
fprintf(stderr, "Unable to set gid %d", (int)gid); fprintf(stderr, "Unable to set gid %d", (int)gid);
@ -1520,7 +1604,7 @@ struct commands commandhandlers[]={
{commandhandlers+20, "logformat", h_logformat, 2, 2}, {commandhandlers+20, "logformat", h_logformat, 2, 2},
{commandhandlers+21, "timeouts", h_timeouts, 2, 0}, {commandhandlers+21, "timeouts", h_timeouts, 2, 0},
{commandhandlers+22, "auth", h_auth, 2, 0}, {commandhandlers+22, "auth", h_auth, 2, 0},
{commandhandlers+23, "users", h_users, 2, 0}, {commandhandlers+23, "users", h_users, 1, 0},
{commandhandlers+24, "maxconn", h_maxconn, 2, 2}, {commandhandlers+24, "maxconn", h_maxconn, 2, 2},
{commandhandlers+25, "flush", h_flush, 1, 1}, {commandhandlers+25, "flush", h_flush, 1, 1},
{commandhandlers+26, "nserver", h_nserver, 2, 2}, {commandhandlers+26, "nserver", h_nserver, 2, 2},
@ -1544,22 +1628,28 @@ struct commands commandhandlers[]={
{commandhandlers+44, "nocountin", h_ace, 1, 0}, {commandhandlers+44, "nocountin", h_ace, 1, 0},
{commandhandlers+45, "countout", h_ace, 4, 0}, {commandhandlers+45, "countout", h_ace, 4, 0},
{commandhandlers+46, "nocountout", h_ace, 1, 0}, {commandhandlers+46, "nocountout", h_ace, 1, 0},
{commandhandlers+47, "connlim", h_ace, 4, 0}, {commandhandlers+47, "countall", h_ace, 4, 0},
{commandhandlers+48, "noconnlim", h_ace, 1, 0}, {commandhandlers+48, "nocountall", h_ace, 1, 0},
{commandhandlers+49, "plugin", h_plugin, 3, 0}, {commandhandlers+49, "connlim", h_ace, 4, 0},
{commandhandlers+50, "logdump", h_logdump, 2, 3}, {commandhandlers+50, "noconnlim", h_ace, 1, 0},
{commandhandlers+51, "filtermaxsize", h_filtermaxsize, 2, 2}, {commandhandlers+51, "plugin", h_plugin, 3, 0},
{commandhandlers+52, "nolog", h_nolog, 1, 1}, {commandhandlers+52, "logdump", h_logdump, 2, 3},
{commandhandlers+53, "weight", h_nolog, 2, 2}, {commandhandlers+53, "filtermaxsize", h_filtermaxsize, 2, 2},
{commandhandlers+54, "authcache", h_authcache, 2, 3}, {commandhandlers+54, "nolog", h_nolog, 1, 1},
{commandhandlers+55, "smtpp", h_proxy, 1, 0}, {commandhandlers+55, "weight", h_nolog, 2, 2},
{commandhandlers+56, "delimchar",h_delimchar, 2, 2}, {commandhandlers+56, "authcache", h_authcache, 2, 3},
{commandhandlers+57, "authnserver", h_authnserver, 2, 2}, {commandhandlers+57, "smtpp", h_proxy, 1, 0},
{commandhandlers+58, "stacksize", h_stacksize, 2, 2}, {commandhandlers+58, "delimchar",h_delimchar, 2, 2},
{commandhandlers+59, "force", h_force, 1, 1}, {commandhandlers+59, "authnserver", h_authnserver, 2, 2},
{commandhandlers+60, "noforce", h_noforce, 1, 1}, {commandhandlers+60, "stacksize", h_stacksize, 2, 2},
{commandhandlers+61, "force", h_force, 1, 1},
{commandhandlers+62, "noforce", h_noforce, 1, 1},
{commandhandlers+63, "parentretries", h_parentretries, 2, 2},
{commandhandlers+64, "auto", h_proxy, 1, 0},
{commandhandlers+65, "backlog", h_backlog, 2, 2},
{commandhandlers+66, "tlspr", h_proxy, 1, 0},
#ifndef NORADIUS #ifndef NORADIUS
{commandhandlers+61, "radius", h_radius, 3, 0}, {commandhandlers+67, "radius", h_radius, 3, 0},
#endif #endif
{specificcommands, "", h_noop, 1, 0} {specificcommands, "", h_noop, 1, 0}
}; };
@ -1681,7 +1771,7 @@ int readconfig(FILE * fp){
argc = parsestr (buf, argv, NPARAMS-1, &buf, &inbuf, &bufsize); argc = parsestr (buf, argv, NPARAMS-1, &buf, &inbuf, &bufsize);
if(argc < 1) { if(argc < 1) {
fprintf(stderr, "Parse error line %d\n", linenum); fprintf(stderr, "Parse error line %d\n", linenum);
return(21); return(11);
} }
argv[argc] = NULL; argv[argc] = NULL;
if(!strcmp((char *)argv[0], "end") && argc == 1) { if(!strcmp((char *)argv[0], "end") && argc == 1) {
@ -1762,6 +1852,7 @@ void freeconf(struct extparam *confp){
confp->bandlimiter = NULL; confp->bandlimiter = NULL;
confp->bandlimiterout = NULL; confp->bandlimiterout = NULL;
confp->bandlimfunc = NULL; confp->bandlimfunc = NULL;
confp->bandlimver++;
pthread_mutex_unlock(&bandlim_mutex); pthread_mutex_unlock(&bandlim_mutex);
pthread_mutex_lock(&connlim_mutex); pthread_mutex_lock(&connlim_mutex);
cl = confp->connlimiter; cl = confp->connlimiter;
@ -1803,6 +1894,7 @@ void freeconf(struct extparam *confp){
*SAFAMILY(&confp->intsa) = AF_INET; *SAFAMILY(&confp->intsa) = AF_INET;
*SAFAMILY(&confp->extsa) = AF_INET; *SAFAMILY(&confp->extsa) = AF_INET;
confp->maxchild = 100; confp->maxchild = 100;
confp->backlog = 0;
resolvfunc = NULL; resolvfunc = NULL;
numservers = 0; numservers = 0;
acl = confp->acl; acl = confp->acl;
@ -1855,6 +1947,7 @@ int reload (void){
FILE *fp; FILE *fp;
int error = -2; int error = -2;
pthread_mutex_lock(&config_mutex);
conf.paused++; conf.paused++;
freeconf(&conf); freeconf(&conf);
conf.paused++; conf.paused++;
@ -1868,5 +1961,6 @@ int reload (void){
} }
if(!writable)fclose(fp); if(!writable)fclose(fp);
} }
pthread_mutex_unlock(&config_mutex);
return error; return error;
} }

View File

@ -1,5 +1,5 @@
/* /*
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -325,24 +325,12 @@ static void * ef_chain_next(struct node * node){
} }
static void * ef_chain_type(struct node * node){ static void * ef_chain_type(struct node * node){
switch (((struct chain *)node->value) -> type) { int i;
case R_TCP:
return "tcp"; for(i=0; redirs[i].name; i++){
case R_CONNECT: if(((struct chain *)node->value) -> type == redirs[i].redir) return redirs[i].name;
return "connect";
case R_SOCKS4:
return "socks4";
case R_SOCKS5:
return "socks5";
case R_HTTP:
return "http";
case R_FTP:
return "ftp";
case R_POP3:
return "pop3";
default:
return "";
} }
return "";
} }
static void * ef_chain_addr(struct node * node){ static void * ef_chain_addr(struct node * node){
@ -365,32 +353,11 @@ static void * ef_ace_next(struct node * node){
return ((struct ace *)node->value) -> next; return ((struct ace *)node->value) -> next;
} }
char * aceaction (int action);
static void * ef_ace_type(struct node * node){ static void * ef_ace_type(struct node * node){
switch (((struct ace *)node->value) -> action) { return aceaction(((struct ace *)node->value) -> action);
case ALLOW:
case REDIRECT:
return "allow";
case DENY:
return "deny";
case BANDLIM:
return "bandlim";
case NOBANDLIM:
return "nobandlim";
case COUNTIN:
return "countin";
case NOCOUNTIN:
return "nocountin";
case COUNTOUT:
return "countout";
case NOCOUNTOUT:
return "nocountout";
case COUNTALL:
return "countall";
case NOCOUNTALL:
return "nocountall";
default:
return "unknown";
}
} }

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -39,16 +39,16 @@ void * dnsprchild(struct clientparam* param) {
} }
buf = bbuf+2; buf = bbuf+2;
size = sizeof(param->sincr); size = sizeof(param->sincr);
i = so._recvfrom(param->srv->srvsock, (char *)buf, BUFSIZE, 0, (struct sockaddr *)&param->sincr, &size); i = param->srv->so._recvfrom(param->sostate, param->srv->srvsock, (char *)buf, BUFSIZE, 0, (struct sockaddr *)&param->sincr, &size);
size = sizeof(param->sinsl); size = sizeof(param->sinsl);
getsockname(param->srv->srvsock, (struct sockaddr *)&param->sincl, &size); getsockname(param->srv->srvsock, (struct sockaddr *)&param->sincl, &size);
#ifdef _WIN32 #ifdef _WIN32
if((param->clisock=so._socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { if((param->clisock=param->srv->so._socket(param->sostate, AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
RETURN(818); RETURN(818);
} }
ioctlsocket(param->clisock, FIONBIO, &ul); ioctlsocket(param->clisock, FIONBIO, &ul);
if(so._setsockopt(param->clisock, SOL_SOCKET, SO_REUSEADDR, (char *)&ul, sizeof(int))) {RETURN(820);}; if(param->srv->so._setsockopt(param->sostate, param->clisock, SOL_SOCKET, SO_REUSEADDR, (char *)&ul, sizeof(int))) {RETURN(820);};
if(so._bind(param->clisock,(struct sockaddr *)&param->sincl,SASIZE(&param->sincl))) { if(param->srv->so._bind(param->sostate, param->clisock,(struct sockaddr *)&param->sincl,SASIZE(&param->sincl))) {
RETURN(822); RETURN(822);
} }
@ -130,17 +130,17 @@ void * dnsprchild(struct clientparam* param) {
else ip = 0; else ip = 0;
} }
if(!ip && numservers){ if(!ip && numservers){
if((param->remsock=so._socket(SASOCK(&nservers[0].addr), nservers[0].usetcp? SOCK_STREAM:SOCK_DGRAM, nservers[0].usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) { if((param->remsock=param->srv->so._socket(param->sostate, SASOCK(&nservers[0].addr), nservers[0].usetcp? SOCK_STREAM:SOCK_DGRAM, nservers[0].usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) {
RETURN(818); RETURN(818);
} }
memset(&param->sinsl, 0, sizeof(param->sinsl)); memset(&param->sinsl, 0, sizeof(param->sinsl));
*SAFAMILY(&param->sinsl) = *SAFAMILY(&nservers[0].addr); *SAFAMILY(&param->sinsl) = *SAFAMILY(&nservers[0].addr);
if(so._bind(param->remsock,(struct sockaddr *)&param->sinsl,SASIZE(&param->sinsl))) { if(param->srv->so._bind(param->sostate, param->remsock,(struct sockaddr *)&param->sinsl,SASIZE(&param->sinsl))) {
RETURN(819); RETURN(819);
} }
param->sinsr = nservers[0].addr; param->sinsr = nservers[0].addr;
if(nservers[0].usetcp) { if(nservers[0].usetcp) {
if(connectwithpoll(param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),CONNECT_TO)) RETURN(830); if(connectwithpoll(param, param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),CONNECT_TO)) RETURN(830);
buf-=2; buf-=2;
*(unsigned short*)buf = htons(i); *(unsigned short*)buf = htons(i);
i+=2; i+=2;
@ -153,12 +153,12 @@ void * dnsprchild(struct clientparam* param) {
#endif #endif
} }
if(socksendto(param->remsock, (struct sockaddr *)&param->sinsr, buf, i, conf.timeouts[SINGLEBYTE_L]*1000) != i){ if(socksendto(param, param->remsock, (struct sockaddr *)&param->sinsr, buf, i, conf.timeouts[SINGLEBYTE_L]*1000) != i){
RETURN(820); RETURN(820);
} }
param->statscli64 += i; param->statscli64 += i;
param->nwrites++; param->nwrites++;
len = sockrecvfrom(param->remsock, (struct sockaddr *)&param->sinsr, buf, BUFSIZE, conf.timeouts[DNS_TO]*1000); len = sockrecvfrom(param, param->remsock, (struct sockaddr *)&param->sinsr, buf, BUFSIZE, conf.timeouts[DNS_TO]*1000);
if(len <= 13) { if(len <= 13) {
RETURN(821); RETURN(821);
} }
@ -174,7 +174,7 @@ void * dnsprchild(struct clientparam* param) {
if(len != us) RETURN(832); if(len != us) RETURN(832);
} }
if(buf[6] || buf[7]){ if(buf[6] || buf[7]){
if(socksendto(param->clisock, (struct sockaddr *)&param->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){ if(socksendto(param, param->clisock, (struct sockaddr *)&param->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
RETURN(822); RETURN(822);
} }
RETURN(0); RETURN(0);
@ -185,7 +185,7 @@ void * dnsprchild(struct clientparam* param) {
buf[2] = 0x85; buf[2] = 0x85;
buf[3] = 0x83; buf[3] = 0x83;
} }
res = socksendto(param->clisock, (struct sockaddr *)&param->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000); res = socksendto(param, param->clisock, (struct sockaddr *)&param->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000);
if(res != len){RETURN(819);} if(res != len){RETURN(819);}
if(!ip) {RETURN(888);} if(!ip) {RETURN(888);}

View File

@ -1,5 +1,5 @@
/* /*
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -29,7 +29,7 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
return 702; return 702;
} }
sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous"); sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous");
if((int)socksend(param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){ if((int)socksend(param, param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){
return 703; return 703;
} }
param->statscli64 += (int)strlen(buf); param->statscli64 += (int)strlen(buf);
@ -46,7 +46,7 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
param->extpassword:(unsigned char *)"") param->extpassword:(unsigned char *)"")
:(unsigned char *)"3proxy@"); :(unsigned char *)"3proxy@");
res = (int)strlen(buf); res = (int)strlen(buf);
if((int)socksend(param->remsock, (unsigned char *)buf, res, conf.timeouts[STRING_S]) != (int)strlen(buf)){ if((int)socksend(param, param->remsock, (unsigned char *)buf, res, conf.timeouts[STRING_S]) != (int)strlen(buf)){
return 705; return 705;
} }
param->statscli64 += res; param->statscli64 += res;
@ -77,7 +77,7 @@ int ftpcd(struct clientparam *param, unsigned char* path, char *nbuf, int *innbu
int inbuf = 0; int inbuf = 0;
sprintf(buf, "CWD %.512s\r\n", path); sprintf(buf, "CWD %.512s\r\n", path);
if((int)socksend(param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){ if((int)socksend(param, param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){
return 711; return 711;
} }
param->statscli64 += (int)strlen(buf); param->statscli64 += (int)strlen(buf);
@ -110,7 +110,7 @@ int ftpres(struct clientparam *param, unsigned char * buf, int l){
int ftpsyst(struct clientparam *param, unsigned char *buf, unsigned len){ int ftpsyst(struct clientparam *param, unsigned char *buf, unsigned len){
int i; int i;
if(socksend(param->remsock, (unsigned char *)"SYST\r\n", 6, conf.timeouts[STRING_S]) != 6){ if(socksend(param, param->remsock, (unsigned char *)"SYST\r\n", 6, conf.timeouts[STRING_S]) != 6){
return 721; return 721;
} }
param->statscli64 += 6; param->statscli64 += 6;
@ -121,7 +121,7 @@ int ftpsyst(struct clientparam *param, unsigned char *buf, unsigned len){
buf[3] = 0; buf[3] = 0;
if(atoi((char *)buf)/100 != 2) return 723; if(atoi((char *)buf)/100 != 2) return 723;
buf[i-2] = 0; buf[i-2] = 0;
strcpy((char *)buf, (char *)buf+4); memmove((char *)buf, (char *)buf+4, strlen((char *)buf+4)+1);
return 0; return 0;
} }
@ -129,7 +129,7 @@ int ftppwd(struct clientparam *param, unsigned char *buf, unsigned len){
int i; int i;
char *b, *e; char *b, *e;
if(socksend(param->remsock, (unsigned char *)"PWD\r\n", 5, conf.timeouts[STRING_S]) != 5){ if(socksend(param, param->remsock, (unsigned char *)"PWD\r\n", 5, conf.timeouts[STRING_S]) != 5){
return 731; return 731;
} }
param->statscli64 += 5; param->statscli64 += 5;
@ -145,7 +145,7 @@ int ftppwd(struct clientparam *param, unsigned char *buf, unsigned len){
b++; b++;
*e = 0; *e = 0;
} }
strcpy((char *)buf, b); memmove((char *)buf, b, strlen(b)+1);
return 0; return 0;
} }
@ -154,7 +154,7 @@ int ftptype(struct clientparam *param, unsigned char* f_type){
int i; int i;
sprintf(buf, "TYPE %.512s\r\n", f_type); sprintf(buf, "TYPE %.512s\r\n", f_type);
if((int)socksend(param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){ if((int)socksend(param, param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){
return 741; return 741;
} }
param->statscli64 += (int)strlen(buf); param->statscli64 += (int)strlen(buf);
@ -176,7 +176,7 @@ SOCKET ftpdata(struct clientparam *param){
unsigned short b5, b6; unsigned short b5, b6;
SASIZETYPE sasize; SASIZETYPE sasize;
if(socksend(param->remsock, (unsigned char *)"PASV\r\n", 6, conf.timeouts[STRING_S]) != 6){ if(socksend(param, param->remsock, (unsigned char *)"PASV\r\n", 6, conf.timeouts[STRING_S]) != 6){
return INVALID_SOCKET; return INVALID_SOCKET;
} }
param->statscli64 += 6; param->statscli64 += 6;
@ -189,9 +189,9 @@ SOCKET ftpdata(struct clientparam *param){
if(!(sb = strchr(buf+4, '(')) || !(se= strchr(sb, ')'))) return INVALID_SOCKET; if(!(sb = strchr(buf+4, '(')) || !(se= strchr(sb, ')'))) return INVALID_SOCKET;
if(sscanf(sb+1, "%lu,%lu,%lu,%lu,%hu,%hu", &b1, &b2, &b3, &b4, &b5, &b6)!=6) return INVALID_SOCKET; if(sscanf(sb+1, "%lu,%lu,%lu,%lu,%hu,%hu", &b1, &b2, &b3, &b4, &b5, &b6)!=6) return INVALID_SOCKET;
sasize = sizeof(param->sinsl); sasize = sizeof(param->sinsl);
if(so._getsockname(param->remsock, (struct sockaddr *)&param->sinsl, &sasize)){return INVALID_SOCKET;} if(param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&param->sinsl, &sasize)){return INVALID_SOCKET;}
sasize = sizeof(param->sinsr); sasize = sizeof(param->sinsr);
if(so._getpeername(param->remsock, (struct sockaddr *)&param->sinsr, &sasize)){return INVALID_SOCKET;} if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)&param->sinsr, &sasize)){return INVALID_SOCKET;}
rem = param->remsock; rem = param->remsock;
param->remsock = INVALID_SOCKET; param->remsock = INVALID_SOCKET;
param->req = param->sinsr; param->req = param->sinsr;
@ -201,7 +201,7 @@ SOCKET ftpdata(struct clientparam *param){
param->operation = FTP_DATA; param->operation = FTP_DATA;
if((param->res = (*param->srv->authfunc)(param))) { if((param->res = (*param->srv->authfunc)(param))) {
if(param->remsock != INVALID_SOCKET) { if(param->remsock != INVALID_SOCKET) {
so._closesocket(param->remsock); param->srv->so._closesocket(param->sostate, param->remsock);
param->remsock = INVALID_SOCKET; param->remsock = INVALID_SOCKET;
} }
memset(&param->sinsl, 0, sizeof(param->sinsl)); memset(&param->sinsl, 0, sizeof(param->sinsl));
@ -227,8 +227,8 @@ SOCKET ftpcommand(struct clientparam *param, unsigned char * command, unsigned c
sprintf(buf, "%.15s%s%.512s\r\n", command, arg? sprintf(buf, "%.15s%s%.512s\r\n", command, arg?
(unsigned char *)" ":(unsigned char *)"", (unsigned char *)" ":(unsigned char *)"",
arg?arg:(unsigned char *)""); arg?arg:(unsigned char *)"");
if((int)socksend(param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){ if((int)socksend(param, param->remsock, (unsigned char *)buf, (int)strlen(buf), conf.timeouts[STRING_S]) != (int)strlen(buf)){
so._closesocket(s); param->srv->so._closesocket(param->sostate, s);
return INVALID_SOCKET; return INVALID_SOCKET;
} }
param->statscli64 += (int)strlen(buf); param->statscli64 += (int)strlen(buf);
@ -236,11 +236,11 @@ SOCKET ftpcommand(struct clientparam *param, unsigned char * command, unsigned c
while((i = sockgetlinebuf(param, SERVER, (unsigned char *)buf, sizeof(buf) - 1, '\n', conf.timeouts[STRING_L])) > 0 && (i < 3 || !isnumber(*buf) || buf[3] == '-')){ while((i = sockgetlinebuf(param, SERVER, (unsigned char *)buf, sizeof(buf) - 1, '\n', conf.timeouts[STRING_L])) > 0 && (i < 3 || !isnumber(*buf) || buf[3] == '-')){
} }
if(i < 3) { if(i < 3) {
so._closesocket(s); param->srv->so._closesocket(param->sostate, s);
return INVALID_SOCKET; return INVALID_SOCKET;
} }
if(buf[0] != '1') { if(buf[0] != '1') {
so._closesocket(s); param->srv->so._closesocket(param->sostate, s);
return INVALID_SOCKET; return INVALID_SOCKET;
} }
return s; return s;

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -29,7 +29,7 @@ void * ftpprchild(struct clientparam* param) {
param->operation = CONNECT; param->operation = CONNECT;
lg.l_onoff = 1; lg.l_onoff = 1;
lg.l_linger = conf.timeouts[STRING_L];; lg.l_linger = conf.timeouts[STRING_L];;
if(socksend(param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);} if(socksend(param, param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);}
for(;;){ for(;;){
i = sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 10, '\n', conf.timeouts[CONNECTION_S]); i = sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 10, '\n', conf.timeouts[CONNECTION_S]);
if(!i) { if(!i) {
@ -44,13 +44,13 @@ void * ftpprchild(struct clientparam* param) {
if (!strncasecmp((char *)buf, "OPEN ", 5)){ if (!strncasecmp((char *)buf, "OPEN ", 5)){
if(parsehostname((char *)buf+5, param, 21)){RETURN(803);} if(parsehostname((char *)buf+5, param, 21)){RETURN(803);}
if(param->remsock != INVALID_SOCKET) { if(param->remsock != INVALID_SOCKET) {
so._shutdown(param->remsock, SHUT_RDWR); param->srv->so._shutdown(param->sostate, param->remsock, SHUT_RDWR);
so._closesocket(param->remsock); param->srv->so._closesocket(param->sostate, param->remsock);
param->remsock = INVALID_SOCKET; param->remsock = INVALID_SOCKET;
} }
if((res = (*param->srv->authfunc)(param))) {RETURN(res);} if((res = (*param->srv->authfunc)(param))) {RETURN(res);}
param->ctrlsocksrv = param->remsock; param->ctrlsocksrv = param->remsock;
if(socksend(param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);} if(socksend(param, param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);}
status = 1; status = 1;
} }
else if (!strncasecmp((char *)buf, "USER ", 5)){ else if (!strncasecmp((char *)buf, "USER ", 5)){
@ -59,7 +59,7 @@ void * ftpprchild(struct clientparam* param) {
if((res = (*param->srv->authfunc)(param))) {RETURN(res);} if((res = (*param->srv->authfunc)(param))) {RETURN(res);}
param->ctrlsocksrv = param->remsock; param->ctrlsocksrv = param->remsock;
} }
if(socksend(param->ctrlsock, (unsigned char *)"331 ok\r\n", 8, conf.timeouts[STRING_S])!=8) {RETURN (807);} if(socksend(param, param->ctrlsock, (unsigned char *)"331 ok\r\n", 8, conf.timeouts[STRING_S])!=8) {RETURN (807);}
status = 2; status = 2;
} }
@ -68,7 +68,7 @@ void * ftpprchild(struct clientparam* param) {
inbuf = BUFSIZE; inbuf = BUFSIZE;
res = ftplogin(param, (char *)buf, &inbuf); res = ftplogin(param, (char *)buf, &inbuf);
param->res = res; param->res = res;
if(inbuf && inbuf != BUFSIZE && socksend(param->ctrlsock, buf, inbuf, conf.timeouts[STRING_S])!=inbuf) {RETURN (807);} if(inbuf && inbuf != BUFSIZE && socksend(param, param->ctrlsock, buf, inbuf, conf.timeouts[STRING_S])!=inbuf) {RETURN (807);}
if(!res) status = 3; if(!res) status = 3;
sprintf((char *)buf, "%.128s@%.128s%c%hu", param->extusername, param->hostname, (ntohs(*SAPORT(&param->sinsr))==21)?0:':', ntohs(*SAPORT(&param->sinsr))); sprintf((char *)buf, "%.128s@%.128s%c%hu", param->extusername, param->hostname, (ntohs(*SAPORT(&param->sinsr))==21)?0:':', ntohs(*SAPORT(&param->sinsr)));
req = mystrdup((char *)buf); req = mystrdup((char *)buf);
@ -105,27 +105,27 @@ void * ftpprchild(struct clientparam* param) {
} }
#endif #endif
if(sc != INVALID_SOCKET) { if(sc != INVALID_SOCKET) {
so._shutdown(sc, SHUT_RDWR); param->srv->so._shutdown(param->sostate, sc, SHUT_RDWR);
so._closesocket(sc); param->srv->so._closesocket(param->sostate, sc);
sc = INVALID_SOCKET; sc = INVALID_SOCKET;
} }
if(ss != INVALID_SOCKET) { if(ss != INVALID_SOCKET) {
so._shutdown(ss, SHUT_RDWR); param->srv->so._shutdown(param->sostate, ss, SHUT_RDWR);
so._closesocket(ss); param->srv->so._closesocket(param->sostate, ss);
ss = INVALID_SOCKET; ss = INVALID_SOCKET;
} }
if(clidatasock != INVALID_SOCKET) { if(clidatasock != INVALID_SOCKET) {
so._shutdown(clidatasock, SHUT_RDWR); param->srv->so._shutdown(param->sostate, clidatasock, SHUT_RDWR);
so._closesocket(clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = INVALID_SOCKET; clidatasock = INVALID_SOCKET;
} }
if ((clidatasock=socket(SASOCK(&param->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);} if ((clidatasock=socket(SASOCK(&param->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
*SAPORT(&param->sincl) = 0; *SAPORT(&param->sincl) = 0;
if(so._bind(clidatasock, (struct sockaddr *)&param->sincl, SASIZE(&param->sincl))){RETURN(822);} if(param->srv->so._bind(param->sostate, clidatasock, (struct sockaddr *)&param->sincl, SASIZE(&param->sincl))){RETURN(822);}
if (pasv) { if (pasv) {
if(so._listen(clidatasock, 1)) {RETURN(823);} if(param->srv->so._listen(param->sostate, clidatasock, 1)) {RETURN(823);}
sasize = sizeof(param->sincl); sasize = sizeof(param->sincl);
if(so._getsockname(clidatasock, (struct sockaddr *)&param->sincl, &sasize)){RETURN(824);} if(param->srv->so._getsockname(param->sostate, clidatasock, (struct sockaddr *)&param->sincl, &sasize)){RETURN(824);}
if(pasv == 1){ if(pasv == 1){
if(*SAFAMILY(&param->sincl) == AF_INET) if(*SAFAMILY(&param->sincl) == AF_INET)
sprintf((char *)buf, "227 OK (%u,%u,%u,%u,%u,%u)\r\n", sprintf((char *)buf, "227 OK (%u,%u,%u,%u,%u,%u)\r\n",
@ -153,8 +153,8 @@ void * ftpprchild(struct clientparam* param) {
if(sscanf((char *)buf+5, "%lu,%lu,%lu,%lu,%hu,%hu", &b1, &b2, &b3, &b4, &b5, &b6)!=6) {RETURN(828);} if(sscanf((char *)buf+5, "%lu,%lu,%lu,%lu,%hu,%hu", &b1, &b2, &b3, &b4, &b5, &b6)!=6) {RETURN(828);}
*SAPORT(&param->sincr) = htons((unsigned short)((b5<<8)^b6)); *SAPORT(&param->sincr) = htons((unsigned short)((b5<<8)^b6));
if(connectwithpoll(clidatasock, (struct sockaddr *)&param->sincr, SASIZE(&param->sincr),CONNECT_TO)) { if(connectwithpoll(param, clidatasock, (struct sockaddr *)&param->sincr, SASIZE(&param->sincr),CONNECT_TO)) {
so._closesocket(clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = INVALID_SOCKET; clidatasock = INVALID_SOCKET;
RETURN(826); RETURN(826);
} }
@ -173,7 +173,7 @@ void * ftpprchild(struct clientparam* param) {
if(action != PASS) RETURN(879); if(action != PASS) RETURN(879);
} }
#endif #endif
if(socksend(param->ctrlsock, buf, (int)strlen((char *)buf), conf.timeouts[STRING_S])!=(int)strlen((char *)buf)) {RETURN (825);} if(socksend(param, param->ctrlsock, buf, (int)strlen((char *)buf), conf.timeouts[STRING_S])!=(int)strlen((char *)buf)) {RETURN (825);}
status = 4; status = 4;
} }
else if (status == 4 && ( else if (status == 4 && (
@ -208,15 +208,15 @@ void * ftpprchild(struct clientparam* param) {
fds.fd = clidatasock; fds.fd = clidatasock;
fds.events = POLLIN; fds.events = POLLIN;
res = so._poll (&fds, 1, conf.timeouts[STRING_L]*1000); res = param->srv->so._poll (param->sostate, &fds, 1, conf.timeouts[STRING_L]*1000);
if(res != 1) { if(res != 1) {
RETURN(857); RETURN(857);
} }
sasize = sizeof(param->sincr); sasize = sizeof(param->sincr);
ss = so._accept(clidatasock, (struct sockaddr *)&param->sincr, &sasize); ss = param->srv->so._accept(param->sostate, clidatasock, (struct sockaddr *)&param->sincr, &sasize);
if (ss == INVALID_SOCKET) { RETURN (858);} if (ss == INVALID_SOCKET) { RETURN (858);}
so._shutdown(clidatasock, SHUT_RDWR); param->srv->so._shutdown(param->sostate, clidatasock, SHUT_RDWR);
so._closesocket(clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = ss; clidatasock = ss;
ss = INVALID_SOCKET; ss = INVALID_SOCKET;
} }
@ -226,20 +226,20 @@ void * ftpprchild(struct clientparam* param) {
status = 3; status = 3;
ss = ftpcommand(param, buf, arg? buf+5 : NULL); ss = ftpcommand(param, buf, arg? buf+5 : NULL);
if (ss == INVALID_SOCKET) { if (ss == INVALID_SOCKET) {
so._shutdown(clidatasock, SHUT_RDWR); param->srv->so._shutdown(param->sostate, clidatasock, SHUT_RDWR);
so._closesocket(clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = INVALID_SOCKET; clidatasock = INVALID_SOCKET;
if(socksend(param->ctrlsock, (unsigned char *)"550 err\r\n", 9, conf.timeouts[STRING_S])!=9) {RETURN (831);} if(socksend(param, param->ctrlsock, (unsigned char *)"550 err\r\n", 9, conf.timeouts[STRING_S])!=9) {RETURN (831);}
continue; continue;
} }
if(socksend(param->ctrlsock, (unsigned char *)"125 data\r\n", 10, conf.timeouts[STRING_S]) != 10) { if(socksend(param, param->ctrlsock, (unsigned char *)"125 data\r\n", 10, conf.timeouts[STRING_S]) != 10) {
param->remsock = INVALID_SOCKET; param->remsock = INVALID_SOCKET;
RETURN (832); RETURN (832);
} }
if(param->srvoffset < param->srvinbuf)while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', 0)) > 3){ if(param->srvoffset < param->srvinbuf)while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', 0)) > 3){
if(socksend(param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN(833);} if(socksend(param, param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN(833);}
if(isnumber(*buf) && buf[3] != '-') { if(isnumber(*buf) && buf[3] != '-') {
ressent = 1; ressent = 1;
break; break;
@ -247,17 +247,17 @@ void * ftpprchild(struct clientparam* param) {
} }
sc = param->remsock; sc = param->remsock;
param->remsock = ss; param->remsock = ss;
so._setsockopt(param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg)); param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
so._setsockopt(clidatasock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg)); param->srv->so._setsockopt(param->sostate, clidatasock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
param->clisock = clidatasock; param->clisock = clidatasock;
res = mapsocket(param, conf.timeouts[CONNECTION_S]); res = mapsocket(param, conf.timeouts[CONNECTION_S]);
if(param->remsock != INVALID_SOCKET) { if(param->remsock != INVALID_SOCKET) {
so._shutdown (param->remsock, SHUT_RDWR); param->srv->so._shutdown (param->sostate, param->remsock, SHUT_RDWR);
so._closesocket(param->remsock); param->srv->so._closesocket(param->sostate, param->remsock);
} }
if(param->clisock != INVALID_SOCKET) { if(param->clisock != INVALID_SOCKET) {
so._shutdown (param->clisock, SHUT_RDWR); param->srv->so._shutdown (param->sostate, param->clisock, SHUT_RDWR);
so._closesocket(param->clisock); param->srv->so._closesocket(param->sostate, param->clisock);
} }
param->clisock = param->ctrlsock; param->clisock = param->ctrlsock;
param->remsock = sc; param->remsock = sc;
@ -266,7 +266,7 @@ void * ftpprchild(struct clientparam* param) {
clidatasock = INVALID_SOCKET; clidatasock = INVALID_SOCKET;
if(!ressent){ if(!ressent){
while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', conf.timeouts[STRING_L])) > 3){ while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', conf.timeouts[STRING_L])) > 3){
if(socksend(param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN(833);} if(socksend(param, param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN(833);}
if(isnumber(*buf) && buf[3] != '-') break; if(isnumber(*buf) && buf[3] != '-') break;
} }
if(i < 3) {RETURN(834);} if(i < 3) {RETURN(834);}
@ -274,7 +274,7 @@ void * ftpprchild(struct clientparam* param) {
} }
else { else {
if(status < 3) { if(status < 3) {
if(socksend(param->remsock, (unsigned char *)"530 login\r\n", 11, conf.timeouts[STRING_S])!=1) {RETURN (810);} if(socksend(param, param->remsock, (unsigned char *)"530 login\r\n", 11, conf.timeouts[STRING_S])!=1) {RETURN (810);}
continue; continue;
} }
if(!strncasecmp((char *)buf, "QUIT", 4)) status = 5; if(!strncasecmp((char *)buf, "QUIT", 4)) status = 5;
@ -282,18 +282,18 @@ void * ftpprchild(struct clientparam* param) {
i = (int)strlen((char *)buf); i = (int)strlen((char *)buf);
buf[i++] = '\r'; buf[i++] = '\r';
buf[i++] = '\n'; buf[i++] = '\n';
if(socksend(param->remsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN (811);} if(socksend(param, param->remsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN (811);}
param->statscli64+=(i); param->statscli64+=(i);
param->nwrites++; param->nwrites++;
while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', conf.timeouts[STRING_L])) > 0){ while((i = sockgetlinebuf(param, SERVER, buf, BUFSIZE, '\n', conf.timeouts[STRING_L])) > 0){
if(socksend(param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN (812);} if(socksend(param, param->ctrlsock, buf, i, conf.timeouts[STRING_S])!=i) {RETURN (812);}
if(i > 4 && isnumber(*buf) && buf[3] != '-') break; if(i > 4 && isnumber(*buf) && buf[3] != '-') break;
} }
if(status == 5) {RETURN (0);} if(status == 5) {RETURN (0);}
if(i < 3) {RETURN (813);} if(i < 3) {RETURN (813);}
} }
sasize = sizeof(param->sincr); sasize = sizeof(param->sincr);
if(so._getpeername(param->ctrlsock, (struct sockaddr *)&param->sincr, &sasize)){RETURN(819);} if(param->srv->so._getpeername(param->sostate, param->ctrlsock, (struct sockaddr *)&param->sincr, &sasize)){RETURN(819);}
if(req && (param->statscli64 || param->statssrv64)){ if(req && (param->statscli64 || param->statssrv64)){
dolog(param, (unsigned char *)req); dolog(param, (unsigned char *)req);
} }
@ -302,19 +302,19 @@ void * ftpprchild(struct clientparam* param) {
CLEANRET: CLEANRET:
if(sc != INVALID_SOCKET) { if(sc != INVALID_SOCKET) {
so._shutdown(sc, SHUT_RDWR); param->srv->so._shutdown(param->sostate, sc, SHUT_RDWR);
so._closesocket(sc); param->srv->so._closesocket(param->sostate, sc);
} }
if(ss != INVALID_SOCKET) { if(ss != INVALID_SOCKET) {
so._shutdown(ss, SHUT_RDWR); param->srv->so._shutdown(param->sostate, ss, SHUT_RDWR);
so._closesocket(ss); param->srv->so._closesocket(param->sostate, ss);
} }
if(clidatasock != INVALID_SOCKET) { if(clidatasock != INVALID_SOCKET) {
so._shutdown(clidatasock, SHUT_RDWR); param->srv->so._shutdown(param->sostate, clidatasock, SHUT_RDWR);
so._closesocket(clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
} }
sasize = sizeof(param->sincr); sasize = sizeof(param->sincr);
so._getpeername(param->ctrlsock, (struct sockaddr *)&param->sincr, &sasize); param->srv->so._getpeername(param->sostate, param->ctrlsock, (struct sockaddr *)&param->sincr, &sasize);
if(param->res != 0 || param->statscli64 || param->statssrv64 ){ if(param->res != 0 || param->statscli64 || param->statssrv64 ){
dolog(param, (unsigned char *)((req && (param->res > 802))? req:NULL)); dolog(param, (unsigned char *)((req && (param->res > 802))? req:NULL));
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,74 +0,0 @@
/*
Minimal version of Henry Spencer's regex library
with minor modifications
*/
#ifndef _REGEX_H_
#define _REGEX_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef off_t regoff_t;
typedef struct {
int re_magic;
size_t re_nsub; /* number of parenthesized subexpressions */
const char *re_endp; /* end pointer for REG_PEND */
struct re_guts *re_g; /* none of your business :-) */
} regex_t;
typedef struct {
regoff_t rm_so; /* start of match */
regoff_t rm_eo; /* end of match */
} regmatch_t;
extern int regcomp(regex_t *, const char *, int);
#define REG_BASIC 0000
#define REG_EXTENDED 0001
#define REG_ICASE 0002
#define REG_NOSUB 0004
#define REG_NEWLINE 0010
#define REG_NOSPEC 0020
#define REG_PEND 0040
#define REG_DUMP 0200
#define REG_OKAY 0
#define REG_NOMATCH 1
#define REG_BADPAT 2
#define REG_ECOLLATE 3
#define REG_ECTYPE 4
#define REG_EESCAPE 5
#define REG_ESUBREG 6
#define REG_EBRACK 7
#define REG_EPAREN 8
#define REG_EBRACE 9
#define REG_BADBR 10
#define REG_ERANGE 11
#define REG_ESPACE 12
#define REG_BADRPT 13
#define REG_EMPTY 14
#define REG_ASSERT 15
#define REG_INVARG 16
#define REG_ATOI 255 /* convert name to number (!) */
#define REG_ITOA 0400 /* convert number to name (!) */
extern int regexec(const regex_t *, const char *, size_t, regmatch_t [], int);
#define REG_NOTBOL 00001
#define REG_NOTEOL 00002
#define REG_STARTEND 00004
#define REG_TRACE 00400 /* tracing of execution */
#define REG_LARGE 01000 /* force large representation */
#define REG_BACKR 02000 /* force use of backref code */
extern void regfree(regex_t *);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,321 +0,0 @@
/*
Unix SMB/CIFS implementation.
a partial implementation of DES designed for use in the
SMB authentication protocol
Copyright (C) Andrew Tridgell 1998
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <string.h>
#include <ctype.h>
#define uchar unsigned char
static const uchar perm1[56] = {57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4};
static const uchar perm2[48] = {14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32};
static const uchar perm3[64] = {58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7};
static const uchar perm4[48] = { 32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1};
static const uchar perm5[32] = { 16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25};
static const uchar perm6[64] ={ 40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25};
static const uchar sc[16] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
static const uchar sbox[8][4][16] = {
{{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}},
{{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}},
{{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}},
{{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}},
{{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}},
{{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}},
{{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}},
{{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}};
static void permute(char *out, const char *in, const uchar *p, int n)
{
int i;
for (i=0;i<n;i++)
out[i] = in[p[i]-1];
}
static void lshift(char *d, int count, int n)
{
char out[64];
int i;
for (i=0;i<n;i++)
out[i] = d[(i+count)%n];
for (i=0;i<n;i++)
d[i] = out[i];
}
static void concat(char *out, char *in1, char *in2, int l1, int l2)
{
while (l1--)
*out++ = *in1++;
while (l2--)
*out++ = *in2++;
}
static void xor(char *out, char *in1, char *in2, int n)
{
int i;
for (i=0;i<n;i++)
out[i] = in1[i] ^ in2[i];
}
static void dohash(char *out, char *in, char *key)
{
int i, j, k;
char pk1[56];
char c[28];
char d[28];
char cd[56];
char ki[16][48];
char pd1[64];
char l[32], r[32];
char rl[64];
permute(pk1, key, perm1, 56);
for (i=0;i<28;i++)
c[i] = pk1[i];
for (i=0;i<28;i++)
d[i] = pk1[i+28];
for (i=0;i<16;i++) {
lshift(c, sc[i], 28);
lshift(d, sc[i], 28);
concat(cd, c, d, 28, 28);
permute(ki[i], cd, perm2, 48);
}
permute(pd1, in, perm3, 64);
for (j=0;j<32;j++) {
l[j] = pd1[j];
r[j] = pd1[j+32];
}
for (i=0;i<16;i++) {
char er[48];
char erk[48];
char b[8][6];
char cb[32];
char pcb[32];
char r2[32];
permute(er, r, perm4, 48);
xor(erk, er, ki[i], 48);
for (j=0;j<8;j++)
for (k=0;k<6;k++)
b[j][k] = erk[j*6 + k];
for (j=0;j<8;j++) {
int m, n;
m = (b[j][0]<<1) | b[j][5];
n = (b[j][1]<<3) | (b[j][2]<<2) | (b[j][3]<<1) | b[j][4];
for (k=0;k<4;k++)
b[j][k] = (sbox[j][m][n] & (1<<(3-k)))?1:0;
}
for (j=0;j<8;j++)
for (k=0;k<4;k++)
cb[j*4+k] = b[j][k];
permute(pcb, cb, perm5, 32);
xor(r2, l, pcb, 32);
for (j=0;j<32;j++)
l[j] = r[j];
for (j=0;j<32;j++)
r[j] = r2[j];
}
concat(rl, r, l, 32, 32);
permute(out, rl, perm6, 64);
}
static void str_to_key(unsigned char *str,unsigned char *key)
{
int i;
key[0] = str[0]>>1;
key[1] = ((str[0]&0x01)<<6) | (str[1]>>2);
key[2] = ((str[1]&0x03)<<5) | (str[2]>>3);
key[3] = ((str[2]&0x07)<<4) | (str[3]>>4);
key[4] = ((str[3]&0x0F)<<3) | (str[4]>>5);
key[5] = ((str[4]&0x1F)<<2) | (str[5]>>6);
key[6] = ((str[5]&0x3F)<<1) | (str[6]>>7);
key[7] = str[6]&0x7F;
for (i=0;i<8;i++) {
key[i] = (key[i]<<1);
}
}
static void smbhash(unsigned char *out, const unsigned char *in, unsigned char *key)
{
int i;
char outb[64];
char inb[64];
char keyb[64];
unsigned char key2[8];
str_to_key(key, key2);
for (i=0;i<64;i++) {
inb[i] = (in[i/8] & (1<<(7-(i%8)))) ? 1 : 0;
keyb[i] = (key2[i/8] & (1<<(7-(i%8)))) ? 1 : 0;
outb[i] = 0;
}
dohash(outb, inb, keyb);
for (i=0;i<8;i++) {
out[i] = 0;
}
for (i=0;i<64;i++) {
if (outb[i])
out[i/8] |= (1<<(7-(i%8)));
}
}
/*
* Converts the password to uppercase, and creates the LM
* password hash.
*/
void lmpwdhash(const unsigned char *password,unsigned char *lmhash)
{
int i;
unsigned char p14[14];
static unsigned char sp8[8] = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
memset(p14, 0, sizeof(p14));
for (i = 0; i < 14 && password[i]; i++) {
p14[i] = toupper((int) password[i]);
}
smbhash(lmhash, sp8, p14);
smbhash(lmhash+8, sp8, p14+7);
}
/*
* Take the NT or LM password, and return the MSCHAP response
*
* The win_password MUST be exactly 16 bytes long.
*/
void mschap(const unsigned char *win_password,
const unsigned char *challenge, unsigned char *response)
{
unsigned char p21[21];
memset(p21, 0, sizeof(p21));
memcpy(p21, win_password, 16);
smbhash(response, challenge, p21);
smbhash(response+8, challenge, p21+7);
smbhash(response+16, challenge, p21+14);
}

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2020 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -174,7 +174,7 @@ int dobuf2(struct clientparam * param, unsigned char * buf, const unsigned char
break; break;
case 'n': case 'n':
len = param->hostname? (int)strlen((char *)param->hostname) : 0; len = param->hostname? (int)strlen((char *)param->hostname) : 0;
if (len > 0 && !strchr((char *)param->hostname, ':')) for(len = 0; param->hostname[len] && i < 256; len++, i++){ if (len > 0 && !strchr((char *)param->hostname, ':')) for(len = 0; param->hostname[len] && i < 4000; len++, i++){
buf[i] = param->hostname[len]; buf[i] = param->hostname[len];
if(param->srv->nonprintable && (buf[i] < 0x20 || strchr((char *)param->srv->nonprintable, buf[i]))) buf[i] = param->srv->replace; if(param->srv->nonprintable && (buf[i] < 0x20 || strchr((char *)param->srv->nonprintable, buf[i]))) buf[i] = param->srv->replace;
if(doublec && strchr((char *)doublec, buf[i])) { if(doublec && strchr((char *)doublec, buf[i])) {

View File

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

View File

@ -1,88 +0,0 @@
/*
3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru>
please read License Agreement
*/
#include "proxy.h"
struct ntlmchal {
unsigned char sig[8];
unsigned char messtype[4];
unsigned char dom_len[2];
unsigned char dom_max_len[2];
unsigned char dom_offset[4];
unsigned char flags[4];
unsigned char challenge[8];
unsigned char reserved[8];
unsigned char addr_len[2];
unsigned char addr_max_len[2];
unsigned char addr_offset[4];
unsigned char data[1];
};
struct ntlmreq {
unsigned char sig[8];
unsigned char messtype[4];
unsigned char flags[4];
unsigned char dom_len[2];
unsigned char dom_max_len[2];
unsigned char dom_offset[4];
unsigned char pad1[2];
unsigned char host_len[2];
unsigned char host_max_len[2];
unsigned char host_offset[4];
unsigned char pad2[2];
unsigned char data[1];
};
int text2unicode(const char * text, char * buf, int buflen){
int count = 0;
buflen = ((buflen>>1)<<1);
if(!text || !buflen) return 0;
do {
buf[count++] = toupper(*text++);
buf[count++] = '\0';
} while (*text && count < buflen);
return count;
}
void unicode2text(const char *unicode, char * buf, int len){
int i;
if(!unicode || !len) return;
for(i=0; i<len; i++){
buf[i] = unicode[(i<<1)];
}
buf[i] = 0;
}
void genchallenge(struct clientparam *param, char * challenge, char *buf){
struct ntlmchal *chal;
char tmpbuf[1024];
char hostname[128];
int len, i;
chal = (struct ntlmchal *)tmpbuf;
memset(chal, 0, 1024);
memcpy(chal->sig, "NTLMSSP", 8);
chal->messtype[0] = 2;
gethostname(hostname, 128);
hostname[15] = 0;
len = (((int)strlen(hostname)) << 1);
chal->dom_len[0] = len;
chal->dom_max_len[0] = len;
chal->dom_offset[0] = (unsigned char)((unsigned char *)chal->data - (unsigned char *)chal);
chal->flags[0] = 0x03;
chal->flags[1] = 0x82;
chal->flags[2] = 0x81;
chal->flags[3] = 0xA0;
text2unicode(hostname, (char *)chal->data, 64);
time((time_t *)challenge);
memcpy(challenge+4, SAADDR(&param->sincr), 4);
challenge[1]^=*SAPORT(&param->sincr);
for(i = 0; i < 8; i++) challenge[i] ^= myrand(challenge, 8);
memcpy(chal->challenge, challenge, 8);
en64((unsigned char *)tmpbuf, (unsigned char *)buf, (int)((unsigned char *)chal->data - (unsigned char *)chal) + len);
}

View File

@ -1,6 +1,6 @@
/* /*
3APA3A simpliest proxy server 3APA3A simpliest proxy server
(c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru> (c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement please read License Agreement
@ -11,8 +11,8 @@
unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout); unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout);
void trafcountfunc(struct clientparam *param); void trafcountfunc(struct clientparam *param);
int checkACL(struct clientparam * param); int checkACL(struct clientparam * param);
void nametohash(const unsigned char * name, unsigned char *hash); void nametohash(const unsigned char * name, unsigned char *hash, unsigned char *rnd);
unsigned hashindex(const unsigned char* hash); unsigned hashindex(struct hashtable *ht, const unsigned char* hash);
void decodeurl(unsigned char *s, int allowcr); void decodeurl(unsigned char *s, int allowcr);
int parsestr (unsigned char *str, unsigned char **argm, int nitems, unsigned char ** buff, int *inbuf, int *bufsize); int parsestr (unsigned char *str, unsigned char **argm, int nitems, unsigned char ** buff, int *inbuf, int *bufsize);
struct ace * make_ace (int argc, unsigned char ** argv); struct ace * make_ace (int argc, unsigned char ** argv);
@ -68,12 +68,15 @@ struct symbol symbols[] = {
{symbols+41, "admin", (void *) adminchild}, {symbols+41, "admin", (void *) adminchild},
{symbols+42, "ftppr", (void *) ftpprchild}, {symbols+42, "ftppr", (void *) ftpprchild},
{symbols+43, "smtpp", (void *) smtppchild}, {symbols+43, "smtpp", (void *) smtppchild},
{symbols+44, "authfuncs", (void *) &authfuncs}, {symbols+44, "auto", (void *) smtppchild},
{symbols+45, "commandhandlers", (void *) &commandhandlers}, {symbols+45, "tlspr", (void *) smtppchild},
{symbols+46, "decodeurl", (void *) decodeurl}, {symbols+46, "authfuncs", (void *) &authfuncs},
{symbols+47, "parsestr", (void *) parsestr}, {symbols+47, "commandhandlers", (void *) &commandhandlers},
{symbols+48, "make_ace", (void *) make_ace}, {symbols+48, "decodeurl", (void *) decodeurl},
{symbols+49, "freeacl", (void *) freeacl}, {symbols+49, "parsestr", (void *) parsestr},
{symbols+50, "make_ace", (void *) make_ace},
{symbols+51, "freeacl", (void *) freeacl},
{symbols+52, "handleredirect", (void *) handleredirect},
{NULL, "", NULL} {NULL, "", NULL}
}; };

View File

@ -1,6 +1,5 @@
/* /*
3APA3A simpliest proxy server (c) 2007-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement please read License Agreement
@ -38,8 +37,10 @@ extern "C" {
#ifndef _WIN32 #ifndef _WIN32
#define WINAPI #define WINAPI
#define fp_size_t size_t #define fp_size_t size_t
#define fp_ssize_t ssize_t
#else #else
#define fp_size_t int #define fp_size_t int
#define fp_ssize_t int
#endif #endif
static struct pluginlink * pl; static struct pluginlink * pl;
@ -261,7 +262,7 @@ static void removefps(struct fp_stream * fps){
} }
static int WINAPI fp_connect(SOCKET s, const struct sockaddr *name, fp_size_t namelen){ static int WINAPI fp_connect(SOCKET s, const struct sockaddr *name, fp_size_t namelen){
return sso._connect(s, name, namelen); return sso._connect(sso.state, s, name, namelen);
} }
void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
@ -286,7 +287,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_SMTP_REQ: case GOT_SMTP_REQ:
case GOT_SMTP_DATA: case GOT_SMTP_DATA:
fps->state = FLUSH_DATA; fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->clisock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]); pl->socksend(fps->fpd.cp->sostate,fps->fpd.cp->clisock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
fps->state = state; fps->state = state;
break; break;
case GOT_HTTP_REQUEST: case GOT_HTTP_REQUEST:
@ -298,7 +299,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_HTTP_SRVDATA: case GOT_HTTP_SRVDATA:
if(!fps->serversent){ if(!fps->serversent){
fps->state = FLUSH_DATA; fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->clisock, fp_stringtable[0], (int)strlen(fp_stringtable[0]), pl->conf->timeouts[STRING_S]); pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, fp_stringtable[0], (int)strlen(fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
fps->state = state; fps->state = state;
} }
break; break;
@ -306,15 +307,15 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_FTP_REQ: case GOT_FTP_REQ:
case GOT_FTP_SRVDATA: case GOT_FTP_SRVDATA:
fps->state = FLUSH_DATA; fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->ctrlsock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]); pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->ctrlsock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
fps->state = state; fps->state = state;
break; break;
default: default:
break; break;
} }
if(fps->fpd.cp->remsock != INVALID_SOCKET)sso._closesocket(fps->fpd.cp->remsock); if(fps->fpd.cp->remsock != INVALID_SOCKET)sso._closesocket(sso.state, fps->fpd.cp->remsock);
fps->fpd.cp->remsock = INVALID_SOCKET; fps->fpd.cp->remsock = INVALID_SOCKET;
if(fps->fpd.cp->clisock != INVALID_SOCKET)sso._closesocket(fps->fpd.cp->clisock); if(fps->fpd.cp->clisock != INVALID_SOCKET)sso._closesocket(sso.state, fps->fpd.cp->clisock);
fps->fpd.cp->clisock = INVALID_SOCKET; fps->fpd.cp->clisock = INVALID_SOCKET;
} }
} }
@ -358,7 +359,7 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
if(fps->serversent >= fps->srvhdrwritten){ if(fps->serversent >= fps->srvhdrwritten){
sprintf(fps->buf, "%lx\r\n", len); sprintf(fps->buf, "%lx\r\n", len);
sendchunk = (int)strlen(fps->buf); sendchunk = (int)strlen(fps->buf);
if(pl->socksend(fps->fpd.cp->clisock, fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){ if(pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
return -4; return -4;
} }
} }
@ -397,20 +398,20 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
#endif #endif
return -3; return -3;
} }
if(pl->socksend(sock, fps->buf, res, pl->conf->timeouts[STRING_S]) != res) { if(pl->socksend(fps->fpd.cp->sostate, sock, fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
return -4; return -4;
} }
len -= res; len -= res;
} }
if(sendchunk){ if(sendchunk){
if(pl->socksend(sock, "\r\n", 2, pl->conf->timeouts[STRING_S]) != 2) if(pl->socksend(fps->fpd.cp->sostate, sock, "\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
return -4; return -4;
} }
fps->state = state; fps->state = state;
return 0; return 0;
} }
static int WINAPI fp_poll(struct pollfd *fds, unsigned int nfds, int timeout){ static int WINAPI fp_poll(void *state, struct pollfd *fds, unsigned int nfds, int timeout){
struct fp_stream *fps = NULL; struct fp_stream *fps = NULL;
int res; int res;
unsigned i; unsigned i;
@ -455,10 +456,10 @@ static int WINAPI fp_poll(struct pollfd *fds, unsigned int nfds, int timeout){
} }
} }
return sso._poll(fds, nfds, timeout); return sso._poll(sso.state, fds, nfds, timeout);
} }
static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){ static fp_ssize_t WINAPI fp_send(void *state, SOCKET s, const char *msg, fp_size_t len, int flags){
struct fp_stream *fps = NULL; struct fp_stream *fps = NULL;
int res; int res;
res = searchsocket(s, &fps); res = searchsocket(s, &fps);
@ -473,7 +474,7 @@ static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
} }
closefiles(fps); closefiles(fps);
fps->state = 0; fps->state = 0;
return sso._send(s, msg, len, flags); return sso._send(sso.state, s, msg, len, flags);
} }
if((((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){ if((((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){
#ifdef _WIN32 #ifdef _WIN32
@ -503,7 +504,7 @@ static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
if(c == '\r' || c == '\n') continue; if(c == '\r' || c == '\n') continue;
if((c<'0'|| c>'9') && (c<'A' || c>'F') && (c<'a' || c>'f')) { if((c<'0'|| c>'9') && (c<'A' || c>'F') && (c<'a' || c>'f')) {
return sso._send(s, msg, len, flags); return sso._send(sso.state, s, msg, len, flags);
} }
if(c != '0') hasnonzero = 1; if(c != '0') hasnonzero = 1;
} }
@ -518,7 +519,7 @@ static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
} }
closefiles(fps); closefiles(fps);
fps->state = 0; fps->state = 0;
return sso._send(s, msg, len, flags); return sso._send(sso.state, s, msg, len, flags);
} }
return len; return len;
} }
@ -540,9 +541,9 @@ static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
return res; return res;
} }
} }
return sso._send(s, msg, len, flags); return sso._send(sso.state, s, msg, len, flags);
} }
static int WINAPI fp_sendto(SOCKET s, const void *msg, int len, int flags, const struct sockaddr *to, fp_size_t tolen){ static fp_ssize_t WINAPI fp_sendto(void *state, SOCKET s, const void *msg, int len, int flags, const struct sockaddr *to, fp_size_t tolen){
struct fp_stream *fps = NULL; struct fp_stream *fps = NULL;
int res; int res;
res = searchsocket(s, &fps); res = searchsocket(s, &fps);
@ -577,7 +578,7 @@ static int WINAPI fp_sendto(SOCKET s, const void *msg, int len, int flags, const
case GOT_FTP_CLIDATA: case GOT_FTP_CLIDATA:
case GOT_FTP_SRVDATA: case GOT_FTP_SRVDATA:
case GOT_HTTP_CLIDATA: case GOT_HTTP_CLIDATA:
if((!fps->what & FP_CLIDATA)) break; if(!(fps->what & FP_CLIDATA)) break;
#ifdef _WIN32 #ifdef _WIN32
if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){ if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){
return -1; return -1;
@ -658,15 +659,15 @@ static int WINAPI fp_sendto(SOCKET s, const void *msg, int len, int flags, const
return res; return res;
} }
} }
return sso._sendto(s, msg, len, flags, to, tolen); return sso._sendto(sso.state, s, msg, len, flags, to, tolen);
} }
static int WINAPI fp_recv(SOCKET s, void *buf, fp_size_t len, int flags){ static fp_ssize_t WINAPI fp_recv(void *state, SOCKET s, void *buf, fp_size_t len, int flags){
return sso._recv(s, buf, len, flags); return sso._recv(sso.state, s, buf, len, flags);
} }
static int WINAPI fp_recvfrom(SOCKET s, void * buf, fp_size_t len, int flags, struct sockaddr * from, fp_size_t * fromlen){ static fp_ssize_t WINAPI fp_recvfrom(void *state, SOCKET s, void * buf, fp_size_t len, int flags, struct sockaddr * from, fp_size_t * fromlen){
return sso._recvfrom(s, buf, len, flags, from, fromlen); return sso._recvfrom(sso.state, s, buf, len, flags, from, fromlen);
} }
static int WINAPI fp_shutdown(SOCKET s, int how){ static int WINAPI fp_shutdown(void *state, SOCKET s, int how){
struct fp_stream *fps = NULL; struct fp_stream *fps = NULL;
int res; int res;
@ -690,10 +691,10 @@ static int WINAPI fp_shutdown(SOCKET s, int how){
} }
} }
return sso._shutdown(s, how); return sso._shutdown(sso.state, s, how);
} }
static int WINAPI fp_closesocket(SOCKET s){ static int WINAPI fp_closesocket(void *state, SOCKET s){
return sso._closesocket(s); return sso._closesocket(sso.state, s);
} }

View File

@ -0,0 +1 @@
include Makefile.var

View File

@ -1,6 +1,5 @@
/* /*
3APA3A simpliest proxy server (c) 2007-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement please read License Agreement
@ -8,6 +7,7 @@
#include "../../structures.h" #include "../../structures.h"
#include <string.h> #include <string.h>
#define PCRE_STATIC
#include "pcre.h" #include "pcre.h"
#ifdef __cplusplus #ifdef __cplusplus
@ -351,7 +351,7 @@ static struct commands pcre_commandhandlers[] = {
static struct symbol regexp_symbols[] = { static struct symbol regexp_symbols[] = {
{regexp_symbols+1, "pcre_compile", (void*) pcre_compile}, {regexp_symbols+1, "pcre_compile", (void*) pcre_compile},
{regexp_symbols+2, "pcre_exec", (void*) pcre_exec}, {regexp_symbols+2, "pcre_exec", (void*) pcre_exec},
{NULL, "pcre_free", NULL}, {NULL, "pcre_options", (void *)&pcre_options},
}; };
#ifdef WATCOM #ifdef WATCOM
@ -371,8 +371,7 @@ PLUGINAPI int PLUGINCALL pcre_plugin (struct pluginlink * pluginlink,
pcre_free = pl->freefunc; pcre_free = pl->freefunc;
pcre_loaded = 1; pcre_loaded = 1;
pthread_mutex_init(&pcre_mutex, NULL); pthread_mutex_init(&pcre_mutex, NULL);
regexp_symbols[6].value = pl->freefunc; regexp_symbols[2].next = pl->symbols.next;
regexp_symbols[6].next = pl->symbols.next;
pl->symbols.next = regexp_symbols; pl->symbols.next = regexp_symbols;
pcre_commandhandlers[3].next = pl->commandhandlers->next; pcre_commandhandlers[3].next = pl->commandhandlers->next;
pl->commandhandlers->next = pcre_commandhandlers; pl->commandhandlers->next = pcre_commandhandlers;

View File

@ -1,3 +1,9 @@
/*
(c) 2002-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
please read License Agreement
*/
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS
@ -14,9 +20,6 @@
#include <openssl/pem.h> #include <openssl/pem.h>
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <openssl/err.h> #include <openssl/err.h>
#ifdef WIN32
#include <openssl/applink.c>
#endif
#include "../../proxy.h" #include "../../proxy.h"
#include "my_ssl.h" #include "my_ssl.h"
@ -29,11 +32,6 @@ typedef struct _ssl_conn {
SSL *ssl; SSL *ssl;
} ssl_conn; } ssl_conn;
static X509 *CA_cert = NULL;
static EVP_PKEY *CA_key = NULL;
static EVP_PKEY *server_key = NULL;
static X509_NAME *name = NULL;
pthread_mutex_t ssl_file_mutex; pthread_mutex_t ssl_file_mutex;
@ -47,19 +45,24 @@ static char hexMap[] = {
static BIO *bio_err=NULL; static BIO *bio_err=NULL;
char * getSSLErr(){
return ERR_error_string(ERR_get_error(), errbuf);
}
static size_t bin2hex (const unsigned char* bin, size_t bin_length, char* str, size_t str_length) static size_t bin2hex (const unsigned char* bin, size_t bin_length, char* str, size_t str_length)
{ {
char *p; char *p;
size_t i; size_t i;
if ( str_length < ( bin_length+1) ) if ( str_length < ( (bin_length*2)+1) )
return 0; return 0;
p = str; p = str;
for ( i=0; i < bin_length; ++i ) for ( i=0; i < bin_length; ++i )
{ {
*p++ = hexMap[*bin >> 4]; *p++ = hexMap[(*(unsigned char *)bin) >> 4];
*p++ = hexMap[*bin & 0xf]; *p++ = hexMap[(*(unsigned char *)bin) & 0xf];
++bin; ++bin;
} }
@ -88,8 +91,6 @@ static int add_ext(X509 *cert, int nid, char *value)
return 1; return 1;
} }
extern char *cert_path;
void del_ext(X509 *dst_cert, int nid, int where){ void del_ext(X509 *dst_cert, int nid, int where){
int ex; int ex;
@ -101,41 +102,45 @@ void del_ext(X509 *dst_cert, int nid, int where){
} }
SSL_CERT ssl_copy_cert(SSL_CERT cert) SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config)
{ {
int err = -1; int err = -1;
FILE *fcache; BIO *fcache;
X509 *src_cert = (X509 *) cert; X509 *src_cert = (X509 *) cert;
X509 *dst_cert = NULL; X509 *dst_cert = NULL;
EVP_PKEY *pk = NULL; EVP_PKEY *pk = NULL;
RSA *rsa = NULL; RSA *rsa = NULL;
unsigned char p1[] = "RU"; int hash_size = 20;
unsigned char p2[] = "3proxy"; unsigned char hash_sha1[20];
unsigned char p3[] = "3proxy CA"; char hash_name_sha1[(20*2) + 1];
char cache_name[256];
char hash_name_sha1[sizeof(src_cert->sha1_hash)*2 + 1]; err = X509_digest(src_cert, EVP_sha1(), hash_sha1, NULL);
char cache_name[200]; if(!err){
return NULL;
}
bin2hex(src_cert->sha1_hash, sizeof(src_cert->sha1_hash), hash_name_sha1, sizeof(hash_name_sha1)); if(config->certcache){
sprintf(cache_name, "%s%s.pem", cert_path, hash_name_sha1); bin2hex(hash_sha1, 20, hash_name_sha1, sizeof(hash_name_sha1));
sprintf(cache_name, "%s%s.pem", config->certcache, hash_name_sha1);
/* check if certificate is already cached */ /* check if certificate is already cached */
fcache = fopen(cache_name, "rb"); fcache = BIO_new_file(cache_name, "rb");
if ( fcache != NULL ) { if ( fcache != NULL ) {
#ifndef _WIN32 #ifndef _WIN32
flock(fileno(fcache), LOCK_SH); flock(BIO_get_fd(fcache, NULL), LOCK_SH);
#endif #endif
dst_cert = PEM_read_X509(fcache, &dst_cert, NULL, NULL); dst_cert = PEM_read_bio_X509(fcache, &dst_cert, NULL, NULL);
#ifndef _WIN32 #ifndef _WIN32
flock(fileno(fcache), LOCK_UN); flock(BIO_get_fd(fcache, NULL), LOCK_UN);
#endif #endif
fclose(fcache); BIO_free(fcache);
if ( dst_cert != NULL ){ if ( dst_cert != NULL ){
return dst_cert; return dst_cert;
} }
} }
}
/* proceed if certificate is not cached */ /* proceed if certificate is not cached */
dst_cert = X509_dup(src_cert); dst_cert = X509_dup(src_cert);
if ( dst_cert == NULL ) { if ( dst_cert == NULL ) {
@ -146,27 +151,19 @@ SSL_CERT ssl_copy_cert(SSL_CERT cert)
del_ext(dst_cert, NID_authority_key_identifier, -1); del_ext(dst_cert, NID_authority_key_identifier, -1);
del_ext(dst_cert, NID_certificate_policies, 0); del_ext(dst_cert, NID_certificate_policies, 0);
err = X509_set_pubkey(dst_cert, server_key); err = X509_set_pubkey(dst_cert, config->server_key?config->server_key:config->CA_key);
if ( err == 0 ) { if ( err == 0 ) {
X509_free(dst_cert); X509_free(dst_cert);
return NULL; return NULL;
} }
/* Its self signed so set the issuer name to be the same as the err = X509_set_issuer_name(dst_cert, X509_get_subject_name(config->CA_cert));
* subject.
*/
err = X509_set_issuer_name(dst_cert, name);
if(!err){ if(!err){
X509_free(dst_cert); X509_free(dst_cert);
return NULL; return NULL;
} }
err = X509_digest(dst_cert, EVP_sha1(), dst_cert->sha1_hash, NULL); err = X509_sign(dst_cert, config->CA_key, EVP_sha256());
if(!err){
X509_free(dst_cert);
return NULL;
}
err = X509_sign(dst_cert, CA_key, EVP_sha256());
if(!err){ if(!err){
X509_free(dst_cert); X509_free(dst_cert);
return NULL; return NULL;
@ -174,81 +171,105 @@ SSL_CERT ssl_copy_cert(SSL_CERT cert)
/* write to cache */ /* write to cache */
fcache = fopen(cache_name, "wb"); if(config->certcache){
fcache = BIO_new_file(cache_name, "wb");
if ( fcache != NULL ) { if ( fcache != NULL ) {
#ifndef _WIN32 #ifndef _WIN32
flock(fileno(fcache), LOCK_EX); flock(BIO_get_fd(fcache, NULL), LOCK_EX);
#endif #endif
PEM_write_X509(fcache, dst_cert); PEM_write_bio_X509(fcache, dst_cert);
#ifndef _WIN32 #ifndef _WIN32
flock(fileno(fcache), LOCK_UN); flock(BIO_get_fd(fcache, NULL), LOCK_UN);
#endif #endif
fclose(fcache); BIO_free(fcache);
}
} }
return dst_cert; return dst_cert;
} }
SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CERT *server_cert, char **errSSL) SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CONFIG *config, SSL_CERT *server_cert, char **errSSL)
{ {
int err = 0; int err = 0;
X509 *cert;
ssl_conn *conn; ssl_conn *conn;
unsigned long ul;
*errSSL = NULL; *errSSL = NULL;
/*FIXME: support SSL_ERROR_WANT_(READ|WRITE) */
#ifdef _WIN32
ul = 0;
ioctlsocket(s, FIONBIO, &ul);
#else
fcntl(s,F_SETFL,0);
#endif
conn = (ssl_conn *)malloc(sizeof(ssl_conn)); conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL ){ if ( conn == NULL ){
return NULL; return NULL;
} }
conn->ctx = NULL;
#if OPENSSL_VERSION_NUMBER < 0x10100000L conn->ssl = SSL_new(config->srv_ctx);
conn->ctx = SSL_CTX_new(SSLv23_client_method()); if ( conn->ssl == NULL ) {
#else
conn->ctx = SSL_CTX_new(TLS_client_method());
#endif
if ( conn->ctx == NULL ) {
free(conn); free(conn);
return NULL; return NULL;
} }
if(hostname && *hostname && config->client_verify){
X509_VERIFY_PARAM *param;
conn->ssl = SSL_new(conn->ctx); param = SSL_get0_param(conn->ssl);
if ( conn->ssl == NULL ) { X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname));
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
} }
if(!SSL_set_fd(conn->ssl, s)){ if(!SSL_set_fd(conn->ssl, s)){
ssl_conn_free(conn); ssl_conn_free(conn);
*errSSL = getSSLErr();
return NULL; return NULL;
} }
if(hostname && *hostname)SSL_set_tlsext_host_name(conn->ssl, hostname); if(hostname && *hostname)SSL_set_tlsext_host_name(conn->ssl, hostname);
err = SSL_connect(conn->ssl); err = SSL_connect(conn->ssl);
if ( err == -1 ) { if ( err == -1 ) {
*errSSL = ERR_error_string(ERR_get_error(), errbuf); *errSSL = getSSLErr();
ssl_conn_free(conn); ssl_conn_free(conn);
return NULL; return NULL;
} }
if(server_cert){
X509 *cert;
cert = SSL_get_peer_certificate(conn->ssl); cert = SSL_get_peer_certificate(conn->ssl);
if(!cert) { if(!cert) {
ssl_conn_free(conn); ssl_conn_free(conn);
return NULL; return NULL;
} }
/* TODO: Verify certificate */
*server_cert = cert; *server_cert = cert;
}
#ifdef _WIN32
ul = 1;
ioctlsocket(s, FIONBIO, &ul);
#else
fcntl(s,F_SETFL,O_NONBLOCK);
#endif
return conn; return conn;
} }
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char** errSSL)
{ SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CONFIG *config, X509 *server_cert, EVP_PKEY *server_key, char** errSSL){
int err = 0; int err = 0;
X509 *cert; X509 *cert;
ssl_conn *conn; ssl_conn *conn;
unsigned long ul;
/*FIXME: support SSL_ERROR_WANT_(READ|WRITE)*/
#ifdef _WIN32
ul = 0;
ioctlsocket(s, FIONBIO, &ul);
#else
fcntl(s,F_SETFL,0);
#endif
*errSSL = NULL; *errSSL = NULL;
@ -256,50 +277,28 @@ SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char** errSSL)
if ( conn == NULL ) if ( conn == NULL )
return NULL; return NULL;
#if OPENSSL_VERSION_NUMBER < 0x10100000L conn->ctx = NULL;
conn->ctx = SSL_CTX_new(SSLv23_server_method()); conn->ssl = NULL;
#else if(!config->cli_ctx){
conn->ctx = SSL_CTX_new(TLS_server_method()); conn->ctx = ssl_cli_ctx(config, server_cert, server_key, errSSL);
#endif if(!conn->ctx){
if ( conn->ctx == NULL ) { ssl_conn_free(conn);
free(conn);
return NULL; return NULL;
} }
}
err = SSL_CTX_use_certificate(conn->ctx, (X509 *) server_cert); conn->ssl = SSL_new(config->cli_ctx?config->cli_ctx : conn->ctx);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
err = SSL_CTX_use_PrivateKey(conn->ctx, server_key);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
/*
err = SSL_CTX_load_verify_locations(conn->ctx, "3proxy.pem",
NULL);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
*/
conn->ssl = SSL_new(conn->ctx);
if ( conn->ssl == NULL ) { if ( conn->ssl == NULL ) {
SSL_CTX_free(conn->ctx); *errSSL = getSSLErr();
if(conn->ctx)SSL_CTX_free(conn->ctx);
free(conn); free(conn);
return NULL; return NULL;
} }
SSL_set_fd(conn->ssl, (int)s); SSL_set_fd(conn->ssl, s);
err = SSL_accept(conn->ssl); err = SSL_accept(conn->ssl);
if ( err <= 0 ) { if ( err <= 0 ) {
*errSSL = ERR_error_string(ERR_get_error(), errbuf); *errSSL = getSSLErr();
ssl_conn_free(conn); ssl_conn_free(conn);
return NULL; return NULL;
} }
@ -313,6 +312,12 @@ SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char** errSSL)
if ( cert != NULL ) if ( cert != NULL )
X509_free(cert); X509_free(cert);
#ifdef _WIN32
ul = 1;
ioctlsocket(s, FIONBIO, &ul);
#else
fcntl(s,F_SETFL,O_NONBLOCK);
#endif
return conn; return conn;
} }
@ -411,75 +416,17 @@ int thread_cleanup(void)
int ssl_file_init = 0; int ssl_file_init = 0;
int ssl_init_done = 0;
void ssl_init(void) void ssl_init()
{ {
FILE *f; if(!ssl_init_done){
static char fname[200]; ssl_init_done = 1;
if(!ssl_file_init++)pthread_mutex_init(&ssl_file_mutex, NULL);
pthread_mutex_lock(&ssl_file_mutex);
thread_setup(); thread_setup();
SSLeay_add_ssl_algorithms(); SSLeay_add_ssl_algorithms();
SSL_load_error_strings(); SSL_load_error_strings();
pthread_mutex_init(&ssl_file_mutex, NULL);
sprintf(fname, "%.128s3proxy.pem", cert_path);
f = fopen(fname, "r");
if ( f != NULL ) {
PEM_read_X509(f, &CA_cert, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
name = X509_get_subject_name(CA_cert);
sprintf(fname, "%.128s3proxy.key", cert_path);
f = fopen(fname, "rb");
if ( f != NULL ) {
CA_key = PEM_read_PrivateKey(f, &CA_key, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
sprintf(fname, "%.128sserver.key", cert_path);
f = fopen(fname, "rb");
if ( f != NULL ) {
server_key = PEM_read_PrivateKey(f, &server_key, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
if(!CA_cert || !CA_key || !server_key){
fprintf(stderr, "failed to init SSL certificate / keys\n");
}
bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
pthread_mutex_unlock(&ssl_file_mutex); }
} }
void ssl_release(void)
{
pthread_mutex_lock(&ssl_file_mutex);
if ( CA_cert != NULL ) {
X509_free(CA_cert);
CA_cert = NULL;
}
if ( CA_key != NULL ) {
EVP_PKEY_free(CA_key);
CA_key = NULL;
}
if ( server_key != NULL ) {
EVP_PKEY_free(server_key);
server_key = NULL;
}
thread_cleanup();
pthread_mutex_unlock(&ssl_file_mutex);
}

View File

@ -10,16 +10,51 @@ typedef void *SSL_CONN;
// //
typedef void *SSL_CERT; typedef void *SSL_CERT;
struct ssl_config {
X509 *CA_cert;
X509 *server_cert;
X509 *client_cert;
EVP_PKEY *CA_key;
EVP_PKEY *server_key;
EVP_PKEY *client_key;
SSL_CTX *cli_ctx;
SSL_CTX *srv_ctx;
char *certcache;
char * client_ciphersuites;
char * server_ciphersuites;
char * client_cipher_list;
char * server_cipher_list;
char * client_ca_file;
char * client_ca_dir;
char * client_ca_store;
char * server_ca_file;
char * server_ca_dir;
char * server_ca_store;
int mitm;
int serv;
int cli;
int client_min_proto_version;
int client_max_proto_version;
int server_min_proto_version;
int server_max_proto_version;
int client_verify;
int server_verify;
};
typedef struct ssl_config SSL_CONFIG;
// //
// Create copy of certificate signed by "other" CA // Create copy of certificate signed by "other" CA
// //
SSL_CERT ssl_copy_cert(SSL_CERT cert); SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config);
// //
// SSL/TLS handshakes // SSL/TLS handshakes
// //
SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CERT *server_cert, char **errSSL); SSL_CTX * ssl_cli_ctx(SSL_CONFIG *config, X509 *server_cert, EVP_PKEY *server_key,char** errSSL);
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char **errSSL); SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CONFIG *config, X509 *server_cert, EVP_PKEY *server_key, char **errSSL);
SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CONFIG *config, SSL_CERT *server_cert, char **errSSL);
// //
// SSL/TLS Read/Write // SSL/TLS Read/Write
@ -38,6 +73,7 @@ void _ssl_cert_free(SSL_CERT cert);
// Global (de)initialization // Global (de)initialization
// //
void ssl_init(void); void ssl_init(void);
void ssl_release(void); char * getSSLErr(void);
#endif // __my_ssl_h__ #endif // __my_ssl_h__

File diff suppressed because it is too large Load Diff

View File

@ -111,7 +111,7 @@ int h_trafcorrect(int argc, unsigned char ** argv) {
newitem->port = atoi((char *)argv[3]); newitem->port = atoi((char *)argv[3]);
newitem->coeff = atof((char *)argv[4]); newitem->coeff = atof((char *)argv[4]);
/* ďđîâĺđęŕ íŕ ęîđđĺęňíîńňü ââîäŕ */ /* ďđîâĺđęŕ íŕ ęîđđĺęňíîńňü ââîäŕ */
if ((newitem->port>65535) | (newitem->coeff<=0) | (newitem->coeff>100)) { if ((newitem->port>65535) || (newitem->coeff<=0) || (newitem->coeff>100)) {
free(newitem); free(newitem);
if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535 and coefficient must be 0<c<100.\n"); if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535 and coefficient must be 0<c<100.\n");
return 2; return 2;
@ -146,7 +146,7 @@ int h_trafcorrect(int argc, unsigned char ** argv) {
newitem->con_type = TCP; newitem->con_type = TCP;
newitem->psize = 52; newitem->psize = 52;
if ((!strcmp((char *)argv[3], "udp")) & (newitem->p_service != S_PROXY) & (newitem->p_service != S_TCPPM) & (newitem->p_service != S_POP3P)) { if ((!strcmp((char *)argv[3], "udp")) && (newitem->p_service != S_PROXY) && (newitem->p_service != S_TCPPM) && (newitem->p_service != S_POP3P)) {
newitem->con_type = UDP; newitem->con_type = UDP;
newitem->psize = 48; newitem->psize = 48;
} }
@ -157,7 +157,7 @@ int h_trafcorrect(int argc, unsigned char ** argv) {
newitem->psize = atoi((char *)argv[5]); newitem->psize = atoi((char *)argv[5]);
} }
if ((newitem->port>65535) | (newitem->psize<=0)) { if ((newitem->port>65535) || (newitem->psize<=0)) {
free(newitem); free(newitem);
if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535.\n"); if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535.\n");
return 2; return 2;

View File

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

View File

@ -1,6 +1,5 @@
/* /*
3APA3A simpliest proxy server (c) 2007-2021 by Vladimir Dubrovin <3proxy@3proxy.org>
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement please read License Agreement

View File

@ -1,31 +0,0 @@
3proxy 0.6 Windows Authentication Plugin Public License Agreement
This software provided "as is" without any guaranties or support.
This software is FREEWARE. You can use it under terms of current version
of GNU GPL (General Public License) available from
http://www.gnu.org/licenses/gpl.txt or under conditions below:
1. You are granted non-exclusive rights to compile, modify, use and
re-distribute this program.
2. In case this software is redistributed in binary form, source code
MUST be available for user for free.
3. In case this software redistributed embedded in hardware device or
pre-installed version of operation system and source code is not available,
documentation MUST refer to http://www.security.nnov.ru/ as a source of
software.
4. In case this software is modified or is used as a part of another project
license MUST NOT be modified.
5. Authors of this software MAY change terms of this license for future
versions of this product.
(c) 2000-2009 by 3APA3A (3APA3A@security.nnov.ru)
(c) 2000-2009 by SECURITY.NNOV (http://www.security.nnov.ru)
(c) 2000-2009 by Vladimir Dubrovin (vlad@sandy.ru)
This software uses:
RSA Data Security, Inc. MD4 Message-Digest Algorithm
RSA Data Security, Inc. MD5 Message-Digest Algorithm
$Id: copying,v 1.1 2006/02/13 16:08:03 vlad Exp $

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