Compare commits

..

1 Commits

Author SHA1 Message Date
ii343hbka
cead2ceaa9
Merge 10453faa9f into 4e8ea2d7f0 2026-04-04 03:15:14 -07:00
59 changed files with 2519 additions and 2563 deletions

View File

@ -78,16 +78,15 @@ jobs:
nmake /F Makefile.msvc64 nmake /F Makefile.msvc64
nmake /F Makefile.msvc64 clean nmake /F Makefile.msvc64 clean
- name: make with CMake POSIX - name: make with CMake POSIX
if: ${{ ! startsWith(matrix.target, 'windows') }} if: ${{ !startsWith(matrix.target, 'windows') }}
run: mkdir build && cd build && cmake .. && cmake --build . run: mkdir build && cd build && cmake .. && make
- name: make with CMake Win - name: make with CMake Win
if: ${{ startsWith(matrix.target, 'windows') }} if: ${{ startsWith(matrix.target, 'windows') }}
shell: cmd
run: | run: |
mkdir build mkdir build
cd build cd build
set "LIB=%LIB%;c:/program files/openssl/lib/VC/x64/MT;c:/vcpkg/installed/x64-windows/lib" # set "LIB=%LIB%;c:/program files/openssl/lib/VC/x64/MT;c:/vcpkg/installed/x64-windows/lib"
set "INCLUDE=%INCLUDE%;c:/program files/openssl/include;c:/vcpkg/installed/x64-windows/include" # set "INCLUDE=%INCLUDE%;c:/program files/openssl/include;c:/vcpkg/installed/x64-windows/include"
cmake .. cmake -DCMAKE_C_COMPILER=clang ..
dir dir
cmake --build . make

View File

@ -509,117 +509,6 @@ if(NOT WIN32)
install(FILES scripts/add3proxyuser.sh DESTINATION ${CMAKE_INSTALL_BINDIR}) install(FILES scripts/add3proxyuser.sh DESTINATION ${CMAKE_INSTALL_BINDIR})
endif() endif()
# Install service files (systemd, launchd, init.d, or rc.d)
if(NOT WIN32)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# macOS - install launchd plist
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/org.3proxy.3proxy.plist.in
${CMAKE_CURRENT_BINARY_DIR}/org.3proxy.3proxy.plist
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/org.3proxy.3proxy.plist
DESTINATION /Library/LaunchDaemons
)
message(STATUS " launchd: YES (/Library/LaunchDaemons)")
elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD|OpenBSD|NetBSD")
# BSD - install rc.d script
set(RCD_DIR "/usr/local/etc/rc.d")
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/rc.d/3proxy.in
${CMAKE_CURRENT_BINARY_DIR}/3proxy.rc
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/3proxy.rc
DESTINATION ${RCD_DIR}
RENAME 3proxy
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)
message(STATUS " rc.d: YES (${RCD_DIR})")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
# Linux - check for systemd
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(SYSTEMD QUIET systemd)
endif()
if(SYSTEMD_FOUND)
# systemd is available - install systemd service
# Get systemd unit directory
pkg_get_variable(SYSTEMD_UNIT_DIR systemd systemdsystemunitdir)
if(NOT SYSTEMD_UNIT_DIR)
# Fallback to common location
set(SYSTEMD_UNIT_DIR "/lib/systemd/system")
endif()
# Configure and install systemd service file
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/3proxy.service.in
${CMAKE_CURRENT_BINARY_DIR}/3proxy.service
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/3proxy.service
DESTINATION ${SYSTEMD_UNIT_DIR}
)
# Install tmpfiles.d configuration for runtime directory
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/3proxy.tmpfiles.in
${CMAKE_CURRENT_BINARY_DIR}/3proxy.conf
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/3proxy.conf
DESTINATION /usr/lib/tmpfiles.d
)
message(STATUS " systemd: YES (${SYSTEMD_UNIT_DIR})")
else()
# No systemd - install init.d script
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/init.d/3proxy.in
${CMAKE_CURRENT_BINARY_DIR}/3proxy.init
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/3proxy.init
DESTINATION /etc/init.d
RENAME 3proxy
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)
message(STATUS " systemd: NO (using init.d)")
endif()
else()
# Other Unix - install init.d script
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/scripts/init.d/3proxy.in
${CMAKE_CURRENT_BINARY_DIR}/3proxy.init
@ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/3proxy.init
DESTINATION /etc/init.d
RENAME 3proxy
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)
message(STATUS " init.d: YES (/etc/init.d)")
endif()
# Create proxy user and group during installation
install(FILES scripts/postinstall.sh
DESTINATION ${CMAKE_INSTALL_BINDIR}
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
)
install(CODE "
execute_process(
COMMAND ${CMAKE_INSTALL_FULL_BINDIR}/postinstall.sh
RESULT_VARIABLE POSTINSTALL_RESULT
)
")
endif()
# Install man pages # Install man pages
if(NOT WIN32) if(NOT WIN32)
file(GLOB MAN3_FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/*.3") file(GLOB MAN3_FILES "${CMAKE_CURRENT_SOURCE_DIR}/man/*.3")

View File

@ -50,7 +50,6 @@ 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/rc.d/3proxy /usr/local/etc/rc.d/3proxy
install scripts/add3proxyuser.sh /usr/local/3proxy/bin/ install scripts/add3proxyuser.sh /usr/local/3proxy/bin/
if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then /usr/local/3proxy/3proxy.cfg already exists ; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then /usr/local/3proxy/3proxy.cfg already exists ; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi
if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi

View File

@ -72,8 +72,8 @@ INSTALL_OBJS = bin/3proxy \
INSTALL_CFG = scripts/3proxy.cfg.chroot INSTALL_CFG = scripts/3proxy.cfg.chroot
INSTALL_CFG_INCHROOT = scripts/3proxy.cfg.inchroot INSTALL_CFG_OBJS = scripts/3proxy.cfg \
INSTALL_CFG_OBJS = scripts/add3proxyuser.sh scripts/add3proxyuser.sh
INSTALL_CFG_OBJS2 = counters bandlimiters INSTALL_CFG_OBJS2 = counters bandlimiters
@ -117,7 +117,6 @@ install-etc-default-config: install-chroot-dir
ln -s $(CHROOTREL)/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); \
$(INSTALL_BIN) $(INSTALL_CFG_INCHROOT) $(INSTALL_CFG_DEST)/3proxy.cfg; \
fi fi
install-etc: install-etc-dir install-etc-default-config install-etc: install-etc-dir install-etc-default-config

View File

@ -48,17 +48,23 @@ endif
include Makefile.inc include Makefile.inc
install: all install: all
if [ ! -d "/usr/local/3proxy/bin" ]; then mkdir -p /usr/local/3proxy/bin/; fi if [ ! -d /usr/local/etc/3proxy/bin ]; then mkdir -p /usr/local/etc/3proxy/bin/; fi
install bin/3proxy /usr/local/3proxy/bin/3proxy install bin/3proxy /usr/local/etc/3proxy/bin/3proxy
install bin/mycrypt /usr/local/3proxy/bin/mycrypt install bin/mycrypt /usr/local/etc/3proxy/bin/mycrypt
install scripts/rc.d/3proxy /usr/local/etc/rc.d/3proxy install scripts/rc.d/proxy.sh /usr/local/etc/rc.d/proxy.sh
install scripts/add3proxyuser.sh /usr/local/3proxy/bin/ install scripts/add3proxyuser.sh /usr/local/etc/3proxy/bin/
if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then /usr/local/3proxy/3proxy.cfg already exists ; else install scripts/3proxy.cfg /usr/local/etc/3proxy/; fi if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then
if [ ! -d /var/log/3proxy/ ]; then mkdir /var/log/3proxy/; fi echo /usr/local/etc/3proxy/3proxy.cfg already exists
touch /usr/local/3proxy/passwd else
touch /usr/local/3proxy/counters install scripts/3proxy.cfg /usr/local/etc/3proxy/
touch /usr/local/3proxy/bandlimiters if [ ! -d /var/log/3proxy/ ]; then
echo Run /usr/local/3proxy/bin/add3proxyuser.sh to add \'admin\' user mkdir /var/log/3proxy/
fi
touch /usr/local/etc/3proxy/passwd
touch /usr/local/etc/3proxy/counters
touch /usr/local/etc/3proxy/bandlimiters
echo Run /usr/local/etc/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

59
Makefile.unix-install Normal file
View File

@ -0,0 +1,59 @@
DESTDIR =
prefix = /usr/local
exec_prefix = $(prefix)
man_prefix = $(prefix)/share
INSTALL = /usr/bin/install
INSTALL_BIN = $(INSTALL) -m 755
INSTALL_DATA = $(INSTALL) -m 644
INSTALL_OBJS = bin/3proxy \
bin/ftppr \
bin/mycrypt \
bin/pop3p \
bin/proxy \
bin/socks \
bin/tcppm \
bin/udppm \
scripts/add3proxyuser.sh
INSTALL_CFG_OBJS = scripts/3proxy.cfg
INSTALL_CFG_DEST = config
INSTALL_CFG_OBJS2 = passwd counters bandlimiters
MANDIR1 = $(DESTDIR)$(man_prefix)/man/man1
MANDIR3 = $(DESTDIR)$(man_prefix)/man/man3
MANDIR8 = $(DESTDIR)$(man_prefix)/man/man8
BINDIR = $(DESTDIR)$(exec_prefix)/bin
ETCDIR = $(DESTDIR)$(prefix)/etc/3proxy
install-bin:
$(INSTALL_BIN) -d $(BINDIR)
$(INSTALL_BIN) -s $(INSTALL_OBJS) $(BINDIR)
install-etc-dir:
$(INSTALL_BIN) -d $(ETCDIR)
install-etc-default-config:
if [ -f $(ETCDIR)/$(INSTALL_CFG_DEST) ]; then \
: ; \
else \
$(INSTALL_DATA) $(INSTALL_CFG_OBJS) $(ETCDIR)/$(INSTALL_CFG_DEST) \
fi
install-etc: install-etc-dir
for file in $(INSTALL_CFG_OBJS2); \
do \
touch $(ETCDIR)/$$file; chmod 0600 $(ETCDIR)/$$file; \
done;
install-man:
$(INSTALL_BIN) -d $(MANDIR1)
$(INSTALL_BIN) -d $(MANDIR3)
$(INSTALL_BIN) -d $(MANDIR8)
$(INSTALL_DATA) man/*.1 $(MANDIR1)
$(INSTALL_DATA) man/*.3 $(MANDIR3)
$(INSTALL_DATA) man/*.8 $(MANDIR8)
install: install-bin install-etc install-man

32
Makefile.winCE Normal file
View File

@ -0,0 +1,32 @@
#
# 3 proxy Makefile for GCC/windows
#
#
# remove -DNOODBC from CFLAGS and add -lodbc to LDFLAGS to compile with ODBC
# library support
BUILDDIR = ../bin/
CC = /opt/cegcc/arm-wince-cegcc/bin/gcc
CFLAGS = -O2 -s -c -mthreads -DNOODBC -D_WINCE -D_WIN32 -DNORADIUS -D__USE_W32_SOCKETS
COUT = -o
LN = /opt/cegcc/arm-wince-cegcc/bin/gcc
LDFLAGS = -O2 -s -mthreads
DLFLAGS = -shared
DLSUFFICS = .dll
LIBS = -lws2
LNOUT = -o
EXESUFFICS = .exe
OBJSUFFICS = .o
DEFINEOPTION = -D
COMPFILES = *.tmp
REMOVECOMMAND = rm -f
TYPECOMMAND = more
COMPATLIBS =
MAKEFILE = Makefile.winCE
PLUGINS = TrafficPlugin StringsPlugin
include Makefile.inc
allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; rm *.o ; cd ../.. ; done

51
README
View File

@ -21,10 +21,10 @@ Devel branch - 3proxy 10 (don't use it)
* Windows installation * Windows installation
3proxy [path_to_config_file] --install 3proxy --install
installs and starts proxy as Windows service installs and starts proxy as Windows service
(config file should be located in the same directory or may be optionally specified) (config file should be located in the same directory)
3proxy --remove 3proxy --remove
@ -33,7 +33,7 @@ Devel branch - 3proxy 10 (don't use it)
* To build in Linux * To build in Linux
With Makefile: 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
@ -41,7 +41,6 @@ ln -s Makefile.Linux Makefile
make make
sudo make install sudo make install
Default configuration (for Linux/Unix): Default configuration (for Linux/Unix):
3proxy uses 2 configuration files: 3proxy uses 2 configuration files:
/etc/3proxy/3proxy.cfg (before-chroot). This configuration file is executed before chroot and should not be modified. /etc/3proxy/3proxy.cfg (before-chroot). This configuration file is executed before chroot and should not be modified.
@ -59,59 +58,15 @@ usage: /etc/3proxy/conf/add3proxyuser.sh username password [day_limit] [bandwidt
or modify /etc/3proxy/conf/ files directly. or modify /etc/3proxy/conf/ files directly.
With CMake:
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
CMake does not use chroot configuration, config file is /etc/3proxy/3proxy.cfg
* For MacOS X / FreeBSD / *BSD * For MacOS X / FreeBSD / *BSD
With Makefile:
git clone https://github.com/z3apa3a/3proxy git clone https://github.com/z3apa3a/3proxy
cd 3proxy cd 3proxy
ln -s Makefile.FreeBSD Makefile ln -s Makefile.FreeBSD Makefile
make make
(binaries are in bin/ directory) (binaries are in bin/ directory)
With CMake (recommended):
git clone https://github.com/z3apa3a/3proxy
cd 3proxy
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .
This installs binaries to /usr/local/bin/, configuration to /etc/3proxy/,
plugins to /usr/local/lib/3proxy/, rc scripts to rc.d for BSD and launchd plist to /Library/LaunchDaemons/ for MacOS.
Service management on macOS:
# Load and start service
sudo launchctl load /Library/LaunchDaemons/org.3proxy.3proxy.plist
# Stop service
sudo launchctl stop org.3proxy.3proxy
# Start service
sudo launchctl start org.3proxy.3proxy
# Unload and disable service
sudo launchctl unload /Library/LaunchDaemons/org.3proxy.3proxy.plist
Features: Features:
1. General 1. General
+ IPv6 support for incoming and outgoing connection, + IPv6 support for incoming and outgoing connection,

View File

@ -137,6 +137,14 @@ dnspr
# this is just an alternative form fo giving external and internal address # this is just an alternative form fo giving external and internal address
# allows you to read this addresses from files # allows you to read this addresses from files
auth strong
# We want to protect internal interface
deny * * 127.0.0.1,192.168.1.1
# and llow HTTP and HTTPS traffic.
allow * * * 80-88,8080-8088 HTTP
allow * * * 443,8443 HTTPS
proxy -n
auth none auth none
# pop3p will be used without any authentication. It's bad choice # pop3p will be used without any authentication. It's bad choice
# because it's possible to use pop3p to access any port # because it's possible to use pop3p to access any port
@ -152,6 +160,16 @@ tcppm 25 mail.my.provider 25
# It's very userfull for services like DNS but not for some massive services # It's very userfull for services like DNS but not for some massive services
# like multimedia streams or online games. # like multimedia streams or online games.
auth strong
flush
allow 3APA3A,test
maxconn 20
socks
# for socks we will use password authentication and different access control -
# we flush previously configured ACL list and create new one to allow users
# test and 3APA3A to connect from any location
auth strong auth strong
flush flush
internal 127.0.0.1 internal 127.0.0.1
@ -181,21 +199,3 @@ admin
# now we needn't any root rights. We can chroot and setgid/setuid. # now we needn't any root rights. We can chroot and setgid/setuid.
auth strong
flush
# We want to protect internal interface
deny * * 127.0.0.1,192.168.1.1
# and llow HTTP and HTTPS traffic.
allow * * * 80-88,8080-8088 HTTP
allow * * * 443,8443 HTTPS
proxy -n
flush
allow 3APA3A,test
maxconn 20
socks
# for socks we will use password authentication and different access control -
# we flush previously configured ACL list and create new one to allow users
# test and 3APA3A to connect from any location

View File

@ -1,2 +1,2 @@
<H2><A href="howtoe.html">See HowTo:</a></H2> <H2><A href="hotoe.html">See HowTo:</a></H2>

View File

@ -1,2 +1,2 @@
<H2><A href="howtoe.html">См. HowTo</a></H2> <H2><A href="hotoe.html">См. HowTo</a></H2>

View File

@ -1,12 +1,12 @@
<h3>Optimizing 3proxy for High Load</h3> <h3>Optimizing 3proxy for high load</h3>
<p>Precaution 1: 3proxy was not initially developed for high load and is positioned as a SOHO product. The main reason is the "one connection - one thread" model 3proxy uses. 3proxy is known to work with over 200,000 connections under proper configuration, but use it in a production environment under high loads at your own risk and do not expect too much. <p>Precaution 1: 3proxy was not initially developed for high load and is positioned as a SOHO product, the main reason is "one connection - one thread" model 3proxy uses. 3proxy is known to work with above 200,000 connections under proper configuration, but use it in production environment under high loads at your own risk and do not expect too much.
<p>Precaution 2: This documentation is incomplete and insufficient. High loads may require very specific system tuning including, but not limited to, specific or customized kernels, builds, settings, sysctls, options, etc. All of this is not covered by this documentation. <p>Precaution 2: This documentation is incomplete and is not sufficient. High loads may require very specific system tuning including, but not limited to specific or cusomized kernels, builds, settings, sysctls, options, etc. All this is not covered by this documentation.
<h4>Configuring 'maxconn'</h4> <h4>Configuring 'maxconn'</h4>
The number of simultaneous connections per service is limited by the 'maxconn' option. A number of simulatineous connections per service is limited by 'maxconn' option.
The default maxconn value since 3proxy 0.8 is 500. You may want to set 'maxconn' Default maxconn value since 3proxy 0.8 is 500. You may want to set 'maxconn'
to a higher value. Under this configuration: to higher value. Under this configuration:
<pre> <pre>
maxconn 1000 maxconn 1000
proxy -p3129 proxy -p3129
@ -14,53 +14,53 @@ proxy -p3128
socks socks
</pre> </pre>
maxconn for every service is 1000, and there are 3 services running maxconn for every service is 1000, and there are 3 services running
(2 proxy and 1 socks), so for all services there can be up to 3000 (2 proxy and 1 socks), so, for all services there can be up to 3000
simultaneous connections to 3proxy. simulatineous connections to 3proxy.
<p>Avoid setting 'maxconn' to an arbitrarily high value; it should be carefully <p>Avoid setting 'maxconn' to arbitrary high value, it should be carefully
chosen to protect the system and proxy from resource exhaustion. Setting maxconn choosen to protect system and proxy from resources exhaution. Setting maxconn
above available resources can lead to denial of service conditions. above resources available can lead to denial of service conditions.
<h4>Understanding Resource Requirements</h4> <h4>Understanding resources requirements</h4>
Each running service requires: Each running service require:
<ul> <ul>
<li>1 thread (process) <li>1*thread (process)
<li>1 socket (file descriptor) <li>1*socket (file descriptor)
<li>1 stack memory segment + some heap memory, ~64K-128K depending on the system <li>1 stack memory segment + some heap memory, ~64K-128K depending on the system
</ul> </ul>
Each connected client requires: Each connected client require:
<ul> <ul>
<li>1 thread (process) <li>1*thread (process)
<li>2 sockets (file descriptors). For FTP, 4 sockets are required. <li>2*socket (file descriptor). For FTP 4 sockets are required.
<br>Under Linux since 0.9, splice() is used. It's much more efficient but requires <br>Under linux since 0.9 splice() is used. It's much more effective, but requires
<br>2 sockets (file descriptors) + 2 pipes (file descriptors) = 4 file descriptors. <br>2*socket (file descriptor) + 2*pipe (file descriptors) = 4 file descriptors.
<br>For FTP with splice(), 4 sockets and 2 pipes are required. <br>For FTP 4 sockets and 2 pipes are required with splice().
<br>Up to 128K (up to 256K in the case of splice()) of kernel buffer memory. This is the theoretical maximum; actual numbers depend on connection quality and traffic amount. <br>Up to 128K (up to 256K in the case of splice()) of kernel buffers memory. This is theoretical maximum, actual numbers depend on connection quality and traffic amount.
<br>1 additional socket (file descriptor) during name resolution for non-cached names <br>1 additional socket (file descriptor) during name resolution for non-cached names
<br>1 additional socket during authentication or logging for RADIUS authentication or logging. <br>1 additional socket during authentication or logging for RADIUS authentication or logging.
<li>1 ephemeral port (3 ephemeral ports for FTP connections). <li>1*ephemeral port (3*ephemeral ports for FTP connection).
<li>1 stack memory segment of ~32K-128K depending on the system + at least 16K and up to a few MB (for 'proxy' and 'ftppr') of heap memory. If you are short on memory, prefer 'socks' over 'proxy' and 'ftppr'. <li>1 stack memory segment of ~32K-128K depending on the system + at least 16K and up to few MB (for 'proxy' and 'ftppr') of heap memory. If you are short of memory, prefer 'socks' to 'proxy' and 'ftppr'.
<li>Many system buffers, especially in the case of slow network connections. <li>a lot of system buffers, specially in the case of slow network connections.
</ul> </ul>
Also, additional resources like system buffers are required for network activity. Also, additional resources like system buffers are required for network activity.
<h4>Setting ulimits</h4> <h4>Setting ulimits</h4>
Hard and soft ulimits must be set above calculated requirements. Under Linux, you can Hard and soft ulimits must be set above calculated requirements. Under Linux, you can
check the limits of a running process with check limits of running process with
<pre> <pre>
cat /proc/PID/limits cat /proc/PID/limits
</pre> </pre>
where PID is the process ID. where PID is a pid of the process.
Validate that ulimits match your expectations, especially if you run 3proxy under a dedicated account Validate ulimits match your expectation, especially if you run 3proxy under dedicated account
by adding, e.g.: by adding e.g.
<pre> <pre>
system "ulimit -Ha >>/tmp/3proxy.ulim.hard" system "ulimit -Ha >>/tmp/3proxy.ulim.hard"
system "ulimit -Sa >>/tmp/3proxy.ulim.soft" system "ulimit -Sa >>/tmp/3proxy.ulim.soft"
</pre> </pre>
at the beginning (before the first service is started) and at the end of the config file. in the beginning (before first service started) and the end of config file.
Perform both a hard restart (i.e., kill and start the 3proxy process) and a soft restart Make both hard restart (that is kill and start 3proxy process) and soft restart
by sending SIGUSR1 to the 3proxy process; check that the ulimits recorded to files match your by sending SIGUSR1 to 3proxy process, check ulimits recorded to files match your
expectations. In systemd-based distros (e.g., latest Debian/Ubuntu), changing limits.conf expecation. In systemd based distros (e.g. latest Debian / Ubuntu) changing limits.conf
is not enough; limits must be adjusted in the systemd configuration, e.g., by setting: is not enough, limits must be ajusted in systemd configuration, e.g. by setting
<pre> <pre>
DefaultLimitDATA=infinity DefaultLimitDATA=infinity
DefaultLimitSTACK=infinity DefaultLimitSTACK=infinity
@ -73,51 +73,51 @@ DefaultLimitMEMLOCK=infinity
</pre> </pre>
in user.conf / system.conf in user.conf / system.conf
<h4>Extending System Limitations</h4> <h4>Extending system limitation</h4>
Check the manuals/documentation for your system's limitations, e.g., the system-wide limit for the number of open files Check manuals / documentation for your system limitations e.g. system-wide limit for number of open files
(fs.file-max in Linux). You may need to change sysctls or even rebuild the kernel from source. (fs.file-max in Linux). You may need to change sysctls or even rebuild the kernel from source.
<p> <p>
To help with socket-based system-dependent settings, since 0.9-devel, 3proxy supports different To help with socket-based system-dependant settings, since 0.9-devel 3proxy supports different
socket options which can be set via the -ol option for the listening socket, -oc for the proxy-to-client socket options which can be set via -ol option for listening socket, -oc for proxy-to-client
socket, and -os for the proxy-to-server socket. Example: socket and -os for proxy-to-server socket. Example:
<pre> <pre>
proxy -olSO_REUSEADDR,SO_REUSEPORT -ocTCP_TIMESTAMPS,TCP_NODELAY -osTCP_NODELAY proxy -olSO_REUSEADDR,SO_REUSEPORT -ocTCP_TIMESTAMPS,TCP_NODELAY -osTCP_NODELAY
</pre> </pre>
Available options are system-dependent. available options are system dependant.
<h4>Using 3proxy in a Virtual Environment</h4> <h4>Using 3proxy in virtual environment</h4>
If 3proxy is used in a VPS environment, there can be additional limitations. If 3proxy is used in VPS environment, there can be additional limitations.
For example, kernel resources, system CPU usage, and IOCTLs can be limited differently, and this can become a bottleneck. For example, kernel resources / system CPU usage / IOCTLs can be limited in a different way, and this can become a bottleneck.
Since 0.9-devel, 3proxy uses splice() by default on Linux. splice() prevents network traffic from being copied from Since 0.9 devel, 3proxy uses splice() by default on Linux, splice() prevents network traffic from being copied from
kernel space to the 3proxy process and generally increases throughput, especially in the case of high-volume traffic. This is especially kernel space to 3proxy process and generally increases throughput, epecially in the case of high volume traffic. It especially
true for virtual environments (it can improve throughput up to 10 times) unless there are additional kernel limitations. true for virtual environment (it can improve thoughput up to 10 times) unless there are additional kernel limitations.
Since some work is moved to the kernel, it requires up to 2 times more kernel resources in terms of CPU, memory, and IOCTLs. Since some work is moved to kernel, it requires up to 2 times more kernel resources in terms of CPU, memory and IOCTLs.
If your hosting additionally limits kernel resources (you can see this as nearly 100% CPU usage without any real CPU activity for If your hosting additionally limits kernel resources (you can see it as nearly 100% CPU usage without any real CPU activity for
any application performing IOCTLs), use the -s0 option to disable splice() usage for a given service, e.g.: any application which performs IOCTLS), use -s0 option to disable splice() usage for given service e.g.
<pre> <pre>
socks -s0 socks -s0
</pre> </pre>
<h4>Extending the Ephemeral Port Range</h4> <h4>Extending ephemeral port range</h4>
Check the ephemeral port range for your system and extend it to the number of Check ephemeral port range for your system and extend it to the number of the
ports required. ports required.
The ephemeral range is always limited to the maximum number of ports (64K). To extend the Ephimeral range is always limited to maximum number of ports (64K). To extend the
number of outgoing connections above this limit, extending the ephemeral port range number of outgoing connections above this limit, extending ephemeral port range
is not enough; you need additional actions: is not enough, you need additional actions:
<ol> <ol>
<li> Configure multiple outgoing IPs <li> Configure multiple outgoing IPs
<li> Make sure 3proxy is configured to use a different outgoing IP by either setting <li> Make sure 3proxy is configured to use different outgoing IP by either setting
the external IP via RADIUS: external IP via RADIUS
<pre> <pre>
radius secret 1.2.3.4 radius secret 1.2.3.4
auth radius auth radius
proxy proxy
</pre> </pre>
or by using multiple services with different external or by using multiple services with different external
interfaces, for example: interfaces, example:
<pre> <pre>
allow user1,user11,user111 allow user1,user11,user111
proxy -p1111 -e1.1.1.1 proxy -p1111 -e1.1.1.1
@ -133,7 +133,7 @@ proxy -p4444 -e4.4.4.4
flush flush
</pre> </pre>
or via "parent extip" rotation, or via "parent extip" rotation,
e.g.: e.g.
<pre> <pre>
allow user1,user11,user111 allow user1,user11,user111
parent 1000 extip 1.1.1.1 0 parent 1000 extip 1.1.1.1 0
@ -156,8 +156,8 @@ socks
</pre> </pre>
<pre> <pre>
</pre> </pre>
Under the latest Linux versions, you can also start multiple services with different Under latest Linux version you can also start multiple services with different
external addresses on a single port with SO_REUSEPORT on the listening socket to external addresses on the single port with SO_REUSEPORT on listening socket to
evenly distribute incoming connections between outgoing interfaces: evenly distribute incoming connections between outgoing interfaces:
<pre> <pre>
socks -olSO_REUSEPORT -p3128 -e 1.1.1.1 socks -olSO_REUSEPORT -p3128 -e 1.1.1.1
@ -165,136 +165,136 @@ socks -olSO_REUSEPORT -p3128 -e 2.2.2.2
socks -olSO_REUSEPORT -p3128 -e 3.3.3.3 socks -olSO_REUSEPORT -p3128 -e 3.3.3.3
socks -olSO_REUSEPORT -p3128 -e 4.4.4.4 socks -olSO_REUSEPORT -p3128 -e 4.4.4.4
</pre> </pre>
For web browsing, the last two examples are not recommended because the same client can get for Web browsing last two examples are not recommended, because same client can get
a different external address for different requests; you should choose the external different external address for different requests, you should choose external
interface with user-based rules instead. interface with user-based rules instead.
<li> You may need additional system-dependent actions to use the same port on different IPs, <li> You may need additional system dependant actions to use same port on different IPs,
usually by adding the SO_REUSEADDR (SO_PORT_SCALABILITY for Windows) socket option to usually by adding SO_REUSEADDR (SO_PORT_SCALABILITY for Windows) socket option to
the external socket. This option can be set (since 0.9-devel) with the -os option: external socket. This option can be set (since 0.9 devel) with -os option:
<pre> <pre>
proxy -p3128 -e1.2.3.4 -osSO_REUSEADDR proxy -p3128 -e1.2.3.4 -osSO_REUSEADDR
</pre> </pre>
The behavior for SO_REUSEADDR and SO_REUSEPORT is different between different systems, Behavior for SO_REUSEADDR and SO_REUSEPORT is different between different system,
even between different kernel versions, and can lead to unexpected results. even between different kernel versions and can lead to unexpected results.
The specifics are described <a href="https://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t">here</a>. Specifics is described <a href="https://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t">here</a>.
Use these options only if actually required and if you fully understand the possible Use this options only if actually required and if you fully understand possible
consequences. For example, SO_REUSEPORT can help establish more connections than the consiquences. E.g. SO_REUSEPORT can help to establish more connections than the
number of client ports available, but it can also lead to situations where connections number of the client port available, but it can also lead to situation connections
randomly fail due to IP+port pair collisions if the remote or local system are randomely fail due to ip+port pairs collision if remote or local system
doesn't support this trick. doesn't support this trick.
</ol> </ol>
<h4>Setting Stack Size</h4> <h4>Setting stacksize</h4>
'stacksize' is a size added to all stack allocations and can be both positive and 'stacksize' is a size added to all stack allocations and can be both positive and
negative. Stack is required for function calls. 3proxy itself doesn't require a large negative. Stack is required in functions call. 3proxy itself doesn't require large
stack, but it can be required if some stack, but it can be required if some
poorly written libc, 3rd party libraries, or system functions are called. There is known purely-written libc, 3rd party libraries or system functions called. There is known\
dirty code in Unix ODBC dirty code in Unix ODBC
implementations and built-in DNS resolvers, especially in the case of IPv6 and a large implementations, build-in DNS resolvers, especially in the case of IPv6 and large
number of interfaces. Under most 64-bit systems, extending stacksize will lead number of interfaces. Under most 64-bit system extending stacksize will lead
to additional memory space usage but does not require actual committed memory, to additional memory space usage, but do not require actual commited memory,
so you can increase stacksize to a relatively large value (e.g., 1024000) without so you can inrease stacksize to relatively large value (e.g. 1024000) without
the need to add additional physical memory, the need to add additional phisical memory,
but it's system/libc dependent and requires additional testing under your but it's system/libc dependant and requires additional testing under your
installation. Don't forget about memory-related ulimits. installation. Don't forget about memory related ulimts.
<p>For 32-bit systems, address space can be a bottleneck you should consider. If <p>For 32-bit systems address space can be a bottlneck you should consider. If
you're short on address space, you can try using a negative stack size. you're short of address space you can try to use negative stack size.
<h4>Known System Issues</h4> <h4>Known system issues</h4>
There are known race condition issues in the Linux/glibc resolver. The probability There are known race condition issues in Linux / glibc resolver. The probability
of a race condition arises under configuration with IPv6, a large number of interfaces of race condition arises under configuration with IPv6, large number of interfaces
or IP addresses, or with resolvers configured. In this case, install a local recursor and or IP addresses or resolvers configured. In this case, install local recursor and
use 3proxy's built-in resolver (nserver / nscache / nscache6). use 3proxy built-in resolver (nserver / nscache / nscache6).
<h4>Do Not Use Public Resolvers</h4> <h4>Do not use public resolvers</h4>
Public resolvers like those from Google have rate limits. For a large number of Public resolvers like ones from Google have ratelimits. For large number of
requests, install a local caching recursor (ISC bind named, PowerDNS recursor, etc). requests install local caching recursor (ISC bind named, PowerDNS recursor, etc).
<h4>Avoid Large Lists</h4> <h4>Avoid large lists</h4>
Currently, 3proxy is not optimized to use large ACLs, user lists, etc. All lists Currently, 3proxy is not optimized to use large ACLs, user lists, etc. All lists
are processed linearly. In the devel version, you can use RADIUS authentication to avoid are processed lineary. In devel version you can use RADIUS authentication to avoid
user lists and ACLs in 3proxy itself. Also, RADIUS allows you to easily set an outgoing IP user lists and ACLs in 3proxy itself. Also, RADIUS allows to easily set outgoing IP
on a per-user basis or implement more sophisticated logic. on per-user basis or more sophisicated logics.
RADIUS is a new beta feature; test it before using it in production. RADIUS is a new beta feature, test it before using in production.
<h4>Avoid Changing Configuration Too Often</h4> <h4>Avoid changing configuration too often</h4>
Every configuration reload requires additional resources. Do not make frequent Every configuration reload requires additional resources. Do not do frequent
changes, such as user addition/deletion via configuration; use alternative changes, like users addition/deletaion via connfiguration, use alternative
authentication methods instead, like RADIUS. authentication methods instead, like RADIUS.
<h4>Consider Using 'noforce'</h4> <h4>Consider using 'noforce'</h4>
The 'force' behavior (default) re-authenticates all connections after 'force' behaviour (default) re-authenticates all connections after
configuration reload; it may be resource-consuming with a large number of configuration reload, it may be resource consuming on large number of
connections. Consider adding the 'noforce' command before services are started connections. Consider adding 'noforce' command before services started
to prevent connection re-authentication. to prevent connections reauthentication.
<h4>Do Not Monitor Configuration Files Directly</h4> <h4>Do not monitor configuration files directly</h4>
Using a configuration file directly in 'monitor' can lead to a race condition where Using configuration file directly in 'monitor' can lead to race condition where
the configuration is reloaded while the file is being written. configuration is reloaded while file is being written.
To avoid race conditions: To avoid race conditions:
<ol> <ol>
<li> Update config files only if there is no lock file <li> Update config files only if there is no lock file
<li> Create a lock file when the 3proxy configuration is updated, e.g., with <li> Create lock file then 3proxy configuration is updated, e.g. with
"touch /some/path/3proxy/3proxy.lck". If you generate config files "touch /some/path/3proxy/3proxy.lck". If you generate config files
asynchronously, e.g., by a user's request via web, you should consider asynchronously, e.g. by user's request via web, you should consider
implementing existence checking and file creation as an atomic operation. implementing existance checking and file creation as atomic operation.
<li> Add <li>add
<pre> <pre>
system "rm /some/path/3proxy/3proxy.lck" system "rm /some/path/3proxy/3proxy.lck"
</pre> </pre>
at the end of the config file to remove it after the configuration is successfully loaded at the end of config file to remove it after configuration is successfully loaded
<li> Use a dedicated version file to monitor, e.g.: <li> Use a dedicated version file to monitor, e.g.
<pre> <pre>
monitor "/some/path/3proxy/3proxy.ver" monitor "/some/path/3proxy/3proxy.ver"
</pre> </pre>
<li> After the config is updated, change the version file for 3proxy to reload the configuration, <li> After config is updated, change version file for 3proxy to reload configuration,
e.g., with "touch /some/path/3proxy/3proxy.ver". e.g. with "touch /some/path/3proxy/3proxy.ver".
</ol> </ol>
<h4>Use TCP_NODELAY to Speed Up Connections with Small Amounts of Data</h4> <h4>Use TCP_NODELAY to speed-up connections with small amount of data</h4>
If most requests require an exchange with a small amount of data in both directions If most requests require exchange with a small amount of data in a both ways
without the need for bandwidth, e.g., messengers or small web requests, without the need for bandwidth, e.g. messengers or small web request,
you can eliminate Nagle's algorithm delay with the TCP_NODELAY flag. Usage example: you can eliminate Nagle's algorithm delay with TCP_NODELAY flag. Usage example:
<pre> <pre>
proxy -osTCP_NODELAY -ocTCP_NODELAY proxy -osTCP_NODELAY -ocTCP_NODELAY
</pre> </pre>
sets TCP_NODELAY for client (oc) and server (os) connections. sets TCP_NODELAY for client (oc) and server (os) connections.
<p>Do not use TCP_NODELAY on slow connections with high delays when <p>Do not use TCP_NODELAY on slow connections with high delays and then
connection bandwidth is a bottleneck. connection bandwidth is a bottleneck.
<h4>Use Splice to Speed Up Large Data Amount Transfers</h4> <h4>Use splice to speedup large data amount transfers</h4>
splice() allows copying data between connections without copying to the process splice() allows to copy data between connections without copying to process
address space. It can speed up the proxy on high-bandwidth connections if most addres space. It can speedup proxy on high bandwidth connections, if most
connections require large data transfers. Splice is enabled by default on Linux connections require large data transfers. Splice is enabled by default on Linux
since 0.9; "-s0" disables splice usage. Example: since 0.9, "-s0" disables splice usage. Example:
<pre> <pre>
proxy -s0 proxy -s0
</pre> </pre>
Splice is only available on Linux. Splice requires more system buffers and file descriptors Splice is only available on Linux. Splice requires more system buffers and file descriptors,
and produces more IOCTLs but reduces process memory and overall CPU usage. and produces more IOCTLs but reduces process memory and overall CPU usage.
Disable splice if there are a lot of short-lived connections with no bandwidth Disable splice if there is a lot of short-living connections with no bandwidth
requirements. requirements.
<p>Use splice only on high-speed connections (e.g., 10GbE) when the processor, memory speed, or <p>Use splice only on high-speed connections (e.g. 10GBE), if processor, memory speed or
system bus are bottlenecks. system bus are bottlenecks.
<p>TCP_NODELAY and splice are not contrary to each other 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> <h4>Add grace delay to reduce system calls<h4>
<pre>proxy -g8000,3,10</pre> <pre>proxy -g8000,3,10</pre>
The first parameter is the average read size we want to keep, the second parameter is First parameter is average read size we want to keep, second parameter is
the minimal number of packets in the same direction to apply the algorithm, minimal number of packets in the same direction to apply algorythm,
and the last value is the delay added after polling and prior to reading data. last value is delay added after polling and prior to reading data.
The example above adds a 10-millisecond delay before reading data if the average An example above adds 10 millisecond delay before reading data if average
polling size is below 8000 bytes and 3 read operations have been made in the same polling size is below 8000 bytes and 3 read operations are made in the same
direction. It's especially useful with splice. <pre>logdump 1 1</pre> is useful direction. It's specially usefule with splice. <pre>logdump 1 1</pre> is useful
to see how grace delays work; choose a delay value to avoid filling the read 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 the chosen average pipe/buffer (typically 64K) but keep the request sizes close to chosen average
on large file uploads/downloads. on large file upload/download.

File diff suppressed because it is too large Load Diff

View File

@ -5,15 +5,16 @@
<li><a href="#COMPILE">Компиляция</a> <li><a href="#COMPILE">Компиляция</a>
<ul> <ul>
<li><a href="#MSVC">Как скомпилировать 3proxy Visual C++</a> <li><a href="#MSVC">Как скомпилировать 3proxy Visual C++</a>
<li><a href="#CMAKE">Как скомпилировать 3proxy с помощью CMake</a> <li><a href="#INTL">Как скомпилировать 3proxy Intel C Compiler под Windows</a>
<li><a href="#GCCWIN">Как скомпилировать 3proxy GCC под Windows</a>
<li><a href="#GCCUNIX">Как скомпилировать 3proxy GCC под Unix/Linux</a> <li><a href="#GCCUNIX">Как скомпилировать 3proxy GCC под Unix/Linux</a>
<li><a href="#CCCUNIX">Как скомпилировать 3proxy Compaq C Compiler под Unix/Linux</a>
</ul> </ul>
<li><a href="#INSTALL">Установка и удаление 3proxy</a> <li><a href="#INSTALL">Установка и удаление 3proxy</a>
<ul> <ul>
<li><a href="#INSTNT">Как установить/удалить 3proxy под Windows NT/2000/XP/2003 как службу</a> <li><a href="#INSTNT">Как установить/удалить 3proxy под Windows 95/98/ME/NT/2000/XP как службу</a>
<li><a href="#INST95">Как установить/удалить 3proxy под Windows 95/98/ME</a>
<li><a href="#INSTUNIX">Как установить/удалить 3proxy под Unix/Linux</a> <li><a href="#INSTUNIX">Как установить/удалить 3proxy под Unix/Linux</a>
<li><a href="#INSTMACOS">Как установить/удалить 3proxy под macOS</a>
<li><a href="#INSTDOCKER">Как использовать 3proxy с Docker</a>
</ul> </ul>
<li><a href="#SERVER">Конфигурация сервера</a> <li><a href="#SERVER">Конфигурация сервера</a>
<ul> <ul>
@ -33,8 +34,6 @@
<li><a href="#NAMES">Как разрешать имена на родительском прокси?</a></li> <li><a href="#NAMES">Как разрешать имена на родительском прокси?</a></li>
<li><a href="#ISFTP">Как настроить FTP прокси?</a></li> <li><a href="#ISFTP">Как настроить FTP прокси?</a></li>
<li><a href="#TLSPR">Как настроить SNI proxy (tlspr)</a></li> <li><a href="#TLSPR">Как настроить SNI proxy (tlspr)</a></li>
<li><a href="#SSLPLUGIN">Как настроить TLS/SSL с помощью SSLPlugin (https прокси, mTLS)</a></li>
<li><a href="#CERTIFICATES">Как создать CA и сертификаты для SSLPlugin</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>
@ -74,69 +73,63 @@
<li><a name="MSVC"><i>Как скомпилировать 3proxy Visual C++</i></a> <li><a name="MSVC"><i>Как скомпилировать 3proxy Visual C++</i></a>
<p> <p>
Извлеките файлы из архива 3proxy.tgz (например, с помощью WinZip). Извлеките файлы из архива 3proxy.tgz (например, с помощью WinZip).
Для 64-битной Windows используйте: Используйте команду nmake /f Makefile.msvc.
<pre>
nmake /f Makefile.msvc64</pre>
Для Windows ARM64 используйте:
<pre>
nmake /f Makefile.msvcARM64</pre>
Исполняемые файлы будут помещены в каталог <code>bin/</code>.
</p> </p>
<li><a name="CMAKE"><i>Как скомпилировать 3proxy с помощью CMake</i></a> <li><a name="INTL"><i>Как скомпилировать 3proxy Intel C Compiler под Windows</i></a>
<p> <p>
CMake предоставляет кроссплатформенную систему сборки. Работает на Windows (MSVC, MinGW), Linux, macOS и BSD. См. <a href="#MSVC">Как скомпилировать 3proxy Visual C++</a>.
<br>Базовые шаги сборки: Используйте Makefile.intl вместо Makefile.msvc
<pre> </p>
mkdir build <li><a name="GCCWIN"><i>Как скомпилировать 3proxy GCC под Windows</i></a></li>
cd build <p>
cmake .. Извлеките файлы из архива 3proxy.tgz (например, с помощью WinZip или, при наличии
cmake --build .</pre> Cygwin, tar -xzf 3proxy.tgz).
На Windows с Visual Studio можно также сгенерировать файл решения: Используйте команду make -f Makefile.win. Если по каким-то причинам вы хотите использовать
<pre> библиотеку POSIX-эмуляции CygWin - используйте make -f Makefile.unix.
cmake -G "Visual Studio 17 2022" -A x64 .. При использовании CygWin, функции, специфичные для Windows (такие, как запуск в
cmake --build . --config Release</pre> качестве службы) будут недоступны.
Опциональные функции можно включить через параметры cmake:
<pre>
cmake -D3PROXY_USE_OPENSSL=ON -D3PROXY_USE_PCRE2=ON ..</pre>
Доступные опции: 3PROXY_USE_OPENSSL, 3PROXY_USE_PCRE2, 3PROXY_USE_PAM, 3PROXY_USE_ODBC.
<br>Исполняемые файлы будут помещены в каталог <code>build/bin/</code>.
</p> </p>
<li><a name="GCCUNIX"><i>Как скомпилировать 3proxy GCC под Unix/Linux</i></a></li> <li><a name="GCCUNIX"><i>Как скомпилировать 3proxy GCC под Unix/Linux</i></a></li>
<p> <p>
Для Linux используйте: Используйте make -f Makefile.unix. Должен использоваться GNU make, на
<pre> некоторых системах необходимо использовать gmake вместо make. Под Linux
ln -sf Makefile.Linux Makefile необходимо использовать Makefile.Linux, под Solaris - Makefile.Solaris-* (в
make</pre> зависимости от используемого компилятора). Компиляция проверена в FreeBSD/i386,
Для FreeBSD используйте: OpenBSD/i386, NetBSD/i386, RH Linux/Alpha, Debian/i386, Gentoo/i386, Gentoo/PPC,
<pre> Solaris 10, но должно собираться в любых версиях *BSD/Linux/Solaris.
ln -sf Makefile.FreeBSD Makefile В других системах может потребоваться модификация make-файла и/или исходных текстов.
make</pre> Для компиляции с поддержкой ODBC необходимо убрать -DNOODBC из флагов
Для других Unix-подобных систем используйте Makefile.unix. На BSD-производных системах компиляции и добавить -lodbc (или другую ODBC-библиотеку) к флагам линковщика.
убедитесь, что используете GNU make; иногда он называется gmake вместо make. </p>
<br>Компиляция проверена на FreeBSD, NetBSD, OpenBSD, Linux, Solaris и macOS. <li><a name="CCCUNIX"><i>Как скомпилировать 3proxy Compaq C Compiler под Unix/Linux</i></a></li>
<br>Для поддержки ODBC необходимо установить Unix ODBC, убрать -DNOODBC из флагов <p>
компиляции и добавить ODBC-библиотеку к флагам линковщика. Используйте make -f Makefile.ccc. Компиляция проверена в RH Linux 7.1/Alpha.
<br>Исполняемые файлы будут помещены в каталог <code>bin/</code>. В других системах может потребоваться модификация файла и/или исходных текстов.
</p> </p>
</ul> </ul>
<hr> <hr>
<li><a name="INSTALL"><b>Установка и удаление 3proxy</b></a> <li><a name="INSTALL"><b>Установка и удаление 3proxy</b></a>
<p> <p>
<ul> <ul>
<li><a name="INSTNT"><i>Как установить/удалить 3proxy под Windows NT/2000/XP/2003 как службу</i></a> <li><a name="INSTNT"><i>Как установить/удалить 3proxy под Windows 95/98/ME/NT/2000/XP/2003 как службу</i></a>
<p> <p>
Извлеките файлы из архива 3proxy.zip в любой каталог Извлеките файлы из архива 3proxy.zip в любой каталог
(например, c:\Program Files\3proxy). Если необходимо, создайте каталог для (например, c:\Program Files\3proxy). Если необходимо, создайте каталог для
хранения файлов журналов. Создайте файл конфигурации 3proxy.cfg в хранения файлов журналов. Создайте файл конфигурации 3proxy.cfg в
каталоге 3proxy (см. раздел <a href="#SERVER">Конфигурация сервера</a>). каталоге 3proxy (см. раздел <a href="#SERVER">Конфигурация сервера</a>).
Откройте командную строку (cmd.exe). Если используется версия более ранняя, чем 0.6, добавьте строку
<pre>
service</pre>
в файл 3proxy.cfg. Откройте командную строку (cmd.exe).
Перейдите в каталог с 3proxy и дайте команду 3proxy.exe --install: Перейдите в каталог с 3proxy и дайте команду 3proxy.exe --install:
<pre> <pre>
D:\>C: D:\>C:
C:\>cd C:\Program Files\3proxy C:\>cd C:\Program Files\3proxy
C:\Program Files\3proxy>3proxy.exe --install</pre> C:\Program Files\3proxy>3proxy.exe --install</pre>
Сервис должен быть установлен и запущен. Если сервис не запускается, Сервис должен быть установлен и запущен. Если сервис не запускается,
попробуйте запустить 3proxy.exe вручную и проанализировать сообщения об ошибках. проверьте содержимое файла журнала,
попробуйте удалить строку service из 3proxy.cfg, запустить 3proxy.exe вручную
и проанализировать сообщения об ошибках.
</p><p> </p><p>
Для удаления 3proxy необходимо остановить сервис и дать Для удаления 3proxy необходимо остановить сервис и дать
команду 3proxy.exe --remove: команду 3proxy.exe --remove:
@ -146,110 +139,43 @@
C:\Program Files\3proxy>net stop 3proxy C:\Program Files\3proxy>net stop 3proxy
C:\Program Files\3proxy>3proxy.exe --remove</pre> C:\Program Files\3proxy>3proxy.exe --remove</pre>
после чего каталог 3proxy можно удалить. после чего каталог 3proxy можно удалить.
<p>
Установка в качестве системной службы под Windows 9x поддерживается с версии 0.5
</p>
<li><a name="INST95"><i>Как установить/удалить 3proxy под Windows 95/98/ME</i></a>
<p>
Извлеките файлы из архива 3proxy.zip в любой каталог
(например, c:\Program Files\3proxy). Если необходимо, создайте каталог для
хранения файлов журналов. Создайте файл конфигурации 3proxy.cfg в
каталоге 3proxy (См. раздел <a href="#SERVER">Конфигурация сервера</a>).
В файле конфигурации удалите строку
<pre>
service</pre>
и добавьте строку
<pre>
daemon</pre>
Создайте ярлык для 3proxy.exe и поместите его в автозагрузку либо с помощью
редактора реестра regedit.exe добавьте в разделе
<br>HKLM\Software\Microsoft\Windows\CurrentVersion\Run</br>
строковый параметр
<br>3proxy = "c:\Program Files\3proxy.exe" "C:\Program Files\3proxy.cfg"<br>
Использование кавычек при наличии в пути пробела обязательно.
Перезагрузитесь.
Если сервер не запускается,
проверьте содержимое файла журнала,
попробуйте удалить строку daemon из 3proxy.cfg, запустить 3proxy.exe вручную
и проанализировать сообщения об ошибках.
</p> </p>
<li><a name="INSTUNIX"><i>Как установить/удалить 3proxy под Unix/Linux</i></a> <li><a name="INSTUNIX"><i>Как установить/удалить 3proxy под Unix/Linux</i></a>
<p> <p>
<b>С помощью Makefile:</b> Скомпилируйте 3proxy (см. раздел <a href="#COMPILE">Компиляция</a>). Скопируйте
<br>Скомпилируйте 3proxy (см. раздел <a href="#COMPILE">Компиляция</a>), затем выполните: исполняемые файлы в подходящий каталог (например, /usr/local/3proxy/sbin для
<pre> серверных приложений или /usr/local/3proxy/bin для клиентских утилит).
sudo make install</pre> Создайте файл /usr/local/etc/3proxy.cfg.
Это установит исполняемые файлы в <code>/usr/local/3proxy/sbin/</code>, (См. раздел <a href="#SERVER">Конфигурация сервера</a>).
конфигурацию в <code>/etc/3proxy/</code> и настроит chroot-каталоги. Изменить расположение файла конфигурации можно, задав параметр при вызове
Файл конфигурации по умолчанию: <code>/etc/3proxy/3proxy.cfg</code>. 3proxy или изменив путь в файле 3proxy.c до компиляции.
</p> Добавьте вызов 3proxy в скрипты начальной инициализации.
<p>
<b>С помощью CMake:</b>
<pre>
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .</pre>
</p>
<p>
<b>С помощью готовых пакетов из GitHub:</b>
<br>Скачайте .deb или .rpm пакеты со страницы <a href="https://github.com/3proxy/3proxy/releases">GitHub Releases</a>.
<br>Для Debian/Ubuntu:
<pre>
sudo dpkg -i 3proxy_*.deb</pre>
Для RHEL/CentOS/Fedora:
<pre>
sudo rpm -i 3proxy-*.rpm</pre>
</p>
<p>
Добавьте 3proxy в скрипты автозапуска или используйте systemd:
<pre>
sudo systemctl enable 3proxy
sudo systemctl start 3proxy</pre>
</p>
<li><a name="INSTMACOS"><i>Как установить/удалить 3proxy под macOS</i></a>
<p>
<b>С помощью CMake (рекомендуется):</b>
<pre>
mkdir build && cd build
cmake ..
cmake --build .
sudo cmake --install .</pre>
Это установит:
<ul>
<li>Исполняемые файлы в <code>/usr/local/bin/</code></li>
<li>Конфигурацию в <code>/etc/3proxy/</code></li>
<li>Плагины в <code>/usr/local/lib/3proxy/</code></li>
<li>Launchd plist в <code>/Library/LaunchDaemons/org.3proxy.3proxy.plist</code></li>
</ul>
</p>
<p>
<b>С помощью Makefile:</b>
<pre>
ln -sf Makefile.FreeBSD Makefile
make
sudo make install</pre>
Это установит исполняемые файлы в <code>/usr/local/3proxy/bin/</code> и конфигурацию в <code>/usr/local/etc/3proxy/</code>.
</p>
<p>
<b>Управление службой через launchd:</b>
<br>После установки через cmake службой можно управлять с помощью launchctl:
<pre>
# Загрузить и запустить службу
sudo launchctl load /Library/LaunchDaemons/org.3proxy.3proxy.plist
# Остановить службу
sudo launchctl stop org.3proxy.3proxy
# Запустить службу
sudo launchctl start org.3proxy.3proxy
# Выгрузить и отключить службу
sudo launchctl unload /Library/LaunchDaemons/org.3proxy.3proxy.plist</pre>
Служба запускается от имени пользователя <code>proxy</code> (создаётся при установке).
Файл конфигурации: <code>/etc/3proxy/3proxy.cfg</code>
</p>
<li><a name="INSTDOCKER"><i>Как использовать 3proxy с Docker</i></a>
<p>
<b>Использование готовых образов из GitHub Container Registry:</b>
<pre>
docker pull ghcr.io/3proxy/3proxy:latest</pre>
</p>
<p>
<b>Сборка Docker-образов:</b>
<br>Предоставляются два Dockerfile:
<ul>
<li><code>Dockerfile.minimal</code> - минимальная статическая сборка без плагинов, конфигурация из stdin:
<pre>
docker build -f Dockerfile.minimal -t 3proxy.minimal .
docker run -i -p 3129:3129 --name 3proxy 3proxy.minimal</pre>
Затем введите конфигурацию, завершив командой "end".
</li>
<li><code>Dockerfile.full</code> - полная сборка с плагинами (SSL, PCRE, Transparent):
<pre>
docker build -f Dockerfile.full -t 3proxy.full .
docker run -p 3129:3129 -v /path/to/config:/usr/local/3proxy/conf 3proxy.full</pre>
Файл конфигурации должен находиться по пути <code>/path/to/config/3proxy.cfg</code>.
</li>
</ul>
</p>
<p>
По умолчанию 3proxy работает в chroot-окружении с uid/gid 65535. Используйте <code>nserver</code> в конфигурации для DNS-разрешения в chroot.
Для запуска без chroot монтируйте конфигурацию в <code>/etc/3proxy</code>.
</p> </p>
</ul> </ul>
<hr> <hr>
@ -293,7 +219,7 @@
<li>Служба уже установлена или запущена <li>Служба уже установлена или запущена
</ul> </ul>
</p> </p>
<li><a name="INTEXT">Как разобраться с internal и external</a></li> <li><a name="INTEXT">Как разобраться с internal и external</a></li></li>
<p> <p>
Убедитесь, что выправильно понимаете что такое internal и external адреса. Убедитесь, что выправильно понимаете что такое internal и external адреса.
Оба адреса - это адреса, принадлежищие хосту, на котором установлен 3proxy. Оба адреса - это адреса, принадлежищие хосту, на котором установлен 3proxy.
@ -585,49 +511,29 @@
</p> </p>
<li><a name="TLSPR"><i>Как настроить SNI proxy (tlspr)</i></a></li> <li><a name="TLSPR"><i>Как настроить SNI proxy (tlspr)</i></a></li>
<p> <p>
SNI proxy может быть использован для транспарентного перенаправления любого TLS трафика (например HTTPS) на внешнем маршрутизаторе
SNI proxy может быть использовать для транспарентного перенаправления любого TLS трафика (например HTTPS) на внешнем маршрутизаторе
или локальными правилами. Так же можно использовать его для извлечения имени хоста из TLS хендшейка с целью логгирования или использования в ACL. или локальными правилами. Так же можно использовать его для извлечения имени хоста из TLS хендшейка с целью логгирования или использования в ACL.
Еще одна задача которую может решать модуль - требование наличия TLS или mTLS (mutual TLS). Еще одна задача которую может решать модуль - требование наличия TLS или mTLS (mutual TLS).
Если tlspr используется как отдельный сервис без использования плагина Transparent, то необходимо задать порт назначения через опцию -P (по умолчанию 443), Если tlspr используется как отдельный сервис без исползования плагина Transparent, то необходимо задать порт назначения через опцию -T (по умолчанию 443),
т.к. TLS хендшейк не содержит информации о порте назначения. т.к. TLS хендшейк не содержит информации о порте назначения.
</p><p> </p><p>
<b>Опции:</b> -c контролирует уровень требования к TLS:
</p><pre> </p><pre>
-P &lt;порт&gt; - порт назначения (по умолчанию: 443) 0 (по умолчанию) - пропустить трафик без TLS
-c &lt;уровень&gt; - уровень проверки TLS: 1 - требовать TLS, проверять наличие client HELLO
0 (по умолчанию) - пропустить трафик без TLS 2 - требовать TLS, проверять наличие client и server HELLO
1 - требовать TLS, проверять наличие client HELLO 3 - требовать TLS, проверять наличие серверного сертификата (не совместим с TLS 1.3+)
2 - требовать TLS, проверять наличие client и server HELLO 4 - требовать взаимный (mutual) TLS, проверять что сервер запрашивает сертификат и клиент его отправляет (не совместим с TLS 1.3+)
3 - требовать TLS, проверять наличие серверного сертификата (не совместим с TLS 1.3+)
4 - требовать взаимный (mutual) TLS, проверять что сервер запрашивает сертификат и клиент его отправляет (не совместим с TLS 1.3+)
</pre> </pre>
<p> <p>
<b>SNI Break (обход DPI):</b> примеры конфигурации:
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI). 1. Порт 1443 можно использовать для перенаправления в него HTTPS трафика по порту 443 (например с внешнего маршрутизатора)
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами, <pre>
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-s</code> на слушающем сервисе с TCP_NODELAY:
</p><pre>
auth iponly
allow *
parent 1000 tls 0.0.0.0 0
allow *
proxy -s -i127.0.0.1 -ocTCP_NODELAY -osTCP_NODELAY -p1443
</pre>
<p>
TCP_NODELAY необходим, чтобы ядро не объединяло разделенные пакеты.
</p>
<p>
<b>Примеры конфигурации:</b>
</p>
<p>
1. Отдельный SNI proxy на порту 1443 с перенаправлением на порт назначения 443:
</p><pre>
tlspr -p1443 -P443 -c1 tlspr -p1443 -P443 -c1
</pre> </pre>
<p> 2. tlspr используется как родительский прокси в SOCKS чтобы обнаруживать реальный hostname назначения (даже если запрашивается подклюение по IP адресу)
2. Использование tlspr как родительского прокси в SOCKS для обнаружения hostname из TLS (даже если клиент подключается по IP): <pre>
</p><pre>
allow * * * 80 allow * * * 80
parent 1000 http 0.0.0.0 0 parent 1000 http 0.0.0.0 0
allow * * * * CONNECT allow * * * * CONNECT
@ -635,208 +541,9 @@ parent 1000 tls 0.0.0.0 0
deny * * some.not.allowed.host deny * * some.not.allowed.host
allow * allow *
socks socks
</pre>
<p>
3. Использование tlspr с HTTP proxy для ACL по имени хоста TLS:
</p><pre>
allow * * * 80
parent 1000 http 0.0.0.0 0
allow * * * 443
parent 1000 tls 0.0.0.0 0
deny * * blocked.example.com
allow *
proxy
</pre> </pre>
</p> </p>
<li><a name="SSLPLUGIN"><i>Как настроить TLS/SSL с помощью SSLPlugin (https прокси, mTLS)</i></a>
<p>
SSLPlugin обеспечивает поддержку TLS/SSL для 3proxy. Он может использоваться для:
<ul>
<li>Создания https:// прокси (TLS-шифрованное соединение между клиентом и прокси)</li>
<li>Реализации MITM для инспекции TLS-трафика</li>
<li>Соединения с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату</li>
<li>Требования аутентификации по клиентскому сертификату (mTLS)</li>
</ul>
</p>
<p>
<b>Создание https:// прокси:</b>
<br>Для создания https:// прокси требуется сертификат и ключ сервера. Сертификат не должен быть самоподписанным
и должен содержать альтернативные имена (SAN) для имени хоста/IP прокси.
</p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key
ssl_serv
proxy -p3129
ssl_noserv
proxy -p3128
</pre>
<p>
Создаётся https:// прокси на порту 3129 и http:// прокси на порту 3128.
Настройте клиенты на использование https://proxy-host:3129/ в качестве URL прокси.
</p>
<p>
<b>Аутентификация по клиентскому сертификату (mTLS):</b>
<br>Чтобы требовать от клиентов аутентификацию по сертификату, используйте ssl_server_verify и укажите CA-сертификат:
</p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_cert /etc/3proxy/certs/server.crt
ssl_server_key /etc/3proxy/certs/server.key
ssl_server_ca_file /etc/3proxy/certs/ca.crt
ssl_server_verify
ssl_serv
proxy -p3129
</pre>
<p>
Только клиенты с действительным сертификатом, подписанным CA, смогут подключиться.
</p>
<p>
<b>MITM для инспекции TLS-трафика:</b>
<br>Для перехвата и расшифровки TLS-трафика требуется CA-сертификат для генерации подделанных серверных сертификатов:
</p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_server_ca_file /etc/3proxy/certs/ca.crt
ssl_server_ca_key /etc/3proxy/certs/ca.key
ssl_client_verify
ssl_client_ca_file /etc/ssl/certs/ca-certificates.crt
ssl_mitm
proxy -p3128
ssl_nomitm
proxy -p3129
</pre>
<p>
CA-сертификат должен быть доверенным для клиентов. ssl_client_verify обеспечивает проверку реальных серверных сертификатов.
Без ssl_client_verify прокси уязвим для MITM-атак.
</p>
<p>
<b>TLS-клиент (соединение с вышестоящим сервером через TLS):</b>
<br>Для соединения с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату:
</p><pre>
plugin /path/to/SSLPlugin.ld.so ssl_plugin
ssl_client_cert /etc/3proxy/certs/client.crt
ssl_client_key /etc/3proxy/certs/client.key
ssl_client_verify
ssl_client_ca_file /etc/ssl/certs/ca-certificates.crt
ssl_cli
proxy -p3128
</pre>
<li><a name="CERTIFICATES"><i>Как создать CA и сертификаты для SSLPlugin</i></a>
<p>
<b>Создание удостоверяющего центра (CA):</b>
<br>Для MITM или mTLS требуется CA. Сгенерируйте закрытый ключ CA и сертификат:
</p><pre>
# Генерация закрытого ключа CA
openssl genrsa -out ca.key 4096
# Генерация сертификата CA (действителен 10 лет)
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 \
-subj "/C=RU/ST=Region/L=City/O=MyOrg/CN=My CA" \
-out ca.crt
</pre>
<p>
Для MITM импортируйте ca.crt в браузеры/ОС клиентов как доверенный корневой CA.
</p>
<p>
<b>Создание серверного сертификата для https:// прокси:</b>
<br>Серверный сертификат должен иметь правильные альтернативные имена (SAN):
</p><pre>
# Генерация закрытого ключа сервера
openssl genrsa -out server.key 2048
# Создание запроса на подпись сертификата (CSR)
openssl req -new -key server.key \
-subj "/C=RU/ST=Region/L=City/O=MyOrg/CN=proxy.example.com" \
-out server.csr
# Создание файла расширений для SAN
cat > server.ext << 'EOF'
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = proxy.example.com
DNS.2 = proxy
IP.1 = 192.168.1.100
EOF
# Подписание сертификата CA
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out server.crt -days 365 -sha256 \
-extfile server.ext
</pre>
<p>
Для публичного https:// прокси используйте CA вроде Let's Encrypt вместо самоподписанного.
</p>
<p>
<b>Создание клиентского сертификата для mTLS:</b>
</p><pre>
# Генерация закрытого ключа клиента
openssl genrsa -out client1.key 2048
# Создание CSR
openssl req -new -key client1.key \
-subj "/C=RU/ST=Region/L=City/O=MyOrg/CN=client1" \
-out client1.csr
# Создание файла расширений
cat > client.ext << 'EOF'
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment
extendedKeyUsage = clientAuth
EOF
# Подписание CA
openssl x509 -req -in client1.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out client1.crt -days 365 -sha256 \
-extfile client.ext
# Создание PKCS#12 для импорта в браузер
openssl pkcs12 -export -out client1.p12 \
-inkey client1.key -in client1.crt -certfile ca.crt
</pre>
<p>
Импортируйте client1.p12 в хранилище сертификатов браузера или ОС клиента.
</p>
<p>
<b>Скрипт быстрой настройки для разработки/тестирования:</b>
</p><pre>
#!/bin/sh
# Создаёт CA, серверный и клиентский сертификаты для тестирования SSLPlugin
# CA
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 \
-subj "/CN=3proxy CA" -out ca.crt
# Сервер
openssl genrsa -out server.key 2048
openssl req -new -key server.key -subj "/CN=localhost" -out server.csr
cat > server.ext << 'EOF'
basicConstraints=CA:FALSE
keyUsage = keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = DNS:localhost,DNS:proxy,IP:127.0.0.1
EOF
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out server.crt -days 365 -sha256 -extfile server.ext
# Клиент
openssl genrsa -out client.key 2048
openssl req -new -key client.key -subj "/CN=client" -out client.csr
cat > client.ext << 'EOF'
basicConstraints=CA:FALSE
extendedKeyUsage = clientAuth
EOF
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out client.crt -days 365 -sha256 -extfile client.ext
openssl pkcs12 -export -out client.p12 -passout pass: \
-inkey client.key -in client.crt -certfile ca.crt
</pre>
<li><a name="AUTH"><i>Как ограничить доступ к службе</i></a> <li><a name="AUTH"><i>Как ограничить доступ к службе</i></a>
<p> <p>
Во-первых, для ограничения доступа необходимо указать внутренний интерфейс, Во-первых, для ограничения доступа необходимо указать внутренний интерфейс,

View File

@ -1,17 +1,17 @@
<html><title>3proxy documentation</title><body><h2>3proxy documentation</h2> <html><title>3proxy documentation</title><body><h2>3proxy documentation</h2>
<a href="securityen.html">Security recommendations</a><br> <a href="securityen.html">Security recommendations</a><br>
<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>
<h3>Man pages:</h3> <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/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/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,9 +1,9 @@
<h3>3proxy Perl Compatible Regular Expressions (PCRE) Plugin</h3> <h3>3proxy Perl Compatible Regular Expressions (PCRE) plugin</h3>
This filtering plugin can be used to create matching and replacement This filtering plugin can be used to create matching and replace
rules with regular expressions for client requests, client and rules with regular expressions for client's request, client and
server headers, and client and server data. It adds 3 additional servers header and client and server data. It adds 3 additional
configuration commands: configuration commands:
<pre> <pre>
@ -12,11 +12,11 @@ pcre_rewrite TYPE FILTER_ACTION REGEXP REWRITE_EXPRESSION [ACE]
pcre_extend FILTER_ACTION [ACE] pcre_extend FILTER_ACTION [ACE]
pcre_options OPTION1 [...] pcre_options OPTION1 [...]
</pre> </pre>
pcre - allows applying a rule for matching pcre - allows to apply some rule for matching
<br>pcre_rewrite - in addition to 'pcre', allows substituting substrings <br>pcre_rewrite - in addition to 'pcre' allows to substitute substrings
<br>pcre_extend - extends the ACL of the last pcre or pcre_rewrite command by <br>pcre_extend - extends ACL of the last pcre or pcre_rewrite comand by
adding an additional ACE (like with allow/deny configuration commands). adding additional ACE (like with allow/deny configuration commands).
<br>pcre_options - allows setting matching options. Available options are: <br>pcre_options - allows to set matching options. Awailable options are:
PCRE_CASELESS, PCRE_CASELESS,
PCRE_MULTILINE, PCRE_MULTILINE,
PCRE_DOTALL, PCRE_DOTALL,
@ -32,7 +32,7 @@ PCRE_UTF8,
PCRE_NO_AUTO_CAPTURE, PCRE_NO_AUTO_CAPTURE,
PCRE_NO_UTF8_CHECK, PCRE_NO_UTF8_CHECK,
PCRE_AUTO_CALLOUT, PCRE_AUTO_CALLOUT,
PCRE_PARTIAL, PCRE_PARTIAL,
PCRE_DFA_SHORTEST, PCRE_DFA_SHORTEST,
PCRE_DFA_RESTART, PCRE_DFA_RESTART,
PCRE_FIRSTLINE, PCRE_FIRSTLINE,
@ -47,31 +47,32 @@ PCRE_BSR_UNICODE
<ul> <ul>
<li>TYPE - type of filtered data. May contain one or more <li>TYPE - type of filtered data. May contain one or more
(comma-delimited list) values: (comma delimited list) values:
<ul> <ul>
<li>request - content of the client's request, e.g., the HTTP GET request string. <li>request - content of client's request e.g. HTTP GET request string.
(known problem: changing the request string doesn't change the IP of the host to connect to) (known problem: changing request string doesn't change IP of the host to connect)
<li>cliheader - content of the client request headers, e.g., HTTP request headers. <li>cliheader - content of client request headers, e.g. HTTP request header.
<li>srvheader - content of the server's reply headers, e.g., HTTP status and headers. <li>srvheader - content of server's reply headers, e.g. HTTP status and headers.
<li>clidata - data received from the client, e.g., HTTP POST request data <li>clidata - data received from client, e.g. HTTP POST request data
<li>srvdata - data received from the server, e.g., an HTML page <li>srvdata - data received from server, e.g. HTML page
</ul> </ul>
<li>FILTER_ACTION - action on match <li>FILTER_ACTION - action on match
<ul><li>allow - allow this request without checking the rest of the rules for the given type <ul>allow - allow this request without checking rest of the given type
<li>deny - deny this request without checking the rest of the rules of the rules
<li>dunno - continue with the rest of the rules (useful with pcre_rewrite) <li>deny - deny this request without checking rest of the rules
<li>dunno - continue with the rest of rules (useful with pcre_rewrite)
</ul> </ul>
<li>REGEXP - PCRE (Perl) regular expression. Use * if no regexp matching <li>REGEXP - PCRE (perl) regular expression. Use * if no regexp matching
is required. required.
<li>REWRITE_EXPRESSION - substitution string. May contain Perl-style <li>REWRITE_EXPRESSION - substitution string. May contain perl-style
substrings substrings
(not tested) $1, $2. $0 means the whole matched string. \r and \n may be used (not tested) $1, $2. $0 - means whole matched string. \r and \n may be used
to insert new strings; the string may be empty (""). to insert new strings, string may be empty ("").
<li>ACE - access control entry (user names, source IPs, destination IPs, <li>ACE - access control entry (user names, source IPs, destination IPs,
ports, etc.), absolutely identical to allow/deny/bandlimin commands. ports, etc), absolutely identical to allow/deny/bandlimin commands.
The regular expression is only matched if the ACL matches the connection data. Regular expression is only matched if ACL matches connection data.
Warning: Warning:
Regular expressions don't require authentication and cannot replace reqular expression doesn't require authentication and can not replace
authentication and/or allow/deny ACLs. authentication and/or allow/deny ACLs.
</ul> </ul>
@ -87,7 +88,7 @@ pcre_extend deny * 192.168.0.1/16
<h4>Download:</h4> <h4>Download:</h4>
<ul> <ul>
<li>Plugin is included in the 3proxy 0.6 binary and source distribution <li>Plugin is included into 3proxy 0.6 binary and source distribution
<li>Example configuration (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A> <li>Example configuration (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A>
</li></ul> </ul>

View File

@ -56,7 +56,7 @@ PCRE_BSR_UNICODE
<li>srvdata - данные полученные от сервера, например содержимое HTML-страницы <li>srvdata - данные полученные от сервера, например содержимое HTML-страницы
</ul> </ul>
<li>FILTER_ACTION - действие при совпадении. Может принимать значение <li>FILTER_ACTION - действие при совпадении. Может принимать значение
<ul><li>allow - разрешить данный запрос без просмотра дальнейших правил <ul>allow - разрешить данный запрос без просмотра дальнейших правил
<li>deny - запретить данный запрос без просмотра дальнейших правил <li>deny - запретить данный запрос без просмотра дальнейших правил
<li>dunno - продолжить анализ правил (полезно для pcre_rewrite) <li>dunno - продолжить анализ правил (полезно для pcre_rewrite)
</ul> </ul>
@ -87,4 +87,4 @@ pcre_extend deny * 192.168.0.1/16
<ul> <ul>
<li>Плагин включен в дистрибутив 3proxy 0.6 <li>Плагин включен в дистрибутив 3proxy 0.6
<li>Пример конфигурации (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A> <li>Пример конфигурации (by Dennis Garber): <A HREF="NoPornLitest.cfg.txt">NoPornLitest.cfg</A>
</li></ul> </ul>

View File

@ -1,61 +1,45 @@
<h3>3proxy SSL/TLS Plugin</h3> <h3>3proxy SSL/TLS plugin</h3>
This plugin can be used to transparently decrypt SSL/TLS data, provide TLS encryption for proxy traffic, and authenticate using client certificates. Plugin can be used to transparently decypher SSL/TLS data and TLS encryption for proxy traffic.
<h4>For transparent certificate spoofing (MITM):</h4>
<h4>For transparent certificate spoofing:</h4>
<br>ssl_mitm - spoof certificates for services started below. Usage without ssl_client_verify is insecure. <br>ssl_mitm - spoof certificates for services started below. Usage without ssl_client_verify is insecure.
<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 the server (https:// proxy):</h4> <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
ssl_serv (or ssl_server) - require TLS connection from clients for services below Parameters:
<br>ssl_noserv (or ssl_noserver) - do not require TLS connection from clients for services below <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
<h4>To use TLS for upstream connections:</h4> <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
ssl_cli (or ssl_client) - establish TLS connection to upstream server for services below <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_nocli (or ssl_noclient) - do not establish TLS connection to upstream server for services below <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)
<h4>Parameters:</h4> <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><b>ssl_server_cert</b> /path/to/cert - Server certificate (should not be self-signed and must contain an Alternative Name) for ssl_serv <br>ssl_server_max_proto_version tls_version - TLS server max TLS version (e.g. TLSv1.2)
<br><b>ssl_server_key</b> /path/to/key - Server certificate key for ssl_server_cert or generated MITM certificate <br>ssl_client_verify - verify certificate for upstream server in TLS client functionality (used with ssl_mitm)
<br><b>ssl_client_cert</b> /path/to/cert - Client certificate for authentication on upstream server (used with ssl_cli) <br>ssl_client_no_verify - do not verify certificate for upstream server in TLS client functionality (default)
<br><b>ssl_client_key</b> /path/to/key - Client certificate key for ssl_client_cert <br>ssl_server_ca_file /path/to/cafile - CA certificate file for mitm
<br><b>ssl_client_ciphersuites</b> ciphersuites_list - TLS client ciphers for TLS 1.3, e.g., ssl_client_ciphersuites TLS_AES_128_GCM_SHA256 <br>ssl_server_ca_key /path/to/cakey - key for ssl_server_ca_file mitm CA
<br><b>ssl_server_ciphersuites</b> ciphersuites_list - TLS server ciphers for TLS 1.3 <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><b>ssl_client_cipher_list</b> ciphers_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_certcache /path/to/cache/ - location for generated mitm certificates cache, optional, if ssl_server_ca_file / ssl_server_ca_key are configured.
<br><b>ssl_server_cipher_list</b> ciphers_list - TLS server ciphers for TLS 1.2 and below Cache may contain 3 files: 3proxy.pem - public
<br><b>ssl_client_min_proto_version</b> tls_version - TLS client minimum TLS version (e.g., TLSv1.2) self-signed certificates (used if ssl_server_ca_file is not configured),
<br><b>ssl_server_min_proto_version</b> tls_version - TLS server minimum TLS version (e.g., TLSv1.2) 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
<br><b>ssl_client_max_proto_version</b> tls_version - TLS client maximum TLS version (e.g., TLSv1.2)
<br><b>ssl_server_max_proto_version</b> tls_version - TLS server maximum TLS version (e.g., TLSv1.2)
<br><b>ssl_client_verify</b> - verify the certificate for the upstream server in TLS client functionality (used with ssl_mitm or ssl_cli)
<br><b>ssl_client_no_verify</b> - do not verify the certificate for the upstream server in TLS client functionality (default)
<br><b>ssl_server_verify</b> - require client certificate authentication (mTLS) for ssl_serv
<br><b>ssl_server_no_verify</b> - do not require client certificate (default)
<br><b>ssl_server_ca_file</b> /path/to/cafile - CA certificate file for MITM
<br><b>ssl_server_ca_key</b> /path/to/cakey - key for ssl_server_ca_file MITM CA
<br><b>ssl_server_ca_dir</b> /path/to/cadir - CA directory for ssl_server_verify
<br><b>ssl_server_ca_store</b> /path/to/castore - CA store for ssl_server_verify (OpenSSL 3.0+)
<br><b>ssl_client_ca_file</b> /path/to/cafile - CA file for ssl_client_verify
<br><b>ssl_client_ca_dir</b> /path/to/cadir - CA directory for ssl_client_verify
<br><b>ssl_client_ca_store</b> /path/to/castore - CA store for ssl_client_verify (OpenSSL 3.0+)
<br><b>ssl_client_sni</b> hostname - SNI hostname to send to upstream server (overrides the requested hostname)
<br><b>ssl_client_alpn</b> protocol1 protocol2 ... - ALPN protocols to negotiate with upstream server (e.g., ssl_client_alpn h2 http/1.1)
<br><b>ssl_client_mode</b> mode - when to establish TLS connection: 0 - on connect (default), 1 - after authentication, 2 - before data
<br><b>ssl_certcache</b> /path/to/cache/ - location for the generated MITM certificates cache, optional if ssl_server_ca_file / ssl_server_ca_key are configured.
The cache may contain 3 files: 3proxy.pem - public
self-signed certificates (used if ssl_server_ca_file is not configured),
3proxy.key - key for public certificates, used if ssl_server_ca_key is not configured, server.key - this key is used if ssl_server_key is not configured to generate
spoofed certificates. If server.key is absent, 3proxy.key is used to generate certificates. spoofed certificates. If server.key is absent, 3proxy.key is used to generate certificates.
Generated certificates are placed in the same path. Generated certificates are placed to the same path.
<h4>MITM example:</h4> <h4>mitm example:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin plugin /path/to/SslPlugin.dll ssl_plugin
ssl_server_ca_file /path/to/cafile ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
@ -63,7 +47,7 @@ proxy -p3128
ssl_nomitm ssl_nomitm
proxy -p3129 proxy -p3129
</pre> </pre>
MITM's traffic with a spoofed certificate for the port 3128 proxy. mitm's traffic with spoofed ceritifacate for port 3128 proxy.
<h4>https:// proxy example:</h4> <h4>https:// proxy example:</h4>
<pre> <pre>
@ -75,30 +59,6 @@ proxy -p33128
ssl_noserv ssl_noserv
proxy -p3128 proxy -p3128
</pre> </pre>
Creates an https:// proxy on port 33128 and an http:// proxy on port 3128 creates https:// proxy on 33128 and http:// proxy on 3128
<h4>TLS client example (connect to upstream via TLS):</h4>
<pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_client_cert /path/to/client.crt
ssl_client_key /path/to/client.key
ssl_client_verify
ssl_client_ca_file /path/to/ca.crt
ssl_cli
proxy -p3128
</pre>
Creates an HTTP proxy that connects to upstream servers via TLS with client certificate authentication.
<h4>mTLS example (require client certificate):</h4>
<pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/server.key
ssl_server_ca_file /path/to/ca.crt
ssl_server_verify
ssl_serv
proxy -p3128
</pre>
Creates an https:// proxy that requires client certificate authentication.
&copy; Vladimir Dubrovin, License: BSD style &copy; Vladimir Dubrovin, License: BSD style

View File

@ -1,58 +1,41 @@
<h3>3proxy SSL/TLS плагин</h3> <h3>3proxy SSL/TLS плагин</h3>
Плагин можно использовать для перехвата и дешифровки SSL/TLS трафика, для шифрования трафика прокси-сервера и аутентификации с помощью клиентских сертификатов. Плагин можно использовать для перехвата и дешифровки SSL/TLS трафика и для шифрования трафика прокси-сервера
<h4>Для прозрачного перехвата трафика (MITM):</h4> <h4>Для транспаретной перехватки трафика (mitm):</h4>
<br>ssl_mitm - подменять сертификаты для сервисов, запущенных ниже. Использование без ssl_client_verify небезопасно. <br>ssl_mitm - подменять сертификаты для сервисов стартованных ниже. Не безопасно использовать без ssl_client_verify.
<br>ssl_nomitm - не подменять сертификаты для сервисов, запущенных ниже. <br>ssl_nomitm - не подменять сертификаты для сервисов стартованных ниже.
<h4>Для защиты трафика прокси-сервера (https:// proxy):</h4>
ssl_serv (или ssl_server) - требовать TLS-соединение от клиентов для сервисов, запущенных ниже <h4>Для защиты трафика прокси-сервера (например https:// proxy) - начиная с 0.9.5</h4>
<br>ssl_noserv (или ssl_noserver) - не требовать TLS-соединение от клиентов для сервисов, запущенных ниже ssl_serv - включает TLS для соединений к сервисам ниже
<br>ssl_noserv - отключает TLS для соединений к сервисам ниже
<h4>Для использования TLS при соединении к вышестоящему серверу:</h4> Параметры:
<br>ssl_server_cert /path/to/cert - сертификат сервера, не должен быть самоподписаным, имя CN должно содержаться в альтернативных именах - используется для ssl_serv
ssl_cli (или ssl_client) - устанавливать TLS-соединение к вышестоящему серверу для сервисов, запущенных ниже <br>ssl_server_key /path/to/key - ключ сертификата сервера для ssl_server_cert или сгенерированного сертификата ssl_mitm
<br>ssl_nocli (или ssl_noclient) - не устанавливать TLS-соединение к вышестоящему серверу для сервисов, запущенных ниже <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
<h4>Параметры:</h4> <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><b>ssl_server_cert</b> /path/to/cert - сертификат сервера (не должен быть самоподписанным, должен содержать альтернативные имена) для ssl_serv <br>ssl_client_min_proto_version tls_version - минимальная версия TLS клиента (например ssl_client_min_proto_version TLSv1.2)
<br><b>ssl_server_key</b> /path/to/key - ключ сертификата сервера для ssl_server_cert или сгенерированного MITM-сертификата <br>ssl_server_min_proto_version tls_version - минимальная версия TLS сервера
<br><b>ssl_client_cert</b> /path/to/cert - клиентский сертификат для аутентификации на вышестоящем сервере (используется с ssl_cli) <br>ssl_client_max_proto_version tls_version - максимальная версия TLS клиента
<br><b>ssl_client_key</b> /path/to/key - ключ клиентского сертификата для ssl_client_cert <br>ssl_server_max_proto_version tls_version - максимальная версия TLS сервера
<br><b>ssl_client_ciphersuites</b> ciphersuites_list - наборы шифров TLS для TLS 1.3 (клиент), пример: ssl_client_ciphersuites TLS_AES_128_GCM_SHA256 <br>ssl_client_verify - проверять сертификат сервера назначения (используется с ssl_mitm)
<br><b>ssl_server_ciphersuites</b> ciphersuites_list - наборы шифров TLS для TLS 1.3 (сервер) <br>ssl_client_no_verify - не проверять сертификат сервера назначения
<br><b>ssl_client_cipher_list</b> ciphers_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_ca_file /path/to/cafile - CA сертификат для ssl_mitm
<br><b>ssl_server_cipher_list</b> ciphers_list - наборы шифров TLS для TLS 1.2 и ниже (сервер) <br>ssl_server_ca_key /path/to/cakey - ключ CA сертификата ssl_server_ca_file mitm
<br><b>ssl_client_min_proto_version</b> tls_version - минимальная версия TLS клиента (например, ssl_client_min_proto_version TLSv1.2) <br>ssl_client_ca_file, ssl_client_ca_dir, ssl_client_ca_store - расположения корневых сертификатов ssl_client_verify
<br><b>ssl_server_min_proto_version</b> tls_version - минимальная версия TLS сервера <br>ssl_certcache /path/to/cache/ - расположение кеша сгенерированных сертификатов ssl_mitm. Кеш может содержать
<br><b>ssl_client_max_proto_version</b> tls_version - максимальная версия TLS клиента файлы 3proxy.pem, 3proxy.key server.key, которые используются как ssl_server_ca_file,
<br><b>ssl_server_max_proto_version</b> tls_version - максимальная версия TLS сервера ssl_server_ca_key и ssl_server_key соответственно если они не заданы. Если server.key не задан,
<br><b>ssl_client_verify</b> - проверять сертификат вышестоящего сервера (используется с ssl_mitm или ssl_cli)
<br><b>ssl_client_no_verify</b> - не проверять сертификат вышестоящего сервера (по умолчанию)
<br><b>ssl_server_verify</b> - требовать клиентский сертификат (mTLS) для ssl_serv
<br><b>ssl_server_no_verify</b> - не требовать клиентский сертификат (по умолчанию)
<br><b>ssl_server_ca_file</b> /path/to/cafile - файл CA-сертификата для MITM
<br><b>ssl_server_ca_key</b> /path/to/cakey - ключ CA-сертификата ssl_server_ca_file для MITM
<br><b>ssl_server_ca_dir</b> /path/to/cadir - директория CA-сертификатов для ssl_server_verify
<br><b>ssl_server_ca_store</b> /path/to/castore - хранилище CA-сертификатов для ssl_server_verify (OpenSSL 3.0+)
<br><b>ssl_client_ca_file</b> /path/to/cafile - файл CA-сертификатов для ssl_client_verify
<br><b>ssl_client_ca_dir</b> /path/to/cadir - директория CA-сертификатов для ssl_client_verify
<br><b>ssl_client_ca_store</b> /path/to/castore - хранилище CA-сертификатов для ssl_client_verify (OpenSSL 3.0+)
<br><b>ssl_client_sni</b> hostname - SNI-имя хоста для отправки вышестоящему серверу (переопределяет запрошенное имя хоста)
<br><b>ssl_client_alpn</b> протокол1 протокол2 ... - ALPN-протоколы для согласования с вышестоящим сервером (например, ssl_client_alpn h2 http/1.1)
<br><b>ssl_client_mode</b> режим - когда устанавливать TLS-соединение: 0 - при подключении (по умолчанию), 1 - после аутентификации, 2 - перед передачей данных
<br><b>ssl_certcache</b> /path/to/cache/ - расположение кеша сгенерированных MITM-сертификатов. Кеш может содержать
файлы 3proxy.pem, 3proxy.key, server.key, которые используются как ssl_server_ca_file,
ssl_server_ca_key и ssl_server_key соответственно, если они не заданы. Если server.key не задан,
3proxy.key используется для генерации серверного сертификата. 3proxy.key используется для генерации серверного сертификата.
<h4>Пример MITM:</h4> <h4>Пример mitm:</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin plugin /path/to/SslPlugin.dll ssl_plugin
ssl_server_ca_file /path/to/cafile ssl_server_ca_file /path/to/cafile
ssl_server_ca_key /path/to/cakey ssl_server_ca_key /path/to/cakey
ssl_mitm ssl_mitm
@ -60,9 +43,9 @@ proxy -p3128
ssl_nomitm ssl_nomitm
proxy -p3129 proxy -p3129
</pre> </pre>
Перехватывается трафик в прокси на порту 3128. Перехватывается трафик в прокси на порту 3128
<h4>Пример конфигурации https:// прокси:</h4> <h4>Пример конфигурации https:// прокси (curl -x https://...):</h4>
<pre> <pre>
plugin /path/to/SSLPlugin.so ssl_plugin plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert path_to_cert ssl_server_cert path_to_cert
@ -72,30 +55,7 @@ proxy -p33128
ssl_noserv ssl_noserv
proxy -p3128 proxy -p3128
</pre> </pre>
На порту 33128 создается https:// прокси, на порту 3128 - http:// прокси. На порту 33128 создается https:// прокси (не путать с CONNECT прокси aka HTTPS over HTTP прокси), на порту 3128
создается http:// прокси (может пропуска в т.ч. и HTTPS коннекты)
<h4>Пример TLS-клиента (соединение к вышестоящему серверу через TLS):</h4>
<pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_client_cert /path/to/client.crt
ssl_client_key /path/to/client.key
ssl_client_verify
ssl_client_ca_file /path/to/ca.crt
ssl_cli
proxy -p3128
</pre>
Создается HTTP-прокси, который соединяется с вышестоящими серверами через TLS с аутентификацией по клиентскому сертификату.
<h4>Пример mTLS (требование клиентского сертификата):</h4>
<pre>
plugin /path/to/SSLPlugin.so ssl_plugin
ssl_server_cert /path/to/server.crt
ssl_server_key /path/to/server.key
ssl_server_ca_file /path/to/ca.crt
ssl_server_verify
ssl_serv
proxy -p3128
</pre>
Создается https:// прокси, требующий аутентификацию по клиентскому сертификату.
&copy; Vladimir Dubrovin, License: BSD style &copy; Vladimir Dubrovin, License: BSD style

View File

@ -1,16 +1,16 @@
<h3>3proxy Strings Substitution Plugin</h3> <h3>3proxy strings substitution plugin</h3>
This may be used to make the interface more attractive or to translate proxy server May be used to make interface more pretty or to translate proxy server
messages to a different language. All messages are taken from proxy.c and messages to different language. All messages are taken from proxy.c and
moved to an external text file (e.g., rus.3ps). At the time of moved to external text file (e.g. rus.3ps). On the moment of
writing, there are 15 sections. Sections are delimited with "[end]". writing there are 15 sections. Sections are delimited with "[end]".
<h4>Example:</h4> <h4>Example:</h4>
<pre>plugin "StringsPlugin.dll" start c:\3proxy\bin\rus.3ps <pre>plugin "StringsPlugin.dll" start c:\3proxy\bin\rus.3ps
</pre> </pre>
<h4>Download:</h4> <h4>Download:</h4>
<ul> <ul>
<li>Plugin is included in the 3proxy 0.6 binary and source distribution <li>Plugin is included into 3proxy 0.6 binary and source distribution
</li></ul> </li></ul>
&copy; Kirill Lopuchov ©Kirill Lopuchov

View File

@ -15,4 +15,4 @@ plugin "StringsPlugin.dll" start c:\3proxy\bin\rus-win1251.3ps
<h4>Загрузить:</h4> <h4>Загрузить:</h4>
<ul> <ul>
<li>Плагин включен в дистрибутив 3proxy 0.6 <li>Плагин включен в дистрибутив 3proxy 0.6
</li></ul> </ul>

View File

@ -1,15 +1,15 @@
<h3>3proxy Traffic Correction Plugin</h3> <h3>3proxy traffic correction plugin</h3>
3proxy logs and counts traffic at the application level, while providers usually do 3proxy logs and counts traffic on application level, while provider usually does
so at the network or link level. This is significant if you use 3proxy for billing, it on network or link level. It's significant if you use 3proxy for billing,
especially in cases where network packets are small, e.g., online games. especially in case where network packets are small, e.g. network games.
<p> <p>
This plugin attempts to correct 3proxy's computations to approximate network or This plugin attempts to correct 3proxy computations to approximate network or
link-level traffic by using either fixed coefficients by port number or link level traffic by using either fixed coefficients by port number or
by attempting to predict the number and sizes of network packets. attempting to predict number and sizes of network packets.
</p><h4>Usage:</h4> </p><h4>Usage:</h4>
<ol> <ol>
<li>Extract TrafficPlugin.dll to the same folder as the 3proxy executable. <li>Extract TrafficPlugin.dll to the same folder with 3proxy executable.
</li><li>Start the plugin in 3proxy.cfg with: </li><li>Start plugin in 3proxy.cfg with
<pre>plugin TrafficPlugin.dll start <pre>plugin TrafficPlugin.dll start
</pre> </pre>
</li><li>Add correction rules: </li><li>Add correction rules:
@ -17,36 +17,36 @@ by attempting to predict the number and sizes of network packets.
FOR FIXED COEFFICIENTS MODE: FOR FIXED COEFFICIENTS MODE:
<pre>trafcorrect m &lt;service&gt; &lt;target port&gt; &lt;coefficient&gt; <pre>trafcorrect m &lt;service&gt; &lt;target port&gt; &lt;coefficient&gt;
</pre> </pre>
where &lt;service&gt; - one of proxy, socks4, socks45, socks5, tcppm, udppm, pop3p; * matches "any". where &lt;service&gt; - one of proxy, socks4, socks45, socks5, tcppm, udppm, pop3p, * matches "any".
<br> &lt;target port&gt; - target port; * matches any <br> &lt;target port&gt; - target port, * matches any
<br> &lt;coefficient&gt; - coefficient to multiply traffic for this port. <br> &lt;coefficient&gt; - coefficient to multiply traffic for this port.
<br> <br>
FOR PACKET HEADER PREDICTION MODE: FOR PACKET HEADER PREDICTION MODE
<pre>trafcorrect p &lt;service&gt; &lt;tcp/udp&gt; &lt;target port&gt; [empty packet size] <pre>trafcorrect p &lt;service&gt; &lt;tcp/udp&gt; &lt;target port&gt; [empty packet size]
</pre> </pre>
tcp or udp - transport-level protocol to apply the rule to tcp ot udp - transport level protocol to apply rule
<br> <br>
empty packet size - average size of an "empty" packet, i.e., the sum of average network/transport headers. empty packet size - average size of "empty" packet, that is sum of average network/transport headers.
You can use a network sniffer such as Ethereal to discover it. Usually, the packet size You can use network sniffer, such is Ethereal to discover it. Usually packet size
is 42 for UDP and is 42 for UDP and
<br>Modes can be mixed. <br>Modes can be mixed.
<br>The plugin creates a list of rules; the first matching rule will be applied. <br>Plugin creates a list of rules, first matching rule will be applied.
</li></ol> </li></ol>
For any mode, the plugin approximates traffic; the logged or counted amount is not exact. For any mode plugin approximates traffic, logged or counted amount is not exact.
<h4>Example:</h4> <h4>Example:</h4>
<pre>plugin "TrafficPlugin.dll" start <pre>plugin "TrafficPlugin.dll" start
trafcorrect m socks5 6112 4.5 trafcorrect m socks5 6112 4.5
trafcorrect m socks5 * 1.1 trafcorrect m socks5 * 1.1
</pre> </pre>
Wrong usage: wrong usage:
<pre>trafcorrect m socks5 * 1.1 <pre>trafcorrect m socks5 * 1.1
trafcorrect m socks5 6112 4.5 trafcorrect m socks5 6112 4.5
</pre> </pre>
The second rule will never be applied. second rule will never be applied.
<h4>Download:</h4> <h4>Download:</h4>
<ul> <ul>
<li>Plugin is included in the 3proxy 0.6 binary and source distribution <li>Plugin is included into 3proxy 0.6 binary and source distribution
</li></ul> </li></ul>
&copy; Maslov Michael aka Flexx(rus) ©Maslov Michael aka Flexx(rus)

View File

@ -46,7 +46,7 @@ trafcorrect p &lt;сервис&gt; &lt;tcp/udp&gt; &lt;исходящий пор
Когда происходит окончание соединения выполняется первое подходящее правило. Когда происходит окончание соединения выполняется первое подходящее правило.
</ol> </ol>
Подсчет трафика в любом режиме не является точным, это некоторая аппроксимация Подсчет трафика в любом режиме не является точным, это некоторая аппроксимация
позволяющая подсчитать трафик с точностью до нескольких процентов. позволяющаяподсчитать трафик с точностью до нескольких процентов.
<h4>Пример:</h4> <h4>Пример:</h4>
<pre> <pre>
@ -66,4 +66,4 @@ trafcorrect m socks5 6112 4.5
<h4>Загрузить:</h4> <h4>Загрузить:</h4>
<ul> <ul>
<li>Плагин включен в дистрибутив 3proxy 0.6 <li>Плагин включен в дистрибутив 3proxy 0.6
</li></ul> </ul>

View File

@ -1,9 +1,9 @@
<h3>3proxy TransparentPlugin (Linux/BSD only)</h3> <h3>3proxy TransparentPlugin plugin (Linux/BSD only)</h3>
This plugin can turn 3proxy into a transparent proxy for virtually any TCP-based protocol Plugin can turn 3proxy into transparent proxy for virtually any TCP-based protocol
and use all 3proxy features - redirections, parent proxies, ACLs, traffic limitations, and use all 3proxy features - redirections, parent proxies, ACLs, traffic limitations,
etc. The TransparentPlugin takes the destination IP:port from Linux and uses this etc. TransparentPlugin plugin takes destination IP:port from Linux and uses this
information as the target IP in the proxy. An example usage: information as a target IP in proxy. An example of usage:
<pre> <pre>
plugin /path/to/TransparentPlugin.ld.so transparent_plugin plugin /path/to/TransparentPlugin.ld.so transparent_plugin
@ -19,13 +19,13 @@ notransparent
proxy proxy
</pre> </pre>
Now, any TCP traffic transparently redirected to port 12345 will be routed via Now, any TCP traffic transparently redirected to port 12345 will be routed via
the parent SOCKSv5 proxy and logged; all URLs for web requests are visible in logs. parent SOCKSv5 proxy and logged, all URLs for web requests are visible in logs.
The parameters '127.0.0.1 11111' in this case are not used and are overwritten by Paremeters '127.0.0.1 11111' in this case are not used and are overwritten by
the destination IP:port for each transparent connection. destination IP:port for each transparent connection.
<h4>Download:</h4> <h4>Download:</h4>
<ul> <ul>
<li>Plugin is included in 3proxy 0.8 <li>Plugin included into 3proxy 0.8
</li></ul> </ul>
&copy; Vladimir Dubrovin, License: BSD style &copy; Vladimir Dubrovin, License: BSD style

View File

@ -28,6 +28,6 @@ HTTP-запросов по порту TCP/80 будут видны параме
<h4>Загрузить:</h4> <h4>Загрузить:</h4>
<ul> <ul>
<li>Плагин включен в дистрибутив 3proxy 0.8 <li>Плагин включен в дистрибутив 3proxy 0.8
</li></ul> </ul>
&copy; Vladimir Dubrovin, License: BSD style &copy; Vladimir Dubrovin, License: BSD style

View File

@ -1,33 +1,33 @@
<h3>3proxy Windows Authentication Plugin</h3> <h3>3proxy Windows Authentication plugin</h3>
Support for cleartext authentication against a Windows domain or local Windows account. Support for cleartext authentication against Windows domain or local Windows account.
<h4>Usage:</h4> <h4>Usage:</h4>
<ol> <ol>
<li>Extract WindowsAuthentication.dll to the same folder as the 3proxy executable. <li>Extract WindowsAuthentication.dll to the same folder with 3proxy executable.
<li>Create 3ProxyAllowedGroup - a Windows system group allowed to use the proxy. <li>Create 3ProxyAllowedGroup - Windows system group allowed to use proxy.
You can choose a different group name. The group can be either local or You can choose different group name. Group can be either local or
Active Directory. Every account allowed to use 3proxy must be included in this Active Directory. Every account allowed to use 3proxy must be included in this
group either directly or through group nesting. group either directly or through group nesting.
<li>Configure the plugin with the 'plugin' command in 3proxy.cfg, e.g.: <li>Configure plugin with 'plugin' command in 3proxy.cfg, e.g.:
<pre><code> <pre><code>
plugin &quot;WindowsAuthentication.dll&quot; WindowsAuthentication &quot;3ProxyAllowedGroup&quot; plugin &quot;WindowsAuthentication.dll&quot; WindowsAuthentication &quot;3ProxyAllowedGroup&quot;
</code></pre> </code></pre>
<br>WindowsAuthentication.dll - location of the DLL; if the DLL is located in a different folder <br>WindowsAuthentication.dll - location of DLL, if DLL is located in different folder
from 3proxy.exe, you must specify the complete path to the DLL here. 3ProxyAllowedGroup - the Windows from 3proxy.exe you must specify complete path to DLL here. 3ProxyAllowedGroup - Windows
system group allowed to use 3proxy. system group allowed to use 3proxy.
After the plugin is loaded, the 'windows' authentication type is supported. After plugin is loaded, 'windows' authentication type is supported.
<li>Configure 'auth windows' for services that require Windows authentication. <li>Configure 'auth windows' for services that require Windows authentication.
<li>It is recommended that you also configure authentication caching (see 'authcache') <li>It's recommended you also configure authentication caching (see 'authcache'),
to prevent excessive workload on the domain controller. Example: to prevent excessive workload for domain controller. Example:
<pre> <pre>
authcache user,pass 900 authcache user,pass 900
auth cache windows auth cache windows
</pre> </pre>
<li>NTLM authentication is not currently supported for plugins; you should use the proxy -n switch to disable it. <li>NTLM authentication is not currently supported for plugins, you should use proxy -n key to disable it.
</ol> </ol>
<h4>Download:</h4> <h4>Download:</h4>
<ul> <ul>
<li>Plugin is included in the 3proxy 0.6 binary and source distribution <li>Plugin is included into 3proxy 0.6 binary and source distribution
</li></ul> </ul>

View File

@ -31,5 +31,5 @@ auth windows
<h4>Загрузить:</h4> <h4>Загрузить:</h4>
<ul> <ul>
<li>Плагин включен в дистрибутив 3proxy 0.6 <li>Плагин включен в дистрибутив 3proxy 0.6
</li></ul> </ul>

View File

@ -1,33 +1,35 @@
<h3>3proxy Security Considerations</h3> <h3>3proxy security considirations</h3>
<ul> </ul>
<li>Never install 3proxy suid. If you need it to run suid, write a <ul>
wrapper with a fixed configuration file. <li>Never install 3proxy suid. If you need it to run suid write some
<li>Make the configuration file accessible only to the account 3proxy starts with. wrapper with fixed configuration file.
<li>Under Windows, if 3proxy is used as a service, create a new <li>Make configuration file only available to account 3proxy starts with.
unprivileged local account without "logon locally" rights. Assign this account <li>Under Windows if 3proxy is used as service create new
to the 3proxy service. unprivileged local account without "logon locally" right. Assign this account
<li>Under Unix, use chroot to jail 3proxy (make sure files included in to 3proxy service.
the configuration file after the 'chroot' command, if any, are available from within the jail). <li>Under unix use chroot to jail 3proxy (make sure files included in
<li>Under Unix, either start 3proxy with an unprivileged account or, if you need configuration file after 'chroot' command, if any, are available from jail)
some privileged ports to be used by 3proxy, use setgid/setuid commands inside <li>Under Unix, either start 3proxy with unprivileged account or, if you need
3proxy.cfg immediately after the last occurrence of a service bound to a some privileged ports to be used by 3proxy, use setgid/setuid commands inside
privileged port in the configuration file (setgid must precede setuid). 3proxy.cfg immediately after last occurance of service binded to
<li>Always use full paths in the configuration file. privileged port in configuration file (setgid must preceed setuid).
<li>Try to avoid 'strong' authentication, because only cleartext <li>Allways use full paths in configuration file
authentication is currently available. <li>Try to avoid 'strong' authentication, because only cleartext
<li>Always specify internal and external interfaces. authentication method is currently available.
<li>Always limit connections to the internal network and localhost (to 127.0.0.1 and <li>Always specify internal and external interfaces.
all interfaces) with ACLs. Be careful, because the BIND command in SOCKS requires the <li>Always limit connections to internal network and localhost (to 127.0.0.1 and
BIND method with the external interface IP address to be allowed. all interfaces) with ACLs. Be carefull, because BIND command in SOCKS requies
<li>Before 3proxy 0.8, always use nserver and nscache under Unix; otherwise, a DoS attack is possible BIND method with external interface IP address to be allowed.
with an unreachable DNS server (because gethostbyname will block other threads). <li> Before 3proxy 0.8 always use nserver and nscache under Unix, overwise DoS attack is possible
<li>Keep logs in a secure location, because some confidential information from with unreachable DNS server (because gethostbyname will block over threads).
user requests can be logged. <li>Keep logs in secure location, because some confidential information from
<li>Use -xyz+A character filtering sequences for 'logformat', especially with user's request can be logged.
ODBC logging, to prevent SQL and log record injections. <li>Use -xyz+A character filtering sequences for 'logformat', especially with
<li>Immediately report all service crashes to the developers. ODBC logging to prevent SQL and log record injections.
<li>Participate in code audit :) <li>Immediately report all service crashes to developers
<li>Participate in code audit :)
</ol>
</ul> </ul>
<p> <p>

View File

@ -3,26 +3,26 @@ KOI8-R
Kirill Lopuchov, lopuchov at mail ru Kirill Lopuchov, lopuchov at mail ru
<3proxy> <3proxy>
Довольно часто перед системным администратором встает задача предоставить доступ к Internet-ресурсам группе пользователей (небольшой офис, Internet-кафе). Данную задачу можно решить, настроив на Internet-шлюзе proxy-сервер, службу NAT (трансляция сетевых адресов) или раздать каждому пользователю реальный IP адрес. Довольно часто перед системным администратором встает задача предоставить доступ к Internet-ресурсам группе пользователей (небольшой офис, Internet-кафе). Данную задачу можно решить, настроив на Internet-шлюзе proxy-сервер, службу NAT (трансляция сетевых адресов) или раздать каждому пользователю реальный IP адрес.
Давайте рассмотрим самый простой способ подключения - установку proxy-сервера. Традиционно для этих целей применяется популярный proxy Squid, но не всегда бывает необходимость в столь тяжеловатой программе :), да и в squid отсутствуют такие иногда необходимые вещи как SOCKS4/5-сервер, TCP/UP порт-маппинг. Поэтому вторым номером хочется представить вашему вниманию PROXY-сервер, под названием "3proxy" (http://3proxy.ru/), разработанный нашим программистом из г. Нижний Новгород. Одним из главных его достоинств является компактность и высокая переносимость. Код сервера написан так, что легко компилируется как для Win9x/2000/XP так и для Linux и FreeBSD. Давайте рассмотрим самый простой способ подключения - установку proxy-сервера. Традиционно для этих целей применяется популярный proxy Squid, но не всегда бывает необходимость в столь тяжеловатой программе :), да и в squid отсутствуют такие иногда необходимые вещи как SOCKS4/5-сервер, TCP/UP порт-маппинг. Поэтому вторым номером хочется представить вашему вниманию PROXY-сервер, под названием "3proxy" (http://3proxy.ru/), разработанный нашим программистом из г. Нижний Новгород. Одним из главных его достоинств является компактность и высокая переносимость. Код сервера написан так, что легко компилируется как для Win9x/2000/XP так и для Linux и FreeBSD.
Сервер поддерживает следующие возможности: Сервер поддерживает следующие возможности:
HTTP(S) proxy; HTTP(S) proxy;
FTP over HTTP proxy; FTP over HTTP proxy;
SOCKS4/5 proxy; SOCKS4/5 proxy;
POP3 proxy; POP3 proxy;
TCP & UDP маппинг портов; TCP & UDP маппинг портов;
листы доступа к различным службам и адресам; листы доступа к различным службам и адресам;
ограничение пропускной способности канала каждого пользователя (чтобы пользователь не съел весь канал, качая кучу файлов в несколько потоков :) ); ограничение пропускной способности канала каждого пользователя (чтобы пользователь не съел весь канал, качая кучу файлов в несколько потоков :) );
ограничение трафика пользователя на день, неделю и месяц; ограничение трафика пользователя на день, неделю и месяц;
авторизацию пользователей ко всем proxy-службам по имени и паролю или по ip адресам; авторизацию пользователей ко всем proxy-службам по имени и паролю или по ip адресам;
ведение журналов через ODBC (по-моему, такого нет ни в одном proxy) и syslog и т. д. ведение журналов через ODBC (по-моему, такого нет ни в одном proxy) и syslog и т. д.
К недостаткам можно отнести отсутствие кэширования информации :-|. Но в последнее время Inernet-контент становится все более динамичным (то есть не поддающийся кэшированию) и может быть для кого-то экономия в 25% трафика за счет его кэширования не будет столь критична. Для тех пользователей, кому она может оказаться критичной, автор предлагает использовать цепочку из 2-х серверов и в качестве кэша такие сервера как wwwoffle или им подобные, либо ждать появления поддержки кеша в 3proxy :) К недостаткам можно отнести отсутствие кэширования информации :-|. Но в последнее время Inernet-контент становится все более динамичным (то есть не поддающийся кэшированию) и может быть для кого-то экономия в 25% трафика за счет его кэширования не будет столь критична. Для тех пользователей, кому она может оказаться критичной, автор предлагает использовать цепочку из 2-х серверов и в качестве кэша такие сервера как wwwoffle или им подобные, либо ждать появления поддержки кеша в 3proxy :)
Установка Установка
# wget http://3proxy.ru/current/3proxy.tgz # wget http://3proxy.ru/current/3proxy.tgz
# tar -xvzf 3proxy.tgz # tar -xvzf 3proxy.tgz
@ -35,64 +35,64 @@ TCP & UDP маппинг портов;
# touch /usr/local/3proxy/3proxy.cfg # touch /usr/local/3proxy/3proxy.cfg
# chown -R nobody:nogroup /usr/local/3proxy # chown -R nobody:nogroup /usr/local/3proxy
Далее приведу небольшой пример конфигурационного файла 3proxy.cfg с Далее приведу небольшой пример конфигурационного файла 3proxy.cfg с
комментариями, более подробную информацию по конфигурированию можно комментариями, более подробную информацию по конфигурированию можно
найти файле 3proxy.cfg.sample или в найти файле 3proxy.cfg.sample или в
HowTo http://3proxy.ru/howtor.asp HowTo http://3proxy.ru/howtor.asp
и FAQ http://3proxy.ru/faqr.asp и FAQ http://3proxy.ru/faqr.asp
-------------3proxy.cfg------------- -------------3proxy.cfg-------------
# ВНИМАНИЕ !! не должны быть пробелов # ВНИМАНИЕ !! не должны быть пробелов
# перед любыми опциями конфигурации !! # перед любыми опциями конфигурации !!
# ip-адрес DNS-сервера провайдера или локального # ip-адрес DNS-сервера провайдера или локального
nserver 127.0.0.1 nserver 127.0.0.1
timeouts 1 5 30 60 180 1800 15 60 timeouts 1 5 30 60 180 1800 15 60
# Создаем двух пользователей vasia, petia и vova # Создаем двух пользователей vasia, petia и vova
# и назначаем им пароли 24555, 14656 и 45455 соответственно # и назначаем им пароли 24555, 14656 и 45455 соответственно
users vasia:CL:24555 users vasia:CL:24555
users petia:CL:14656 users petia:CL:14656
users vova:CL:45455 users vova:CL:45455
# Лог-файл со списком запросов пользователей # Лог-файл со списком запросов пользователей
# будет создаваться каждый день новый # будет создаваться каждый день новый
log /usr/local/3proxy/logs/3proxy.log D log /usr/local/3proxy/logs/3proxy.log D
logformat "%d-%m-%Y %H:%M:%S %U %C:%c %R:%r %O %I %T" logformat "%d-%m-%Y %H:%M:%S %U %C:%c %R:%r %O %I %T"
# Внешний интерфейс, # Внешний интерфейс,
# через который будут уходить запросы от сервера # через который будут уходить запросы от сервера
external 10.1.1.1 external 10.1.1.1
# ip-адрес интерфейса, на котором будут приниматься # ip-адрес интерфейса, на котором будут приниматься
# запросы от клиентов # запросы от клиентов
internal 192.168.1.1 internal 192.168.1.1
# Устанавливаем тип авторизации по имени и паролю # Устанавливаем тип авторизации по имени и паролю
auth strong auth strong
# Разрешаем доступ к портам 80,8080-8088 # Разрешаем доступ к портам 80,8080-8088
allow * * * 80,8080-8088 allow * * * 80,8080-8088
# Расскоментировать секцию parent, если у вас есть прокси верхнего # Расскоментировать секцию parent, если у вас есть прокси верхнего
# уровня и заменить ip, порт, имя пользователя и пароль на свои значения # уровня и заменить ip, порт, имя пользователя и пароль на свои значения
# parent 1000 http 192.168.0.1 8080 username passwd # parent 1000 http 192.168.0.1 8080 username passwd
# allow * # allow *
# Запускаем службу HTTP-proxy на порту (3128) и # Запускаем службу HTTP-proxy на порту (3128) и
# (-n) c отключенной NTLM-авторизацией) # (-n) c отключенной NTLM-авторизацией)
proxy -p3128 -n proxy -p3128 -n
# Ограничиваем толшину канала для пользователей # Ограничиваем толшину канала для пользователей
# vasia и petia в 20000 bps, # vasia и petia в 20000 bps,
# а для vova 10000 bps # а для vova 10000 bps
bandlimin 20000 vasia,petia bandlimin 20000 vasia,petia
bandlimin 10000 vova bandlimin 10000 vova
# Запускаем сервер от пользователя nobody # Запускаем сервер от пользователя nobody
# (возможно в вашей ОС uid и gid пользователя nobody # (возможно в вашей ОС uid и gid пользователя nobody
# будут другими. Для их определения воспользуйтесь коммандой id nobody) # будут другими. Для их определения воспользуйтесь коммандой id nobody)
setgid 65534 setgid 65534
setuid 65534 setuid 65534
------------------------------------ ------------------------------------
После того как мы создали конфигурационный файл сервера, запускаем 3proxy командой: После того как мы создали конфигурационный файл сервера, запускаем 3proxy командой:
/usr/local/3proxy/3proxy /usr/local/3proxy/3proxy.cfg /usr/local/3proxy/3proxy /usr/local/3proxy/3proxy.cfg

View File

@ -2,9 +2,9 @@ KOI8-R
Kirill Lopuchov, lopuchov at mail ru Kirill Lopuchov, lopuchov at mail ru
Ведение логов сервера в SQL-базе имеет свои приемущества перед обычными текстовыми файлами. 3proxy поддерживает ведение логов через ODBC-менеджер в любой базе данных, имеющих ODBC-драйвер. Этот менеджер стал стандартом де-факто в среде Windows, чего, к сожалению, не скажешь про Unix. Поэтому далее рассмотрим на примере FreeBSD настройку ведения логов в базе SQLite. Эта база данных выбрана в качестве примера потому, что она проста в установке и настроке (в принципе настройка ведения логов в любой другой базе mysql или postgresql отличается только настройкой его odbc-драйвера) Ведение логов сервера в SQL-базе имеет свои приемущества перед обычными текстовыми файлами. 3proxy поддерживает ведение логов через ODBC-менеджер в любой базе данных, имеющих ODBC-драйвер. Этот менеджер стал стандартом де-факто в среде Windows, чего, к сожалению, не скажешь про Unix. Поэтому далее рассмотрим на примере FreeBSD настройку ведения логов в базе SQLite. Эта база данных выбрана в качестве примера потому, что она проста в установке и настроке (в принципе настройка ведения логов в любой другой базе mysql или postgresql отличается только настройкой его odbc-драйвера)
Устанавливаем SQLite Устанавливаем SQLite
wget http://www.sqlite.org/sqlite-2.8.14.tar.gz wget http://www.sqlite.org/sqlite-2.8.14.tar.gz
tar -xvzf sqlite-2.8.14.tar.gz tar -xvzf sqlite-2.8.14.tar.gz
cd sqlite cd sqlite
@ -12,7 +12,7 @@ cd sqlite
gmake gmake
gmake install gmake install
Устанавливаем iODBC менеджер Устанавливаем iODBC менеджер
wget http://www.iodbc.org/libiodbc-3.51.2.tar.gz wget http://www.iodbc.org/libiodbc-3.51.2.tar.gz
tar -xvzf libiodbc-3.51.2.tar.gz tar -xvzf libiodbc-3.51.2.tar.gz
cd libiodbc-3.51.2 cd libiodbc-3.51.2
@ -20,24 +20,24 @@ cd libiodbc-3.51.2
make make
make install make install
Устанавливаем odbc драйвер SQLite Устанавливаем odbc драйвер SQLite
wget http://www.ch-werner.de/sqliteodbc/sqliteodbc-0.62.tar.gz wget http://www.ch-werner.de/sqliteodbc/sqliteodbc-0.62.tar.gz
tar -xvzf sqliteodbc-0.62.tar.gz tar -xvzf sqliteodbc-0.62.tar.gz
cd sqliteodbc-0.62 cd sqliteodbc-0.62
./configure ./configure
Если у вас скрипт configure выдал ошибку : Если у вас скрипт configure выдал ошибку :
(configure: error: SQLite library too old) (configure: error: SQLite library too old)
то ее можно попробовать обойти, вставив (SQLITE_COMPILE=1 то ее можно попробовать обойти, вставив (SQLITE_COMPILE=1
в стр. 5092 после условия if endif) в файле configure в стр. 5092 после условия if endif) в файле configure
make make
make install make install
Далее настраиваем записи для iODBC менеджера в Далее настраиваем записи для iODBC менеджера в
файлах /etc/odbcinst.ini и /etc/odbc.ini файлах /etc/odbcinst.ini и /etc/odbc.ini
Настраиваем odbc драйвер Настраиваем odbc драйвер
--------------/etc/odbcinst.ini------------- --------------/etc/odbcinst.ini-------------
[ODBC Drivers] [ODBC Drivers]
SQLite=Installed SQLite=Installed
@ -46,8 +46,8 @@ SQLite=Installed
Driver=/usr/local/lib/libsqliteodbc.so Driver=/usr/local/lib/libsqliteodbc.so
--------------------------------------- ---------------------------------------
Создаем DSN для базы c именем "sqlite", которая будет Создаем DSN для базы c именем "sqlite", которая будет
располагаться в каталоге: /usr/local/3proxy/logs.db располагаться в каталоге: /usr/local/3proxy/logs.db
--------------/etc/odbc.ini---------------- --------------/etc/odbc.ini----------------
[ODBC Data Sources] [ODBC Data Sources]
@ -61,8 +61,8 @@ Database=/usr/local/3proxy/logs.db
Timeout=2000 Timeout=2000
--------------------------------------- ---------------------------------------
Создаем базу для логов и таблицу в формате (logformat Создаем базу для логов и таблицу в формате (logformat
см. описание в 3proxy.cfg.sample ) см. описание в 3proxy.cfg.sample )
sqlite /usr/local/3proxy/logs.db sqlite /usr/local/3proxy/logs.db
@ -79,7 +79,7 @@ sqlite>create table log (
...>); ...>);
Добавляем следующие записи в конфигурационный файл 3proxy.cfg Добавляем следующие записи в конфигурационный файл 3proxy.cfg
---------------3proxy.cfg----------------- ---------------3proxy.cfg-----------------
log &sqlite log &sqlite
@ -88,12 +88,12 @@ l_descr)
values ('%d-%m-%Y', '%H:%M:%S', '%U', '%N', %I, %O, '%T')" values ('%d-%m-%Y', '%H:%M:%S', '%U', '%N', %I, %O, '%T')"
------------------------------------------ ------------------------------------------
Cобрать 3proxy c поддрежкой iODBC, для этого в Makefile.unix поменять Cобрать 3proxy c поддрежкой iODBC, для этого в Makefile.unix поменять
CFLAGS = -Wall -O2 -c -pthread -D_THREAD_SAFE -D_REENTRANT -DWITH_STD_MALLOC -I/usr/local/include CFLAGS = -Wall -O2 -c -pthread -D_THREAD_SAFE -D_REENTRANT -DWITH_STD_MALLOC -I/usr/local/include
LIBS = -L /usr/local/lib -lodbc LIBS = -L /usr/local/lib -lodbc
и дать команды и дать команды
make clean make clean
make -f Makefile.unix make -f Makefile.unix

View File

@ -1,6 +1,6 @@
Eugene: Re: 3proxy 0.6 + iODBC + PostgreSQL 22.11.2007 19:04:23 Eugene: Re: 3proxy 0.6 + iODBC + PostgreSQL 22.11.2007 19:04:23
Наконец-то я разобрался и запустил. Наконец-то я разобрался и запустил.
1. Я использовал пакет unixODBC. 1. Я использовал пакет unixODBC.
2. /etc/unixODBC/odbc.ini 2. /etc/unixODBC/odbc.ini
[proxy] [proxy]
Description = PostgreSQL ODBC driver Description = PostgreSQL ODBC driver
@ -12,7 +12,7 @@ ServerName = localhost
Description = PostgreSQL ODBC driver Description = PostgreSQL ODBC driver
Driver = /usr/local/lib/psqlodbcw.so Driver = /usr/local/lib/psqlodbcw.so
Setup = /usr/lib/libodbcpsqlS.so Setup = /usr/lib/libodbcpsqlS.so
4. Собирал вручную psqlodbc-08.02.0500, слитый с postgresql.org (получился psqlodbcw.so). 4. Собирал вручную psqlodbc-08.02.0500, слитый с postgresql.org (получился psqlodbcw.so).
5. 3proxy.conf 5. 3proxy.conf
log &proxy,logger,123 log &proxy,logger,123
logformat "LINSERT INTO logger (ldatetime,username,userip,trafin,trafout,service,host,port, logformat "LINSERT INTO logger (ldatetime,username,userip,trafin,trafout,service,host,port,
@ -20,9 +20,9 @@ url) VALUES ('%Y-%m-%d %H:%M:%S','%U','%C',
'%I','%O','%N', '%I','%O','%N',
'%n','%r','%T');" '%n','%r','%T');"
То есть пароли и логины в odbc.ini прописывать не надо - система падает на драйвере ODBC. То есть пароли и логины в odbc.ini прописывать не надо - система падает на драйвере ODBC.
Использовать libiodbc тоже не надо - система падает на libiodbc.so. Использовать libiodbc тоже не надо - система падает на libiodbc.so.
Все вышесказанное справедливо для unixODBC + psqlodbc производства postgresql.org, как с -DSAFESQL, так и без оного. Все вышесказанное справедливо для unixODBC + psqlodbc производства postgresql.org, как с -DSAFESQL, так и без оного.
С myodbc + unixODBC проблем не наблюдалось никаких. С myodbc + unixODBC проблем не наблюдалось никаких.
Шаманство, в общем ;) Шаманство, в общем ;)

View File

@ -14,18 +14,18 @@ server
.RI [ \-\-remove ] .RI [ \-\-remove ]
.SH DESCRIPTION .SH DESCRIPTION
.B 3proxy .B 3proxy
is a universal proxy server. It can be used to provide internal users with is universal proxy server. It can be used to provide internal users wuth
fully controllable access to external resources or to provide external fully controllable access to external resources or to provide external
users with access to internal resources. 3proxy is not developed to replace users with access to internal resources. 3proxy is not developed to replace
.BR squid (8), .BR squid (8),
but it can extend the functionality of an existing caching proxy. but it can extend functionality of existing cashing proxy.
It can be used to route requests between different types of clients and proxy It can be used to route requests between different types of clients and proxy
servers. Think about it as application level servers. Think about it as application level
gateway with configuration like hardware router has for network layer. gateway with configuration like hardware router has for network layer.
It can establish multiple It can establish multiple
gateways with HTTP and HTTPS proxy with FTP over HTTP support, SOCKS v4, gateways with HTTP and HTTPS proxy with FTP over HTTP support, SOCKS v4,
v4.5 and v5, POP3 proxy, UDP and TCP portmappers. Each gateway is started v4.5 and v5, POP3 proxy, UDP and TCP portmappers. Each gateway is started
from the configuration file like an independent service from configuration file like independant service
.BR proxy (8) .BR proxy (8)
.BR socks (8) .BR socks (8)
.BR pop3p (8) .BR pop3p (8)
@ -35,24 +35,24 @@ from the configuration file like an independent service
.BR dnspr .BR dnspr
but but
.BR 3proxy .BR 3proxy
is not a kind of wrapper or superserver for these daemons. It just has the same is not a kind of wrapper or superserver for this daemons. It just has same
code compiled in, but provides much more functionality. SOCKSv5 code compiled in, but provides much more functionality. SOCKSv5
implementation allows you to use 3proxy with any UDP or TCP based client implementatation allows to use 3proxy with any UDP or TCP based client
applications designed without applications designed without
proxy support (with proxy support (with
.IR SocksCAP , .IR SocksCAP ,
.I FreeCAP .I FreeCAP
or another client-side redirector under Windows or with a socksification library or another client-side redirector under Windows of with socksification library
under Unix). So you can play your favourite games, listen to music, exchange under Unix). So you can play your favourite games, listen music, exchange
files and messages and even accept incoming connections behind a proxy server. files and messages and even accept incoming connections behind proxy server.
.PP .PP
.I dnspr .I dnspr
does not exist as an independent service. It's a DNS caching proxy (it requires does not exist as independant service. It\' DNS caching proxy (it requires
.I nscache .I nscache
and and
.I nserver .I nserver
to be set in the configuration. Only A-records are cached. Please note that to be set in configuration. Only A-records are cached. Please note, the
this caching is mostly a 'hack' and has nothing to do with a real this caching is mostly a 'hack' and has nothing to do with real
DNS server, but it works perfectly for SOHO networks. DNS server, but it works perfectly for SOHO networks.
.PP .PP
@ -65,9 +65,9 @@ NetBIOS name for Windows clients (it\'s very like ident authentication).
Depending on ACL action request can be allowed, denied or redirected to another Depending on ACL action request can be allowed, denied or redirected to another
host or to another proxy server or even to a chain of proxy servers. host or to another proxy server or even to a chain of proxy servers.
.PP .PP
It supports different types of logging: to logfiles, It supports different types of logging: to logfiles,
.BR syslog (3) .BR syslog (3)
(only under Unix) or to an ODBC database. Logging format is tunable to provide (only under Unix) or to ODBC database. Logging format is turnable to provide
compatibility with existing log file parsers. It makes it possible to use compatibility with existing log file parsers. It makes it possible to use
3proxy with IIS, ISA, Apache or Squid log parsers. 3proxy with IIS, ISA, Apache or Squid log parsers.
.SH OPTIONS .SH OPTIONS
@ -77,12 +77,12 @@ Name of config file. See
.BR 3proxy.cfg (3) .BR 3proxy.cfg (3)
for configuration file format. Under Windows, if config_file is not specified, for configuration file format. Under Windows, if config_file is not specified,
.BR 3proxy .BR 3proxy
looks for a file named looks for file named
.I 3proxy.cfg .I 3proxy.cfg
in the default location (in the same directory as the executable file and in the current in the default location (in same directory with executable file and in current
directory). Under Unix, if no config file is specified, 3proxy reads directory). Under Unix, if no config file is specified, 3proxy reads
configuration from stdin. It makes it possible to use the 3proxy.cfg file as configuration from stdin. It makes it possible to use 3proxy.cfg file as
an executable script just by setting +x mode and adding executable script just by setting +x mode and adding
.br .br
#!/usr/local/3proxy/3proxy #!/usr/local/3proxy/3proxy
.br .br
@ -98,28 +98,28 @@ as a system service
.BR 3proxy .BR 3proxy
from system services from system services
.SH SIGNALS .SH SIGNALS
Under Unix there are a few signals Under Unix there are few signals
.BR 3proxy .BR 3proxy
catches. See catches. See
.BR kill (1). .BR kill (1).
.TP .TP
.B SIGTERM .B SIGTERM
clean up connections and exit cleanup connections and exit
.TP .TP
.B SIGPAUSE .B SIGPAUSE
stop accepting new connections, on second signal - start and re-read stop to accept new connections, on second signal - start and re-read
configuration configuration
.TP .TP
.B SIGCONT .B SIGCONT
start to accept new connections start to accept new conenctions
.TP .TP
.B SIGUSR1 .B SIGUSR1
reload configuration reload configuration
.PP .PP
Under Windows, if Under Windows, if
.BR 3proxy .BR 3proxy
is installed as a service you can use standard service management to start, stop, is installed as service you can standard service management to start, stop,
pause and continue the 3proxy service, for example: pause and continue 3proxy service, for example:
.br .br
.BR "net start 3proxy" .BR "net start 3proxy"
.br .br

View File

@ -6,9 +6,9 @@
Common structure: Common structure:
.br .br
Configuration file is a text file 3proxy reads configuration from. Each line Configuration file is a text file 3proxy reads configuration from. Each line
of the file is a command executed immediately, as if it were given from the of the file is a command executed immediately, as it was given from
console. The sequence of commands is important. The configuration file is actually a console. Sequence of commands is important. Configuration file as actually a
script for the 3proxy executable. script for 3proxy executable.
Each line of the file is treated as a blank (space or tab) separated Each line of the file is treated as a blank (space or tab) separated
command line. Additional space characters are ignored. command line. Additional space characters are ignored.
Think about 3proxy as "application level router" with console interface. Think about 3proxy as "application level router" with console interface.
@ -16,16 +16,16 @@ Think about 3proxy as "application level router" with console interface.
.br .br
Comments: Comments:
.br .br
Any line beginning with a space character or \'#\' character is a comment. It\'s Any string beginning with space character or \'#\' character is comment. It\'s
ignored. <LF>s are ignored. <CR> is the end of a command. ignored. <LF>s are ignored. <CR> is end of command.
.br .br
Quotation: Quotation:
.br .br
The quotation character is " (double quote). Quotation must be used to quote Quotation character is " (double quote). Quotation must be used to quote
spaces or other special characters. To use a quotation character inside spaces or another special characters. To use quotation character inside
a quoted string, the character must be doubled (BASIC convention). For example, to use quotation character must be dubbed (BASIC convention). For example to use
HELLO "WORLD" as an argument, you should write it as "HELLO ""WORLD""". HELLO "WORLD" as an argument you should use it as "HELLO ""WORLD""".
Good practice is to quote any argument you use. Good practice is to quote any argument you use.
.br .br
@ -37,7 +37,7 @@ to file, for example $/usr/local/etc/3proxy/conf.incl or
required in last example because path contains space character. required in last example because path contains space character.
For included file <CR> (end of line characters) is treated as space character For included file <CR> (end of line characters) is treated as space character
(arguments delimiter instead of end of command delimiter). (arguments delimiter instead of end of command delimiter).
Thus, include files are only useful to store long single-line commands Thus, include files are only useful to store long signle-line commands
(like userlist, network lists, etc). (like userlist, network lists, etc).
To use dollar sign somewhere in argument it must be quoted. To use dollar sign somewhere in argument it must be quoted.
Recursion is not allowed. Recursion is not allowed.
@ -55,9 +55,6 @@ Recursion is not allowed.
.B pop3p .B pop3p
[options] [options]
.br .br
.B smtpp
[options]
.br
.B ftppr .B ftppr
[options] [options]
.br .br
@ -123,7 +120,7 @@ disable NTLM authentication (required if passwords are stored in Unix crypt form
enable NTLMv1 authentication. enable NTLMv1 authentication.
.br .br
.B -g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY) .B -g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY)
delay GRACE_DELAY milliseconds before polling if average polling size is below GRACE_TRAFF bytes and GRACE_NUM read operations in a single direction are detected within 1 second. Useful to minimize polling 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.
@ -145,7 +142,7 @@ Never ask for username/password
(for proxy) anonymous proxy (random client information reported) (for proxy) anonymous proxy (random client information reported)
.br .br
.B -a2 .B -a2
(for proxy) generate Via: and X-Forwarded-For: instead of Forwarded: (for proxy) generate Via: and X-Forwared-For: instead of Forwarded:
.br .br
.B -6 .B -6
Only resolve IPv6 addresses. IPv4 addresses are packed in IPv6 in IPV6_V6ONLY compatible way. Only resolve IPv6 addresses. IPv4 addresses are packed in IPv6 in IPV6_V6ONLY compatible way.
@ -170,17 +167,17 @@ options for proxy-to-client (oc), proxy-to-server (os), proxy listening (ol), co
Options like TCP_CORK, TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS, USE_TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT, SO_PORT_SCALABILITY, SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be supported depending on OS. Options like TCP_CORK, TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS, USE_TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT, SO_PORT_SCALABILITY, SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be supported depending on OS.
.br .br
.B -DiINTERFACE, -DeINTERFACE .B -DiINTERFACE, -DeINTERFACE
bind internal interface / external interface to given INTERFACE (e.g. eth0) if SO_BINDTODEVICE is supported by the system. You may need to run as root or have CAP_NET_RAW capability in order to bind to an interface, depending on the system, so this option may require root privileges and can be incompatible with some configuration commands like chroot and setuid (and daemon if setcap is used). bind internal interface / external inteface to given INTERFACE (e.g. eth0) if SO_BINDTODEVICE supported by system. You may need to run as root or to have CAP_NET_RAW capability in order to bind to interface, depending on system, so this option may require root privileges and can be incompatible with some configuraton commands like chroot and setuid (and daemon if setcap is used).
.br .br
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. External IP must be specified if you need incoming connections. from. External IP must be specified if you need incoming connections.
By default the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.br .br
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. By default connection to any interface is accepted.
.br .br
.B -N .B -N
(for socks) External NAT address 3proxy reports to client for BIND and UDPASSOC (for socks) External NAT address 3proxy reports to client for BIND and UDPASSOC
@ -259,17 +256,13 @@ alternate config file. Think twice before using it.
.br .br
LOGTYPE is one of: LOGTYPE is one of:
.br .br
c Minutely M Monthly
.br
H Hourly
.br
D Daily
.br .br
W Weekly (starting from Sunday) W Weekly (starting from Sunday)
.br .br
M Monthly D Daily
.br .br
Y Annually H Hourly
.br .br
if logfile is not specified logging goes to stdout. You can specify individual logging options for gateway by using -l if logfile is not specified logging goes to stdout. You can specify individual logging options for gateway by using -l
option in gateway configuration. option in gateway configuration.
@ -305,7 +298,7 @@ with space and all time based elemnts are in local time zone.
.br .br
%m Month number %m Month number
.br .br
%o Month abbreviation %o Month abbriviature
.br .br
%d Day %d Day
.br .br
@ -315,17 +308,17 @@ with space and all time based elemnts are in local time zone.
.br .br
%S Second %S Second
.br .br
%t Timestamp (in seconds since 01-Jan-1970) %t Timstamp (in seconds since 01-Jan-1970)
.br .br
%. milliseconds %. milliseconds
.br .br
%z time zone (from Greenwich) %z timeZone (from Grinvitch)
.br .br
%D request duration (in milliseconds) %D request duration (in milliseconds)
.br .br
%b average send rate per request (in bytes per second); this speed is typically below the connection speed shown by the download manager. %b average send rate per request (in Bytes per second) this speed is typically below connection speed shown by download manager.
.br .br
%B average receive rate per request (in bytes per second); this speed is typically below the connection speed shown by the download manager. %B average receive rate per request (in Bytes per second) this speed is typically below connection speed shown by download manager.
.br .br
%U Username %U Username
.br .br
@ -361,9 +354,9 @@ with space and all time based elemnts are in local time zone.
.br .br
%T service specific Text %T service specific Text
.br .br
%N1-N2T (N1 and N2 are positive numbers) log only fields from N1 through N2 of service-specific text %N1-N2T (N1 and N2 are positive numbers) log only fields from N1 thorugh N2 of service specific text
.br .br
In the case of ODBC logging, logformat specifies an SQL statement, for example: in the case of ODBC logging logformat specifies SQL statement, for exmample:
.br .br
logformat "-\'+_Linsert into log (l_date, l_user, l_service, l_in, l_out, l_descr) values (\'%d-%m-%Y %H:%M:%S\', \'%U\', \'%N\', %I, %O, \'%T\')" logformat "-\'+_Linsert into log (l_date, l_user, l_service, l_in, l_out, l_descr) values (\'%d-%m-%Y %H:%M:%S\', \'%U\', \'%N\', %I, %O, \'%T\')"
@ -376,14 +369,6 @@ traffic is achieved for connection, without waiting for connection to finish.
It may be useful to prevent information about long-lasting downloads on server It may be useful to prevent information about long-lasting downloads on server
shutdown. shutdown.
.br
.B delimchar
<char>
.br
Sets the delimiter character used to separate username from hostname in proxy
authentication strings (e.g. for FTP, POP3 proxies). Default is \'@\'. For example,
to use \'#\' instead: delimchar #. This allows usernames to contain the \'@\' character.
.br .br
.B archiver .B archiver
<ext> <commandline> <ext> <commandline>
@ -416,14 +401,6 @@ 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 maxseg
<value>
.br
Sets TCP maximum segment size (MSS) for outgoing connections. This can be used
to work around path MTU discovery issues or to optimize traffic for specific
network conditions.
.br .br
.B radius .B radius
<NAS_SECRET> <radius_server_1[:port][/local_address_1]> <radius_server_2[:port][/local_address_2]> <NAS_SECRET> <radius_server_1[:port][/local_address_1]> <radius_server_2[:port][/local_address_2]>
@ -451,19 +428,12 @@ Use authcache to speedup authentication. RADIUS feature is currently experimenta
.B nserver .B nserver
<ipaddr>[:port][/tcp] <ipaddr>[:port][/tcp]
.br .br
Nameserver to use for name resolutions. If none specified Nameserver to use for name resolutions. If none specified
system routines for name resolution is system routines for name resolution is
used. Optional port number may be specified. used. Optional port number may be specified.
If optional /tcp is added to IP address, name resolution is If optional /tcp is added to IP address, name resolution is
performed over TCP. performed over TCP.
.br
.B authnserver
<ipaddr>[:port][/tcp]
.br
Nameserver to use for DNS-based authentication (e.g. dnsname auth type).
If not specified, nserver is used. The syntax is the same as for nserver.
.br .br
.B nscache .B nscache
<cachesize> <cachesize>
@ -471,8 +441,8 @@ If not specified, nserver is used. The syntax is the same as for nserver.
<cachesize> <cachesize>
.br .br
Cache <cachesize> records for name resolution (nscache for IPv4, Cache <cachesize> records for name resolution (nscache for IPv4,
nscache6 for IPv6). The cache size should usually be large enough nscache6 for IPv6). Cachesize usually should be large enougth
(for example, 65536). (for example 65536).
.br .br
.B nsrecord .B nsrecord
@ -487,8 +457,8 @@ command to set up UDL for dialing.
.br .br
.B fakeresolve .B fakeresolve
.br .br
All names are resolved to the 127.0.0.2 address. Useful if all requests are All names are resolved to 127.0.0.2 address. Usefull if all requests are
redirected to a parent proxy with http, socks4+, connect+ or socks5+. redirected to parent proxy with http, socks4+, connect+ or socks5+.
.br .br
.B dialer .B dialer
@ -521,8 +491,8 @@ External or -e can be given twice: once with IPv4 and once with IPv6 address.
.B maxconn .B maxconn
<number> <number>
.br .br
sets the maximum number of simultaneous connections to each service sets maximum number of simulationeous connections to each service
started after this command at the network level. Default is 100. started after this command on network level. Default is 100.
.br .br
To limit clients, use connlim instead. maxconn will silently ignore To limit clients, use connlim instead. maxconn will silently ignore
new connections, while connlim will report back to the client that new connections, while connlim will report back to the client that
@ -537,17 +507,17 @@ the connection limit has been reached.
.br .br
.B service .B service
.br .br
(deprecated). Indicates that 3proxy should behave as a Windows 95/98/NT/2000/XP (depricated). Indicates 3proxy to behave as Windows 95/98/NT/2000/XP
service; has no effect under Unix. Not required for 3proxy 0.6 and above. If service, no effect for Unix. Not required for 3proxy 0.6 and above. If
you upgraded from a previous version of 3proxy, use --remove and --install you upgraded from previous version of 3proxy use --remove and --install
to reinstall the service. to reinstall service.
.br .br
.B daemon .B daemon
.br .br
Should be specified to close the console. Do not use \'daemon\' with \'service\'. Should be specified to close console. Do not use \'daemon\' with \'service\'.
At least under FreeBSD, \'daemon\' should precede any proxy service At least under FreeBSD \'daemon\' should preceed any proxy service
and log commands to avoid socket problems. Always place it in the beginning and log commands to avoid sockets problem. Always place it in the beginning
of the configuration file. of the configuration file.
.br .br
@ -558,8 +528,8 @@ of the configuration file.
.br .br
none - no authentication or authorization required. none - no authentication or authorization required.
.br .br
Note: if auth is none, any IP-based limitation, redirection, etc. will not work. Note: is auth is none any ip based limitation, redirection, etc will not work.
This is the default authentication type This is default authentication type
.br .br
iponly - authentication by access control list with username ignored. iponly - authentication by access control list with username ignored.
Appropriate for most cases Appropriate for most cases
@ -568,11 +538,11 @@ This is the default authentication type
authorization by ACLs. Useful for e.g. SOCKSv4 proxy and icqpr (icqpr set UIN / authorization by ACLs. Useful for e.g. SOCKSv4 proxy and icqpr (icqpr set UIN /
AOL screen name as a username) AOL screen name as a username)
.br .br
dnsname - authentication by DNS hostname with authorization by ACLs. dnsname - authentication by DNS hostnname with authorization by ACLs.
The DNS hostname is resolved via a PTR (reverse) record and validated (the resolved DNS hostname is resolved via PTR (reverse) record and validated (resolved
name must resolve to the same IP address). It\'s recommended to use authcache by name must resolve to same IP address). It\'s recommended to use authcache by
IP for this authentication. ip for this authentication.
NB: there is no password check; the name may be spoofed. NB: there is no any password check, name may be spoofed.
.br .br
strong - username/password authentication required. It will work with strong - username/password authentication required. It will work with
SOCKSv5, FTP, POP3 and HTTP proxy. SOCKSv5, FTP, POP3 and HTTP proxy.
@ -584,23 +554,23 @@ SOCKSv5, FTP, POP3 and HTTP proxy.
Plugins may add additional authentication types. Plugins may add additional authentication types.
.br .br
It\'s possible to use multiple authentication types in the same command. E.g. It\'s possible to use few authentication types in the same commands. E.g.
.br .br
auth iponly strong auth iponly strong
.br .br
In this case, \'strong\' authentication will be used only if resource In this case \'strong\' authentication will be used only in case resource
access cannot be performed with \'iponly\' authentication, that is, a username is access can not be performed with \'iponly\' authentication, that is username is
required in the ACL. It\'s useful to protect access to some resources with required in ACL. It\'s usefull to protect access to some resources with
a password while allowing passwordless access to other resources, or to use password allowing passwordless access to another resources, or to use
IP-based authentication for dedicated laptops and request a username/password for IP-based authentication for dedicated laptops and request username/password for
shared ones. shared ones.
.br .br
.B authcache .B authcache
<cachtype> <cachtime> <cachtype> <cachtime>
.br .br
Cache authentication information for a given amount of time (cachetime) in seconds. Cache authentication information to given amount of time (cachetime) in seconds.
Cachetype is one of: Cahtype is one of:
.br .br
ip - after successful authentication all connections during caching time ip - after successful authentication all connections during caching time
from same IP are assigned to the same user, username is not requested. from same IP are assigned to the same user, username is not requested.
@ -628,19 +598,15 @@ Use auth type \'cache\' for cached authentication
.B deny .B deny
<userlist> <sourcelist> <targetlist> <targetportlist> <operationlist> <userlist> <sourcelist> <targetlist> <targetportlist> <operationlist>
<weekdayslist> <timeperiodslist> <weekdayslist> <timeperiodslist>
.br
.B redirect
<ip> <port> <userlist> <sourcelist> <targetlist> <targetportlist> <operationlist>
<weekdayslist> <timeperiodslist>
.br .br
Access control entries. All lists are comma-separated, no spaces are Access control entries. All lists are comma-separated, no spaces are
allowed. Usernames are case sensitive (if used with authtype nbname allowed. Usernames are case sensitive (if used with authtype nbname
username must be in uppercase). Source and target lists may contain username must be in uppercase). Source and target lists may contain
IP addresses (W.X.Y.Z), ranges A.B.C.D - W.X.Y.Z (since 0.8) or CIDRs (W.X.Y.Z/L). IP addresses (W.X.Y.Z), ranges A.B.C.D - W.X.Y.Z (since 0.8) or CIDRs (W.X.Y.Z/L).
Since 0.6, the targetlist may also contain host names, Since 0.6, targetlist may also contain host names,
instead of addresses. It\'s possible to use a wildmask in instead of addresses. It\'s possible to use wildmask in
the beginning and at the end of the hostname, e.g. *badsite.com or *badcontent*. the begginning and in the the end of hostname, e.g. *badsite.com or *badcontent*.
The hostname is only checked if a hostname is present in the request. Hostname is only checked if hostname presents in request.
Targetportlist may contain ports (X) or port ranges lists (X-Y). For any field * Targetportlist may contain ports (X) or port ranges lists (X-Y). For any field *
sign means ANY. If access list is empty it\'s assumed to be sign means ANY. If access list is empty it\'s assumed to be
.br .br
@ -691,14 +657,14 @@ to appropriate interface only or to use ip filters.
FTP_LIST FTP list request FTP_LIST FTP list request
.br .br
FTP_DATA FTP data connection. Note: FTP_DATA requires access to dynamic FTP_DATA FTP data connection. Note: FTP_DATA requires access to dynamic
non-privileged (1024-65535) ports on the remote side. non-ptivileged (1024-65535) ports on remote side.
.br .br
FTP matches any FTP/FTP Data request FTP matches any FTP/FTP Data request
.br .br
ADMIN access to administration interface ADMIN access to administration interface
.br .br
Weekdays are week day numbers or periods, 0 or 7 means Sunday, 1 is Monday, 1-5 means Monday through Friday. Weeksdays are week days numbers or periods, 0 or 7 means Sunday, 1 is Monday, 1-5 means Monday through Friday.
.br .br
Timeperiodlists is a list of time Timeperiodlists is a list of time
periods in HH:MM:SS-HH:MM:SS format. For example, 00:00:00-08:00:00,17:00:00-24:00:00 lists non-working hours. periods in HH:MM:SS-HH:MM:SS format. For example, 00:00:00-08:00:00,17:00:00-24:00:00 lists non-working hours.
@ -712,9 +678,9 @@ build proxy chain. Proxies may be grouped. Proxy inside the
group is selected randomly. If few groups are specified one proxy group is selected randomly. If few groups are specified one proxy
is randomly picked from each group and chain of proxies is created is randomly picked from each group and chain of proxies is created
(that is second proxy connected through first one and so on). (that is second proxy connected through first one and so on).
Weight is used to group proxies. Weight is a number between 1 and 1000. Weight is used to group proxies. Weigt is a number between 1 and 1000.
Weights are summed and proxies are grouped together until the weight of Weights are summed and proxies are grouped together untill weight of
the group is 1000. That is: group is 1000. That is:
.br .br
allow * allow *
.br .br
@ -742,7 +708,7 @@ with probability of 0.7) for outgoing web connections. Chains are only applied t
.br .br
type is one of: type is one of:
.br .br
extip does not actually redirect the request; it sets the external address for this request to <ip>. It can be chained with another parent type. It's useful to set the external IP based on ACL or make it random. 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
@ -766,8 +732,8 @@ if used with different service, it works as tcp redirection.
socks5+ parent is SOCKSv5 proxy with name resolution socks5+ parent is SOCKSv5 proxy with name resolution
.br .br
socks4b parent is SOCKS4b (broken SOCKSv4 implementation with shortened socks4b parent is SOCKS4b (broken SOCKSv4 implementation with shortened
server reply; I never saw this kind of server, but they say there are some). server reply. I never saw this kind ofservers byt they say there are).
Normally you should not use this option. Do not confuse this option with Normally you should not use this option. Do not mess this option with
SOCKSv4a (socks4+). SOCKSv4a (socks4+).
.br .br
socks5b parent is SOCKS5b (broken SOCKSv5 implementation with shortened socks5b parent is SOCKS5b (broken SOCKSv5 implementation with shortened
@ -793,18 +759,18 @@ locally redirects to
locally redirects to locally redirects to
.B pop3p .B pop3p
.B http .B http
locally redirects to locally redurects to
.B proxy .B proxy
.B admin .B admin
locally redirects to the admin -s service. locally redirects to admin -s service.
.br .br
Main purpose of local redirections is to have the requested resource Main purpose of local redirections is to have requested resource
(URL or POP3 username) logged and protocol-specific filters applied. (URL or POP3 username) logged and protocol-specific filters to be applied.
In case of local redirection, ACLs are reviewed twice: first, by the SOCKS proxy up to the \'parent\' In case of local redirection ACLs are revied twice: first, by SOCKS proxy up to \'parent\'
command and then by the gateway service the connection is command and then with gateway service connection is
redirected to (HTTP, FTP or POP3) after the \'parent\' command. It means redirected (HTTP, FTP or POP3) after \'parent\' command. It means,
an additional \'allow\' command is required for redirected requests, for additional \'allow\' command is required for redirected requests, for
example: example:
.br .br
allow * * * 80 allow * * * 80
@ -820,17 +786,11 @@ local HTTP proxy parses requests and allows only GET and POST requests.
.br .br
parent 1000 http 1.2.3.4 0 parent 1000 http 1.2.3.4 0
.br .br
Changes the external address for a given connection to 1.2.3.4 (equivalent to -e1.2.3.4) Changes external address for given connection to 1.2.3.4 (an equivalent to -e1.2.3.4)
.br .br
Optional username and password are used to authenticate on parent Optional username and password are used to authenticate on parent
proxy. Username of \'*\' means username must be supplied by user. proxy. Username of \'*\' means username must be supplied by user.
.br
.B parentretries
<number>
.br
Number of retries to connect to parent proxy. Default is 1.
.br .br
.B nolog .B nolog
@ -883,17 +843,15 @@ noforce allows to keep previously authenticated connections.
<userlist> <sourcelist> <targetlist> <targetportlist> <operationlist> <userlist> <sourcelist> <targetlist> <targetportlist> <operationlist>
<weekdayslist> <timeperiodslist> <weekdayslist> <timeperiodslist>
.br .br
bandlim sets a bandwidth limitation filter to <rate> bps (bits per second). bandlim sets bandwith limitation filter to <rate> bps (bits per second)
If you want to specify bytes per second, multiply your value by 8. If you want to specife bytes per second - multiply your value to 8.
bandlim rules act in the same manner as allow/deny rules, except for bandlim rules act in a same manner as allow/deny rules except
one thing: bandwidth limiting is applied to all services, not to some one thing: bandwidth limiting is applied to all services, not to some
specific service. specific service.
bandlimin and nobandlimin apply to incoming traffic bandlimin and nobandlimin applies to incoming traffic
.br bandlimout and nobandlimout applies to outgoing traffic
bandlimout and nobandlimout apply to outgoing traffic If tou want to ratelimit your clients with IPs 192.168.10.16/30 (4
.br addresses) to 57600 bps you have to specify 4 rules like
If you want to ratelimit your clients with IPs 192.168.10.16/30 (4
addresses) to 57600 bps, you have to specify 4 rules like
.br .br
bandlimin 57600 * 192.168.10.16 bandlimin 57600 * 192.168.10.16
.br .br
@ -903,12 +861,12 @@ addresses) to 57600 bps, you have to specify 4 rules like
.br .br
bandlimin 57600 * 192.168.10.19 bandlimin 57600 * 192.168.10.19
.br .br
and each of your clients will have a 56K channel. If you specify and every of you clients will have 56K channel. If you specify
.br .br
bandlimin 57600 * 192.168.10.16/30 bandlimin 57600 * 192.168.10.16/30
.br .br
you will have a 56K channel shared between all clients. you will have 56K channel shared between all clients.
If you want, for example, to limit all speed except access to POP3, you can use if you want, for example, to limit all speed ecept access to POP3 you can use
.br .br
nobandlimin * * * 110 nobandlimin * * * 110
.br .br
@ -933,17 +891,17 @@ connlim limits a number of parallel connections.
.br .br
connlim 20 0 * 127.0.0.1 connlim 20 0 * 127.0.0.1
.br .br
allows 20 simultaneous connections for 127.0.0.1. allows 20 simulationeous connections for 127.0.0.1.
.br .br
Like with bandlimin, if an individual limit is required per client, a separate Like with bandlimin, if individual limit is required per client, separate
rule must be added for every client. Like with nobandlimin, noconnlim adds an rule mustbe added for every client. Like with nobanlimin, noconnlim adds an
exception. exception.
.br .br
.B counter .B counter
<filename> <reporttype> <reportname> <filename> <reporttype> <repotname>
.br .br
.B countin .B countin
<number> <type> <limit> <userlist> <sourcelist> <targetlist> <targetportlist> <operationlist> <number> <type> <limit> <userlist> <sourcelist> <targetlist> <targetportlist> <operationlist>
@ -970,29 +928,29 @@ exception.
<weekdayslist> <timeperiodslist> <weekdayslist> <timeperiodslist>
.br .br
counter, countin, nocountin, countout, nocountout, countall, counter, countin, nocountin, countout, noucountout, countall,
nocountall commands are used to set a traffic limit nocountall commands are used to set traffic limit
in MB for a period of time (day, week or month). Filename is a path in MB for period of time (day, week or month). Filename is a path
to a special file where traffic information is permanently stored. to a special file where traffic information is permanently stored.
The number is the sequential number of the record in this file. If the number is 0, number is sequential number of record in this file. If number is 0
this counter is not preserved in the counter file (that is, this counter is not preserved in counter file (that is
if the proxy is restarted, all counters with 0 are flushed); otherwise, it if proxy restarted all counters with 0 are flushed) overwise it
should be a unique sequential number which points to the position of should be unique sequential number which points to position of
the counter within the file. the couter within the file.
Type specifies a type of counter. Type is one of: Type specifies a type of counter. Type is one of:
.br .br
H - counter is reset hourly H - counter is resetted hourly
.br .br
D - counter is reset daily D - counter is resetted daily
.br .br
W - counter is reset weekly W - counter is resetted weekly
.br .br
M - counter is reset monthly M - counter is resetted monthely
.br .br
reporttype/reportname may be used to generate traffic reports. reporttype/repotname may be used to generate traffic reports.
Reporttype is one of D, W, M, H (hourly) and reportname specifies the filename Reporttype is one of D,W,M,H(hourly) and repotname specifies filename
template for reports. The report is a text file with counter values in template for reports. Report is text file with counter values in
the format: format:
.br .br
<COUNTERNUMBER> <TRAF> <COUNTERNUMBER> <TRAF>
.br .br
@ -1011,8 +969,6 @@ username[:pwtype:password] ...
CR - password is crypt-style password CR - password is crypt-style password
.br .br
NT - password is NT password (in hex) NT - password is NT password (in hex)
.br
LM - password is LM password (in hex)
.br .br
example: example:
.br .br
@ -1020,13 +976,13 @@ username[:pwtype:password] ...
.br .br
users test3:NT:BD7DFBF29A93F93C63CB84790DA00E63 users test3:NT:BD7DFBF29A93F93C63CB84790DA00E63
.br .br
Note: double quotes are required because the password contains a $ sign. Note: double quotes are requiered because password contains $ sign.
.br .br
.B flush .B flush
.br .br
empty the active access list. The access list must be flushed every time you create a empty active access list. Access list must be flushed avery time you creating
new access list for a new service. For example: new access list for new service. For example:
.br .br
allow * allow *
.br .br
@ -1087,14 +1043,14 @@ for all threads.
.B stacksize .B stacksize
<value_to_add_to_default_stack_size> <value_to_add_to_default_stack_size>
.br .br
Change the default size for thread stacks. May be required in some situations, Change default size for threads stack. May be required in some situation,
e.g. with non-default plugins, or on some platforms (some FreeBSD versions e.g. with non-default plugins, on on some platforms (some FreeBSD version
may require adjusting the stack size due to an incorrectly defined value in system may require adjusting stack size due to invalid defined value in system
header files; this value is also often required to be changed for ODBC and header files, this value is also oftent reqruied to be changed for ODBC and
PAM support on Linux). If you experience 3proxy PAM support on Linux. If you experience 3proxy
crash on request processing, try to set some positive value. You may start with crash on request processing, try to set some positive value. You may start with
stacksize 65536 stacksize 65536
and then find the minimal value for the service to work. If you experience and then find the minimal value for service to work. If you experience
memory shortage, you can try to experiment with negative values. memory shortage, you can try to experiment with negative values.
.SH PLUGINS .SH PLUGINS
@ -1114,9 +1070,9 @@ as
.B filtermaxsize .B filtermaxsize
<max_size_of_data_to_filter> <max_size_of_data_to_filter>
.br .br
If Content-length (or another data length) is greater than the given value, no If Content-length (or another data length) is greater than given value, no
data filtering will be performed through filtering plugins to avoid data data filtering will be performed thorugh filtering plugins to avoid data
corruption and/or Content-Length changing. Default is 1MB (1048576). corruption and/or Content-Length chaging. Default is 1MB (1048576).
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to

View File

@ -19,7 +19,7 @@ servers.
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -28,17 +28,17 @@ Be silenT. Do not log start/stop/accept error records.
Never look for username authentication. Never look for username authentication.
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -h .B -h
Default destination. It's used if the target address is not specified by the user. Default destination. It's used if targed address is not specified by user.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 21. Port. Port proxy listens for incoming connections. Default is 21.
@ -48,7 +48,7 @@ Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
@ -56,24 +56,24 @@ syslog is used for logging.
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You can use any FTP client, regardless of FTP proxy support. For a client with You can use any FTP client, regardless of FTP proxy support. For client with
FTP proxy support, configure FTP proxy support configure
.I internal_ip .I internal_ip
and and
.IR port .IR port
in the FTP proxy parameters. in FTP proxy parameters.
For clients without FTP proxy support, use For clients without FTP proxy support use
.I internal_ip .I internal_ip
and and
.IR port .IR port
as the FTP server. The address of the real FTP server must be configured as a part of as FTP server. Address of real FTP server must be configured as a part of
the FTP username. The format for the username is FTP username. Format for username is
.IR username \fB@ server , .IR username \fB@ server ,
where where
.I server .I server
is the address of the FTP server and is address of FTP server and
.I username .I username
is the user\'s login on this FTP server. The login itself may contain an \'@\' sign. 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

View File

@ -19,7 +19,7 @@ servers.
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -28,27 +28,27 @@ Be silenT. Do not log start/stop/accept error records.
Never look for username authentication. Never look for username authentication.
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 110. Port. Port proxy listens for incoming connections. Default is 110.
.TP .TP
.B -h .B -h
Default destination. It's used if the target address is not specified by the user. Default destination. It's used if targed address is not specified by user.
.TP .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
@ -56,21 +56,21 @@ syslog is used for logging.
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You can use any MUA (Mail User Agent) with POP3 support. Set the client to use You can use any MUA (Mail User Agent) with POP3 support. Set client to use
.I internal_ip .I internal_ip
and and
.IR port .IR port
as a POP3 server. The address of the real POP3 server must be configured as a part of as a POP3 server. Address of real POP3 server must be configured as a part of
the POP3 username. The format for the username is POP3 username. Format for username is
.IR username \fB@ server , .IR username \fB@ server ,
where where
.I server .I server
is the address of the POP3 server and is address of POP3 server and
.I username .I username
is the user\'s login on this POP3 server. The login itself may contain an \'@\' sign. is user\'s login on this POP3 server. Login itself may contain \'@\' sign.
Only cleartext authentication is supported, because challenge-response Only cleartext authentication is supported, because challenge-response
authentication (APOP, CRAM-MD5, etc.) requires a challenge from the server before authentication (APOP, CRAM-MD5, etc) requires challenge from server before
we know which server to connect to. we know which server to connect.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.org .BR 3proxy@3proxy.org

View File

@ -17,7 +17,7 @@ is HTTP gateway service with HTTPS and FTP over HTTPS support.
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -26,14 +26,14 @@ Be silenT. Do not log start/stop/accept error records.
Never ask for username authentication Never ask for username authentication
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -a .B -a
Anonymous. Hide information about client. Anonymous. Hide information about client.
@ -57,12 +57,12 @@ syslog is used for logging.
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You should use a client with HTTP proxy support or configure a router to redirect You should use client with HTTP proxy support or configure router to redirect
HTTP traffic to the proxy (transparent proxy). Configure the client to connect to HTTP traffic to proxy (transparent proxy). Configure client to connect to
.I internal_ip .I internal_ip
and and
.IR port . .IR port .
HTTPS support allows you to use almost any TCP-based protocol. If you need to HTTPS support allows to use almost any TCP based protocol. If you need to
limit clients, use limit clients, use
.BR 3proxy (8) .BR 3proxy (8)
instead. instead.

View File

@ -19,7 +19,7 @@ servers.
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -28,27 +28,27 @@ Be silenT. Do not log start/stop/accept error records.
Never look for username authentication. Never look for username authentication.
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 25. Port. Port proxy listens for incoming connections. Default is 25.
.TP .TP
.B -h .B -h
Default destination. It's used if the target address is not specified by the user. Default destination. It's used if targed address is not specified by user.
.TP .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
@ -57,21 +57,21 @@ Increase or decrease stack size. You may want to try something like -S8192 if yo
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You can use any MUA (Mail User Agent) with SMTP authentication support. You can use any MUA (Mail User Agent) with SMTP authentication support.
Set the client to use Set client to use
.I internal_ip .I internal_ip
and and
.IR port .IR port
as an SMTP server. The address of the real SMTP server must be configured as a part of as a SMTP server. Address of real SMTP server must be configured as a part of
the SMTP username. The format for the username is SMTP username. Format for username is
.IR username \fB@ server , .IR username \fB@ server ,
where where
.I server .I server
is the address of the SMTP server and is address of SMTP server and
.I username .I username
is the user\'s login on this SMTP server. The login itself may contain an \'@\' sign. is user\'s login on this SMTP server. Login itself may contain \'@\' sign.
Only cleartext authentication is supported, because challenge-response Only cleartext authentication is supported, because challenge-response
authentication (CRAM-MD5, SPA, etc.) requires a challenge from the server before authentication (CRAM-MD5, SPA, etc) requires challenge from server before
we know which server to connect to. we know which server to connect.
.SH BUGS .SH BUGS
Report all bugs to Report all bugs to
.BR 3proxy@3proxy.org .BR 3proxy@3proxy.org

View File

@ -19,7 +19,7 @@ outgoing and reverse TCP connections and UDP portmapping.
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -28,19 +28,19 @@ Be silenT. Do not log start/stop/accept error records.
Never ask for username authentication Never ask for username authentication
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. External IP must be specified if you need incoming connections. from. External IP must be specified if you need incoming connections.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -N .B -N
External NAT address 3proxy reports to client for BIND and UDPASSOC. External NAT address 3proxy reports to client for BIND and UDPASSOC
By default, the external address is reported. It's only useful in the case By default external address is reported. It's only useful in the case
of IP-IP NAT (will not work for PAT). of IP-IP NAT (will not work for PAT)
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -p .B -p
Port. Port proxy listens for incoming connections. Default is 1080. Port. Port proxy listens for incoming connections. Default is 1080.
@ -58,7 +58,7 @@ syslog is used for logging.
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You should use a client with SOCKS support or use some socksification support You should use client with SOCKS support or use some socksification support
(for example (for example
.I SocksCAP .I SocksCAP
or or
@ -67,9 +67,9 @@ Configure client to use
.I internal_ip .I internal_ip
and and
.IR port . .IR port .
SOCKS allows you to use almost any application protocol without limitation. This SOCKS allows to use almost any application protocol without limitation. This
implementation also allows you to open privileged ports on the server (if socks has implementation also allows to open priviledged port on server (if socks has
sufficient privileges). If you need to control access, use sufficient privileges). If you need to control access use
.BR 3proxy (8) .BR 3proxy (8)
instead. instead.
.SH BUGS .SH BUGS

View File

@ -17,27 +17,27 @@ forwards connections from local to remote TCP port
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
@ -47,19 +47,19 @@ crashes.
.SH ARGUMENTS .SH ARGUMENTS
.TP .TP
.I local_port .I local_port
- port tcppm accepts connections on - port tcppm accepts connection
.TP .TP
.I remote_host .I remote_host
- IP address of the host the connection is forwarded to - IP address of the host connection is forwarded to
.TP .TP
.I remote_port .I remote_port
- remote port the connection is forwarded to - remote port connection is forwarded to
.SH CLIENTS .SH CLIENTS
Any TCP-based application can be used as a client. Use Any TCP based application can be used as a client. Use
.I internal_ip .I internal_ip
and and
.I local_port .I local_port
as the destination in the client application. The connection is forwarded to 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

View File

@ -11,15 +11,15 @@
.IB \fR[ -i internal_ip\fR] .IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR] .IB \fR[ -e external_ip\fR]
.SH DESCRIPTION .SH DESCRIPTION
.B tlspr .B proxy
is an SNI gateway service (destination host is taken from TLS handshake). The destination port must be specified via the -P option (or it may be detected with the Transparent plugin). 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 .SH OPTIONS
.TP .TP
.B -I .B -I
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
@ -28,14 +28,14 @@ Be silenT. Do not log start/stop/accept error records.
Never ask for username authentication Never ask for username authentication
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate connections External address. IP address of interface proxy should initiate connections
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts connections to. Internal address. IP address proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -a .B -a
Anonymous. Hide information about client. Anonymous. Hide information about client.
@ -47,17 +47,17 @@ Anonymous. Show fake information about client.
listening_port. Port proxy listens for incoming connections. Default is 1443. listening_port. Port proxy listens for incoming connections. Default is 1443.
.TP .TP
.B -P .B -P
destination_port. Port to establish outgoing connections. Required unless the Transparent plugin is used, because the TLS handshake does not contain port information. Default is 443. 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 .TP
.B -c .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 that the server sends a certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check that the server sends a certificate request and the client sends a certificate (not compatible with TLS 1.3) 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 .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
@ -65,12 +65,13 @@ syslog is used for logging.
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes. crashes.
.SH CLIENTS .SH CLIENTS
You should use a client with TLS support or configure a router to redirect You should use client with HTTP proxy support or configure router to redirect
TLS traffic to the proxy (transparent proxy). Configure the client to connect to HTTP traffic to proxy (transparent proxy). Configure client to connect to
.I internal_ip .I internal_ip
and and
.IR port . .IR port .
If you need to limit clients, use HTTPS support allows to use almost any TCP based protocol. If you need to
limit clients, use
.BR 3proxy (8) .BR 3proxy (8)
instead. instead.
.SH BUGS .SH BUGS

View File

@ -3,7 +3,7 @@
.B udppm .B udppm
\- UDP port mapper \- UDP port mapper
.SH SYNOPSIS .SH SYNOPSIS
.BR "udppm " [ -ds ] .BR "pop3p " [ -ds ]
.IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]] .IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]]
.IB \fR[ -i internal_ip\fR] .IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR] .IB \fR[ -e external_ip\fR]
@ -17,35 +17,35 @@ forwards datagrams from local to remote UDP port
Inetd mode. Standalone service only. Inetd mode. Standalone service only.
.TP .TP
.B -d .B -d
Daemonize. Detach service from console and run in the background. Daemonise. Detach service from console and run in the background.
.TP .TP
.B -t .B -t
Be silenT. Do not log start/stop/accept error records. Be silenT. Do not log start/stop/accept error records.
.TP .TP
.B -e .B -e
External address. IP address of the interface the proxy should initiate datagrams External address. IP address of interface proxy should initiate datagrams
from. from.
By default, the system will decide which address to use in accordance By default system will deside which address to use in accordance
with the routing table. with routing table.
.TP .TP
.B -i .B -i
Internal address. IP address the proxy accepts datagrams to. Internal address. IP address proxy accepts datagrams to.
By default, connections to any interface are accepted. It\'s usually unsafe. By default connection to any interface is accepted. It\'s usually unsafe.
.TP .TP
.B -l .B -l
Log. By default logging is to stdout. If Log. By default logging is to stdout. If
.I logfile .I logfile
is specified logging is to file. Under Unix, if is specified logging is to file. Under Unix, if
.RI \' @ \' .RI \' @ \'
precedes preceeds
.IR logfile , .IR logfile ,
syslog is used for logging. syslog is used for logging.
.TP .TP
.B -s .B -s
Single packet. By default, only one client can use the udppm service, but Single packet. By default only one client can use udppm service, but
if -s is specified, only one packet will be forwarded between client and server. if -s is specified only one packet will be forwarded between client and server.
This allows the service to be shared between multiple clients for single-packet services It allows to share service between multiple clients for single packet services
(for example, name lookups). (for example name lookups).
.TP .TP
.B -S .B -S
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
@ -53,7 +53,7 @@ crashes.
.SH ARGUMENTS .SH ARGUMENTS
.TP .TP
.I local_port .I local_port
- port udppm accepts datagrams on - port udppm accepts datagrams
.TP .TP
.I remote_host .I remote_host
- IP address of the host datagrams are forwarded to - IP address of the host datagrams are forwarded to
@ -61,11 +61,11 @@ crashes.
.I remote_port .I remote_port
- remote port datagrams are forwarded to - remote port datagrams are forwarded to
.SH CLIENTS .SH CLIENTS
Any UDP-based application can be used as a client. Use Any UDP based application can be used as a client. Use
.I internal_ip .I internal_ip
and and
.I local_port .I local_port
as the destination in the client application. All datagrams are forwarded to 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

View File

@ -0,0 +1,985 @@
#!/bin/bash
# 3proxy build and install script for Debian Linux
# Release 2.0 at 29.12.2016
# (с) Evgeniy Solovyev
# mail-to: eugen-soloviov@yandex.ru
ScriptPath=""
Src3proxyDirPath=""
ScriptName=""
ScriptFullName=""
SourceRoot=""
ResourcesData=""
ProxyVersion=""
LasestProxyVersion=""
LasestProxyVersionLink=""
UseSudo=0
PacketFiles=""
NeedSourceUpdate=0
main()
{
local msgNewVersion
local msgInsertYorN
VarsInit
LoadResources
CheckRunConditions
if [ $UseSudo == 1 ]
then
sudo bash "${0}"
exit $?
fi
CheckLocation
GetLasestVersionInfo
SourceDownloadOrUpdate
cd "${SourceRoot}"
Build3Proxy
BinInstall
ManInstall
CreateLogDir
CopyConfig
SetInit
Pack3proxyFiles
}
VarsInit()
{
cd `dirname $0`
ScriptPath="${PWD}"
ScriptName=`basename $0`
ScriptFullName="${ScriptPath}/${ScriptName}"
}
CheckLocation()
{
Src3proxyDirPath="${ScriptPath}"
if echo ${ScriptPath} | grep -e "/scripts$"
then
if [ -e "../src/version.h" ]
then
ProxyVersion=`cat "../src/version.h" | awk '/VERSION/ { gsub("\"", "\n"); print; exit }' | grep "3proxy"`
cd ../
SourceRoot="${PWD}"
cd ../
Src3proxyDirPath="${PWD}"
cd "${ScriptPath}"
fi
fi
}
GetLasestVersionInfo()
{
local Githublink
local msg
Githublink=`wget https://github.com/3proxy/3proxy/releases/latest -O /dev/stdout |
awk '/<a.+href=.+\.tar\.gz/ { gsub("\"", "\n"); print; exit }' |
grep -e ".tar.gz"`
if [ $? != 0 ]
then
msg=`GetResource "msgInternetConnectionError"`
echo -e "${msg}"
exit 255
fi
LasestProxyVersionLink="https://github.com${Githublink}"
LasestProxyVersion=`basename "${Githublink}" | awk 'gsub(".tar.gz", "") { print "3proxy-" $0 }'`
}
CheckRunConditions()
{
local UserName
local answer
local msg
local msgContinueWork
local msgInsertYorN
UserName=`whoami`
if [ $UID != 0 ]
then
if [ `CheckPacketInstall "sudo"` == 0 ]
then
msg=`GetResource "msgSudoNotInstalled"`
echo -e "${msg}"
exit 255
fi
UseSudo=1
if [ -z `cat /etc/group | grep -e "^sudo" | grep "${UserName}"` ]
then
msg=`GetResource "msgUserNotMemberOfSudoGroup"`
echo -e "${msg}"
exit 255
fi
if [ `env | grep -e ^http_proxy` != "" ]
then
msg=`GetResource "msgSystemUseProxy"`
echo -e "${msg}"
msgContinueWork=`GetResource "msgDoYouWishContinue"`
msgInsertYorN=`GetResource "msgPleaseInsertYorN"`
while true; do
read -s -n1 -p "${msgContinueWork}" answer
case $answer in
[Yy]* ) echo -ne "\n";break;;
[Nn]* ) echo -ne "\n"; sleep 0; exit 0;;
* ) echo -e "${msgInsertYorN}";;
esac
done
fi
fi
}
DonwnloadSource()
{
if [ ! -e "${Src3proxyDirPath}/${LasestProxyVersion}.tar.gz" ]
then
wget "${LasestProxyVersionLink}" -O "${Src3proxyDirPath}/${LasestProxyVersion}.tar.gz"
fi
ProxyVersion="${LasestProxyVersion}"
}
UnpackSource()
{
if [ ! -d "${Src3proxyDirPath}/${LasestProxyVersion}" ]
then
tar -xvf "${Src3proxyDirPath}/${LasestProxyVersion}.tar.gz" -C "${Src3proxyDirPath}"
fi
SourceRoot="${Src3proxyDirPath}/${LasestProxyVersion}"
}
SourceDownloadOrUpdate()
{
if [ -z "${ProxyVersion}" ]
then
NeedSourceUpdate=1
else
if [ "${ProxyVersion}" != "${LasestProxyVersion}" ]
then
msgNewVersion=`GetResource "msgNewVersion"`
msgInsertYorN=`GetResource "msgPleaseInsertYorN"`
echo -ne "\a"
while true; do
read -s -n1 -p "${msgNewVersion}" answer
case $answer in
[Yy]* ) echo -ne "\n"; NeedSourceUpdate=1; sleep 0; break;;
[Nn]* ) echo -ne "\n"; NeedSourceUpdate=0; sleep 0; break;;
* ) echo -e "${msgInsertYorN}";;
esac
done
fi
fi
if [ $NeedSourceUpdate == 1 ]
then
DonwnloadSource
UnpackSource
fi
}
Build3Proxy()
{
local msg
if [ `CheckPacketInstall "build-essential"` == 0 ]
then
apt-get -y install build-essential
fi
if [ `CheckPacketInstall "build-essential"` == 0 ]
then
msg=`GetResource "msgBuildEssentialNotInstalled"`
echo -e "${msg}"
exit 255
fi
make -f Makefile.Linux
}
BinInstall()
{
local binlist
local liblist
if [! -d bin]
then
mkdir bin
fi
cd bin
binlist=`ls -l --time-style="+%d.%m.%Y %H:%m" | awk '$1 ~ /x$/ && $1 ~ /^[^d]/ && $8 !~ /\.so$/ { print $8 }'`
for file in $binlist
do
cp -vf "${file}" /usr/bin
PacketFiles=`echo -e "${PacketFiles}\n/usr/bin/${file}"`
done
liblist=`ls -l --time-style="+%d.%m.%Y %H:%m" | awk '$1 ~ /x$/ && $1 ~ /^[^d]/ && $8 ~ /\.so$/ { print $8 }'`
for file in $liblist
do
cp -vf "${file}" /usr/lib
PacketFiles=`echo -e "${PacketFiles}\n/usr/lib/${file}"`
done
cd ..
}
ManInstall()
{
local man3list
local man8list
cd man
man3list=`ls -l --time-style="+%d.%m.%Y %H:%m" | awk '$8 ~ /\.3$/ { print $8 }'`
gzip -vfk $man3list
man3list=`echo "${man3list}" | awk '{ print $1 ".gz" }'`
for file in $man3list
do
mv -vf "${file}" /usr/share/man/man3
PacketFiles="${PacketFiles}\n/usr/share/man/man3/${file}"
done
man8list=`ls -l --time-style="+%d.%m.%Y %H:%m" | awk '$8 ~ /\.8$/ { print $8 }'`
gzip -vfk $man8list
man8list=`echo "${man8list}" | awk '{ print $1 ".gz" }'`
for file in $man8list
do
mv -vf "${file}" /usr/share/man/man8
PacketFiles=`echo -e "${PacketFiles}\n/usr/share/man/man8/${file}"`
done
cd ..
}
CreateLogDir()
{
local LogDir
LogDir="/var/log/3proxy"
if [ ! -d "${LogDir}" ]
then
mkdir "${LogDir}"
fi
chown nobody:nogroup "${LogDir}"
chmod 775 "${LogDir}"
PacketFiles="${PacketFiles}\n${LogDir}"
}
CopyConfig()
{
local ConfigDir
ConfigDir="/etc/3proxy"
if [ ! -d "${ConfigDir}" ]
then
mkdir "${ConfigDir}"
fi
LoadGlobalResource "ConfigFile" > "${ConfigDir}/3proxy.cfg"
PacketFiles=`echo -e "${PacketFiles}\n${ConfigDir}/3proxy.cfg"`
}
SetInit()
{
LoadGlobalResource "InitScript" > "/etc/init.d/3proxy"
chown root:root "/etc/init.d/3proxy"
chmod 755 "/etc/init.d/3proxy"
PacketFiles=`echo -e "${PacketFiles}\n/etc/init.d/3proxy"`
update-rc.d 3proxy defaults
}
Pack3proxyFiles()
{
local CPU_Arc
CPU_Arc=`uname -m`
cd ../
tar -czPpvf "${ProxyVersion}-${CPU_Arc}.tar.gz" $PacketFiles
}
LoadResources()
{
local StartRow
local EndRow
local LngLabel
local msgResourceErr="\aError! Script could not find resources!"
if env | grep -q 'LANG=ru_RU.UTF-8'
then
LngLabel="RU"
#LngLabel="EN"
else
LngLabel="EN"
fi
StartRow=`cat "${ScriptFullName}" | awk "/^#Resources_${LngLabel}/ { print NR; exit}"`
if [ -z "${StartRow}" ]
then
echo -e "${msgResourceErr}"
exit 255
fi
EndRow=`cat "${ScriptFullName}" | awk "NR > ${StartRow} && /^#Resources_${LngLabel}_end/ { print NR; exit}"`
if [ -z "${EndRow}" ]
then
echo -e "${msgResourceErr}"
exit 255
fi
ResourcesData=`cat "${ScriptFullName}" | awk -v StartRow="${StartRow}" -v EndRow="${EndRow}" 'NR > StartRow && NR < EndRow { print $0 }'`
}
# $1 - Name of Resource
GetResource()
{
local StartRow
local EndRow
local msgResourceErr="\aError! Script could not find resource \"${1}\"!"
StartRow=`echo "${ResourcesData}" | awk "/^#Resource=${1}/ { print NR; exit}"`
if [ -z "${StartRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
EndRow=`echo "${ResourcesData}" | awk "NR > ${StartRow} && /^#endResource=${1}/ { print NR; exit}"`
if [ -z "${EndRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
echo "${ResourcesData}" | awk -v StartRow="${StartRow}" -v EndRow="${EndRow}" 'NR > StartRow && NR < EndRow { print $0 }'
}
# $1 - Name of Resource
LoadGlobalResource()
{
local StartRow
local EndRow
local LngLabel
local msgResourceErr="\aError! Script could not find resource \"${1}\"!"
StartRow=`cat "${ScriptFullName}" | awk "/^#Resource=${1}/ { print NR; exit}"`
if [ -z "${StartRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
EndRow=`cat "${ScriptFullName}" | awk "NR > ${StartRow} && /^#endResource=${1}/ { print NR; exit}"`
if [ -z "${EndRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
cat "${ScriptFullName}" | awk -v StartRow="${StartRow}" -v EndRow="${EndRow}" 'NR > StartRow && NR < EndRow { print $0 }'
}
CheckPacketInstall()
{
if [ `dpkg -l ${1} 2>&1 | wc -l` -le 1 ]
then
echo 0
return
fi
if [ `dpkg -l ${1} | grep -e ^un | wc -l` == 1 ]
then
echo 0
return
fi
echo 1
}
main
exit 0
#Resources_EN
#Resource=msgSudoNotInstalled
\aThe script is running under the account a non-privileged user.
"Sudo" package is not installed in the system.
The script can not continue, as the execution of operations,
requiring rights "root" - is not possible!
Please run the script under the account "root",
or install and configure "sudo" package!
#endResource=msgSudoNotInstalled
#Resource=msgUserNotMemberOfSudoGroup
\aThe script is running under account a non-privileged user.
The account of the current user is not included in the "sudo" group!
The script can not continue, as the execution of operations,
requiring rights "root" - is not possible!
Please run the script under the account "root",
or configure "sudo" package!
#endResource=msgUserNotMemberOfSudoGroup
#Resource=msgSystemUseProxy
\aAttention! The operating system uses proxy-server.
For correctly work of package manager "apt"
in the file "/etc/sudoers" should be present line:
Defaults env_keep = "http_proxy https_proxy"
#endResource=msgSystemUseProxy
#Resource=msgDoYouWishContinue
Do you wish to the script continued executing? (y/n):
#endResource=msgDoYouWishContinue
#Resource=msgPleaseInsertYorN
\a\nPlease insert "y" or "n"!
#endResource=msgPleaseInsertYorN
#Resource=msgInternetConnectionError
\aError downloading "https://github.com/z3APA3A/3proxy/releases/latest"!
Please check the settings of the Internet connection.
#endResource=msgInternetConnectionError
#Resource=msgNewVersion
The new version of "3proxy" detected, do you want download it?
#endResource=msgNewVersion
#Resource=msgBuildEssentialNotInstalled
\aPackage "build-essential" was not installed.
The installation can not be continued!
#endResource=msgBuildEssentialNotInstalled
#Resources_EN_end
#Resources_RU
#Resource=msgSudoNotInstalled
\aСкрипт запущен под учётной записью обычного пользователя.
В системе не установлен пакет "sudo".
Скрипт не может продолжить работу, так как выполнение операций,
требующих прав "root" - не представляется возможным!
Пожалуйста, запустите скрипт под учётной записью "root",
либо установите и настройте пакет "sudo"!
#endResource=msgSudoNotInstalled
#Resource=msgUserNotMemberOfSudoGroup
\aСкрипт запущен под учётной записью обычного пользователя.
Учётная запись текущего пользователя не включена в группу "sudo"!
Скрипт не может продолжить работу, так как выполнение операций,
требующих прав "root" - не представляется возможным!
Пожалуйста, запустите скрипт под учётной записью "root",
либо настройте пакет "sudo"!
#endResource=msgUserNotMemberOfSudoGroup
#Resource=msgSystemUseProxy
\aВнимание! В системе используется прокси-сервер.
Чтобы менеджер пакетов "apt" работал корректно,
в файле "/etc/sudoers" должна присутствовать строка:
Defaults env_keep = "http_proxy https_proxy"
#endResource=msgSystemUseProxy
#Resource=msgDoYouWishContinue
Хотите чтобы скрипт дальше продолжил работу? (y/n):
#endResource=msgDoYouWishContinue
#Resource=msgPleaseInsertYorN
\a\nПожалуйста введите "y" или "n"!
#endResource=msgPleaseInsertYorN
#Resource=msgInternetConnectionError
\aОшибка закачки "https://github.com/z3APA3A/3proxy/releases/latest"!
Пожалуйста, проверьте настройки интернет соединения.
#endResource=msgInternetConnectionError
#Resource=msgNewVersion
Обнаружена новая версия "3proxy", скачать её (y/n)?
#endResource=msgNewVersion
#Resource=msgBuildEssentialNotInstalled
\aПакет "build-essential" не был установлен.
Дальнейшая установка не может быть продолжена!
#endResource=msgBuildEssentialNotInstalled
#Resources_RU_end
#Resource=ConfigFile
noconfig
# If in this file have line "noconfig", then 3proxy not to be runned!
# For usung this configuration file 3proxy you must to delete
# or comment out the line with "noconfig".
daemon
# Parameter "daemon" - means run 3proxy as daemon
pidfile /tmp/3proxy.pid
# PID file location
# This parameter must have the same value as
# the variable "PidFile" in the script "/etc/init.d/3proxy"
# Configuration file location
config /etc/3proxy/3proxy.cfg
internal 127.0.0.1
# Internal is address of interface proxy will listen for incoming requests
# 127.0.0.1 means only localhost will be able to use this proxy. This is
# address you should specify for clients as proxy IP.
# You MAY use 0.0.0.0 but you shouldn't, because it's a chance for you to
# have open proxy in your network in this case.
external 192.168.0.1
# External is address 3proxy uses for outgoing connections. 0.0.0.0 means any
# interface. Using 0.0.0.0 is not good because it allows to connect to 127.0.0.1
# DNS IP addresses
nserver 8.8.8.8
nserver 8.8.4.4
# DNS cache size
nscache 65536
# Timeouts settings
timeouts 1 5 30 60 180 1800 15 60
# log file location
log /var/log/3proxy/3proxy.log D
# log file format
logformat "L%C - %U [%d-%o-%Y %H:%M:%S %z] ""%T"" %E %I %O %N/%R:%r"
archiver gz /usr/bin/gzip %F
# If archiver specified log file will be compressed after closing.
# you should specify extension, path to archiver and command line, %A will be
# substituted with archive file name, %f - with original file name.
# Original file will not be removed, so archiver should care about it.
rotate 30
# We will keep last 30 log files
proxy -p3128
# Run http/https proxy on port 3128
auth none
# No authentication is requires
setgid 65534
setuid 65534
# Run 3proxy under account "nobody" with group "nobody"
#endResource=ConfigFile
#Resource=InitScript
#!/bin/sh
#
# 3proxy daemon control script
#
### BEGIN INIT INFO
# Provides: 3proxy
# Required-Start: $network $remote_fs $syslog
# Required-Stop: $network $remote_fs $syslog
# Should-Start: $named
# Should-Stop: $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: 3proxy HTTP Proxy
### END INIT INFO
ScriptName="3proxy"
ScriptFullName="/etc/init.d/3proxy"
ConfigFile="/etc/3proxy/3proxy.cfg"
LogDir="/var/log/3proxy"
PidFile="/tmp/3proxy.pid"
ResourcesData=""
main()
{
LoadResources
if [ ! -d "${LogDir}" ]
then
mkdir -p "${LogDir}";
fi
case "$1" in
start) Start ;;
stop) Stop ;;
restart) Stop; Start ;;
status) Status ;;
*) ShowHelp;;
esac
}
Start()
{
local msg
local ProxyPID
if [ ! -f "${ConfigFile}" ]
then
msg=`GetResource "msgConfigFileNotFound"`
printf "${msg}" "${ConfigFile}"
return
fi
if cat "${ConfigFile}" | grep -qe "^noconfig"
then
msg=`GetResource "msgNoconfigDetected"`
printf "${msg}" "${ConfigFile}"
return
fi
ProxyPID=`Get3proxyPID`
if [ ! -z "${ProxyPID}" ]
then
msg=`GetResource "msg3proxyAlreadyRunning"`
printf "${msg}" "${ProxyPID}"
return
fi
3proxy "${ConfigFile}"
sleep 1
ProxyPID=`Get3proxyPID`
if [ ! -f "${PidFile}" ]
then
msg=`GetResource "msg3proxyStartProblems"`
printf "${msg}"
return
fi
if [ `cat "${PidFile}"` != "${ProxyPID}" ]
then
msg=`GetResource "msg3proxyStartProblems"`
printf "${msg}"
return
fi
msg=`GetResource "msg3proxyStartedSuccessfully"`
printf "${msg}" `date +%d-%m-%Y" "%H:%M:%S` "${ProxyPID}"
}
Stop()
{
local msg
local ProxyPID
ProxyPID=`Get3proxyPID`
if [ -f "${PidFile}" ]
then
if [ `cat "${PidFile}"` = "${ProxyPID}" ]
then
kill -9 "${ProxyPID}"
rm -f "${PidFile}"
msg=`GetResource "msg3proxyStoppedSuccessfully"`
printf "${msg}" `date +%d-%m-%Y" "%H:%M:%S`
return
fi
fi
if [ -z "${ProxyPID}" ]
then
msg=`GetResource "msg3proxyProxyNotDetected"`
printf "${msg}"
return
fi
pkill -o 3proxy
msg=`GetResource "msg3proxyStoppedByKillall"`
printf "${msg}" `date +%d-%m-%Y" "%H:%M:%S` "${PidFile}"
}
Status()
{
local msg
local ProxyPID
if [ -f "${PidFile}" ]
then
msg=`GetResource "msgPidFileExists"`
printf "${msg}" "${PidFile}" `cat "${PidFile}"`
else
msg=`GetResource "msgPidFileNotExists"`
printf "${msg}" "${PidFile}"
fi
ProxyPID=`Get3proxyPID`
if [ ! -z "${ProxyPID}" ]
then
msg=`GetResource "msg3proxyProcessDetected"`
printf "${msg}"
ps -ef | awk '$8 ~ /^3proxy/ { print "User: " $1 "\tPID: " $2 }'
else
msg=`GetResource "msg3proxyProcessNotDetected"`
printf "${msg}"
fi
}
ShowHelp()
{
local msg
msg=`GetResource "msg3proxyHelp"`
printf "${msg}" "${ScriptFullName}" "${ScriptName}"
}
Get3proxyPID()
{
ps -ef | awk '$8 ~ /^3proxy/ { print $2; exit }'
}
LoadResources()
{
local StartRow
local EndRow
local LngLabel
local msgResourceErr="\aError! Script could not find resources!"
if env | grep -q 'LANG=ru_RU.UTF-8'
then
LngLabel="RU"
else
LngLabel="EN"
fi
StartRow=`cat "${ScriptFullName}" | awk "/^#Resources_${LngLabel}/ { print NR; exit}"`
if [ -z "${StartRow}" ]
then
echo -e "${msgResourceErr}"
exit 255
fi
EndRow=`cat "${ScriptFullName}" | awk "NR > ${StartRow} && /^#Resources_${LngLabel}_end/ { print NR; exit}"`
if [ -z "${EndRow}" ]
then
echo -e "${msgResourceErr}"
exit 255
fi
ResourcesData=`cat "${ScriptFullName}" | awk -v StartRow="${StartRow}" -v EndRow="${EndRow}" 'NR > StartRow && NR < EndRow { print $0 }'`
}
# $1 - Name of Resource
GetResource()
{
local StartRow
local EndRow
local msgResourceErr="\aError! Script could not find resource \"${1}\"!"
StartRow=`echo "${ResourcesData}" | awk "/^#Resource=${1}/ { print NR; exit}"`
if [ -z "${StartRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
EndRow=`echo "${ResourcesData}" | awk "NR > ${StartRow} && /^#endResource=${1}/ { print NR; exit}"`
if [ -z "${EndRow}" ]
then
echo -e "${msgResourceErr}" > /dev/stderr
exit 255
fi
echo "${ResourcesData}" | awk -v StartRow="${StartRow}" -v EndRow="${EndRow}" 'NR > StartRow && NR < EndRow { print $0 }'
}
main $@
exit 0;
#Resources_EN
#Resource=msg3proxyHelp
Usage:
\t%s {start|stop|restart}
or
\tservice %s {start|stop|restart|status}\\n
#endResource=msg3proxyHelp
#Resource=msgConfigFileNotFound
\a3proxy configuration file - "%s" is not found!\\n
#endResource=msgConfigFileNotFound
#Resource=msgNoconfigDetected
Parameter "noconfig" found in 3proxy configuration file -
"% s" !
To run 3proxy this parameter should be disabled.\\n
#endResource=msgNoconfigDetected
#Resource=msg3proxyAlreadyRunning
\a3proxy already running PID: %s\\n
#endResource=msg3proxyAlreadyRunning
#Resource=msg3proxyStartProblems
With the start of 3proxy, something is wrong!
Use: service 3proxy status\\n
#endResource=msg3proxyStartProblems
#Resource=msg3proxyStartedSuccessfully
[ %s %s ] 3proxy started successfully! PID: %s\\n
#endResource=msg3proxyStartedSuccessfully
#Resource=msg3proxyStoppedSuccessfully
[ %s %s ] 3proxy stopped successfully!\\n
#endResource=msg3proxyStoppedSuccessfully
#Resource=msg3proxyProxyNotDetected
Process "3proxy" is not detected!\\n
#endResource=msg3proxyProxyNotDetected
#Resource=msg3proxyStoppedByKillall
[ %s %s ] Command "pkill -o 3proxy" was executed,
because process number was not stored in "%s",
but in fact 3proxy was runned!\\n
#endResource=msg3proxyStoppedByKillall
#Resource=msgPidFileExists
File "%s" exists. It contains the PID: %s\\n
#endResource=msgPidFileExists
#Resource=msgPidFileNotExists
File "%s" not found, that is, PID 3proxy was not stored!\\n
#endResource=msgPidFileNotExists
#Resource=msg3proxyProcessDetected
Process 3proxy detected:\\n
#endResource=msg3proxyProcessDetected
#Resource=msg3proxyProcessNotDetected
Processes of 3proxy is not found!\\n
#endResource=msg3proxyProcessNotDetected
#Resources_EN_end
#Resources_RU
#Resource=msg3proxyHelp
Используйте:
\t%s {start|stop|restart}
или
\tservice %s {start|stop|restart|status}\\n
#endResource=msg3proxyHelp
#Resource=msgConfigFileNotFound
\aФайл конфигурации 3proxy - "%s", не найден!\\n
#endResource=msgConfigFileNotFound
#Resource=msgNoconfigDetected
\aОбнаружен параметр "noconfig" в файле конфигурации 3proxy -
"%s" !
Для запуска 3proxy этот параметр нужно отключить.\\n
#endResource=msgNoconfigDetected
#Resource=msg3proxyAlreadyRunning
\a3proxy уже запущен PID: %s\\n
#endResource=msg3proxyAlreadyRunning
#Resource=msg3proxyStartProblems
\aСо стартом 3proxy, что-то не так!
Используйте: service 3proxy status\\n
#endResource=msg3proxyStartProblems
#Resource=msg3proxyStartedSuccessfully
[ %s %s ] 3proxy успешно стартовал! PID: %s\\n
#endResource=msg3proxyStartedSuccessfully
#Resource=msg3proxyStoppedSuccessfully
[ %s %s ] 3proxy успешно остановлен!\\n
#endResource=msg3proxyStoppedSuccessfully
#Resource=msg3proxyProxyNotDetected
Процесс "3proxy" не обнаружен!\\n
#endResource=msg3proxyProxyNotDetected
#Resource=msg3proxyStoppedByKillall
[ %s %s ] Выполнена команда "pkill -o 3proxy",
т.к. номер процесса не записан в "%s",
но по факту 3proxy рабатал!\\n
#endResource=msg3proxyStoppedByKillall
#Resource=msgPidFileExists
Файл "%s" есть. Он содержит PID: %s\\n
#endResource=msgPidFileExists
#Resource=msgPidFileNotExists
Файл "%s" не найден, т.е. PID 3proxy не был сохранён!\\n
#endResource=msgPidFileNotExists
#Resource=msg3proxyProcessDetected
Обнаружен процесс 3proxy:\\n
#endResource=msg3proxyProcessDetected
#Resource=msg3proxyProcessNotDetected
Процессов 3proxy не обнаружено!\\n
#endResource=msg3proxyProcessNotDetected
#Resources_RU_end
#endResource=InitScript

View File

@ -1,4 +1,25 @@
#!/usr/local/bin/3proxy nscache 65536
nserver 8.8.8.8
nserver 8.8.4.4
#use standard syslog logging config /conf/3proxy.cfg
log @3proxy monitor /conf/3proxy.cfg
log /logs/3proxy-%y%m%d.log D
rotate 60
counter /count/3proxy.3cf
users $/conf/passwd
include /conf/counters
include /conf/bandlimiters
auth strong
deny * * 127.0.0.1
allow *
proxy -n
socks
flush
allow admin
admin -p8080

View File

@ -1,25 +0,0 @@
nscache 65536
nserver 8.8.8.8
nserver 8.8.4.4
config /conf/3proxy.cfg
monitor /conf/3proxy.cfg
log /logs/3proxy-%y%m%d.log D
rotate 60
counter /count/3proxy.3cf
users $/conf/passwd
include /conf/counters
include /conf/bandlimiters
auth strong
deny * * 127.0.0.1
allow *
proxy -n
socks
flush
allow admin
admin -p8080

View File

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

View File

@ -1,3 +0,0 @@
# tmpfiles.d configuration for 3proxy
# This creates the runtime directory for 3proxy
d /run/3proxy 0755 proxy proxy -

View File

@ -1,109 +0,0 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: 3proxy
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start/stop 3proxy
# Description: Start/stop 3proxy, tiny proxy server
### END INIT INFO
# chkconfig: 2345 20 80
# description: 3proxy tiny proxy server
DAEMON=@CMAKE_INSTALL_FULL_BINDIR@/3proxy
CONFIGFILE=/etc/3proxy/3proxy.cfg
PIDFILE=/var/run/3proxy/3proxy.pid
USER=proxy
GROUP=proxy
# Source function library if available
if [ -f /etc/init.d/functions ]; then
. /etc/init.d/functions
fi
case "$1" in
start)
echo -n "Starting 3Proxy: "
if [ ! -d /var/run/3proxy ]; then
mkdir -p /var/run/3proxy
chown $USER:$GROUP /var/run/3proxy 2>/dev/null || true
fi
if command -v start-stop-daemon >/dev/null 2>&1; then
# Debian/Ubuntu style
start-stop-daemon --start --quiet --pidfile $PIDFILE \
--chuid $USER:$GROUP --exec $DAEMON -- $CONFIGFILE
elif [ -f /etc/init.d/functions ]; then
# RedHat/CentOS style
daemon --user=$USER $DAEMON $CONFIGFILE
else
# Fallback
su -s /bin/sh $USER -c "$DAEMON $CONFIGFILE"
fi
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/3proxy
;;
stop)
echo -n "Stopping 3Proxy: "
if command -v start-stop-daemon >/dev/null 2>&1; then
# Debian/Ubuntu style
start-stop-daemon --stop --quiet --pidfile $PIDFILE
elif [ -f /etc/init.d/functions ]; then
# RedHat/CentOS style
killproc -p $PIDFILE $DAEMON
else
# Fallback
if [ -f $PIDFILE ]; then
kill `cat $PIDFILE` 2>/dev/null
else
killall 3proxy 2>/dev/null
fi
fi
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/3proxy
;;
restart|reload)
echo -n "Reloading 3Proxy: "
if [ -f $PIDFILE ]; then
kill -s USR1 `cat $PIDFILE` 2>/dev/null
RETVAL=$?
else
echo "PID file not found, cannot reload"
RETVAL=1
fi
echo
;;
status)
if command -v status >/dev/null 2>&1; then
status -p $PIDFILE $DAEMON
elif [ -f $PIDFILE ]; then
if kill -0 `cat $PIDFILE` 2>/dev/null; then
echo "3proxy is running (pid `cat $PIDFILE`)"
RETVAL=0
else
echo "3proxy is dead but pid file exists"
RETVAL=1
fi
else
echo "3proxy is not running"
RETVAL=3
fi
;;
*)
echo "Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit ${RETVAL:-0}

22
scripts/install-unix.sh Normal file
View File

@ -0,0 +1,22 @@
#!/bin/sh
cd ..
cp Makefile.unix Makefile
make
if [ ! -d /usr/local/etc/3proxy/bin ]; then mkdir -p /usr/local/etc/3proxy/bin/; fi
install bin/3proxy /usr/local/bin/3proxy
install bin/mycrypt /usr/local/bin/mycrypt
install scripts/rc.d/proxy.sh /usr/local/etc/rc.d/proxy.sh
install scripts/add3proxyuser.sh /usr/local/etc/3proxy/bin/
if [ -s /usr/local/etc/3proxy/3proxy.cfg ]; then
echo /usr/local/etc/3proxy/3proxy.cfg already exists
else
install scripts/3proxy.cfg /usr/local/etc/3proxy/
if [ ! -d /var/log/3proxy/ ]; then
mkdir /var/log/3proxy/
fi
touch /usr/local/etc/3proxy/passwd
touch /usr/local/etc/3proxy/counters
touch /usr/local/etc/3proxy/bandlimiters
echo Run /usr/local/etc/3proxy/bin/add3proxyuser.sh to add \'admin\' user
fi

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>org.3proxy.3proxy</string>
<key>ProgramArguments</key>
<array>
<string>@CMAKE_INSTALL_FULL_BINDIR@/3proxy</string>
<string>/etc/3proxy/3proxy.cfg</string>
</array>
<key>UserName</key>
<string>proxy</string>
<key>GroupName</key>
<string>proxy</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/var/log/3proxy.log</string>
<key>StandardErrorPath</key>
<string>/var/log/3proxy.log</string>
<key>SoftResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>65536</integer>
</dict>
<key>HardResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>65536</integer>
</dict>
</dict>
</plist>

View File

@ -1,45 +0,0 @@
#!/bin/sh
# Post-install script for 3proxy
# Creates proxy user and group if they don't exist
set -e
# Check if user already exists
if id proxy >/dev/null 2>&1; then
echo "User 'proxy' already exists"
exit 0
fi
echo "Creating proxy user and group..."
# Determine which commands are available
if command -v groupadd >/dev/null 2>&1; then
# Linux (shadow-utils)
groupadd -r proxy 2>/dev/null || true
useradd -r -g proxy -d /var/run/3proxy -s /usr/sbin/nologin proxy 2>/dev/null || true
elif command -v addgroup >/dev/null 2>&1; then
# Alpine Linux / BusyBox
addgroup -S proxy 2>/dev/null || true
adduser -S -D -H -G proxy -s /sbin/nologin proxy 2>/dev/null || true
elif command -v pw >/dev/null 2>&1; then
# FreeBSD
pw groupadd proxy 2>/dev/null || true
pw useradd proxy -g proxy -d /var/run/3proxy -s /usr/sbin/nologin 2>/dev/null || true
elif command -v dscl >/dev/null 2>&1; then
# macOS
dscl . create /Groups/proxy 2>/dev/null || true
dscl . create /Users/proxy 2>/dev/null || true
dscl . create /Users/proxy UserShell /usr/bin/false 2>/dev/null || true
dscl . create /Users/proxy NFSHomeDirectory /var/run/3proxy 2>/dev/null || true
else
echo "Warning: Could not create proxy user - no suitable user management tool found"
exit 0
fi
if id proxy >/dev/null 2>&1; then
echo "User 'proxy' created successfully"
else
echo "Warning: Failed to create user 'proxy'"
fi
exit 0

View File

@ -1,27 +0,0 @@
#!/bin/sh
# PROVIDE: 3proxy
# REQUIRE: LOGIN DAEMON
# KEYWORD: shutdown
. /etc/rc.subr
name="3proxy"
rcvar="3proxy_enable"
command="/usr/local/3proxy/bin/3proxy"
pidfile="/var/run/3proxy/${name}.pid"
command_args="${3proxy_config:-/usr/local/etc/3proxy/3proxy.cfg}"
required_files="${3proxy_config:-/usr/local/etc/3proxy/3proxy.cfg}"
start_precmd="3proxy_precmd"
3proxy_precmd()
{
if [ ! -d /var/run/3proxy ]; then
mkdir -p /var/run/3proxy
fi
}
load_rc_config $name
run_rc_command "$1"

View File

@ -1,29 +0,0 @@
#!/bin/sh
# PROVIDE: 3proxy
# REQUIRE: LOGIN DAEMON
# KEYWORD: shutdown
. /etc/rc.subr
name="3proxy"
rcvar="3proxy_enable"
command="@CMAKE_INSTALL_FULL_BINDIR@/3proxy"
pidfile="/var/run/3proxy/${name}.pid"
command_args="${3proxy_config:-/etc/3proxy/3proxy.cfg}"
required_files="${3proxy_config:-/etc/3proxy/3proxy.cfg}"
command_user="proxy:proxy"
start_precmd="3proxy_precmd"
3proxy_precmd()
{
if [ ! -d /var/run/3proxy ]; then
mkdir -p /var/run/3proxy
chown proxy:proxy /var/run/3proxy
fi
}
load_rc_config $name
run_rc_command "$1"

View File

@ -1248,7 +1248,7 @@ 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(NULL, sock,(struct sockaddr *)sinsr,SASIZE(sinsr),conf.timeouts[CONNECT_TO])) { if(connectwithpoll(NULL, sock,(struct sockaddr *)sinsr,SASIZE(sinsr),CONNECT_TO)) {
so._shutdown(so.state, sock, SHUT_RDWR); so._shutdown(so.state, sock, SHUT_RDWR);
so._closesocket(so.state, sock); so._closesocket(so.state, sock);
break; break;

View File

@ -608,7 +608,7 @@ int doconnect(struct clientparam * param){
} }
if(param->operation >= 256 || (param->operation & CONNECT)){ if(param->operation >= 256 || (param->operation & CONNECT)){
if(connectwithpoll(param, param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),conf.timeouts[CONNECT_TO])) { if(connectwithpoll(param, param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),CONNECT_TO)) {
return 13; return 13;
} }
} }

View File

@ -140,7 +140,7 @@ void * dnsprchild(struct clientparam* param) {
} }
param->sinsr = nservers[0].addr; param->sinsr = nservers[0].addr;
if(nservers[0].usetcp) { if(nservers[0].usetcp) {
if(connectwithpoll(param, param->remsock,(struct sockaddr *)&param->sinsr,SASIZE(&param->sinsr),conf.timeouts[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;

View File

@ -153,7 +153,7 @@ 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(param, clidatasock, (struct sockaddr *)&param->sincr, SASIZE(&param->sincr),conf.timeouts[CONNECT_TO])) { if(connectwithpoll(param, clidatasock, (struct sockaddr *)&param->sincr, SASIZE(&param->sincr),CONNECT_TO)) {
param->srv->so._closesocket(param->sostate, clidatasock); param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = INVALID_SOCKET; clidatasock = INVALID_SOCKET;
RETURN(826); RETURN(826);

View File

@ -187,6 +187,147 @@ SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config)
return dst_cert; return dst_cert;
} }
SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CONFIG *config, SSL_CERT *server_cert, char **errSSL)
{
int err = 0;
ssl_conn *conn;
unsigned long ul;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL ){
return NULL;
}
conn->ctx = NULL;
conn->ssl = SSL_new(config->srv_ctx);
if ( conn->ssl == NULL ) {
free(conn);
return NULL;
}
if(hostname && *hostname && config->client_verify){
X509_VERIFY_PARAM *param;
param = SSL_get0_param(conn->ssl);
X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname));
}
if(!SSL_set_fd(conn->ssl, s)){
ssl_conn_free(conn);
*errSSL = getSSLErr();
return NULL;
}
if(hostname && *hostname)SSL_set_tlsext_host_name(conn->ssl, hostname);
do {
struct pollfd fds[1] = {{}};
int sslerr;
err = SSL_connect(conn->ssl);
if (err != -1) break;
sslerr = SSL_get_error(conn->ssl, err);
if(sslerr == SSL_ERROR_WANT_READ){
fds[0].fd = s;
fds[0].events = POLLIN;
}
else if(sslerr == SSL_ERROR_WANT_WRITE){
fds[0].fd = s;
fds[0].events = POLLOUT;
}
else break;
if(sso._poll(sso.state, fds, 1, CONNECT_TO*1000) <= 0 || !(fds[0].revents & (POLLOUT|POLLIN))) break;
} while (err == -1);
if ( err != 1 ) {
*errSSL = getSSLErr();
ssl_conn_free(conn);
return NULL;
}
if(server_cert){
X509 *cert;
cert = SSL_get_peer_certificate(conn->ssl);
if(!cert) {
ssl_conn_free(conn);
return NULL;
}
*server_cert = cert;
}
return conn;
}
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CONFIG *config, X509 *server_cert, EVP_PKEY *server_key, char** errSSL){
int err = 0;
X509 *cert;
ssl_conn *conn;
unsigned long ul;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL )
return NULL;
conn->ctx = NULL;
conn->ssl = NULL;
if(!config->cli_ctx){
conn->ctx = ssl_cli_ctx(config, server_cert, server_key, errSSL);
if(!conn->ctx){
ssl_conn_free(conn);
return NULL;
}
}
conn->ssl = SSL_new(config->cli_ctx?config->cli_ctx : conn->ctx);
if ( conn->ssl == NULL ) {
*errSSL = getSSLErr();
if(conn->ctx)SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
SSL_set_fd(conn->ssl, s);
do {
struct pollfd fds[1] = {{}};
int sslerr;
err = SSL_accept(conn->ssl);
if (err != -1) break;
sslerr = SSL_get_error(conn->ssl, err);
if(sslerr == SSL_ERROR_WANT_READ){
fds[0].fd = s;
fds[0].events = POLLIN;
}
else if(sslerr == SSL_ERROR_WANT_WRITE){
fds[0].fd = s;
fds[0].events = POLLOUT;
}
else break;
if(sso._poll(sso.state, fds, 1, CONNECT_TO*1000) <= 0 || !(fds[0].revents & (POLLOUT|POLLIN))) break;
} while (err == -1);
if ( err != 1 ) {
*errSSL = getSSLErr();
ssl_conn_free(conn);
return NULL;
}
cert = SSL_get_peer_certificate(conn->ssl);
if ( cert != NULL )
X509_free(cert);
return conn;
}
int ssl_read(SSL_CONN connection, void * buf, int bufsize) int ssl_read(SSL_CONN connection, void * buf, int bufsize)
{ {
ssl_conn *conn = (ssl_conn *) connection; ssl_conn *conn = (ssl_conn *) connection;

View File

@ -33,6 +33,7 @@ static struct pluginlink * pl;
static struct alpn client_alpn_protos; static struct alpn client_alpn_protos;
static int ssl_loaded = 0; static int ssl_loaded = 0;
static int ssl_connect_timeout = 0;
static char *certcache = NULL; static char *certcache = NULL;
static char *srvcert = NULL; static char *srvcert = NULL;
static char *srvkey = NULL; static char *srvkey = NULL;
@ -63,8 +64,8 @@ static char * client_sni = NULL;
static int client_mode = 0; static int client_mode = 0;
typedef struct _ssl_conn { typedef struct _ssl_conn {
SSL_CTX *ctx; struct SSL_CTX *ctx;
SSL *ssl; struct SSL *ssl;
} ssl_conn; } ssl_conn;
@ -245,150 +246,19 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
return ret; return ret;
} }
SSL_CONN ssl_handshake_to_server(SOCKET s, char * hostname, SSL_CONFIG *config, SSL_CERT *server_cert, char **errSSL)
{
int err = 0;
ssl_conn *conn;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL ){
return NULL;
}
conn->ctx = NULL;
conn->ssl = SSL_new(config->srv_ctx);
if ( conn->ssl == NULL ) {
free(conn);
return NULL;
}
if(hostname && *hostname && config->client_verify){
X509_VERIFY_PARAM *param;
param = SSL_get0_param(conn->ssl);
X509_VERIFY_PARAM_set1_host(param, hostname, strlen(hostname));
}
if(!SSL_set_fd(conn->ssl, s)){
ssl_conn_free(conn);
*errSSL = getSSLErr();
return NULL;
}
if(hostname && *hostname)SSL_set_tlsext_host_name(conn->ssl, hostname);
do {
struct pollfd fds[1] = {{}};
int sslerr;
err = SSL_connect(conn->ssl);
if (err != -1) break;
sslerr = SSL_get_error(conn->ssl, err);
if(sslerr == SSL_ERROR_WANT_READ){
fds[0].fd = s;
fds[0].events = POLLIN;
}
else if(sslerr == SSL_ERROR_WANT_WRITE){
fds[0].fd = s;
fds[0].events = POLLOUT;
}
else break;
if(sso._poll(sso.state, fds, 1, pl->conf->timeouts[CONNECT_TO]*1000) <= 0 || !(fds[0].revents & (POLLOUT|POLLIN))) break;
} while (err == -1);
if ( err != 1 ) {
*errSSL = getSSLErr();
ssl_conn_free(conn);
return NULL;
}
if(server_cert){
X509 *cert;
cert = SSL_get_peer_certificate(conn->ssl);
if(!cert) {
ssl_conn_free(conn);
return NULL;
}
*server_cert = cert;
}
return conn;
}
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CONFIG *config, X509 *server_cert, EVP_PKEY *server_key, char** errSSL){
int err = 0;
X509 *cert;
ssl_conn *conn;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL )
return NULL;
conn->ctx = NULL;
conn->ssl = NULL;
if(!config->cli_ctx){
conn->ctx = ssl_cli_ctx(config, server_cert, server_key, errSSL);
if(!conn->ctx){
ssl_conn_free(conn);
return NULL;
}
}
conn->ssl = SSL_new(config->cli_ctx?config->cli_ctx : conn->ctx);
if ( conn->ssl == NULL ) {
*errSSL = getSSLErr();
if(conn->ctx)SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
SSL_set_fd(conn->ssl, s);
do {
struct pollfd fds[1] = {{}};
int sslerr;
err = SSL_accept(conn->ssl);
if (err != -1) break;
sslerr = SSL_get_error(conn->ssl, err);
if(sslerr == SSL_ERROR_WANT_READ){
fds[0].fd = s;
fds[0].events = POLLIN;
}
else if(sslerr == SSL_ERROR_WANT_WRITE){
fds[0].fd = s;
fds[0].events = POLLOUT;
}
else break;
if(sso._poll(sso.state, fds, 1, pl->conf->timeouts[CONNECT_TO]*1000) <= 0 || !(fds[0].revents & (POLLOUT|POLLIN))) break;
} while (err == -1);
if ( err != 1 ) {
*errSSL = getSSLErr();
ssl_conn_free(conn);
return NULL;
}
cert = SSL_get_peer_certificate(conn->ssl);
if ( cert != NULL )
X509_free(cert);
return conn;
}
#define PCONF (((struct SSLstate *)param->sostate)->config) #define PCONF (((struct SSLstate *)param->sostate)->config)
SSL_CONN dosrvcon(struct clientparam* param, SSL_CERT* cert){ SSL_CONN dosrvcon(struct clientparam* param, SSL_CERT* cert){
SSL_CONN ServerConn; SSL_CONN ServerConn;
char *errSSL=NULL; char *errSSL=NULL;
unsigned long ul;
if(ssl_connect_timeout){
ul = ((unsigned long)ssl_connect_timeout)*1000;
setsockopt(param->remsock, SOL_SOCKET, SO_RCVTIMEO, (char *)&ul, 4);
ul = ((unsigned long)ssl_connect_timeout)*1000;
setsockopt(param->remsock, SOL_SOCKET, SO_SNDTIMEO, (char *)&ul, 4);
}
ServerConn = ssl_handshake_to_server(param->remsock, (char *)param->hostname, PCONF, cert, &errSSL); ServerConn = ssl_handshake_to_server(param->remsock, (char *)param->hostname, PCONF, cert, &errSSL);
if ( ServerConn == NULL) { if ( ServerConn == NULL) {
if(ServerConn) ssl_conn_free(ServerConn); if(ServerConn) ssl_conn_free(ServerConn);
@ -1064,7 +934,9 @@ struct vermap{
}; };
int string_to_version(unsigned char *ver){ int string_to_version(unsigned char *ver){
struct vermap *v;
int i; int i;
int res;
for (i=0; versions[i].sver; i++){ for (i=0; versions[i].sver; i++){
if(!strcasecmp(versions[i].sver, (char *)ver)) return versions[i].iver; if(!strcasecmp(versions[i].sver, (char *)ver)) return versions[i].iver;
} }
@ -1175,6 +1047,8 @@ PLUGINAPI int PLUGINCALL ssl_plugin (struct pluginlink * pluginlink,
pl = pluginlink; pl = pluginlink;
ssl_connect_timeout = 0;
free(certcache); free(certcache);
certcache = NULL; certcache = NULL;
free(srvcert); free(srvcert);

View File

@ -9,4 +9,4 @@
#define MINOR3PROXY 5 #define MINOR3PROXY 5
#define SUBMINOR3PROXY 0 #define SUBMINOR3PROXY 0
#define RELEASE3PROXY "3proxy-0.9.5(" BUILDDATE ")\0" #define RELEASE3PROXY "3proxy-0.9.5(" BUILDDATE ")\0"
#define YEAR3PROXY "2026" #define YEAR3PROXY "2025"