Compare commits

..
42 Commits
Author SHA1 Message Date
Vladimir Dubrovin 1461dbaff0 dnspr: a name server's answer with no records relayed as it is (#1292)
C/C++ CI Linux / ubuntu-24.04-arm (push) Waiting to run
C/C++ CI Linux / ubuntu-latest (push) Waiting to run
C/C++ CI MacOS / macos-15 (push) Waiting to run
C/C++ CI Windows / windows-2022 (push) Waiting to run
C/C++ CI cmake / macos-15 (push) Waiting to run
C/C++ CI cmake / ubuntu-24.04-arm (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (push) Waiting to run
C/C++ CI cmake / windows-2022 (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
2026-11-26 15:45:43 +03:00
Vladimir Dubrovin 142f89cb4d tlspr: the SNI break split sent once the destination is connected 2026-11-26 15:39:33 +03:00
Vladimir Dubrovin ba796e3c71 portmap: the half-closed client's check says when it timed out
The whole answer behind a 32 K window, delivered to a client asleep
for a second, can take longer than the thirty seconds its socket
waited for on a busy runner — and the timeout, caught with every
other error, looked like an answer cut short, a bug where there was
none. The answer is four megabytes now, a quarter of it before, and
a timeout is told apart: it says so, with how much had arrived.
2026-11-24 19:09:20 +03:00
Vladimir Dubrovin 29058ddadc acl: the targetlist names the service by its addresses, too
One @ in the targetlist and one in the targetportlist delimit the lists
of destinations from the lists of the services the request came
through — the addresses it listens on in the first, its ports in the
second, both sides written as any other list:

 allow * * 192.168.1.0/24@10.0.0.1 443@1080,1090

matches only requests of the service on 10.0.0.1:1080 or :1090. A side
of the @ may be left out: @1080 names a port alone, *@10.0.0.1 an
address alone, and an @ with nothing after it is refused; an IPv6
address needs no brackets there, no port follows it.

The targetlist and the targetportlist are parsed by the same functions
now — ipadd() over scanipl() and portadd() — the chains of inline
allocations in make_ace() gone, and with them the mixed form of a
service named by an address and a port behind one @, which the two
fields make unnecessary.
2026-11-23 16:35:08 +03:00
Vladimir Dubrovin b423efcc33 acl: a rule names several services by repeating the entry
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
A comma ends an entry of a port list, so a rule names several
services by repeating it, one with each: *@1080,*@1090 names the
two, and @1080-1090 names a range of ports. A bare @1080,1090
leaves 1090 a destination port, which the man page warns of.
2026-11-21 17:10:40 +03:00
Vladimir Dubrovin a3e93aa23a acl: a rule's port names the service it came through by @, not by a slash
The part after the @ of a port in a rule names the service: by its
port, by the address it listens on, or by both, the address in
brackets when IPv6 —

 connlim 5 60 * * * @1080
 connlim 5 60 * * * @10.0.0.1:1080
 deny * * * @[::1]

A slash, as the delimiter of the first take, would have read as a
CIDR habit the day a service is named inside an address list, and
@ cannot appear in a port or an address. Digits alone are a port, a
dashed pair a port range, anything else an address with a port behind
a colon; an @ with nothing after it is refused. The destination port
before the @ is unchanged, and so is every rule without one.
2026-11-21 17:07:09 +03:00
Vladimir Dubrovin f951160329 acl: a rule's port may name the service it came through (#665)
A port in a rule's targetportlist may carry a service port after a
slash, X-Y/S, or, for any destination, */S: the rule matches only
requests that arrived through the service listening on the port S,
the port of its proxy -p or socks -p, whatever their destination. The
limiters are shared by all the services of a configuration, so this is
how a limit is given to the connections of one service alone:

 connlim 5 60 * * * */1080

denies the sixth concurrent connection of the service on port 1080.
The destination port and the service port are both ranges or single
ports, a slash with nothing after it is refused, and a rule without a
slash is what it always was.
2026-11-21 16:55:44 +03:00
Vladimir Dubrovin 51cbdb2fad mark: the rule's connections send with a mark (#846)
mark <number> extends the allow or deny rule above it, as nolog and
weight do: a connection the rule lets through carries the mark on its
outgoing sockets, towards the destination and towards the parents, so
policy routing and firewall rules can tell its packets apart (SO_MARK
of Linux, SO_USER_COOKIE of FreeBSD; on a system with no mark the
command sets it to nothing). The UDP sockets of a session towards a
destination are marked the same, the SOCKS UDP ASSOCIATE relays among
them, for the rule that let the session through is looked up for each
destination. A mark with no rule above it, or not a number, is refused.
2026-11-21 16:40:51 +03:00
Vladimir Dubrovin eec09dc4e9 port: a reservation kept only while the configuration in force has it
Once reserved, a port is dropped when a configuration comes in force
that neither reserves it anew nor has a service on it: after chroot no
reservation can be made again, only the usage of the socket a service
takes over keeps it. The reservation of the configuration before no
longer waits for its last client to let it go: the reload releases it
at once, the socket living on where a service of the new one has
claimed it, closing where none has.
2026-11-21 16:17:35 +03:00
Vladimir Dubrovin 17306f63f9 port: a listening socket reserved while the configuration is read
port tcp|udp [ip:]port [socket_options] opens, binds and listens at
the time the line is read, so a privileged port can be taken before
setuid and chroot drop the rights to open it: a service of the
configuration on the same address, of the same type, takes the socket
over when it starts, instead of binding one of its own, and a port no
service takes stays reserved until the configuration is left. A
reservation of the configuration before holds the port over a reload:
the new one shares its socket, each dropping its hold with its
configuration.

The socket is what the reservation made of it: the options which act
only before bind() cannot follow a service's wishes on a socket already
bound, so the service takes it as it is, its other options set on it.
The reservation is built from the same default address a service is, so
it matches in every byte a listener is compared by.
2026-11-21 16:12:40 +03:00
Vladimir Dubrovin 37dfb863fb radius: a server may be a name, and the port is taken as written (#1027)
The port was promised by the man page but never parsed: a server
address with a port was refused, and only the default 1812 could be
used. The address is parsed with parsehost() now, as nserver and
authnserver are, so a name is resolved when the configuration is read,
an IPv6 address may be written in brackets, and the port is the one
authentication is asked on, the accounting of the same server going to
the port after it. The man page says which name servers resolve the
name.
2026-11-21 14:42:59 +03:00
Vladimir Dubrovin c36e3f5b8e pcre: ,log in an action writes what the pattern matched (#794)
An action word of a pcre or pcre_rewrite rule may end with ,log: every
match writes a record of its own carrying the matched part of the
buffer, so a header can be watched without changing the request's fate
(dunno,log), or a refusal can leave its trace (deny,log). The matched
text reaches the log through %T, like any service text. The pcre
options apply to such a pattern as to any other, so it can be written
case-insensitively and by the line.
2026-11-21 14:21:16 +03:00
Vladimir Dubrovin 251a91d6b4 radius: the time of the request sent in it (#966)
Every request to a RADIUS server carries an Event-Timestamp (RFC 2869,
attribute 55), the time it was made in seconds since the epoch, so a
server no longer has to fish the time out of Acct-Session-Id.
2026-11-21 14:07:10 +03:00
Vladimir Dubrovin d0c840766f resolve: a name server answering with an error asks the next one (#735)
A reply with no answers and an error code - FORMERR, SERVFAIL, NOTIMP,
REFUSED - ended the resolution as if the name had no address, and the
servers after the one that answered were never asked, so one broken
server made every name it broke fail. Such an answer is passed over for
the next server now; a reply without data, and one that says the name is
not there, still end the search.
2026-11-21 13:58:55 +03:00
github-actions[bot] 719bbed0e2 Update version files for 1.1.0-pre2
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
Update version files / version (push) Canceled after 0s
2026-11-20 17:51:34 +00:00
Vladimir Dubrovin 246b21d9a1 Release as 1.1.0-pre2 2026-11-20 20:51:23 +03:00
Vladimir Dubrovin 8d0a715057 socks: a SOCKS4a request is not a connect to the null address
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
2026-11-18 21:37:29 +03:00
Vladimir Dubrovin 8cbf067f10 auth: the pre-authorization of a UDP ASSOCIATE is not cached 2026-11-18 20:32:11 +03:00
Vladimir Dubrovin 41a813811c socks: a UDP association is not relayed direct when its parent fails 2026-11-18 20:32:11 +03:00
Vladimir Dubrovin 9acfe35103 socks: a host name with control bytes or spaces is refused where it is read 2026-11-18 20:10:49 +03:00
Vladimir Dubrovin 6b9f6cb1e1 smtpp: a login name of a port alone names no destination 2026-11-18 20:10:10 +03:00
Vladimir Dubrovin f4dca5d462 tcptoudp, udptotcp: tunnels between TCP and UDP
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Datagrams on a TCP connection, each with a two byte length in network
order in front of it, which is how udptunnel (the rfc1036 one) and
ProxyGuard (eduVPN) put them there, the framing alone or after a
handshake: udptunnel's 32 bytes, or ProxyGuard's HTTP Upgrade for
UoTLV/1 answered with 101 Switching Protocols.

tcptoudp takes the connections, a UDP socket of its own to the target
for each, the handshake a client speaks recognised by its first bytes
and answered; a parent the ACL gives is a SOCKS5 UDP relay, as for
udppm. udptotcp takes the datagrams, each client a session of the
service's with a TCP connection of its own, connected as the service's
loop sees it writable (dnspr asks a name server over TCP the same way);
-m sends udptunnel's handshake to the target, -m2 ProxyGuard's, -m0
(the default) none, so both ends of either tool are stood in for.

The service names take two places of the string table, the default
configuration path moving two later (stringtable[27]).

Built by the Makefiles and CMake, with the standalone binaries, and
installed by them; a case of the test suite speaks all three handshakes.
2026-11-15 17:36:42 +03:00
Vladimir Dubrovin e18cd526bc proxy: credentials of an earlier request not inherited by the next
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-13 17:56:26 +03:00
Vladimir Dubrovin cc7274d2b5 httpsrv: credentials of an earlier request not inherited by the next 2026-11-13 17:15:55 +03:00
Vladimir Dubrovin 908449e360 tlspr: a ServerHello too short for the extensions length refused (#1286)
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-10 15:20:03 +03:00
Vladimir Dubrovin 5a2e9d27c3 httpsrv: a limit exceeded answered with 503, not ignored
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Authorization reports 10 when a limit of the service was exceeded,
which every other child answers with 503; the http server took it as
success and answered the request anyway. It now says 503 for itself,
after the body of the request is drained as any answer here does.
2026-11-08 14:39:54 +03:00
Vladimir Dubrovin c0eb7a65c6 httpsrv: a dot-dot segment of a path refused, with either separator
A path ending in a backslashed dot-dot, or carrying one in a form the
checks did not name, was taken as it stood. Any dot-dot segment is now
refused wherever it is and whichever separator carries it, and a path
ending in a bare dot of either kind.
2026-11-08 14:39:50 +03:00
Vladimir Dubrovin a7e5a8b48b pcre: a rule with no ACL a match data of its own, not itself
A rule whose ACL was missing was handed to the filters as the
connection's data, which they read as a match data block and freed:
a pointer into the configuration, dereferenced as another type and
given back to malloc. A rule without an ACL now skips the check and
goes on with a block of its own, and nothing a filter is given is
ever the rule itself.
2026-11-08 14:39:32 +03:00
Vladimir Dubrovin 83974cb7ca pcre: a match data of the connection's own, not of the rule's
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Every connection matching a pcre rule matched on the one match data
block of the rule, which pcre2_match() writes into: two connections
matching at the same time wrote the same block, a race that corrupts
memory and brings the process down after a while under load. A
connection that passes the rule's ACL now makes a match data block of
its own when it starts and frees it when it ends; the match context is
kept, as it is only read while matching.
2026-11-02 12:26:55 +03:00
Vladimir Dubrovin 38b62bd30b help: the features of the build listed, and the tests skip what they need
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
3proxy --help (and the usage message of a bad invocation) now lists
what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6,
UNIX sockets, the built-in HTTP server, transparency, ODBC and the
optional proxy services. The test runner reads the list before the
first case and the cases state the features they need with
t.skip_unless(), so a build without a feature skips its cases instead
of failing them; a binary too old to report anything skips the cases
with needs and runs the rest.
2026-10-30 14:18:05 +03:00
Vladimir Dubrovin c0d9914fb8 radius: the reply hashed with the secret, and taken only from the server asked
The reply digest copied the shared secret right after the received
bytes, so a reply of 4100 bytes with a secret of 17 or more characters
wrote up to 47 bytes of it past the reply buffer on the stack, before
the reply was authenticated. The digest is now taken over the reply
and the secret in place, with nothing written past the reply, and it
fails closed when the hash cannot be made. A reply is also taken only
from the address and port of the server the request went to, and only
when its identifier and length field match the request, all before any
digest work; the reply's sender was never checked before.
2026-10-30 13:47:12 +03:00
Vladimir Dubrovin b4416a8282 resolve: the PTR answer of dnsname walked inside its record data
The label walk of a DNS PTR answer ran to the end of the whole message,
not to the end of the record's data, and took a compression pointer for
a label length, so it could write past the end of the answer buffer on
the stack. An answer of 3841 bytes or more reached past the buffer
itself. A record that ended exactly at the end of the message was also
read one byte past it. The walk now stops at the end of the record's
data, a name that does not end there, or one that is compressed or
empty is not accepted, and the answer loop reads nothing past the
message.
2026-10-30 12:42:01 +03:00
Vladimir Dubrovin c3702866de StringsPlugin: a line's end cut off without reading past it
load_string() put a NUL where a line read from the file had its CR or
LF, and stepped over it as well as over the character after: past the
line's NUL terminator, into what was left in the buffer from longer
lines before, or past its end, writing NULs wherever it found CR or LF.
The line is cut at its first CR or LF instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e396da2696)
2026-10-28 12:02:37 +03:00
Vladimir DubrovinandClaude Opus 5.5 982536b389 Windows: an error set where socket errors are read
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
errno is WSAGetLastError() on Windows, but seterrno3() set the C
library's errno there: the EAGAIN of a TLS read or write wanting the
socket again was not seen as one, and the error left was whatever the
socket call before had set. seterrno3() sets the socket error now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:11:24 +03:00
Vladimir DubrovinandClaude Opus 5.5 bd4db18413 connlim: a connection's slot given back once
releaseparam() gave the connection limits' slot back without clearing
param->connlim: a second call, made on the event loops' end of a relayed
client, gave it back again, letting one more connection in for each
such end while another held its slot, or, with no connlimconf, followed
param->srv, cleared by the first call. It is cleared now.

A UDP session taken over by the new service on a reload gave its slot
back but kept connlim set, so the new service's authorization did not
count it, and its end gave it back a second time. It is counted again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:03:33 +03:00
Vladimir DubrovinandClaude Opus 5.5 e3ef7bb54a ftppr: the server's answer to USER reaches the client (#1284)
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
A server which logs in on USER alone (230, anonymous FTP often does) or
refuses it had its answer read but not handed back: ftplogin() gave the
length of what it read only for the answer to PASS. The client, told
331 by ftppr and waiting for the answer to its PASS, waited until the
time out. The answer to USER is the client's now when there is no PASS.

The test case logs in through ftppr to a server answering 230, a
multiline 230, 331 then 230, 530, and 331 then 530.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:39:25 +03:00
Vladimir DubrovinandClaude Opus 5.5 359ce5f8b4 -B: the TLS ClientHello split at the SNI, which -s is taken for splice
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
tlspr splits the ClientHello it passes in the middle of the server name
(SNI) when the service has s_option, set by -s. In builds with splice()
(Linux, the default there) -s is splice for every service but UDP ones,
admin and httpsrv, so the split was never made, and the How-To's SNI
break did nothing on Linux.

-B sets it whatever the build: for TCP services but admin and httpsrv,
where s_option has a meaning of its own. -s still does it where it is
not splice. The How-To, 3proxy.cfg(5) and tlspr(8) give -B.

Fixes #1283

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:52:39 +03:00
Vladimir DubrovinandClaude Opus 5.5 65213b172d Outgoing connections bound with IP_BIND_ADDRESS_NO_PORT
The socket of a connection to the destination is bound to the external
address before connect(), with port 0 unless a range is given. bind()
then takes an ephemeral port for the socket alone: not one in use
towards another destination, nor one of a connection still closing in
TIME_WAIT, which connect() would reuse. With many connections the range
runs out and bind() fails, result 12, or searches long for a port: 7 ms
a call was seen. The more connections are open at once, the sooner:
with event loops, serving more of them at once, the client of every
tenth connection or so of a saturated relay got its end at once.

Where the system has IP_BIND_ADDRESS_NO_PORT (Linux 4.2), the port is
left to connect() for a socket that is going to connect: chosen for
the pair with the destination, together with IP_LOCAL_PORT_RANGE when
a range is given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:34:14 +03:00
Vladimir Dubrovin 237a4499fa ftppr: the data socket towards the client from the socket functions
It was made with socket(): in the main network namespace rather than
the -ni one the client is reached in, and past the socket functions of
the service, which the rest of its life went through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7718ffa9f7)
2026-10-24 20:55:40 +03:00
Vladimir Dubrovin 2d06b4672a Connect back: a connection one client takes leaves the others waiting
The clients of a -R service all wait for the connection back on the
same listening socket, which was blocking: one connection woke them
all, one took it, and the others were left in accept() until the next,
past their time out and through a reload. The socket is non-blocking,
and an accept() which finds nothing, the connection taken by another
client or gone, is not one of the client's tries. nonblock() makes a
socket non-blocking, acceptagain() tells such an accept().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 126c7d00ec)
2026-10-24 20:55:40 +03:00
Vladimir DubrovinandClaude Opus 5.5 f4c5c723bd TLS: a read needing to write, or a write to read, waits for it
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
Update version files / version (push) Has been cancelled
A read TLS could do only once it wrote, or a write once it read, was an
error which ended the connection, as when TLS 1.3 answers a key update
while the socket cannot take more. Each TLS socket remembers what a read
and a write it could not do wait for, and the poll of the TLS layer
waits for it instead of what was asked: whatever that gets is the
caller's chance to try again, revents what it asked for, and its events
are given back as they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:15:05 +03:00
Vladimir Dubrovin 6ec8a4d1ac FilePlugin: socksend() given no clientparam, not a TLS state for one
socksend() takes the client's parameters, and was passed the socket
functions' state instead: NULL, the global functions used then, as
intended, but on a TLS connection the state of its TLS layer, which
socksend() read as a clientparam.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 718798c7fc)
2026-10-24 20:06:58 +03:00
94 changed files with 3063 additions and 220 deletions

No files matched your search

+2
View File
@@ -45,6 +45,8 @@ jobs:
cp -f doc/html/man8/tlspr.8.html wiki/tlspr.md
cp -f doc/html/man8/tcppm.8.html wiki/tcppm.md
cp -f doc/html/man8/udppm.8.html wiki/udppm.md
cp -f doc/html/man8/tcptoudp.8.html wiki/tcptoudp.md
cp -f doc/html/man8/udptotcp.8.html wiki/udptotcp.md
cp -f doc/html/man5/3proxy.cfg.5.html wiki/3proxy.cfg.md
cp -f doc/html/highload.html wiki/High-Load.md
cp -f doc/html/howtoe.html wiki/How-To.md
+2
View File
@@ -268,8 +268,10 @@ bin/3proxy_proxy
bin/3proxy_smtpp
bin/3proxy_socks
bin/3proxy_tcppm
bin/3proxy_tcptoudp
bin/3proxy_tlspr
bin/3proxy_udppm
bin/3proxy_udptotcp
build*/*
testcerts/
/.claude
+3 -1
View File
@@ -1,7 +1,8 @@
3proxy-1.1.0-pre1 Released October, 24 2026
3proxy-1.1.0-pre2 Released November, 20 2026
! Fix: a connect back service (-r) replaced by a configuration reload went on waiting up to 60 seconds for the go-ahead, holding a slot and a thread, and every reload left another connection in the queue of the far side (-R); a connection the -r side closed cost the -R side a client
! Fix: numbered traffic counters were reset by a configuration reload when no counter file was used
! Fix: a connection limit (connlim) could be exceeded: the end of a relayed client, or of a UDP session a new service took over on a reload, gave the connection's slot back a second time, letting one more connection in, and a taken-over UDP session was not counted by the new service's authorization at all
+ Configuration reload is atomic: a configuration with an error is refused and the one in force keeps running; a new service on the same address, network namespace and device takes over the old service's listening TCP or UDP socket, so no connection is refused or lost and UDP sessions go on; connections of the old services are re-authenticated against the new configuration (unless noforce), and closed if their service was removed or has no free slot; FTP commands and data connections are authorized by the rules in force
+ Services of one configuration on one address share its listening socket; the admin services page shows the clients and traffic of each listening socket, kept across reloads
+ Logs: each log is opened once and shared by every service using it, kept open over a reload while used and closed once unused; -l takes the same arguments as log; each log is written by a thread of its own from a queue, so a client never waits for a slow log (ODBC, RADIUS, a full disk); a record which finds the queue full is dropped, and dropped records and log failures are reported
@@ -14,6 +15,7 @@
+ -s:MIN,STREAK,SMALL tunes when the automatic splice() mode splices a direction and when it copies again
+ filtermaxsize 0 removes the limit
+ UDP services (udppm, dnspr) run in one thread each, with no thread per client, using epoll on Linux; dnspr waits for name servers without holding a thread
+ tcptoudp / udptotcp: tunnels between TCP and UDP: datagrams on a TCP connection, each with a two byte length in front of it, as udptunnel and ProxyGuard (eduVPN) put them, the framing alone or after their handshake; -m sends udptunnel's handshake to the target, -m2 ProxyGuard's, -m0 (the default) none; a parent the ACL gives tcptoudp is a SOCKS5 UDP relay, as for udppm
+ Connection buffers are allocated with the connection structure, together with the thread pool fewer allocations per connection
+ Build-time defaults: -DLOGQUEUEMIN, -DLOGQUEUEMAX, -DDEFAULT_POOLMAX, -DPOOLPERSERVICE, -DDEFAULT_POOLTIMEOUT, -DDEFAULT_MAXCHILD
- splice() in the automatic mode is the default on Linux (-s0 turns it off); a service with data filters, or beginning or ending TLS without kernel TLS both ways, does not splice
+3 -1
View File
@@ -1,7 +1,8 @@
3proxy-1.1.0-pre1 Вышел 24 Октября 2026
3proxy-1.1.0-pre2 Вышел 20 Ноября 2026
! Исправление: служба обратного соединения (-r), заменённая при перезагрузке конфигурации, продолжала до 60 секунд ждать разрешения, занимая место и поток, и каждая перезагрузка оставляла ещё одно соединение в очереди другой стороны (-R); соединение, закрытое стороной -r, стоило стороне -R клиента
! Исправление: нумерованные счётчики трафика сбрасывались при перезагрузке конфигурации, если файл счётчиков не использовался
! Исправление: лимит соединений (connlim) мог быть превышен: конец клиента, переданного через родителя, или UDP-сессии, принятой новой службой при перезагрузке, возвращал слот соединения второй раз, впуская лишнее соединение, а принятая UDP-сессия вовсе не учитывалась авторизацией новой службы
+ Перезагрузка конфигурации атомарна: конфигурация с ошибкой отвергается, и действующая продолжает работать; новая служба на том же адресе, в том же сетевом пространстве имён и на том же устройстве принимает слушающий сокет TCP или UDP старой службы, так что ни одно соединение не отвергается и не теряется, а сессии UDP продолжаются; соединения старых служб заново проходят аутентификацию по новой конфигурации (если не задан noforce) и закрываются, если их служба удалена или в ней нет свободного места; команды и соединения данных FTP авторизуются по действующим правилам
+ Службы одной конфигурации на одном адресе разделяют его слушающий сокет; страница служб admin показывает клиентов и трафик каждого слушающего сокета, сохраняемые при перезагрузке
+ Журналы: каждый журнал открывается один раз и используется всеми службами, которые в него пишут, остаётся открытым при перезагрузке, пока используется, и закрывается, когда больше не нужен; -l принимает те же аргументы, что и log; каждый журнал пишется отдельным потоком из очереди, так что клиент никогда не ждёт медленного журнала (ODBC, RADIUS, заполненный диск); запись, заставшая очередь заполненной, отбрасывается, об отброшенных записях и сбоях журнала сообщается
@@ -14,6 +15,7 @@
+ -s:MIN,STREAK,SMALL настраивает, когда автоматический режим splice() включает splice() для направления и когда возвращается к копированию
+ filtermaxsize 0 снимает ограничение
+ Службы UDP (udppm, dnspr) работают каждая в одном потоке, без потока на клиента, в Linux через epoll; dnspr ждёт ответа серверов имён, не занимая поток
+ tcptoudp / udptotcp: туннели между TCP и UDP: дейтаграммы в TCP-соединении, каждая с двухбайтовой длиной впереди, как их передают udptunnel и ProxyGuard (eduVPN), только обрамление или с их рукопожатием; -m отправляет цели рукопожатие udptunnel, -m2 — ProxyGuard, -m0 (по умолчанию) — ничего; родитель, назначенный ACL для tcptoudp, — SOCKS5 UDP relay, как для udppm
+ Буферы соединения выделяются вместе со структурой соединения; вместе с пулом потоков — меньше выделений памяти на соединение
+ Значения по умолчанию при сборке: -DLOGQUEUEMIN, -DLOGQUEUEMAX, -DDEFAULT_POOLMAX, -DPOOLPERSERVICE, -DDEFAULT_POOLTIMEOUT, -DDEFAULT_MAXCHILD
- Автоматический режим splice() включён по умолчанию в Linux (-s0 выключает его); служба с фильтрами данных, а также начинающая или завершающая TLS без TLS в ядре в обе стороны, splice() не использует
+18 -8
View File
@@ -94,10 +94,12 @@ option(3PROXY_BUILD_SMTPP "Build standalone smtpp binary" OFF)
option(3PROXY_BUILD_FTPPR "Build standalone ftppr binary" OFF)
option(3PROXY_BUILD_TCPPM "Build standalone tcppm binary" ON)
option(3PROXY_BUILD_UDPPM "Build standalone udppm binary" ON)
option(3PROXY_BUILD_TCPTOUDP "Build standalone tcptoudp binary" ON)
option(3PROXY_BUILD_UDPTOTCP "Build standalone udptotcp binary" ON)
option(3PROXY_BUILD_TLSPR "Build standalone tlspr binary" ON)
if(3PROXY_BUILD_NONE)
foreach(_M PROXY SOCKS POP3P IMAPP SMTPP FTPPR TCPPM UDPPM TLSPR)
foreach(_M PROXY SOCKS POP3P IMAPP SMTPP FTPPR TCPPM UDPPM TCPTOUDP UDPTOTCP TLSPR)
set(3PROXY_BUILD_${_M} OFF)
endforeach()
endif()
@@ -447,6 +449,7 @@ add_library(srv_modules OBJECT
src/smtpp.c
src/ftppr.c
src/tcppm.c
src/tcptoudp.c
src/tlspr.c
src/auto.c
src/socks.c
@@ -464,6 +467,12 @@ target_include_directories(srvudppm_obj PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
# UDP to TCP tunnel server module (without WITHMAIN)
add_library(srvudptotcp_obj OBJECT src/udptotcp.c)
target_include_directories(srvudptotcp_obj PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
# UDP socket relay (used by 3proxy, socks, udppm)
add_library(udpsockmap_obj OBJECT src/udpsockmap.c)
target_include_directories(udpsockmap_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
@@ -497,6 +506,7 @@ add_executable(3proxy
${3PROXY_CORE_SOURCES}
$<TARGET_OBJECTS:srv_modules>
$<TARGET_OBJECTS:srvudppm_obj>
$<TARGET_OBJECTS:srvudptotcp_obj>
$<TARGET_OBJECTS:mainfunc>
$<TARGET_OBJECTS:common_obj>
$<TARGET_OBJECTS:udpsockmap_obj>
@@ -689,7 +699,7 @@ else()
endif()
# Build standalone proxy executables
foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tcptoudp udptotcp tlspr)
string(TOUPPER "${PROXY_NAME}" _MODULE_OPT)
if(NOT 3PROXY_BUILD_${_MODULE_OPT})
continue()
@@ -728,8 +738,8 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
target_compile_definitions(${PROXY_NAME} PRIVATE WITHMAIN)
# each takes the main loop of its kind only: udppm UDP, the others TCP
if(PROXY_NAME STREQUAL "udppm")
# each takes the main loop of its kind only: udppm and udptotcp UDP, the others TCP
if(PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "udptotcp")
target_compile_definitions(${PROXY_NAME} PRIVATE NOTCPMAIN)
else()
target_compile_definitions(${PROXY_NAME} PRIVATE NOUDPMAIN)
@@ -743,7 +753,7 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
# port mappers take port, host and port as arguments, the others options
# only; one of the two is defined, as in src/Makefile.inc
if(PROXY_NAME STREQUAL "tcppm" OR PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "tlspr")
if(PROXY_NAME STREQUAL "tcppm" OR PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "tcptoudp" OR PROXY_NAME STREQUAL "udptotcp" OR PROXY_NAME STREQUAL "tlspr")
target_compile_definitions(${PROXY_NAME} PRIVATE PORTMAP)
else()
target_compile_definitions(${PROXY_NAME} PRIVATE NOPORTMAP)
@@ -757,11 +767,11 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
target_sources(${PROXY_NAME} PRIVATE $<TARGET_OBJECTS:base64_obj>)
endif()
if(PROXY_NAME STREQUAL "udppm")
if(PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "udptotcp")
target_sources(${PROXY_NAME} PRIVATE src/hash.c)
endif()
if(PROXY_NAME STREQUAL "socks" OR PROXY_NAME STREQUAL "udppm")
if(PROXY_NAME STREQUAL "socks" OR PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "tcptoudp")
target_sources(${PROXY_NAME} PRIVATE src/udpsockmap.c)
endif()
endforeach()
@@ -797,7 +807,7 @@ install(TARGETS 3proxy 3proxy_crypt
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tcptoudp udptotcp tlspr)
string(TOUPPER "${PROXY_NAME}" _MODULE_OPT)
if(3PROXY_BUILD_${_MODULE_OPT})
install(TARGETS ${PROXY_NAME}
+1 -1
View File
@@ -1 +1 @@
1.1.0-pre1
1.1.0-pre2
+2 -2
View File
@@ -117,7 +117,7 @@ install: all
if [ ! -d "$(DESTDIR)$(BINPREFIX)" ]; then mkdir -p $(DESTDIR)$(BINPREFIX)/; fi
install bin/3proxy $(DESTDIR)$(BINPREFIX)/3proxy
install bin/$(CRYPT_PREFIX)crypt $(DESTDIR)$(BINPREFIX)/$(CRYPT_PREFIX)crypt
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr; do \
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tcptoudp udptotcp tlspr; do \
if [ -f bin/$(PREFIX)$$f ]; then install bin/$(PREFIX)$$f $(DESTDIR)$(BINPREFIX)/$(PREFIX)$$f; fi; \
done
install -d $(DESTDIR)$(prefix)/etc/3proxy/conf
@@ -134,7 +134,7 @@ install: all
touch $(DESTDIR)$(prefix)/etc/3proxy/conf/bandlimiters
install -d $(DESTDIR)$(MANDIR)/man8
install -m 644 man/3proxy.8 $(DESTDIR)$(MANDIR)/man8/3proxy.8
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr; do \
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tcptoudp udptotcp tlspr; do \
if [ -f man/$$f.8 ] && [ -f bin/$(PREFIX)$$f ]; then install -m 644 man/$$f.8 $(DESTDIR)$(MANDIR)/man8/$(PREFIX)$$f.8; fi; \
done
install -m 644 man/3proxy_crypt.8 $(DESTDIR)$(MANDIR)/man8/$(CRYPT_PREFIX)crypt.8
+4 -2
View File
@@ -126,8 +126,10 @@ INSTALL_OBJS = bin/3proxy \
bin/$(PREFIX)proxy \
bin/$(PREFIX)socks \
bin/$(PREFIX)tcppm \
bin/$(PREFIX)tcptoudp \
bin/$(PREFIX)tlspr \
bin/$(PREFIX)udppm
bin/$(PREFIX)udppm \
bin/$(PREFIX)udptotcp
# the mail proxies and ftppr are only there when they were built
ifeq ($(MAILPROXY),true)
INSTALL_OBJS += bin/$(PREFIX)imapp bin/$(PREFIX)pop3p bin/$(PREFIX)smtpp
@@ -191,7 +193,7 @@ install-man:
$(INSTALL_BIN) -d $(MANDIR8)
$(INSTALL_DATA) man/3proxy.cfg.5 $(MANDIR5)
$(INSTALL_DATA) man/3proxy.8 $(MANDIR8)
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr; do \
for f in proxy socks pop3p imapp smtpp ftppr tcppm udppm tcptoudp udptotcp tlspr; do \
if [ -f man/$$f.8 ] && [ -f bin/$(PREFIX)$$f ]; then $(INSTALL_DATA) man/$$f.8 $(MANDIR8)/$(PREFIX)$$f.8; fi; \
done
$(INSTALL_DATA) man/3proxy_crypt.8 $(MANDIR8)/$(CRYPT_PREFIX)crypt.8
+6
View File
@@ -1,3 +1,9 @@
3proxy (1.1.0-pre2-1) buster; urgency=medium
*3proxy 1.1.0-pre2 initial build
-- z3APA3A <3apa3a@3proxy.org> Fri, 20 Nov 2026 17:51:34 +0000
3proxy (1.1.0-pre1-1) buster; urgency=medium
*3proxy 1.1.0-pre1 initial build
+11
View File
@@ -0,0 +1,11 @@
! Fix: RADIUS authentication: the reply digest copied the shared secret right after the received bytes, so a reply of 4100 bytes with a secret of 17 or more characters wrote up to 47 bytes of it past the reply buffer on the stack, before the reply was authenticated; the digest is hashed over the reply and the secret in place now, with nothing written past the reply, and a reply is taken only from the address and port of the server the request went to, with the request's identifier and length, which was never checked before
! Fix: the PTR answer of a name server could write past the answer buffer on the stack: the label walk ran to the end of the whole message instead of the end of the record's data and could take a compression pointer for a label length (an answer of 3841 bytes or more reached past the buffer itself); the walk now stops at the end of the record's data, and a compressed, empty or truncated name is not accepted
! Fix: every connection matching a pcre: (or regex:) rule matched on the one match data block of the rule, which pcre2_match() writes into: two connections matching at the same time raced and corrupted memory, bringing the process down under load; a connection now makes a match data block of its own
! Fix: TLS: a read which could only be done once a write was, or a write once a read was (a TLS 1.3 key update answered while the socket cannot take more, for example), ended the connection with an error; each TLS socket remembers now what its pending read and write wait for, and the poll of the TLS layer waits for that
! Fix: Windows: a TLS read or write which wanted the socket again was not seen as one and dropped the connection with an unrelated error: the C library's errno was set where the socket error is read
! Fix: a client of a connect back (-R) service stayed in accept() for the connection another client of the same service took, until the next one came, past its time out and through a configuration reload; the connect back socket is non-blocking now, and an accept() with nothing to take does not count as one of the client's tries
! Fix: ftppr: the answer of a server which logs in on USER alone (230, as anonymous FTP often does) or refuses the login was read but never handed to the client, which was left waiting for the answer to its PASS until the time out (#1284)
! Fix: plugins: StringsPlugin, cutting a string table line at its end, wrote NULs past the line, into what the buffer kept of longer lines read before or past its end; FilePlugin passed the TLS state of the connection where the client's parameters were expected, so sending a string table over a TLS connection read a TLS state as a clientparam
+ -B (for TCP services) splits the TLS ClientHello passed through tlspr in the middle of the server name (SNI), so DPI systems which do not reassemble it do not see the host name; TCP_NODELAY, set by default, must not be turned off, or the kernel may join the segments again; -s keeps the same effect where -s is not splice (#1283)
+ 3proxy --help (and the usage message of a bad invocation) lists what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6, UNIX sockets, the built-in HTTP server, transparency, ODBC and the optional proxy services
+ An outgoing connection bound to an external address is bound with IP_BIND_ADDRESS_NO_PORT on Linux 4.2 and later: the port is chosen by connect() for the pair with the destination, so ports in use towards other destinations or closing in TIME_WAIT do not run the ephemeral range out; bind() no longer failed with result 12 or searched long for a port under many connections
+2
View File
@@ -1,5 +1,6 @@
! Fix: a connect back service (-r) replaced by a configuration reload went on waiting up to 60 seconds for the go-ahead, holding a slot and a thread, and every reload left another connection in the queue of the far side (-R); a connection the -r side closed cost the -R side a client
! Fix: numbered traffic counters were reset by a configuration reload when no counter file was used
! Fix: a connection limit (connlim) could be exceeded: the end of a relayed client, or of a UDP session a new service took over on a reload, gave the connection's slot back a second time, letting one more connection in, and a taken-over UDP session was not counted by the new service's authorization at all
+ Configuration reload is atomic: a configuration with an error is refused and the one in force keeps running; a new service on the same address, network namespace and device takes over the old service's listening TCP or UDP socket, so no connection is refused or lost and UDP sessions go on; connections of the old services are re-authenticated against the new configuration (unless noforce), and closed if their service was removed or has no free slot; FTP commands and data connections are authorized by the rules in force
+ Services of one configuration on one address share its listening socket; the admin services page shows the clients and traffic of each listening socket, kept across reloads
+ Logs: each log is opened once and shared by every service using it, kept open over a reload while used and closed once unused; -l takes the same arguments as log; each log is written by a thread of its own from a queue, so a client never waits for a slow log (ODBC, RADIUS, a full disk); a record which finds the queue full is dropped, and dropped records and log failures are reported
@@ -12,6 +13,7 @@
+ -s:MIN,STREAK,SMALL tunes when the automatic splice() mode splices a direction and when it copies again
+ filtermaxsize 0 removes the limit
+ UDP services (udppm, dnspr) run in one thread each, with no thread per client, using epoll on Linux; dnspr waits for name servers without holding a thread
+ tcptoudp / udptotcp: tunnels between TCP and UDP: datagrams on a TCP connection, each with a two byte length in front of it, as udptunnel and ProxyGuard (eduVPN) put them, the framing alone or after their handshake; -m sends udptunnel's handshake to the target, -m2 ProxyGuard's, -m0 (the default) none; a parent the ACL gives tcptoudp is a SOCKS5 UDP relay, as for udppm
+ Connection buffers are allocated with the connection structure, together with the thread pool fewer allocations per connection
+ Build-time defaults: -DLOGQUEUEMIN, -DLOGQUEUEMAX, -DDEFAULT_POOLMAX, -DPOOLPERSERVICE, -DDEFAULT_POOLTIMEOUT, -DDEFAULT_MAXCHILD
- splice() in the automatic mode is the default on Linux (-s0 turns it off); a service with data filters, or beginning or ending TLS without kernel TLS both ways, does not splice
+3 -3
View File
@@ -648,16 +648,16 @@ see <a href="#DNSPR">How to set up a DNS proxy (dnspr)</a>.
<br>tlspr can be used as a parent with the "tls" type to implement SNI splitting for DPI bypass (similar to NoDPI/GoodByeDPI).
The client sends the first part of the TLS ClientHello, tlspr splits it at the SNI extension and sends it in two TCP packets,
which can bypass some DPI systems that look for blocked hostnames in TLS handshakes.
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-s</code> option on the listening service with TCP_NODELAY:
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-B</code> option on the listening service:
</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
proxy -B -i127.0.0.1 -p1443
</pre>
<p>
TCP_NODELAY is required to prevent the kernel from merging the split packets.
TCP_NODELAY, set by default, is required to prevent the kernel from merging the split packets: do not turn it off with -ocTCP_NODELAY=0 or -osTCP_NODELAY=0.
</p>
<p>
<b>Configuration examples:</b>
+3 -3
View File
@@ -656,16 +656,16 @@ iptables -t nat -A PREROUTING -p tcp -m multiport --dports 443,993,465 -j REDIRE
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI).
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами,
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-s</code> на слушающем сервисе с TCP_NODELAY:
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-B</code> на слушающем сервисе:
</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
proxy -B -i127.0.0.1 -p1443
</pre>
<p>
TCP_NODELAY необходим, чтобы ядро не объединяло разделенные пакеты.
TCP_NODELAY, установленный по умолчанию, необходим, чтобы ядро не объединяло разделенные пакеты: не отключайте его опциями -ocTCP_NODELAY=0 или -osTCP_NODELAY=0.
</p>
<p>
<b>Примеры конфигурации:</b>
+3 -1
View File
@@ -32,6 +32,8 @@ from the configuration file like an independent service
.BR imapp (8)
.BR tcppm (8)
.BR udppm (8)
.BR tcptoudp (8)
.BR udptotcp (8)
.BR ftppr (8)
.BR dnspr
but
@@ -161,7 +163,7 @@ configuration file
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy.cfg(5), proxy(8), ftppr(8), socks(8), pop3p(8), imapp(8), tcppm(8), udppm(8),
3proxy.cfg(5), proxy(8), ftppr(8), socks(8), pop3p(8), imapp(8), tcppm(8), udppm(8), tcptoudp(8), udptotcp(8),
kill(1), syslogd(8),
.br
https://3proxy.org/
+121 -5
View File
@@ -79,6 +79,14 @@ Recursion is not allowed.
.B udppm
[options]
\fI<SRCPORT>\fR \fI<DSTADDR>\fR \fI<DSTPORT>\fR
.br
.B tcptoudp
[options]
\fI<SRCPORT>\fR \fI<DSTADDR>\fR \fI<DSTPORT>\fR
.br
.B udptotcp
[options]
\fI<SRCPORT>\fR \fI<DSTADDR>\fR \fI<DSTPORT>\fR
.br
Descriptions:
.br
@@ -127,6 +135,25 @@ but must be specified for syntax compatibility.
.B udppm
UDP portmapper
.br
.B tcptoudp
TCP to UDP tunnel: connections on SRCPORT carry datagrams, each with a
two byte length in network order in front of it, sent as UDP datagrams
to DSTADDR:DSTPORT, the answers framed the same way back. The handshake
a client speaks \(em udptunnel's (the rfc1036 one) or ProxyGuard's HTTP
Upgrade for UoTLV/1 (eduVPN) \(em is recognised and answered; a
connection that begins with a length needs none. Each connection has a
UDP socket of its own to the target.
.br
.B udptotcp
UDP to TCP tunnel: each client sending datagrams to SRCPORT is a session
of the service with a TCP connection of its own to DSTADDR:DSTPORT, its
datagrams sent on it with a two byte length in front of each, what comes
back answered to the client. \fB-m\fR sends udptunnel's handshake to the
target first, \fB-m2\fR ProxyGuard's (an HTTP Upgrade for UoTLV/1), \fB-m0\fR
sends none, which is the default.
.br
Options:
.br
@@ -198,6 +225,13 @@ any protocol-specific data.
.B -g(\fIGRACE_TRAFF\fB,\fIGRACE_NUM\fB,\fIGRACE_DELAY\fR)
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
.br
.B -B
(for TCP services) split the TLS ClientHello across two TCP segments in the
middle of the server name (SNI) when it is passed through tlspr, as with
\fBparent ... tls 0.0.0.0 0\fR: some DPI systems looking for blocked host names
do not reassemble it. TCP_NODELAY, set by default, must not be turned off, or the
kernel may join the segments again. In builds without splice() \fB-s\fR does the same.
.br
.B -s
(for admin) secure, allow only secure operations, currently only traffic counters
view without ability to reset.
@@ -554,7 +588,10 @@ network conditions. Applies to the services started after it.
\fI<NAS_SECRET>\fR \fI<radius_server_1\fR[:\fIport\fR][/\fIlocal_address_1\fR]\fR \fI<radius_server_2\fR[:\fIport\fR][/\fIlocal_address_2\fR]\fR
.br
Configures RADIUS servers to be used for logging and authentication (log and auth types
must be set to radius). port and local address to use with given server may be specified.
must be set to radius). A server is a name or an address, resolved when the
configuration is read. port and local address to use with given server may be specified:
the port named is the one authentication is asked on, and the accounting requests of
the same server go to the port after it (1812 and 1813 by default).
.br
Attributes within request: User-Name, Password: (username and password if presented by client),
Service Type: Authenticate-Only,
@@ -566,7 +603,8 @@ Framed-IPv6-Address / Framed-IP-Address: (IP address of the client),
Called-Station-ID: (requested Hostname, if presents),
Login-Service: (type of request, e.g. 1001 - SOCKS CONNECT, 1010 - HTTP GET, 1013 - HTTP CONNECT),
Login-TCP-Port: (requested port),
Login-IPv6-Host / Login-IP-Host: (requested IP).
Login-IPv6-Host / Login-IP-Host: (requested IP),
Event-Timestamp: (the time of the request, in seconds since the epoch).
.br
Supported reply attributes for authentication:
Framed-IP-Address / Framed-IPv6-Address (IP to assign to user), Reply-Message.
@@ -576,7 +614,10 @@ Use \fBauthcache\fR to speedup authentication. RADIUS feature is currently exper
.BR nserver
\fI<ipaddr>\fR[:\fIport\fR][/\fItcp\fR]
.br
Nameserver to use for name resolutions; up to 3, asked in order.
Nameserver to use for name resolutions; up to 3, asked in order; a
server that answers with an error (FORMERR, SERVFAIL, REFUSED and the
like) is passed over for the next one, while a name answered with no
data, or as not there, ends the search.
Optional port number may be specified.
If optional /tcp is added to IP address, name resolution is
performed over TCP.
@@ -876,7 +917,26 @@ quoted or written \fB$$\fR, since a lone dollar outside quotes begins the name
of a file to include. The same patterns, and the same prefix, are used by the
\fBhttp\fR command, see BUILT IN HTTP SERVER. Regular expressions are matched
per request and cost more than a wildmask, which is enough for most rules.
Targetportlist may contain ports (X) or port ranges lists (X-Y). For any field *
Targetlist and targetportlist may name, after one @, the service the
request came through: the targetlist by the addresses it listens on,
the targetportlist by its ports, the lists before and after the @ each
written as any other —
.br
allow * * 192.168.1.0/24@10.0.0.1 443@1080,1090
.br
matches only requests of the service on 10.0.0.1:1080 or :1090. A side
of the @ may be left out: * (any) before it, or nothing after it —
@1080 names a port alone, *@10.0.0.1 an address alone, and an @ with
nothing after it is refused. An IPv6 address needs no brackets there,
for no port follows it. The limiters are shared by all the services,
so this is how a limit is given to one service's connections alone:
.br
connlim 5 60 * * * @1080
.br
denies the sixth concurrent connection of the service on port 1080,
whatever it connects to. For any field *
sign means ANY. If access list is empty it\'s assumed to be
.br
allow *
@@ -1209,6 +1269,24 @@ nolog
Weight may be used for different purposes.
.br
.BR mark
\fI<number>\fR
.br
extends last allow or deny command to set a mark for this request: the
sockets it goes out on, towards the destination and towards the parents,
carry the mark (SO_MARK of Linux, SO_USER_COOKIE of FreeBSD), so that
the packets of the request can be told apart by it in policy routing and
firewall rules. A number is written as in C. UDP is marked the same: the
sockets towards a destination, and the SOCKS UDP ASSOCIATE relays. On a
system with no mark the command sets it to nothing. The mark of a kept
alive request follows the rule which allowed the request (#846).
.br
allow * * 192.168.1.0/24
.br
mark 20
.br
.B force
.br
@@ -1466,6 +1544,30 @@ and
If file monitored changes in modification time or size, 3proxy reloads
configuration within one minute. Any number of files may be monitored.
.br
.BR port
\fItcp|udp\fR \fI[<ip>:]<port>\fR [\fIsocket_options\fR]
.br
Reserves a listening socket at the time the configuration is read: a
privileged port can be opened before \fBsetuid\fR and \fBchroot\fR take the
rights to open it away, the \fBport\fR line placed above them and the
service below. A service of the configuration on the same address, of
the same type, takes the socket over when it starts, instead of opening
one of its own; a port no service takes stays reserved. After chroot no
reservation can be made again, so a reload keeps a port only while the
configuration coming in force reserves it anew or has a service on it:
the port line can be left out of what is read there, the service on
the socket that is already open keeping it. The address is an IPv4 one
by default, an IPv6 one in brackets. The socket options are written as
for \fB-o\fR, and are what the socket has: those which act only before
bind() cannot be changed on a socket the service takes over.
.br
port tcp 443
.br
port tcp [::]:80 TCP_FASTOPEN
.br
port udp 53
.br
.BR setuid
\fI<uid>\fR
@@ -1763,6 +1865,20 @@ FILTER_ACTION - action on match:
deny - deny this request without checking the rest of the rules
.br
dunno - continue with the rest of the rules (useful with pcre_rewrite)
.br
An action may be followed by ,log (as in allow,log or dunno,log): what
the pattern matched is written to the log as a record of its own, one
per match, in addition to the connection's own record. Put %T in
logformat to have the matched text in the line. The options apply to the
pattern as to any other, so for example
.br
pcre_options PCRE2_CASELESS PCRE2_MULTILINE
.br
pcre cliheader dunno,log "^user-agent:.*$"
.br
watches the User-Agent: header whatever its case, with the ^ and $
anchors holding for every line of the headers, wherever the header
comes, and decides nothing about the request.
REGEXP - PCRE (Perl) regular expression. Use * if no regexp matching is required.
@@ -2022,7 +2138,7 @@ the tree is refused outright.
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy(8), 3proxy_crypt(8), proxy(8), ftppr(8), socks(8), pop3p(8), imapp(8), smtpp(8), tlspr(8), tcppm(8), udppm(8), syslogd(8),
3proxy(8), 3proxy_crypt(8), proxy(8), ftppr(8), socks(8), pop3p(8), imapp(8), smtpp(8), tlspr(8), tcppm(8), udppm(8), tcptoudp(8), udptotcp(8), syslogd(8),
.br
https://3proxy.org/
.SH AUTHORS
+99
View File
@@ -0,0 +1,99 @@
.TH tcptoudp "8" "November 2026" "3proxy" "Universal proxy server"
.SH NAME
.B tcptoudp
\- TCP to UDP tunnel
.SH SYNOPSIS
.BR "tcptoudp " [ -d ]
.IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]]
.IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR]
.I local_port remote_host remote_port
.SH DESCRIPTION
.B tcptoudp
takes TCP connections on
.I local_port
and sends what they carry as datagrams to
.IR remote_host : remote_port ,
framing each datagram with its length on the connection. This is the
server side of udptunnel (the rfc1036 one, started with \fB-s\fR) and of
ProxyGuard (eduVPN), whose clients it answers: a connection that begins
with udptunnel's 32 byte handshake has it taken off, one that asks with
an HTTP Upgrade for UoTLV/1 is told the protocols are switched, and one
that begins with a length goes to the framing at once. What comes back
from the target is sent on the connection framed the same way. Each
connection has a UDP socket of its own to the target; a parent the ACL
gives is a SOCKS5 UDP relay, as for udppm.
.SH OPTIONS
.TP
.B -I
Inetd mode. Standalone service only.
.TP
.B -d
Daemonize. Detach service from console and run in the background.
.TP
.B -t
Be silenT. Do not log start/stop/accept error records.
.TP
.B -e
External address. IP address of the interface the proxy should send datagrams
from.
By default, the system will decide which address to use in accordance
with the routing table.
.TP
.B \-ni\fIPATH\fR
(Linux only) Switch to the network namespace identified by
.I PATH
before opening the listening socket. The current namespace is saved and restored
immediately after binding, so outgoing datagrams run in the original namespace
unless
.B \-ne
is also given.
.TP
.B \-ne\fIPATH\fR
(Linux only) Switch to the network namespace identified by
.I PATH
after the listening socket has been bound (and after restoring from
.B \-ni
if applicable). Both options accept any namespace file path
(e.g.\& \fI/var/run/netns/myns\fR or \fI/proc/PID/ns/net\fR)
and require \fBCAP_SYS_ADMIN\fR.
.TP
.B -i
Internal address. IP address the proxy accepts connections to.
By default, connections to any interface are accepted. It\'s usually unsafe.
.TP
.B -l
Log. By default logging is to stdout. If
.I logfile
is specified logging is to file. Under Unix, if
.RI \' @ \'
precedes
.IR logfile ,
syslog is used for logging.
.TP
.B -S
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes.
.SH ARGUMENTS
.TP
.I local_port
- port tcptoudp accepts connections on
.TP
.I remote_host
- IP address of the host datagrams are sent to
.TP
.I remote_port
- remote port datagrams are sent to
.SH CLIENTS
udptunnel's client (without \fB-s\fR), ProxyGuard's client
(\fBproxyguard-client\fR), or anything that puts datagrams on a TCP
connection with a two byte length in network order in front of each.
.SH BUGS
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy(8), 3proxy.cfg(5), udptotcp(8), tcppm(8), udppm(8), syslogd(8),
.br
https://3proxy.org/
.SH AUTHORS
3proxy is designed by Vladimir Dubrovin <vlad@3proxy.org>
+2 -2
View File
@@ -76,8 +76,8 @@ destination_port. Port to establish outgoing connections. Required unless the Tr
.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)
.TP
.B -s
Split the TLS Client HELLO packet across multiple TCP segments to make SNI-based DPI detection harder. An optional numeric value can follow (e.g. \fB-s1\fR) to control the splitting behaviour.
.B -B
Split the TLS Client HELLO packet across two TCP segments, in the middle of the SNI, to make SNI-based DPI detection harder. In builds without splice() \fB-s\fR does the same; with splice() (Linux) \fB-s\fR is splice, see \fB3proxy.cfg\fR(5).
.TP
.B -Ximap | -Xpop3 | -Xsmtp
STARTTLS mode for the given protocol. The proxy speaks the plaintext protocol
+113
View File
@@ -0,0 +1,113 @@
.TH udptotcp "8" "November 2026" "3proxy" "Universal proxy server"
.SH NAME
.B udptotcp
\- UDP to TCP tunnel
.SH SYNOPSIS
.BR "udptotcp " [ -d ", " \fR[ -m \fR| \fR -m2 \fR| \fR -m0 \fR] ]
.IB \fR[ -l \fR[ \fR[ @ \fR] logfile \fR]]
.IB \fR[ -i internal_ip\fR]
.IB \fR[ -e external_ip\fR]
.I local_port remote_host remote_port
.SH DESCRIPTION
.B udptotcp
takes datagrams on
.I local_port
and sends them on a TCP connection to
.IR remote_host : remote_port ,
each with its length in front of it. This is the client side of udptunnel
(the rfc1036 one) and of ProxyGuard (eduVPN): each client is a session of
the service with a TCP connection of its own, and what comes back on the
connection is answered to that client as datagrams. A parent the ACL
gives is asked for a TCP connection to the target, not a UDP relay as
udppm's.
.SH OPTIONS
.TP
.B -I
Inetd mode. Standalone service only.
.TP
.B -d
Daemonize. Detach service from console and run in the background.
.TP
.B -t
Be silenT. Do not log start/stop/accept error records.
.TP
.B -e
External address. IP address of the interface the proxy should initiate the
TCP connection from.
By default, the system will decide which address to use in accordance
with the routing table.
.TP
.B \-ni\fIPATH\fR
(Linux only) Switch to the network namespace identified by
.I PATH
before opening the listening socket. The current namespace is saved and restored
immediately after binding, so the TCP connection runs in the original namespace
unless
.B \-ne
is also given.
.TP
.B \-ne\fIPATH\fR
(Linux only) Switch to the network namespace identified by
.I PATH
after the listening socket has been bound (and after restoring from
.B \-ni
if applicable). Both options accept any namespace file path
(e.g.\& \fI/var/run/netns/myns\fR or \fI/proc/PID/ns/net\fR)
and require \fBCAP_SYS_ADMIN\fR.
.TP
.B -i
Internal address. IP address the proxy accepts datagrams to.
By default, datagrams to any interface are accepted. It\'s usually unsafe.
.TP
.B -l
Log. By default logging is to stdout. If
.I logfile
is specified logging is to file. Under Unix, if
.RI \' @ \'
precedes
.IR logfile ,
syslog is used for logging.
.TP
.B -m
udptunnel's handshake: the 32 bytes a client of udptunnel sends are sent
to the target before the datagrams.
.TP
.B -m2
ProxyGuard's handshake: an HTTP Upgrade for UoTLV/1 is asked of the
target, and the datagrams begin once the target has switched protocols.
.TP
.B -m0
No handshake: the datagrams are sent with none at all, which tcptoudp
and ProxyGuard's server also take. This is the default.
.TP
.B -S
Increase or decrease stack size. You may want to try something like -S8192 if you experience 3proxy
crashes.
.SH ARGUMENTS
.TP
.I local_port
- port udptotcp accepts datagrams on
.TP
.I remote_host
- IP address of the host the TCP connection is made to
.TP
.I remote_port
- remote port the TCP connection is made to
.SH CLIENTS
Any UDP-based application can be used as a client. Use
.I internal_ip
and
.I local_port
as the destination in the client application. The datagrams are carried
to
.IR remote_host : remote_port
and the answers come back.
.SH BUGS
Report all bugs to
.BR 3proxy@3proxy.org
.SH SEE ALSO
3proxy(8), 3proxy.cfg(5), tcptoudp(8), tcppm(8), udppm(8), syslogd(8),
.br
https://3proxy.org/
.SH AUTHORS
3proxy is designed by Vladimir Dubrovin <vlad@3proxy.org>
+3 -1
View File
@@ -1,5 +1,5 @@
Name: 3proxy
Version: 1.1.0~pre1
Version: 1.1.0~pre2
Release: 1%{?dist}
Summary: 3proxy tiny proxy server
License: GPL/LGPL/Apache/BSD
@@ -39,8 +39,10 @@ make clean
/bin/3proxy_proxy
/bin/3proxy_socks
/bin/3proxy_tcppm
/bin/3proxy_tcptoudp
/bin/3proxy_tlspr
/bin/3proxy_udppm
/bin/3proxy_udptotcp
/bin/add3proxyuser
%config(noreplace) /etc/3proxy/3proxy.cfg
/etc/3proxy/conf
+23 -13
View File
@@ -29,7 +29,7 @@ void httpsrv_init(void);
#endif
#ifndef DEFAULTCONFIG
#define DEFAULTCONFIG conf->stringtable[25]
#define DEFAULTCONFIG conf->stringtable[27]
#endif
FILE * confopen();
@@ -296,6 +296,21 @@ void cyclestep(void){
#define RETURN(x) {res = x; goto CLEARRETURN;}
static void printusage(struct extparam *cconf, int argc, char * argv[]){
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
#ifdef _WIN32
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
#else
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
#endif
fprintf(stderr, "\n\t%s --help\n\tthis message\n", argv[0]);
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
fprintf(stderr, "built with:\n\t%s\n", printfeatures("\n\t"));
fprintf(stderr, "\n%s %s\n%s\n", cconf->stringtable[2], cconf->stringtable[3], copyright);
}
#ifndef _WINCE
int main(int argc, char * argv[]) {
@@ -338,6 +353,10 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
#endif
conf->stringtable = strings;
if(argc == 2 && (!strcmp((char *)argv[1], "--help") || !strcmp((char *)argv[1], "-h"))) {
printusage(conf, argc, argv);
return 0;
}
#ifdef _WIN32
#ifndef _WINCE
if((argc == 2 || argc == 3)&& !strcmp((char *)argv[1], "--install")) {
@@ -448,20 +467,11 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
if(!fp) fp = stdin;
#endif
}
if(argc > 2 || !(fp)) {
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
#ifdef _WIN32
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
#else
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
#endif
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
fprintf(stderr, "\n%s %s\n%s\n", conf->stringtable[2], conf->stringtable[3], copyright);
if(argc > 2 || !(fp)) {
printusage(conf, argc, argv);
return 1;
}
}
#ifdef __linux__
nsopen(); /* before a chroot in the configuration takes /proc away */
+22 -3
View File
@@ -5,7 +5,7 @@ PROXYMAIN = proxymain.c mainconf.c mainlisten.c mainclient.c maintcp.c mainudp.c
# 3 proxy common Makefile
#
all: $(BUILDDIR)3proxy$(EXESUFFICS) $(BUILDDIR)$(CRYPT_PREFIX)crypt$(EXESUFFICS) $(MAIL_EXES) $(FTP_EXES) $(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) allplugins
all: $(BUILDDIR)3proxy$(EXESUFFICS) $(BUILDDIR)$(CRYPT_PREFIX)crypt$(EXESUFFICS) $(MAIL_EXES) $(FTP_EXES) $(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(BUILDDIR)$(PREFIX)tcptoudp$(EXESUFFICS) $(BUILDDIR)$(PREFIX)udptotcp$(EXESUFFICS) $(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) allplugins
sockmap$(OBJSUFFICS): sockmap.c proxy.h structures.h
$(CC) $(CFLAGS) sockmap.c
@@ -52,6 +52,12 @@ tcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h $(PROXYMAIN)
udppm$(OBJSUFFICS): udppm.c proxy.h structures.h $(PROXYMAIN)
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOTCPMAIN udppm.c
tcptoudp$(OBJSUFFICS): tcptoudp.c proxy.h structures.h udptunnel.h $(PROXYMAIN)
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tcptoudp.c
udptotcp$(OBJSUFFICS): udptotcp.c proxy.h structures.h udptunnel.h $(PROXYMAIN)
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOTCPMAIN udptotcp.c
tlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h $(PROXYMAIN)
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tlspr.c
@@ -86,6 +92,12 @@ $(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUF
$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) hash$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)$(PREFIX)tcptoudp$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcptoudp$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tcptoudp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcptoudp$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)$(PREFIX)udptotcp$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udptotcp$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) hash$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)udptotcp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udptotcp$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS)
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(LIBS)
@@ -131,6 +143,12 @@ srvhttpsrv$(OBJSUFFICS): httpsrv.c proxy.h structures.h
srvudppm$(OBJSUFFICS): udppm.c proxy.h structures.h
$(CC) $(COUT)srvudppm$(OBJSUFFICS) $(CFLAGS) udppm.c
srvtcptoudp$(OBJSUFFICS): tcptoudp.c proxy.h structures.h udptunnel.h
$(CC) $(COUT)srvtcptoudp$(OBJSUFFICS) $(CFLAGS) tcptoudp.c
srvudptotcp$(OBJSUFFICS): udptotcp.c proxy.h structures.h udptunnel.h
$(CC) $(COUT)srvudptotcp$(OBJSUFFICS) $(CFLAGS) udptotcp.c
srvdnspr$(OBJSUFFICS): dnspr.c proxy.h structures.h
$(CC) $(COUT)srvdnspr$(OBJSUFFICS) $(CFLAGS) dnspr.c
@@ -200,6 +218,7 @@ ssl$(OBJSUFFICS): ssl.c structures.h proxy.h ssl.h
pcre$(OBJSUFFICS): pcre.c structures.h
$(CC) $(COUT)pcre$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITH_PCRE pcre.c
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(VERSIONDEP)
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(LIBS) $(PCRE_LIBS)
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) srvtcptoudp$(OBJSUFFICS) srvudptotcp$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(VERSIONDEP)
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) srvtcptoudp$(OBJSUFFICS) srvudptotcp$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(LIBS) $(PCRE_LIBS)
+20
View File
@@ -310,6 +310,25 @@ int ACLmatches(struct ace* acentry, struct clientparam * param){
}
if(!ipentry && !hstentry) return 0;
}
/* the service the request came through, by the port it listens on
and by its address: what the part after the @ of a port in a
rule names */
if(acentry->viasrc) {
for (ipentry = acentry->viasrc; ipentry; ipentry = ipentry->next)
if(IPInentry((struct sockaddr *)&param->srv->intsa, ipentry)) {
break;
}
if(!ipentry) return 0;
}
if(acentry->viaports) {
int viaport = ntohs(*SAPORT(&param->srv->intsa));
for (portentry = acentry->viaports; portentry; portentry = portentry->next)
if(viaport >= portentry->startport && viaport <= portentry->endport) {
break;
}
if(!portentry) return 0;
}
if(preauth && acentry->ports) {
dstdep = 1;
}
@@ -364,6 +383,7 @@ int checkACL(struct clientparam * param){
if(ACLmatches(acentry, param)) {
param->nolog = acentry->nolog;
param->weight = acentry->weight;
param->mark = acentry->mark;
if(acentry->action == 2) {
struct ace dup;
int res=60,i=0;
+4 -1
View File
@@ -122,7 +122,10 @@ int doauth(struct clientparam * param){
if(authfuncs->authorize &&
(res = (*authfuncs->authorize)(param)))
return res;
if(param->srv->authcachetype && authfuncs->authenticate && authfuncs->authenticate != cacheauth && *param->username && (!(param->srv->authcachetype&4) || (!param->pwtype && *param->password))){
/* A UDP ASSOCIATE is pre-authorized without looking at the
destination its rules depend on, so its verdict holds for
that association alone and is not kept for later requests. */
if(param->srv->authcachetype && param->preauth != 1 && authfuncs->authenticate && authfuncs->authenticate != cacheauth && *param->username && (!(param->srv->authcachetype&4) || (!param->pwtype && *param->password))){
struct authcache ac={.username=""};
strncpy((char *)ac.username, (char *)param->username, 64);
+31 -5
View File
@@ -194,12 +194,20 @@ static int calc_replydigest(char *packet, char *original, const char *secret, in
int secretlen;
uint8_t calc_digest[AUTH_VECTOR_LEN];
uint8_t calc_vector[AUTH_VECTOR_LEN];
unsigned int dlen = AUTH_VECTOR_LEN;
mdh_ctx *ctx;
memcpy(calc_vector, packet + 4, AUTH_VECTOR_LEN);
memcpy(packet + 4, original, AUTH_VECTOR_LEN);
secretlen = strlen(secret);
memcpy(packet + len, secret, secretlen);
md5_calc(calc_digest, (u_char *)packet, len + secretlen);
/* hash the reply, then the secret: nothing is written past the reply */
if(!(ctx = mdh_init(MDH_MD5, 16))) return 2;
if(!mdh_update(ctx, packet, len) || !mdh_update(ctx, secret, secretlen) ||
!mdh_final(ctx, calc_digest, &dlen)) {
mdh_free(ctx);
return 2;
}
mdh_free(ctx);
/*
* Return 0 if OK, 2 if not OK.
@@ -294,6 +302,7 @@ int radsend(struct clientparam * param, int auth, int stop){
int total_length;
int len;
PROXYSOCKADDRTYPE saremote;
PROXYSOCKADDRTYPE safrom;
struct pollfd fds[1];
char vector[AUTH_VECTOR_LEN];
radius_packet_t packet, rpacket;
@@ -340,6 +349,13 @@ int radsend(struct clientparam * param, int auth, int stop){
ptr+=len;
total_length+=len+2;
/* Event-Timestamp */
*ptr++ = PW_EVENT_TIMESTAMP;
*ptr++ = 6;
(*(uint32_t *)ptr)=htonl((uint32_t)time(0));
ptr+=4;
total_length+=6;
/* NAS-Port-Type */
*ptr++ = PW_NAS_PORT_TYPE;
*ptr++ = 6;
@@ -564,15 +580,25 @@ int radsend(struct clientparam * param, int auth, int stop){
continue;
}
salen = sizeof(saremote);
salen = sizeof(safrom);
data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
0, (struct sockaddr *)&saremote, &salen);
0, (struct sockaddr *)&safrom, &salen);
if (data_len < 20) {
continue;
}
/* the reply must come from the server we asked */
if(*SAFAMILY(&safrom) != *SAFAMILY(&saremote) ||
memcmp(SAADDR(&safrom), SAADDR(&saremote), SAADDRLEN(&saremote)) ||
*SAPORT(&safrom) != *SAPORT(&saremote)) {
continue;
}
/* and answer this request, and be of its own length */
if(data_len != ntohs(rpacket.length) || rpacket.id != packet.id) {
continue;
}
if( auth && rpacket.code != PW_AUTHENTICATION_ACK &&
rpacket.code != PW_AUTHENTICATION_REJECT ){
+74
View File
@@ -543,11 +543,26 @@ int parsehost(int family, unsigned char *host, struct sockaddr *sa){
return ret;
}
/* A host name is written into the request lines of parent protocols and
matched against rules, so a control byte or a space in it could end a
line early or pose as another destination. A name carrying one is
refused where it is read, and every name a client sends is read on
its way to the field. */
int badhostname(const char *hostname){
const unsigned char *c;
if(!hostname) return 1;
for(c = (const unsigned char *)hostname; *c; c++)
if(*c <= ' ' || *c == 0x7f) return 1;
return 0;
}
int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
char *sp=NULL,*se=NULL;
int ret = 0;
if(!hostname || !*hostname)return 2;
if(badhostname(hostname)) return 1;
if(*hostname == '[') se=strchr(hostname, ']');
if ((sp = strchr(se?se:hostname, ':'))) {
if(strchr(sp+1, ':'))sp = NULL;
@@ -561,6 +576,9 @@ int parsehostname(char *hostname, struct clientparam *param, uint16_t port){
port = atoi(sp+1);
*sp = ':';
}
/* A port alone overrides the port of a host already set; without
one it names no destination to connect to. */
if(!*param->hostname) return 1;
*SAPORT(&param->req) = htons(port);
return 0;
}
@@ -649,6 +667,26 @@ int parseconnusername(char *username, struct clientparam *param, int extpasswd,
}
/* What waits for a socket waits in sockpoll(): a call on it never does. */
void nonblock(SOCKET sock){
#ifdef _WIN32
unsigned long ul = 1;
ioctlsocket(sock, FIONBIO, &ul);
#else
fcntl(sock, F_SETFL, O_NONBLOCK | fcntl(sock, F_GETFL));
#endif
}
/* accept() with nothing to accept: another took it, or it was gone */
int acceptagain(void){
#ifdef _WIN32
int err = WSAGetLastError();
return err == WSAEWOULDBLOCK || err == WSAECONNRESET || err == WSAEINTR;
#else
return errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR;
#endif
}
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
struct pollfd fds[1];
#ifdef _WIN32
@@ -720,6 +758,25 @@ int intbindtodevice(struct clientparam *param, SOCKET sock){
#endif
}
/* The mark the matched rule gave the connection, set on its outgoing
sockets where the system has one: SO_MARK of Linux, SO_USER_COOKIE of
FreeBSD. Nowhere else it is silently nothing. */
void setmark(struct clientparam *param, SOCKET sock){
#if defined SO_MARK || defined SO_USER_COOKIE
if(param->mark)
so._setsockopt(so.state, sock, SOL_SOCKET,
#ifdef SO_MARK
SO_MARK,
#else
SO_USER_COOKIE,
#endif
(char *)&param->mark, sizeof(param->mark));
#else
(void)param;
(void)sock;
#endif
}
int doconnect(struct clientparam * param){
SASIZETYPE size;
@@ -769,12 +826,29 @@ int doconnect(struct clientparam * param){
}
*SAPORT(&param->sinsl) = 0;
setopts(param->remsock, &param->srv->srvsockopts, param->srv->maxseg);
setmark(param, param->remsock);
#ifndef _WIN32
/* not on Windows, see the accepting side in proxymain.c */
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
#endif
if(extbindtodevice(param, param->remsock)) return 12;
#ifdef IP_BIND_ADDRESS_NO_PORT
/* A port the kernel chooses is chosen by connect(), for the pair with
the destination: one in use towards another destination, or closing
from an earlier connection, does as well. bind() would take one of
its own, and with many connections find none left, or search long
for it. */
if((param->operation >= 256 || (param->operation & CONNECT) || param->redirected)
# ifdef WITH_UN
&& *SAFAMILY(&param->sinsl) != AF_UNIX
# endif
){
int one = 1;
param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, (char *)&one, sizeof(one));
}
#endif
#ifdef WITH_UN
if(*SAFAMILY(&param->sinsl) != AF_UNIX)
#endif
+190 -57
View File
@@ -31,7 +31,7 @@ void transparent_install(void);
#endif
#ifndef DEFAULTCONFIG
#define DEFAULTCONFIG conf->stringtable[25]
#define DEFAULTCONFIG conf->stringtable[27]
#endif
_3proxy_mutex_t bandlim_mutex;
@@ -308,6 +308,21 @@ static int h_proxy(int argc, unsigned char ** argv){
childdef.service = S_UDPPM;
childdef.helpmessage = " -s single packet UDP service for request/reply (DNS-like) services\n";
}
else if(!strcmp((char *)argv[0], "tcptoudp")) {
childdef.pf = tcptoudpchild;
childdef.port = 0;
childdef.isudp = 0;
childdef.service = S_TCPTOUDP;
childdef.helpmessage = " the handshake a client speaks, udptunnel's or ProxyGuard's, is answered\n";
}
else if(!strcmp((char *)argv[0], "udptotcp")) {
childdef.pf = NULL;
childdef.udp = &udptotcpservice;
childdef.port = 0;
childdef.isudp = 1;
childdef.service = S_UDPTOTCP;
childdef.helpmessage = " -m - udptunnel handshake with the target, -m2 - ProxyGuard's, -m0 - none\n";
}
#ifdef WITH_HTTPSRV
else if(!strcmp((char *)argv[0], "admin")) {
/* The same service as httpsrv, with the administration pages
@@ -424,6 +439,45 @@ static int h_threadpool(int argc, unsigned char **argv){
return 0;
}
/* Reserves a listening socket while the configuration is read: a
privileged port is opened before setuid and chroot take the rights
away, and a service of the configuration on the same address takes
the socket over when it starts. After chroot no reservation can be
made again: a reload keeps the port only while the configuration in
force reserves it anew or has a service on it. */
static int h_port(int argc, unsigned char **argv){
struct portreservation *r;
PROXYSOCKADDRTYPE sa;
struct sockoptset opts;
int isudp;
if(!strcmp((char *)argv[1], "udp")) isudp = 1;
else if(!strcmp((char *)argv[1], "tcp")) isudp = 0;
else return 1;
memset(&opts, 0, sizeof(opts));
if(argc > 3 && getopts((char *)argv[3], &opts)) return 2;
/* as a service's address: from the defaults, so the same in every
byte a listener is matched by */
sa = conf->intsa;
if(strchr((char *)argv[2], ':') || *argv[2] == '['){
if(parsehost(46, argv[2], (struct sockaddr *)&sa)) return 3;
}
else {
*SAFAMILY(&sa) = AF_INET;
*SAPORT(&sa) = htons((uint16_t)atoi((char *)argv[2]));
}
if(!*SAPORT(&sa)) return 3;
if(!(r = malloc(sizeof(*r)))) return 4;
if(!(r->listener = mainreserve(isudp, &sa, &opts, 0))){
free(r);
fprintf(stderr, "Unable to reserve port, line %d\n", linenum);
return 5;
}
r->next = conf->reservations;
conf->reservations = r;
return 0;
}
static int h_force(int argc, unsigned char **argv){
conf->noforce = 0;
@@ -1248,15 +1302,35 @@ static int h_http(int argc, unsigned char **argv){
static int h_nolog(int argc, unsigned char **argv){
struct ace *acl = NULL;
acl = conf->acl;
if(!acl) {
fprintf(stderr, "Chaining error: last ACL entry was not \"allow/deny\" on line %d\n", linenum);
return(1);
}
while(acl->next) acl = acl->next;
if(argc == 1) acl->nolog = 1;
else acl->weight = atoi((char*)argv[1]);
return 0;
acl = conf->acl;
if(!acl) {
fprintf(stderr, "Chaining error: last ACL entry was not \"allow/deny\" on line %d\n", linenum);
return(1);
}
while(acl->next) acl = acl->next;
if(argc == 1) acl->nolog = 1;
else acl->weight = atoi((char*)argv[1]);
return 0;
}
/* mark <number>: the rule above sends with this mark, on its sockets
towards the destination and the parents, where the system has one */
static int h_mark(int argc, unsigned char **argv){
struct ace *acl = NULL;
char *end;
acl = conf->acl;
if(!acl) {
fprintf(stderr, "Chaining error: last ACL entry was not \"allow/deny\" on line %d\n", linenum);
return(1);
}
while(acl->next) acl = acl->next;
acl->mark = (int)strtol((char *)argv[1], &end, 0);
if(end == (char *)argv[1] || *end) {
fprintf(stderr, "Wrong mark, line %d\n", linenum);
return(1);
}
return 0;
}
int scanipl(unsigned char *arg, struct iplist *dst){
@@ -1308,14 +1382,58 @@ int scanipl(unsigned char *arg, struct iplist *dst){
return 0;
}
/* Appends a port or a port range to a list: 0, or 1 for one that is
neither, or for want of memory. */
static int portadd(struct portlist **head, const char *s){
struct portlist **tail;
uint16_t start = 0, end = 0;
int res;
for(tail = head; *tail; tail = &(*tail)->next);
res = sscanf(s, "%hu-%hu", &start, &end);
if(res < 1) return 1;
if(!(*tail = malloc(sizeof(struct portlist)))) return 1;
(*tail)->next = NULL;
(*tail)->startport = start;
(*tail)->endport = (res == 1)? start : end;
return 0;
}
/* Appends an IP, an IP range or a CIDR to a list: 0, or 1 for one that
is none of them, or for want of memory. */
static int ipadd(struct iplist **head, const char *s){
struct iplist **tail, tmp;
for(tail = head; *tail; tail = &(*tail)->next);
memset(&tmp, 0, sizeof(tmp));
if(scanipl((unsigned char *)s, &tmp)) return 1;
if(!(*tail = malloc(sizeof(struct iplist)))) return 1;
**tail = tmp;
(*tail)->next = NULL;
return 0;
}
/* The part of a field after its one @: the service the request came
through, named by the addresses it listens on in the targetlist and
by its ports in the targetportlist, the lists written as any other. */
static unsigned char * viapart(unsigned char *field, int argi, int argc){
if(argi < argc){
unsigned char *via = (unsigned char *)strchr((char *)field, '@');
if(via) *via++ = 0;
return via;
}
return NULL;
}
struct ace * make_ace (int argc, unsigned char ** argv){
struct ace * acl;
unsigned char *arg;
struct iplist *ipl=NULL;
struct portlist *portl=NULL;
unsigned char *arg, *via;
struct userlist *userl=NULL;
struct hostname *hostnamel=NULL;
int res;
struct iplist tmpip={NULL};
int arglen;
acl = malloc(sizeof(struct ace));
if(!acl) return acl;
@@ -1343,30 +1461,16 @@ struct ace * make_ace (int argc, unsigned char ** argv){
if(argc > 1 && strcmp("*", (char *)argv[1])) {
arg = (unsigned char *)strtok((char *)argv[1], ",");
if(arg) do {
if(!acl->src) {
acl->src = ipl = malloc(sizeof(struct iplist));
}
else {
ipl->next = malloc(sizeof(struct iplist));
ipl = ipl -> next;
}
if(!ipl) {
fprintf(stderr, "No memory for ACL entry, line %d\n", linenum);
return(NULL);
}
memset(ipl, 0, sizeof(struct iplist));
if (scanipl(arg, ipl)) {
if(ipadd(&acl->src, (char *)arg)) {
fprintf(stderr, "Invalid IP, IP range or CIDR, line %d\n", linenum);
return(NULL);
}
} while((arg = (unsigned char *)strtok((char *)NULL, ",")));
}
via = viapart(argv[2], 2, argc);
if(argc > 2 && strcmp("*", (char *)argv[2])) {
arg = (unsigned char *)strtok((char *)argv[2], ",");
if(arg) do {
int arglen;
struct iplist tmpip={NULL};
arglen = (int)strlen((char *)arg);
if(scanipl(arg, &tmpip)){
if(!arglen) continue;
@@ -1388,43 +1492,45 @@ struct ace * make_ace (int argc, unsigned char ** argv){
}
}
else {
if(!acl->dst) {
acl->dst = ipl = malloc(sizeof(struct iplist));
}
else {
ipl->next = malloc(sizeof(struct iplist));
ipl = ipl -> next;
}
if(!ipl) {
if(ipadd(&acl->dst, (char *)arg)) {
fprintf(stderr, "No memory for ACL entry, line %d\n", linenum);
return(NULL);
}
*ipl = tmpip;
}
}while((arg = (unsigned char *)strtok((char *)NULL, ",")));
}
if(via){
if(!*via || !(arg = (unsigned char *)strtok((char *)via, ","))) {
fprintf(stderr, "Invalid IP, IP range or CIDR, line %d\n", linenum);
return(NULL);
}
do {
if(ipadd(&acl->viasrc, (char *)arg)) {
fprintf(stderr, "Invalid IP, IP range or CIDR, line %d\n", linenum);
return(NULL);
}
} while((arg = (unsigned char *)strtok((char *)NULL, ",")));
}
via = viapart(argv[3], 3, argc);
if(argc > 3 && strcmp("*", (char *)argv[3])) {
arg = (unsigned char *)strtok((char *)argv[3], ",");
if(arg) do {
if(!acl->ports) {
acl->ports = portl = malloc(sizeof(struct portlist));
}
else {
portl->next = malloc(sizeof(struct portlist));
portl = portl -> next;
}
if(!portl) {
fprintf(stderr, "No memory for ACL entry, line %d\n", linenum);
return(NULL);
}
memset(portl, 0, sizeof(struct portlist));
res = sscanf((char *)arg, "%hu-%hu", &portl->startport, &portl->endport);
if(res < 1) {
if(portadd(&acl->ports, (char *)arg)) {
fprintf(stderr, "Invalid port or port range, line %d\n", linenum);
return(NULL);
}
} while((arg = (unsigned char *)strtok((char *)NULL, ",")));
}
if(via){
if(!*via || !(arg = (unsigned char *)strtok((char *)via, ","))) {
fprintf(stderr, "Invalid port or port range, line %d\n", linenum);
return(NULL);
}
do {
if(portadd(&acl->viaports, (char *)arg)) {
fprintf(stderr, "Invalid port or port range, line %d\n", linenum);
return(NULL);
}
if (res == 1) portl->endport = portl->startport;
} while((arg = (unsigned char *)strtok((char *)NULL, ",")));
}
if(argc > 4 && strcmp("*", (char *)argv[4])) {
@@ -1803,8 +1909,8 @@ static int h_radius(int argc, unsigned char **argv){
*s = 0;
s++;
}
if( !getip46(46, argv[conf->nradservers + 2], (struct sockaddr *)&conf->radiuslist[conf->nradservers].authaddr)) return 1;
if( s && !getip46(46, (unsigned char *)s, (struct sockaddr *)&conf->radiuslist[conf->nradservers].localaddr)) return 2;
if(parsehost(46, argv[conf->nradservers + 2], (struct sockaddr *)&conf->radiuslist[conf->nradservers].authaddr)) return 1;
if(s && parsehost(46, (unsigned char *)s, (struct sockaddr *)&conf->radiuslist[conf->nradservers].localaddr)) return 2;
if(!*SAPORT(&conf->radiuslist[conf->nradservers].authaddr))*SAPORT(&conf->radiuslist[conf->nradservers].authaddr) = htons(1812);
port = ntohs(*SAPORT(&conf->radiuslist[conf->nradservers].authaddr));
conf->radiuslist[conf->nradservers].logaddr = conf->radiuslist[conf->nradservers].authaddr;
@@ -2064,6 +2170,8 @@ struct commands commandhandlers[]={
{NULL, "socks", h_proxy, 1, 0},
{NULL, "tcppm", h_proxy, 4, 0},
{NULL, "udppm", h_proxy, 4, 0},
{NULL, "tcptoudp", h_proxy, 4, 0},
{NULL, "udptotcp", h_proxy, 4, 0},
#ifdef WITH_HTTPSRV
{NULL, "admin", h_proxy, 1, 0},
#endif
@@ -2121,6 +2229,7 @@ struct commands commandhandlers[]={
{NULL, "filtermaxsize", h_filtermaxsize, 2, 2},
{NULL, "nolog", h_nolog, 1, 1},
{NULL, "weight", h_nolog, 2, 2},
{NULL, "mark", h_mark, 2, 2},
{NULL, "authcache", h_authcache, 2, 4},
{NULL, "smtpp", h_proxy, 1, 0},
{NULL, "delimchar",h_delimchar, 2, 2},
@@ -2129,6 +2238,7 @@ struct commands commandhandlers[]={
{NULL, "minlogqueue", h_minlogqueue, 2, 2},
{NULL, "maxlogqueue", h_maxlogqueue, 2, 2},
{NULL, "threadpool", h_threadpool, 2, 3},
{NULL, "port", h_port, 3, 4},
{NULL, "force", h_force, 1, 1},
{NULL, "noforce", h_noforce, 1, 1},
{NULL, "parentretries", h_parentretries, 2, 2},
@@ -2397,11 +2507,21 @@ void freeconf(struct extparam *confp){
struct trafcount * tc;
struct ace *acl;
struct filemon *fm;
struct portreservation *pr;
int counterd, archiverc;
unsigned char **archiver;
unsigned char * logformat;
int i;
while(confp->reservations){
pr = confp->reservations;
confp->reservations = pr->next;
/* dropped already at the reload, the configuration after it neither
reserving the port nor using it */
if(pr->listener) maindropreserved(pr->listener);
free(pr);
}
_3proxy_mutex_lock(&tc_mutex);
confp->trafcountfunc = NULL;
tc = confp->trafcounter;
@@ -2547,6 +2667,7 @@ int reload (void){
int error = -2;
struct extparam *old = conf, *new;
struct deferred *d;
struct portreservation *pr;
if(!(new = malloc(sizeof(*new)))) return -1;
*new = confdefaults;
@@ -2614,6 +2735,18 @@ int reload (void){
/* the new services take over the listening sockets of the old ones on
the same addresses, which then stop accepting, and start */
for(d = deferred; d; d = d->next) mainclaim(d->service);
/* A port reserved before setuid and chroot is dropped now, unless the
configuration in force reserves it anew or has a service on it:
after chroot no reservation can be made again, only the usage of
the socket a service takes over keeps it */
for(pr = old->reservations; pr; pr = pr->next){
struct portreservation *pn;
for(pn = new->reservations; pn; pn = pn->next) if(pn->listener == pr->listener) break;
if(pn) continue;
maindropreserved(pr->listener);
pr->listener = NULL;
}
old->paused++;
while((d = deferred)){
deferred = d->next;
+15
View File
@@ -422,6 +422,14 @@ static void * ef_ace_ports(struct node * node){
return ((struct ace *)node->value) -> ports;
}
static void * ef_ace_viaports(struct node * node){
return ((struct ace *)node->value) -> viaports;
}
static void * ef_ace_viasrc(struct node * node){
return ((struct ace *)node->value) -> viasrc;
}
static void * ef_ace_chain(struct node * node){
return ((struct ace *)node->value) -> chains;
}
@@ -442,6 +450,10 @@ static void * ef_ace_nolog(struct node * node){
return &((struct ace *)node->value) -> nolog;
}
static void * ef_ace_mark(struct node * node){
return &((struct ace *)node->value) -> mark;
}
static void * ef_bandlimit_next(struct node * node){
return ((struct bandlim *)node->value) -> next;
}
@@ -853,11 +865,14 @@ static struct property prop_ace[] = {
{"dst", ef_ace_dst, TYPE_IPLIST, "list of destination ips"},
{"dstnames", ef_ace_dstnames, TYPE_HOSTNAME, "list of destination hostnames"},
{"ports", ef_ace_ports, TYPE_PORTLIST, "list of destination ports"},
{"viaports", ef_ace_viaports, TYPE_PORTLIST, "the services' ports it matches"},
{"viasrc", ef_ace_viasrc, TYPE_IPLIST, "the services' addresses it matches"},
{"chain", ef_ace_chain, TYPE_CHAIN, "redirect to parent(s)"},
{"wdays", ef_ace_weekdays, TYPE_WEEKDAYS, "days of week"},
{"periods", ef_ace_period, TYPE_PERIOD, "time of the day"},
{"weight", ef_ace_weight, TYPE_INTEGER, "ace weight"},
{"nolog", ef_ace_nolog, TYPE_INTEGER, "do not log"},
{"mark", ef_ace_mark, TYPE_INTEGER, "mark the outgoing sockets with"},
{"next", ef_ace_next, TYPE_ACE, "next"}
};
+6 -9
View File
@@ -117,8 +117,8 @@ static void dnscache(struct clientparam *param, struct dnsquery *q, unsigned cha
}
}
/* An answer from a name server: to the client as it is if it has answers,
else as the name not found. 1: the query is done. */
/* An answer from a name server: to the client as it is, whatever it
says. 1: the query is done. */
static int dnsreply(struct udploop *u, struct udpsession *ss, unsigned char *buf, int len){
struct clientparam *param = ss->param;
struct dnsquery *q = ss->data;
@@ -131,13 +131,10 @@ static int dnsreply(struct udploop *u, struct udpsession *ss, unsigned char *buf
buf[1] = q->cid[1];
param->statssrv64 += len;
param->nreads++;
if(buf[6] || buf[7]){
dnscache(param, q, buf, len);
param->res = (udpanswer(u, param, buf, len) == len)? 0 : 822;
return 1;
}
q->ip = 0;
param->res = dnsanswer(u, param, q, buf, len);
/* the answer goes to the client as it is, its code with no records
among them: the name not found is the server's word, not ours */
if(buf[6] || buf[7]) dnscache(param, q, buf, len);
param->res = (udpanswer(u, param, buf, len) == len)? 0 : 822;
return 1;
}
+4 -1
View File
@@ -38,7 +38,7 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
if(i < 3) return 706;
buf[i] = 0;
if(atoi(buf)/100 != 2) {
*innbuf = i;
if(innbuf)*innbuf = i;
return 702;
}
sprintf(buf, "USER %.128s\r\n", *param->extusername?param->extusername:(unsigned char *)"anonymous");
@@ -74,6 +74,9 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
return 701;
}
}
/* USER answered at once, logged in (230) or refused: that answer is
the client's, waiting for one to its PASS */
else if(innbuf)*innbuf = i;
if(res != 2) {
return 700;
}
+1 -1
View File
@@ -132,7 +132,7 @@ void * ftpprchild(struct clientparam* param) {
param->srv->so._closesocket(param->sostate, clidatasock);
clidatasock = INVALID_SOCKET;
}
if ((clidatasock=socket(SASOCK(&param->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
if ((clidatasock=nssocket(param->srv, &param->srv->so, param->sostate, NS_IN, SASOCK(&param->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
if(intbindtodevice(param, clidatasock)){RETURN(822);}
*SAPORT(&param->sincl) = 0;
if(bindwithrange(param, clidatasock, &param->sincl, param->intport)){RETURN(822);}
+26 -6
View File
@@ -428,11 +428,12 @@ static int targetunsafe(const char *path)
#endif
}
if(!strncmp(path, "./", 2) || !strncmp(path, "../", 3)) return 1;
if(strstr(path, "/./") || strstr(path, "/../")) return 1;
if(strstr(path, "\\.\\") || strstr(path, "\\..\\")) return 1;
/* a dot-dot segment, with either separator, wherever it is in the
path: a walk out of the tree, or a file named to look like one */
if(strstr(path, "/..") || strstr(path, "\\..")) return 1;
if(strstr(path, "/./") || strstr(path, "\\.\\")) return 1;
p = path + strlen(path);
if(p - path >= 2 && !strcmp(p - 2, "/.")) return 1;
if(p - path >= 3 && !strcmp(p - 3, "/..")) return 1;
if(p - path >= 2 && (!strcmp(p - 2, "/.") || !strcmp(p - 2, "\\."))) return 1;
return 0;
}
@@ -1475,16 +1476,27 @@ static int httpsrv_request(struct clientparam *param, struct httpreq *r)
return 1;
}
}
if(i && i != 10){
if(i){
/* The body goes before the answer, as for any answer this server
gives: left in the stream it would be read as the next request. */
if(!r->drained){
if(r->contentlen) httpsrv_drain(param, r->contentlen);
r->drained = 1;
}
/* 10: a limit of the service was exceeded, which the other
services answer with 503. */
if(i == 10){
static const char body[] = "exceeded your limits\n";
r->hdrs = NULL;
r->maxage = -1;
r->keepalive = 0;
if(httpsrv_head(r, 503, "text/plain", (int64_t)sizeof(body) - 1, NULL)) return 1;
httpsrv_send(r, body, (int)sizeof(body) - 1);
}
/* 4 no credentials, 5 unknown user, 6 wrong password: all of them
should let the client offer credentials again. */
if(i >= 4 && i <= 6) op_authrequired(r);
else if(i >= 4 && i <= 6) op_authrequired(r);
else op_forbidden(r);
RETURN(i);
}
@@ -1586,6 +1598,14 @@ void * httpsrvchild(struct clientparam *param)
r.lasthost = lasthost;
param->res = 0;
/* What the request brought belongs to it alone. A connection
can carry a client's request after another's, as a reverse
proxy reuses its upstreams, so the credentials and the host
of an earlier request decide nothing for this one. */
*param->hostname = 0;
*param->username = 0;
*param->password = 0;
answered = httpsrv_request(param, &r);
handoff = r.handoff;
param->climark = -1;
+4
View File
@@ -54,6 +54,8 @@ static void serveparam(struct clientparam *param){
}
param->remsock = param->srv->so._accept(param->sostate, param->srv->cbsock, (struct sockaddr*)&param->sinsr, &size);
if(param->remsock == INVALID_SOCKET) {
/* another client of the service took it: not a try */
if(acceptagain()) { i++; continue; }
dolog(param, (unsigned char *)"Connect back accept() failed");
continue;
}
@@ -417,7 +419,9 @@ void releaseparam(struct clientparam * param) {
if(param->filters[param->nfilters].filter->filter_clear)
(*param->filters[param->nfilters].filter->filter_clear)(param->filters[param->nfilters].data);
}
/* once: a second release must not give the slot back again */
if(param->connlim) stopconnlims(param);
param->connlim = 0;
/* a slot held in the newest service on the listener after a reload */
if(param->newsrv){
slotrelease(param->newsrv);
+79
View File
@@ -86,6 +86,69 @@ char * printopts(char *sep){
}
char featsbuf[1024];
/* The features of this build, by the names the manual and the test suite
know them, so a user can see what a binary was made with. */
char * printfeatures(char *sep){
int pos=0;
#define ADDFEATURE(x) pos += sprintf(featsbuf+pos,"%s%s",pos?sep:"",x)
#ifdef WITH_SSL
ADDFEATURE("ssl");
#ifdef WITH_WOLFSSL
ADDFEATURE("wolfssl");
#else
ADDFEATURE("openssl");
#endif
#endif
#ifndef NORADIUS
ADDFEATURE("radius");
#endif
#ifdef WITH_PCRE
ADDFEATURE("pcre");
#endif
#ifndef NOIPV6
ADDFEATURE("ipv6");
#endif
#ifdef WITH_UN
ADDFEATURE("unix");
#endif
#ifdef WITH_HTTPSRV
ADDFEATURE("httpsrv");
#endif
#ifdef WITH_TRANSPARENT
ADDFEATURE("transparent");
#endif
#ifdef WITH_NETFILTER
ADDFEATURE("netfilter");
#endif
#ifdef WITH_PF
ADDFEATURE("pf");
#endif
#ifdef WITH_ODBC
ADDFEATURE("odbc");
#endif
#ifdef WITH_FTP
ADDFEATURE("ftppr");
#endif
#ifdef WITH_POP3P
ADDFEATURE("pop3p");
#endif
#ifdef WITH_SMTPP
ADDFEATURE("smtpp");
#endif
#ifdef WITH_IMAPP
ADDFEATURE("imapp");
#endif
#ifndef NOPLUGINS
ADDFEATURE("plugins");
#endif
#undef ADDFEATURE
return featsbuf;
}
/* A comma separated list of options, each NAME or NAME=VALUE; a name alone
stands for 1, or for TCP_MAXSEG for the value of maxseg. Options are added
to what is already set, so a default is changed only by naming it, and
@@ -221,6 +284,7 @@ static int srvprepare(struct srvstart *s, int argc, char **argv){
" association: 1 - log, 2 - authorize, 3 - both (default), 0 (same as -U) -\n"
" neither. The first destination is always authorized and logged\n"
#endif
" -B split the TLS ClientHello passed through tlspr at the SNI (DPI bypass)\n"
"-g(GRACE_TRAFF,GRACE_NUM,GRACE_DELAY) - delay GRACE_DELAY milliseconds before polling if average polling size below GRACE_TRAFF bytes and GRACE_NUM read operations in single directions are detected within 1 second to minimize polling\n"
" -fFORMAT logging format (see documentation)\n"
" -l log to stdout\n"
@@ -486,6 +550,19 @@ static int srvprepare(struct srvstart *s, int argc, char **argv){
case 'U':
srv->udpauth = *(argv[i]+2)? atoi(argv[i]+2) : 0;
break;
case 'm':
/* udptotcp: which handshake the target is spoken to with */
if(srv->service == S_UDPTOTCP)
srv->s_option = argv[i][2]? atoi(argv[i]+2) : 1;
else error = 1;
break;
case 'B':
/* the TLS ClientHello split at the SNI (tlspr), which -s is
where -s is not splice; s_option means something else
for these */
if(!s->isudp && srv->service != S_ADMIN && srv->service != S_HTTPSRV)
srv->s_option = 1 + atoi(argv[i]+2);
break;
case 's':
#ifdef WITHSPLICE
/* admin is an httpsrv, where -s is the limited mode */
@@ -1132,6 +1209,8 @@ void freeacl(struct ace *ac){
for(ipl = ac->src; ipl; ipl = (struct iplist *)itfree(ipl, ipl->next));
for(ipl = ac->dst; ipl; ipl = (struct iplist *)itfree(ipl,ipl->next));
for(pl = ac->ports; pl; pl = (struct portlist *)itfree(pl, pl->next));
for(pl = ac->viaports; pl; pl = (struct portlist *)itfree(pl, pl->next));
for(ipl = ac->viasrc; ipl; ipl = (struct iplist *)itfree(ipl, ipl->next));
for(pel = ac->periods; pel; pel = (struct period *)itfree(pel, pel->next));
for(ul = ac->users; ul; ul = (struct userlist *)itfree(ul, ul->next)){
if(ul->user)free(ul->user);
+165 -20
View File
@@ -289,26 +289,30 @@ static int bindtimeopt(const char *name){
!strcmp(name, "TCP_FASTOPEN");
}
/* Whether a socket with the options of l can be made one with those of srv:
/* Whether a socket with the options of l can be made one with those of b:
the same bind-time ones, with the same values; TCP_MAXSEG, whose default
is not 0, cannot be turned off again. */
static int sameopts(struct listener *l, struct srvparam *srv){
const struct sockoptset *a = &l->opts, *b = &srv->lissockopts;
static int sameoptset(struct listener *l, const struct sockoptset *b){
const struct sockoptset *a = &l->opts;
int i;
for(i = 0; sockopts[i].optname && i < MAXSOCKOPTS; i++){
unsigned bit = 1u << i;
for(i = 0; sockopts[i].optname && i < MAXSOCKOPTS; i++){
unsigned bit = 1u << i;
if(bindtimeopt(sockopts[i].optname)){
if((a->set & bit) != (b->set & bit)) return 0;
if((a->set & bit) && a->value[i] != b->value[i]) return 0;
}
if(bindtimeopt(sockopts[i].optname)){
if((a->set & bit) != (b->set & bit)) return 0;
if((a->set & bit) && a->value[i] != b->value[i]) return 0;
}
#ifdef TCP_MAXSEG
else if(sockopts[i].opt == TCP_MAXSEG && *sockopts[i].optname == 'T' &&
(a->set & bit) && !(b->set & bit)) return 0;
else if(sockopts[i].opt == TCP_MAXSEG && *sockopts[i].optname == 'T' &&
(a->set & bit) && !(b->set & bit)) return 0;
#endif
}
return 1;
}
return 1;
}
static int sameopts(struct listener *l, struct srvparam *srv){
return sameoptset(l, &srv->lissockopts);
}
/* Sets the options of srv on the socket of l taken over: those given, and
@@ -345,6 +349,32 @@ static int samelistener(struct listener *l, struct srvparam *srv, int isudp){
sameopts(l, srv);
}
/* samelistener without the options: the address, and what else makes a
socket of a place. */
static int samelistener_noopts(struct listener *l, struct srvparam *srv, int isudp){
if(l->isudp != isudp || l->cbdest) return 0;
#ifdef __linux__
if(!samestr(l->netns, srv->inetns)) return 0;
#endif
#if defined SO_BINDTODEVICE || defined IP_BOUND_IF
if(!samestr(l->device, srv->ibindtodevice)) return 0;
#endif
return SASIZE(&l->sa) == SASIZE(&srv->intsa) &&
!memcmp(&l->sa, &srv->intsa, SASIZE(&srv->intsa));
}
/* Whether a service takes over a reserved port: the socket is bound
already, so the options which act only before bind() cannot follow the
service's wishes — it must name them the same, or not name them at all.
The rest of its options are set on the socket when it is taken. */
/* Whether a service takes over a reserved port: the socket is bound
already, so it is what the reservation made of it — the options which
act only before bind() can follow neither's wishes but their author's,
and the service's other options are set on it when it is taken. */
static int samereservation(struct listener *l, struct srvparam *srv, int isudp){
return samelistener_noopts(l, srv, isudp);
}
/* Whether s goes on listener l: one connecting back (-r) on the
pseudo-listener of the place it connects to, any other on the socket for
its address. */
@@ -410,14 +440,24 @@ void mainclaim(void *service){
}
_3proxy_mutex_lock(&listener_mutex);
for(l = listeners; l; l = l->next){
if(!l->owners || !listenerfor(l, s)) continue;
if(listenerhas(l, srv->config)){
found = l;
break;
/* a reserved port: no service of it, its socket open; a service
of the address takes it over. A listener whose services are
gone, their last clients draining, has no socket to give */
if(!l->owners){
if(l->sock != INVALID_SOCKET && samereservation(l, srv, s->isudp)){
found = l;
break;
}
continue;
}
if(!listenerfor(l, s)) continue;
if(listenerhas(l, srv->config)){
found = l;
break;
}
if(!found || (l->owners->service == srv->service && found->owners->service != srv->service))
found = l;
}
if(!found || (l->owners->service == srv->service && found->owners->service != srv->service))
found = l;
}
if(!found && (found = newl)){
newl = NULL;
found->next = listeners;
@@ -502,6 +542,111 @@ static void slotrelease(struct srvparam *srv){
_3proxy_mutex_unlock(&srv->counter_mutex);
}
/* The port command: the listening socket opened here, at the time the
configuration is read, while the rights to open a privileged port may
still be had — before setuid and chroot. A service of the configuration
on the same address, of the same type, takes the socket over when it
starts; a port no service takes stays reserved while the configuration
in force has it: a reload drops it unless the new configuration
reserves it anew or a service of it claims it — after chroot only the
usage of the socket keeps it. A reservation of the configuration
before already holds the port: its socket is shared, the holds dropped
when the configurations that made them are left or a reload without
a claim on it comes. NULL if the socket cannot be opened. */
void * mainreserve(int isudp, PROXYSOCKADDRTYPE *sa, const struct sockoptset *opts, int maxseg){
struct listener *l, *nl;
SOCKET sock;
if(!(nl = malloc(sizeof(*nl)))) return NULL;
memset(nl, 0, sizeof(*nl));
nl->isudp = isudp;
nl->sa = *sa;
nl->opts = *opts;
nl->maxseg = maxseg;
/* older than the configuration being read: a service taking the
socket over applies its own options to it, as one of a
configuration before does */
nl->optversion = conf->version - 1;
nl->sock = INVALID_SOCKET;
_3proxy_mutex_lock(&listener_mutex);
for(l = listeners; l; l = l->next){
if(l->isudp != isudp || l->cbdest || l->sock == INVALID_SOCKET) continue;
if(SASIZE(&l->sa) != SASIZE(sa) || memcmp(&l->sa, sa, SASIZE(sa))) continue;
if(!sameoptset(l, opts)) continue;
l->users++; /* this reservation's hold with it */
_3proxy_mutex_unlock(&listener_mutex);
free(nl);
return l;
}
sock = so._socket(so.state, SASOCK(sa), isudp? SOCK_DGRAM: SOCK_STREAM,
isudp? IPPROTO_UDP: IPPROTO_TCP);
if(sock == INVALID_SOCKET){
_3proxy_mutex_unlock(&listener_mutex);
free(nl);
return NULL;
}
setopts(sock, opts, maxseg);
#ifndef _WIN32
fcntl(sock, F_SETFL, O_NONBLOCK | fcntl(sock, F_GETFL));
#else
{
unsigned long ul = 1;
ioctlsocket(sock, FIONBIO, &ul);
}
#endif
if(so._bind(so.state, sock, (struct sockaddr *)sa, SASIZE(sa)) == -1 ||
(!isudp && so._listen(so.state, sock, 1+(conf->maxchild>>3)) == -1)){
so._closesocket(so.state, sock);
_3proxy_mutex_unlock(&listener_mutex);
free(nl);
return NULL;
}
nl->sock = sock;
nl->users = 1; /* the reservation's hold */
_3proxy_mutex_init(&nl->open_mutex);
_3proxy_mutex_init(&nl->count_mutex);
nl->next = listeners;
listeners = nl;
_3proxy_mutex_unlock(&listener_mutex);
return nl;
}
/* The configuration which made the reservation is left: its hold on the
listener is given back, the socket closed and the listener freed by
whoever lets go of it last, a reservation or the clients of a service. */
void maindropreserved(void *v){
struct listener *l = (struct listener *)v, **lp;
SOCKET sock = INVALID_SOCKET;
struct udpsession *hand = NULL;
int last;
_3proxy_mutex_lock(&listener_mutex);
last = !--l->users;
if(last) for(lp = &listeners; *lp; lp = &(*lp)->next) if(*lp == l){
*lp = l->next;
sock = l->sock;
l->sock = INVALID_SOCKET;
hand = l->udphand;
l->udphand = NULL;
break;
}
_3proxy_mutex_unlock(&listener_mutex);
#ifndef NOUDPMAIN
udpendall(hand, 26);
#endif
if(sock != INVALID_SOCKET) so._closesocket(so.state, sock);
if(!last) return;
#ifdef WITH_UN
ununlink(&l->sa, l->undev, l->unino);
#endif
_3proxy_mutex_destroy(&l->open_mutex);
_3proxy_mutex_destroy(&l->count_mutex);
if(l->netns) free(l->netns);
if(l->device) free(l->device);
if(l->cbdest) free(l->cbdest);
free(l);
}
/* After a reload, unless noforce: a client goes by the rules of a newest
service of its type on its listener, now accepting there, re-authenticated
as it if auth is set. It takes one of that service's maxconn slots,
+2
View File
@@ -23,6 +23,8 @@ static int cblisten(struct srvstart *s){
return -6;
}
setopts(srv->cbsock, &srv->cbssockopts, srv->maxseg);
/* the clients of the service all wait for it: one accepts what comes */
nonblock(srv->cbsock);
if(srv->so._bind(srv->so.state, srv->cbsock, (struct sockaddr*)&cbsa, SASIZE(&cbsa))==-1) {
dolog(defparam, (unsigned char *)"Failed to bind connect back socket");
+2
View File
@@ -433,7 +433,9 @@ static void udpadopt(struct udpstate *st){
if(param->filters[param->nfilters].filter->filter_clear)
(*param->filters[param->nfilters].filter->filter_clear)(param->filters[param->nfilters].data);
}
/* counted again by the new service's authorization */
if(param->connlim) stopconnlims(param);
param->connlim = 0;
param->bandlimfunc = NULL;
param->bandlims[0] = param->bandlimsout[0] = NULL;
param->trafcountfunc = NULL;
+55 -13
View File
@@ -5,7 +5,7 @@
*/
#include "structures.h"
#include "proxy.h"
#include <string.h>
#define PCRE2_CODE_UNIT_WIDTH 8
#define PCRE2_STATIC
@@ -216,10 +216,19 @@ struct pcre_filter_data {
pcre2_match_data * match_data;
pcre2_match_context * match_context;
int action;
int log;
char * replace;
struct ace *acl;
};
/* What a connection matches with: pcre2_match() writes into its match
data, so a thread matching on the rule's own one would race every
other thread doing the same. */
struct pcre_client_data {
struct pcre_filter_data *pcrefd;
pcre2_match_data * match_data;
};
static void pcre_data_free(struct pcre_filter_data *pcrefd){
_3proxy_mutex_lock(&pcre_mutex);
pcrefd->users--;
@@ -253,16 +262,31 @@ static void* pcre_filter_open(void * idata, struct srvparam * param){
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
int res;
struct ace tmpace;
struct pcre_filter_data *rule = (struct pcre_filter_data *)fo;
struct pcre_client_data *pcd;
*fc = fo;
*fc = NULL;
if(!fo) return PASS;
#define pcrefd ((struct pcre_filter_data *)fo)
if(!pcrefd->acl) return CONTINUE;
memset (&tmpace, 0, sizeof(struct ace));
tmpace.src = pcrefd->acl->src;
res = pl->ACLMatches(&tmpace, param);
#undef pcrefd
return (res)? CONTINUE:PASS;
if(rule->acl){
memset (&tmpace, 0, sizeof(struct ace));
tmpace.src = rule->acl->src;
res = pl->ACLMatches(&tmpace, param);
if(!res) return PASS;
}
/* the connection goes on with a match data of its own */
if(!(pcd = pl->mallocfunc(sizeof(struct pcre_client_data)))){
*fc = NULL;
return rule->action;
}
pcd->pcrefd = rule;
pcd->match_data = NULL;
if(rule->re && !(pcd->match_data = pcre2_match_data_create_from_pattern(rule->re, NULL))){
pl->freefunc(pcd);
*fc = NULL;
return rule->action;
}
*fc = pcd;
return CONTINUE;
}
/* What a rewritten buffer keeps free for its caller to append to. */
@@ -277,8 +301,10 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
char * replace;
char * tmpbuf, *target, *newbuf;
unsigned char *given = *buf_p;
unsigned char *matched;
int nreplaces=0;
#define pcrefd ((struct pcre_filter_data *)fc)
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
#define pcrefd (pcd->pcrefd)
for(acl = pcrefd->acl; acl; acl=acl->next){
if(pl->ACLMatches(acl, param)){
@@ -291,10 +317,18 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
for(; offset < *length_p; nreplaces++){
int repsz;
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcrefd->match_data, pcrefd->match_context);
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcd->match_data, pcrefd->match_context);
if(count <= 0) break;
ovector = pcre2_get_ovector_pointer(pcrefd->match_data);
ovector = pcre2_get_ovector_pointer(pcd->match_data);
if(ovector[0] > (PCRE2_SIZE)*length_p || ovector[1] > (PCRE2_SIZE)*length_p || ovector[1] < ovector[0]) break;
/* What the pattern matched, one record per match: with dunno,log
it is the whole point of the rule */
if(pcrefd->log && (matched = malloc(ovector[1] - ovector[0] + 1))){
memcpy(matched, *buf_p + ovector[0], ovector[1] - ovector[0]);
matched[ovector[1] - ovector[0]] = 0;
dolog(param, matched);
free(matched);
}
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
replen = *length_p - ovector[1];
@@ -379,7 +413,13 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
#undef pcrefd
}
static void pcre_filter_clear(void *fo){
static void pcre_filter_clear(void *fc){
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
if(pcd){
if(pcd->match_data) pcre2_match_data_free(pcd->match_data);
pl->freefunc(pcd);
}
}
static void pcre_filter_close(void *fo){
@@ -464,6 +504,7 @@ int h_pcre(int argc, unsigned char **argv){
memset(flt, 0, sizeof(struct pcre_filter_data));
memset(newf, 0, sizeof(struct filter));
flt->action = action;
flt->log = (strstr((char *)argv[2],"log") != 0);
flt->re = re;
flt->match_data = match_data;
flt->acl = acl;
@@ -578,6 +619,7 @@ int h_pcre_rewrite(int argc, unsigned char **argv){
memset(flt, 0, sizeof(struct pcre_filter_data));
memset(newf, 0, sizeof(struct filter));
flt->action = action;
flt->log = (strstr((char *)argv[2],"log") != 0);
flt->re = re;
flt->match_data = match_data;
flt->acl = acl;
+6 -6
View File
@@ -286,7 +286,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_SMTP_REQ:
case GOT_SMTP_DATA:
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->sostate,fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), fps->fpd.cp->srv->timeouts[STRING_S]);
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), fps->fpd.cp->srv->timeouts[STRING_S]);
fps->state = state;
break;
case GOT_HTTP_REQUEST:
@@ -298,7 +298,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_HTTP_SRVDATA:
if(!fps->serversent){
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), fps->fpd.cp->srv->timeouts[STRING_S]);
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), fps->fpd.cp->srv->timeouts[STRING_S]);
fps->state = state;
}
break;
@@ -306,7 +306,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
case GOT_FTP_REQ:
case GOT_FTP_SRVDATA:
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), fps->fpd.cp->srv->timeouts[STRING_S]);
pl->socksend(NULL, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), fps->fpd.cp->srv->timeouts[STRING_S]);
fps->state = state;
break;
default:
@@ -358,7 +358,7 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
if(fps->serversent >= fps->srvhdrwritten){
sprintf(fps->buf, "%lx\r\n", len);
sendchunk = (int)strlen(fps->buf);
if(pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, fps->fpd.cp->srv->timeouts[STRING_S]) != sendchunk){
if(pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, fps->fpd.cp->srv->timeouts[STRING_S]) != sendchunk){
return -4;
}
}
@@ -397,13 +397,13 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
#endif
return -3;
}
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)fps->buf, res, fps->fpd.cp->srv->timeouts[STRING_S]) != res) {
if(pl->socksend(NULL, sock, (unsigned char *)fps->buf, res, fps->fpd.cp->srv->timeouts[STRING_S]) != res) {
return -4;
}
len -= res;
}
if(sendchunk){
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)"\r\n", 2, fps->fpd.cp->srv->timeouts[STRING_S]) != 2)
if(pl->socksend(NULL, sock, (unsigned char *)"\r\n", 2, fps->fpd.cp->srv->timeouts[STRING_S]) != 2)
return -4;
}
fps->state = state;
+3 -8
View File
@@ -61,14 +61,9 @@ char **load_string(FILE *f,int max_count_str, int *countloadstr,
if (strstr(tmpbuf1,"[end]")==NULL)
{
/* find and replace \n \r*/
rstr = tmpbuf1;
while (*rstr!='\0')
{
if (*rstr=='\r' || *rstr=='\n' )
{ *rstr='\0'; rstr++; }
rstr++;
}
/* the line's end cut off: what the file says with \n is what is
sent */
tmpbuf1[strcspn(tmpbuf1, "\r\n")] = '\0';
while ((rstr=strstr(tmpbuf1,"\\n")))
{
+9
View File
@@ -561,6 +561,15 @@ for(;;){
hdrfree(&buf, &bufown);
hdrsdone = 0;
/* What the request brought belongs to it alone. A connection can carry
a request after another's, so the credentials of an earlier request
decide nothing for this one. */
*param->username = 0;
*param->password = 0;
param->pwtype = 0;
*param->extusername = 0;
*param->extpassword = 0;
if(keepalive && (param->cliinbuf == param->clioffset) && (param->remsock != INVALID_SOCKET)){
memset(fds, 0, sizeof(fds));
fds[0].fd = param->clisock;
+11 -2
View File
@@ -182,7 +182,8 @@ size_t threadstacksize(int extra);
#ifndef strncasecmp
#define strncasecmp strnicmp
#endif
#define seterrno3(x) _set_errno(x)
/* errno is WSAGetLastError() here */
#define seterrno3(x) WSASetLastError(x)
#else
#define seterrno3(x) (errno = x)
#endif
@@ -317,7 +318,7 @@ struct udploop {
uint64_t monotime(void);
int udpanswer(struct udploop *u, struct clientparam *param, unsigned char *buf, int len);
extern const struct udpservice udppmservice, dnsprservice;
extern const struct udpservice udppmservice, dnsprservice, udptotcpservice;
int socks5_setaddr(int family, int atyp, const unsigned char *addr, PROXYSOCKADDRTYPE *sa);
/* which of a service's network namespaces a socket is made in */
#define NS_IN 0 /* -ni: what faces the clients */
@@ -332,6 +333,8 @@ int nsbroken(void);
/* a function everywhere, never a macro: its callers have preprocessor
lines among its arguments */
SOCKET nssocket(struct srvparam *srv, struct sockfuncs *sf, void *state, int side, int domain, int type, int protocol);
void nonblock(SOCKET sock);
int acceptagain(void);
int socksend(struct clientparam *param, SOCKET sock, unsigned char * buf, int bufsize, int to);
int socksendto(struct clientparam *param, SOCKET sock, struct sockaddr * sin, unsigned char * buf, int bufsize, int to);
int sockrecvfrom(struct clientparam *param, SOCKET sock, struct sockaddr * sin, unsigned char * buf, int bufsize, int to);
@@ -464,6 +467,7 @@ void hashdelete(struct hashtable *ht, void* name);
int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl);
int parsehost(int family, unsigned char *host, struct sockaddr *sa);
int badhostname(const char *hostname);
int parsehostname(char *hostname, struct clientparam *param, uint16_t port);
int parseusername(char *username, struct clientparam *param, int extpasswd);
int parseconnusername(char *username, struct clientparam *param, int extpasswd, uint16_t port);
@@ -558,6 +562,7 @@ void * smtppchild(struct clientparam * param);
void * proxychild(struct clientparam * param);
void * sockschild(struct clientparam * param);
void * tcppmchild(struct clientparam * param);
void * tcptoudpchild(struct clientparam * param);
void * autochild(struct clientparam * param);
#ifdef WITH_HTTPSRV
int op_admin(struct httpreq *r, const unsigned char *params);
@@ -624,6 +629,10 @@ extern struct socketoptions {
int getopts(const char *s, struct sockoptset *opts);
void setopts(SOCKET s, const struct sockoptset *opts, int maxseg);
char * printopts(char *sep);
char * printfeatures(char *sep);
void * mainreserve(int isudp, PROXYSOCKADDRTYPE *sa, const struct sockoptset *opts, int maxseg);
void maindropreserved(void *listener);
void setmark(struct clientparam *param, SOCKET sock);
#ifdef _WINCE
char * CEToUnicode (const char *str);
+14 -5
View File
@@ -177,7 +177,13 @@ static uint32_t udpresolvec(struct extparam *c, int af, unsigned char * name, un
continue; /* question does not match the query */
}
if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
return 0;
switch(buf[3] & 0x0F){
case 0: /* the name has no address */
case 3: /* the name is not there */
return 0;
default: /* the server failed: ask the next one */
continue;
}
}
for(k = 13; k<len && buf[k]; k++) {
}
@@ -188,6 +194,7 @@ static uint32_t udpresolvec(struct extparam *c, int af, unsigned char * name, un
k += 4;
if(na > 255) na = 255; /* somebody is very evil */
for (j = 0; j < na; j++) { /* now there should be answers */
if(k >= len) break;
while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
if(!buf[k]) k--;
if((k+(af == AF_INET6?28:16)) > len) {
@@ -216,12 +223,14 @@ static uint32_t udpresolvec(struct extparam *c, int af, unsigned char * name, un
k+= (12 + flen);
continue; /* we need A PTR */
}
for (s2 = buf + k + 12; s2 < (buf + k + 12 + len) && *s2; ){
s1 = s2 + ((unsigned)*s2) + 1;
s1 = buf + k + 12 + flen; /* the end of this record's data, inside the answer */
for (s2 = buf + k + 12; s2 < s1 && *s2 && *s2 < 64; ){
unsigned char *next = s2 + ((unsigned)*s2) + 1;
*s2 = '.';
s2 = s1;
s2 = next;
}
*s2 = 0;
if(s2 >= s1 || *s2 || s2 == buf + k + 12)
break; /* the name runs past its data, is compressed or empty */
/* a name longer than the field is no name to authenticate */
if(PARAMSTR(param, username, buf + k + 13)) return 0;
+6 -1
View File
@@ -120,7 +120,10 @@ void * sockschild(struct clientparam* param) {
}
res = socks5_setaddr(param->srv->family, c, buf, &param->req);
if(res == 1) {RETURN(997);}
if(res == 2 && command == 1) {RETURN(431);}
/* The null address is no destination to connect to, except in
SOCKS4a, where it says that the destination is the name which
follows it. */
if(res == 2 && ver == 5 && command == 1) {RETURN(431);}
param->sinsr = param->req;
myinet_ntop(*SAFAMILY(&param->sinsr), SAADDR(&param->sinsr), (char *)buf, 64);
break;
@@ -138,6 +141,7 @@ void * sockschild(struct clientparam* param) {
default:
RETURN(997);
}
if(badhostname((char *)buf)) {RETURN(21);}
if(PARAMSTR(param, hostname, buf)){RETURN(21);}
if (ver == 5) {
if ((res = sockgetcharcli(param, param->srv->timeouts[SINGLEBYTE_S], 0)) == EOF) {RETURN(441);}
@@ -157,6 +161,7 @@ void * sockschild(struct clientparam* param) {
param->service = S_SOCKS45;
if(sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 1, 0, param->srv->timeouts[STRING_S]) < 0) {RETURN(441);}
buf[127] = 0;
if(badhostname((char *)buf)) {RETURN(21);}
if(PARAMSTR(param, hostname, buf)){RETURN(21);}
if(!getip46m(param->srv->resolvmode, param->srv->family, buf, (struct sockaddr *) &param->req)) RETURN(100);
param->sinsr = param->req;
+41 -5
View File
@@ -75,6 +75,9 @@ static int ktls = 0;
struct SSLsock {
SOCKET s;
SSL_CONN conn;
/* what a read and a write which could not be done wait for, POLLIN
or POLLOUT, 0 once one is: TLS may have to write to read */
short rwant, wwant;
};
struct SSLstate {
@@ -103,10 +106,12 @@ static void addSSL(
if (cli_s != INVALID_SOCKET){
SOSTATE->cli.s = cli_s;
SOSTATE->cli.conn = cli_conn;
SOSTATE->cli.rwant = SOSTATE->cli.wwant = 0;
}
if (srv_s != INVALID_SOCKET){
SOSTATE->srv.s = srv_s;
SOSTATE->srv.conn = srv_conn;
SOSTATE->srv.rwant = SOSTATE->srv.wwant = 0;
}
}
@@ -137,12 +142,14 @@ static ssize_t ssl_send(void *state, SOCKET s, const void *msg, size_t len, int
int res, err;
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
if (err == SSL_ERROR_WANT_WRITE){
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
seterrno3(EAGAIN);
return -1;
}
else seterrno3(err);
}
else sslq->wwant = 0;
return res;
}
@@ -159,14 +166,16 @@ static ssize_t ssl_sendto(void *state, SOCKET s, const void *msg, size_t len, in
if ((sslq = searchSSL(state, s))){
int res, err;
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0) {
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
if (err == SSL_ERROR_WANT_WRITE){
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
seterrno3(EAGAIN);
return -1;
}
else seterrno3(err);
}
else sslq->wwant = 0;
return res;
}
@@ -184,12 +193,14 @@ static ssize_t ssl_recvfrom(void *state, SOCKET s, void *msg, size_t len, int f
int res, err;
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
if (err == SSL_ERROR_WANT_READ) {
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
seterrno3(EAGAIN);
return -1;
}
else seterrno3(err);
}
else sslq->rwant = 0;
return res;
}
return sso._recvfrom(sso.state, s, msg, len, flags, from, fromlen);
@@ -206,12 +217,14 @@ static ssize_t ssl_recv(void *state, SOCKET s, void *msg, size_t len, int flags)
int res, err;
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
if (err == SSL_ERROR_WANT_READ) {
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
seterrno3(EAGAIN);
return -1;
}
else seterrno3(err);
}
else sslq->rwant = 0;
return res;
}
@@ -236,6 +249,8 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
struct SSLsock *sslq = NULL;
unsigned int i;
int ret = 0;
short own[64], *events = own, ev;
for(i = 0; i < nfds; i++){
if((fds[i].events & POLLIN) && (sslq = searchSSL(state, fds[i].fd)) && ssl_pending(sslq->conn)){
fds[i].revents = POLLIN;
@@ -244,8 +259,29 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
else fds[i].revents = 0;
}
if(ret) return ret;
for(i = 0; i < nfds; i++) if((sslq = searchSSL(state, fds[i].fd)) && (sslq->rwant || sslq->wwant)) break;
if(i == nfds) return sso._poll(state, fds, nfds, timeout);
/* A read or a write TLS could not do waits for what TLS needs, a read
for the socket to be writable: whatever that gets is the caller's
chance to try again, revents what it asked for, and its events are
given back as they were. */
if(nfds > sizeof(own)/sizeof(own[0]) && !(events = malloc(nfds * sizeof(*events)))) return -1;
for(i = 0; i < nfds; i++){
events[i] = fds[i].events;
if(!(sslq = searchSSL(state, fds[i].fd))) continue;
ev = fds[i].events & ~(POLLIN|POLLOUT);
if(fds[i].events & POLLIN) ev |= sslq->rwant? sslq->rwant : POLLIN;
if(fds[i].events & POLLOUT) ev |= sslq->wwant? sslq->wwant : POLLOUT;
fds[i].events = ev;
}
ret = sso._poll(state, fds, nfds, timeout);
for(i = 0; i < nfds; i++){
if(ret > 0 && fds[i].events != events[i] && (fds[i].revents & ~(POLLERR|POLLHUP|POLLNVAL)))
fds[i].revents = events[i] | (fds[i].revents & (POLLERR|POLLHUP|POLLNVAL));
fds[i].events = events[i];
}
if(events != own) free(events);
return ret;
}
+8 -8
View File
@@ -32,20 +32,20 @@ unsigned char * strings[] = {
/* 19 */ (unsigned char *)"TLSPR",
/* 20 */ (unsigned char *)"IMAPP",
/* 21 */ (unsigned char *)"HTTPSRV",
/* 22 */ (unsigned char *)"ZOMBIE",
/* 23 */ NULL,
/* 24 */ NULL,
/* 22 */ (unsigned char *)"TCPTOUDP",
/* 23 */ (unsigned char *)"UDPTOTCP",
/* 24 */ (unsigned char *)"ZOMBIE",
/* 25 */ NULL,
/* 26 */ NULL,
#ifndef TPROXY_CONF
#ifndef _WIN32
/* 25 */ (unsigned char *)"/usr/local/etc/3proxy/3proxy.cfg",
/* 27 */ (unsigned char *)"/usr/local/etc/3proxy/3proxy.cfg",
#else
/* 25 */ (unsigned char *)"3proxy.cfg",
/* 27 */ (unsigned char *)"3proxy.cfg",
#endif
#else
/* 25 */ (unsigned char *)TPROXY_CONF,
/* 27 */ (unsigned char *)TPROXY_CONF,
#endif
/* 26 */ NULL,
/* 27 */ NULL,
/* 28 */ NULL,
/* 29 */ NULL,
/* 30 */ NULL,
+17 -3
View File
@@ -240,6 +240,8 @@ typedef enum {
S_TLSPR,
S_IMAPP,
S_HTTPSRV,
S_TCPTOUDP,
S_UDPTOTCP,
S_ZOMBIE
}PROXYSERVICE;
@@ -447,11 +449,14 @@ struct ace {
int wdays;
int weight;
int nolog;
int mark;
struct period *periods;
struct userlist *users;
struct iplist *src, *dst;
struct hostname *dstnames;
struct portlist *ports;
struct portlist *viaports;
struct iplist *viasrc;
struct chain *chains;
};
@@ -848,6 +853,7 @@ struct clientparam {
int pwtype,
weight,
nolog,
mark,
nolongdatfilter,
nosplice, /* a TLS socket of the connection is not in the kernel */
nooverwritefilter,
@@ -963,9 +969,16 @@ struct threadpool {
extern struct threadpool tpool;
struct filemon {
char * path;
struct stat sb;
struct filemon *next;
char * path;
struct stat sb;
struct filemon *next;
};
/* A port the configuration reserved with the port command: its listener,
opaque here, held until the configuration is left */
struct portreservation {
struct portreservation *next;
void *listener;
};
@@ -1020,6 +1033,7 @@ struct extparam {
int refs;
struct hashtable pwl_table; /* users */
int resolvmode; /* RESOLVE_*: the last read, each service taking the one read before it */
struct portreservation *reservations; /* the port command's, dropped with the configuration */
};
struct property {
+230
View File
@@ -0,0 +1,230 @@
/*
3APA3A simplest proxy server
(c) 2002-2026 by Vladimir Dubrovin <vlad@3proxy.org>
please read License Agreement
*/
#include "proxy.h"
#include "udptunnel.h"
#ifndef PORTMAP
#define PORTMAP
#endif
#define RETURN(xxx) { param->res = xxx; goto CLEANRET; }
/* tcptoudp: a TCP connection in, datagrams out, to the one target the
service is given. What the connection carries is datagrams with
their length in front of them (udptunnel.h); the handshake a client
speaks, udptunnel's or ProxyGuard's, is recognised and answered. A
parent the ACL gives is a SOCKS UDP relay, as for udppm. */
/* what the connection's first bytes have said, or not yet */
enum { HS_MAYBE, HS_RAW, HS_TUNNEL, HS_HTTP };
/* ProxyGuard's server answer, which ends its handshake */
static const unsigned char tcptoudp101[] =
"HTTP/1.1 101 Switching Protocols\r\n"
"Connection: Upgrade\r\n"
"Upgrade: " UDPTUN_PROTO "\r\n"
"\r\n";
/* A datagram of the client, from buf, on to the target or the first
relay of a chain, the headers of the hops after it and of the target
in front of it: as udppm sends one. */
static void tcptoudpforward(struct clientparam *param, unsigned char *data, int len){
int i, off = 0;
if(param->bandlimfunc && (*param->bandlimfunc)(param, 0, len)) return;
if(param->udp_nhops){
for(i = 1; i < param->udp_nhops; i++)
off += socks5_udp_build_hdr(param->clibuf + off, &param->udp_relay[i-1]);
off += socks5_udp_build_hdr(param->clibuf + off, &param->req);
}
if(len > param->clibufsize - off) len = param->clibufsize - off;
memcpy(param->clibuf + off, data, len);
param->srv->so._sendto(param->sostate, param->remsock, (char *)param->clibuf, off + len, 0,
(struct sockaddr *)&param->sinsr, SASIZE(&param->sinsr));
param->statscli64 += len;
param->nwrites++;
}
/* The datagrams framed in b[0..*len): each on to the target, what is
left of one moved to the front. 0, or the res of a framing no
datagram can be (a length the buffers cannot hold). */
static int tcptoudpframes(struct clientparam *param, unsigned char *b, int *len){
int off = 0, n;
while(*len - off >= UDPTUN_HDR){
n = udptunget(b + off);
if(n > param->srvbufsize - UDPTUN_HDR) return 483;
if(*len - off < UDPTUN_HDR + n) break;
tcptoudpforward(param, b + off + UDPTUN_HDR, n);
off += UDPTUN_HDR + n;
}
if(off){
memmove(b, b + off, *len - off);
*len -= off;
}
return 0;
}
/* Where the end of a handshake's header block was looked for up to */
static int tcptoudphdrend(unsigned char *b, int from, int len){
int i;
for(i = from; i + 3 < len; i++)
if(b[i] == '\r' && b[i+1] == '\n' && b[i+2] == '\r' && b[i+3] == '\n') return i;
return -1;
}
static int tcptoudpmap(struct clientparam *param, int timeo){
struct pollfd fds[2];
PROXYSOCKADDRTYPE from;
SASIZETYPE size;
unsigned char *b = param->srvbuf;
int bufsize = param->srvbufsize;
int len = 0, res, n, hs = HS_MAYBE, hscan = 0;
for(;;){
fds[0].fd = param->clisock;
fds[0].events = POLLIN;
fds[0].revents = 0;
fds[1].fd = param->remsock;
fds[1].events = POLLIN;
fds[1].revents = 0;
res = param->srv->so._poll(param->sostate, fds, 2, timeo * 1000);
if(res < 0) return 481;
if(res == 0) return 92;
/* a reload: the session goes by the newest configuration's
rules, as a connection of sockmap() does */
if(param->version < runconf->version) {
if(param->srv->noforce || !reattachfunc) param->version = runconf->version;
else if((n = (*reattachfunc)(param, 1)) && n != 2) return n;
}
if(fds[0].revents){
n = (int)param->srv->so._recvfrom(param->sostate, param->clisock,
(char *)b + len, bufsize - len, 0, NULL, NULL);
if(n == 0) return 0;
if(n < 0){
if(errno == EAGAIN || errno == EINTR) n = 0;
else return 482;
}
len += n;
/* the handshake, until the first bytes tell which */
if(hs == HS_MAYBE){
/* 'G' of "GET " or 'u' of "udptunnel by ", or neither */
if(len >= 1 && b[0] != 'G' && b[0] != 'u') hs = HS_RAW;
else if(len >= 4){
if(!memcmp(b, "GET ", 4)) hs = HS_HTTP;
else if(!memcmp(b, "udpt", 4)) hs = HS_TUNNEL;
else hs = HS_RAW;
}
}
if(hs == HS_TUNNEL){
if(len < UDPTUN_MAGIC_LEN) continue;
memmove(b, b + UDPTUN_MAGIC_LEN, len - UDPTUN_MAGIC_LEN);
len -= UDPTUN_MAGIC_LEN;
hs = HS_RAW;
}
else if(hs == HS_HTTP){
n = tcptoudphdrend(b, hscan > 3? hscan - 3 : 0, len);
if(n < 0){
hscan = len;
if(len >= UDPTUN_MAXHDR || len >= bufsize) return 484;
continue;
}
/* the header block names the protocol or it is not
ProxyGuard asking */
if(!udptunprotoin(b, n)) return 484;
if(socksend(param, param->clisock, (unsigned char *)tcptoudp101,
(int)sizeof(tcptoudp101) - 1, timeo) != (int)sizeof(tcptoudp101) - 1)
return 487;
memmove(b, b + n + 4, len - n - 4);
len -= n + 4;
hs = HS_RAW;
}
if((res = tcptoudpframes(param, b, &len))) return res;
/* a datagram longer than the buffer is no client's */
if(len == bufsize) return 483;
}
if(fds[1].revents){
int k, next, off = 0;
size = sizeof(from);
n = (int)param->srv->so._recvfrom(param->sostate, param->remsock,
(char *)param->clibuf + UDPTUN_HDR, param->clibufsize - UDPTUN_HDR, 0,
(struct sockaddr *)&from, &size);
if(n < 0 && (errno == EAGAIN || errno == EINTR)) continue;
#ifdef _WIN32
/* an earlier datagram was refused (ICMP): not fatal */
if(n < 0 && WSAGetLastError() == WSAECONNRESET) continue;
#endif
if(n <= 0) return 486;
if(!param->udp_nhops){
/* none but the target itself */
if(!SAISNULL(&param->sinsr) && *SAPORT(&param->sinsr) &&
(SAADDRLEN(&from) != SAADDRLEN(&param->sinsr) ||
memcmp(SAADDR(&from), SAADDR(&param->sinsr), SAADDRLEN(&from)) ||
memcmp(SAPORT(&from), SAPORT(&param->sinsr), 2)))
return 0;
}
else for(k = 0; k < param->udp_nhops; k++){
if((next = socks5_udp_skip_hdr(param->clibuf + UDPTUN_HDR + off, n - off)) < 0) break;
off += next;
}
if(off) n -= off;
param->statssrv64 += n;
param->nreads++;
if(param->bandlimfunc && (*param->bandlimfunc)(param, n, 0)) continue;
udptunput(param->clibuf, n);
if(socksend(param, param->clisock, param->clibuf, n + UDPTUN_HDR, timeo) != n + UDPTUN_HDR)
return 487;
}
}
}
void *tcptoudpchild(struct clientparam* param) {
int res;
if(!*param->hostname){
if(parsehostname((char *)param->srv->target, param, ntohs(param->srv->targetport))) RETURN(100);
}
param->sinsl = *SAFAMILY(&param->req) == AF_INET6? param->srv->extsa6 : param->srv->extsa;
*SAPORT(&param->sinsl) = 0;
param->sinsr = param->req;
param->operation = UDPASSOC;
res = (*param->srv->authfunc)(param);
if(res) {RETURN(res);}
if (param->npredatfilters){
int action;
action = handlepredatflt(param);
if(action == HANDLED) RETURN(0);
if(action != PASS) RETURN(19);
}
if(param->redirectfunc){
return (void *)param->redirectfunc;
}
if((res = udpbind(param))) RETURN(res);
RETURN(tcptoudpmap(param, param->srv->timeouts[CONNECTION_L]));
CLEANRET:
dolog(param, *param->hostname? param->hostname : NULL);
return (NULL);
}
#ifdef WITHMAIN
struct proxydef childdef = {
tcptoudpchild,
0,
0,
S_TCPTOUDP,
" the handshake a client speaks, udptunnel's or ProxyGuard's, is answered\n",
NULL
};
#include "proxymain.c"
#endif
+14 -10
View File
@@ -224,6 +224,7 @@ int parsehello(int type, unsigned char *hello, unsigned len, char *sni, int * sn
else if(type == 2){
offset += 3;
}
if((offset + 2) > len) return -6;
elen = size16(hello+offset);
offset += 2;
if(elen+offset != len) return -9;
@@ -300,6 +301,7 @@ void * tlsprchild(struct clientparam* param) {
int lv=-1;
char proto[PROTOLEN]="-";
int snipos = 0;
int snlen = 0;
PROXYSERVICE stlsproto = param->clientstarttls? param->clientstarttls :
(param->starttls? param->starttls : param->srv->srvstarttls);
@@ -321,16 +323,7 @@ void * tlsprchild(struct clientparam* param) {
if(PARAMSTR(param, hostname, sni)) RETURN (100);
}
else if (parsehostname(sni, param, param->srv->targetport? ntohs(param->srv->targetport):starttlsport(stlsproto))) RETURN (100);
if(param->srv->s_option && snipos && res > 1){
int len;
len = socksend(param, param->remsock, param->clibuf+param->clioffset,snipos + (res/2), param->srv->timeouts[STRING_S]);
if(len != snipos + (res/2)){
RETURN(310);
}
param->clioffset += snipos + (res/2);
}
snlen = res;
}
else if (res < 0 && param->srv->requirecert) RETURN(310-res);
}
@@ -350,6 +343,17 @@ void * tlsprchild(struct clientparam* param) {
return (void *)param->redirectfunc;
}
if(param->srv->s_option && snipos && snlen > 1){
int len;
len = socksend(param, param->remsock, param->clibuf+param->clioffset,snipos + (snlen/2), param->srv->timeouts[STRING_S]);
if(len != snipos + (snlen/2)){
RETURN(310);
}
param->clioffset += snipos + (snlen/2);
}
if(stlsproto){
res = srvstarttls(param, stlsproto);
if(res){
+9 -4
View File
@@ -105,6 +105,7 @@ int udpbind(struct clientparam *param)
s = nssocket(param->srv, &param->srv->so, param->sostate, NS_OUT, SASOCK(&param->sinsl), SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) return 11;
setmark(param, s);
#ifdef _WIN32
{ unsigned long ul = 1; ioctlsocket(s, FIONBIO, &ul); }
#else
@@ -152,8 +153,10 @@ static void udpreset(struct clientparam *param)
/*
* Authorize param->req and (re)build the server side of the association:
* a parent proxy chain and/or an external address may be selected by the ACL.
* Returns the authorization result. param->remsock is INVALID_SOCKET if the
* socket can not be created, in this case the association can not continue.
* Returns the authorization result. param->remsock is INVALID_SOCKET when
* the authorization refused the association or the socket can not be
* created; the association can not continue then, so that a parent the
* rules demand is never quietly replaced by a direct relay.
*/
static int udpreconnect(struct clientparam *param)
{
@@ -179,9 +182,10 @@ static int udpreconnect(struct clientparam *param)
param->remsock = INVALID_SOCKET;
}
udpreset(param);
return res;
}
if (udpbind(param)) return res? res : 11;
return res;
if (udpbind(param)) return 11;
return 0;
}
int udpsockmap(struct clientparam *param, int timeo)
@@ -271,6 +275,7 @@ int udpsockmap(struct clientparam *param, int timeo)
if (len < 7 + sz) return 485;
memcpy(dstnamebuf, base + 5, sz);
dstnamebuf[sz] = 0;
if (badhostname(dstnamebuf)) continue;
dstname = dstnamebuf;
i = 5 + sz;
if (!getip46m(param->srv->resolvmode, param->srv->family, (unsigned char *)dstnamebuf,
+307
View File
@@ -0,0 +1,307 @@
/*
3APA3A simplest proxy server
(c) 2002-2026 by Vladimir Dubrovin <vlad@3proxy.org>
please read License Agreement
*/
#include "proxy.h"
#include "udptunnel.h"
#ifndef PORTMAP
#define PORTMAP
#endif
#ifndef UDP
#define UDP
#endif
/* udptotcp: datagrams in, from any number of clients, each client a
session of the service's own (see udploop() in proxymain.c) with a
TCP connection of its own to the target. On the connection the
datagrams carry their length in front of them (udptunnel.h); -m
sends udptunnel's handshake to the target first, -m2 ProxyGuard's
HTTP Upgrade, -m0 (the default) none. What comes back on the
connection is answered to the client the session is. A parent the
ACL gives is asked for a TCP connection, unlike udppm's UDP relay. */
/* the handshake -m asks for: none, udptunnel's, ProxyGuard's */
enum { U2T_NONE, U2T_TUNNEL, U2T_HTTP };
/* what the session's connection is up to */
enum { U2T_CONNECTING, U2T_ASKING, U2T_RUN };
struct u2t {
int state;
int mode; /* the handshake of U2T_* */
unsigned char *out; /* framed datagrams waiting to be written */
int outlen, outoff, outcap;
unsigned char in[UDPTUN_HDR + UDPBUFSIZE]; /* a datagram being read */
int inlen;
};
/* udptunnel's handshake, "udptunnel by md." of the rfc1036 udptunnel
followed by zeroes and a counting sequence */
static const unsigned char u2tmagic[UDPTUN_MAGIC_LEN] =
"udptunnel by md."
"\0\0\0\001\003\006\020\025\041\050\066\105\125\146\170\221";
/* bytes at the end of the queue, or -1 if the connection is gone */
static int u2tflush(struct clientparam *param, struct u2t *d){
while(d->outoff < d->outlen){
int s = (int)param->srv->so._send(param->sostate, param->remsock,
(char *)d->out + d->outoff, d->outlen - d->outoff, 0);
if(s > 0){ d->outoff += s; continue; }
if(s < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
return -1;
}
return 1;
}
static void u2tcompact(struct u2t *d){
if(d->outoff){
memmove(d->out, d->out + d->outoff, d->outlen - d->outoff);
d->outlen -= d->outoff;
d->outoff = 0;
}
}
/* bytes without a prefix on the queue, a handshake's; -1 without room */
static int u2tput(struct u2t *d, const unsigned char *data, int n){
unsigned char *o;
if(d->outlen + n > d->outcap){
int want = d->outcap? 2 * d->outcap : UDPBUFSIZE;
while(want < d->outlen + n){
int w = 2 * want;
if(w <= want) return -1;
want = w;
}
if(!(o = realloc(d->out, want))) return -1;
d->out = o;
d->outcap = want;
}
memcpy(d->out + d->outlen, data, n);
d->outlen += n;
return 0;
}
/* a datagram, with its length in front of it, on the queue */
static int u2tframe(struct u2t *d, const unsigned char *data, int n){
unsigned char h[UDPTUN_HDR];
udptunput(h, n);
if(u2tput(d, h, UDPTUN_HDR)) return -1;
return u2tput(d, data, n);
}
/* Where the end of a header block was looked for up to */
static int u2thdrend(unsigned char *b, int from, int len){
int i;
for(i = from; i + 3 < len; i++)
if(b[i] == '\r' && b[i+1] == '\n' && b[i+2] == '\r' && b[i+3] == '\n') return i;
return -1;
}
static int udptotcpfirst(struct udploop *u, struct udpsession *ss, unsigned char *buf, int len){
struct clientparam *param = ss->param;
struct u2t *d;
int res;
SOCKET s;
if(parsehostname((char *)param->srv->target, param, ntohs(param->srv->targetport))) return (param->res = 100);
param->sinsl = *SAFAMILY(&param->req) == AF_INET6? param->srv->extsa6 : param->srv->extsa;
*SAPORT(&param->sinsl) = 0;
param->sinsr = param->req;
/* a parent, if the ACL gives one, is asked for a TCP connection */
param->operation = CONNECT;
if((res = (*param->srv->authfunc)(param))) return (param->res = res);
if(!(d = calloc(1, sizeof(*d)))) return (param->res = 21);
ss->data = d;
d->mode = param->srv->s_option == U2T_TUNNEL || param->srv->s_option == U2T_HTTP?
param->srv->s_option : U2T_NONE;
/* the chain walk, if a parent gave a connection, has connected it;
otherwise the session's own is connected as the loop sees it
writable (dnspr asks a name server over TCP the same way) */
if(param->remsock == INVALID_SOCKET){
if((s = nssocket(param->srv, &param->srv->so, param->sostate, NS_OUT, SASOCK(&param->sinsr), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET){
free(d);
ss->data = NULL;
return (param->res = 11);
}
param->remsock = s;
if((*param->srv->so._connect)(param->sostate, s, (struct sockaddr *)&param->sinsr, SASIZE(&param->sinsr))
#ifdef _WIN32
&& WSAGetLastError() != WSAEWOULDBLOCK
#else
&& errno != EINPROGRESS
#endif
){
free(d);
ss->data = NULL;
return (param->res = 12);
}
}
d->state = U2T_CONNECTING;
ss->events = POLLOUT;
ss->deadline = u->now + (uint64_t)param->srv->timeouts[CONNECT_TO] * 1000;
/* the handshake the mode asks for, sent once the connection is
made, the first datagram after it */
if(d->mode == U2T_TUNNEL){
if(u2tput(d, u2tmagic, UDPTUN_MAGIC_LEN)) return (param->res = 21);
}
else if(d->mode == U2T_HTTP){
char req[HOSTNAMELEN + 128];
res = sprintf(req, "GET / HTTP/1.1\r\nHost: %.256s\r\nUser-Agent: 3proxy\r\nConnection: Upgrade\r\nUpgrade: " UDPTUN_PROTO "\r\n\r\n",
(char *)param->srv->target);
if(u2tput(d, (unsigned char *)req, res)) return (param->res = 21);
}
if(!param->bandlimfunc || !(*param->bandlimfunc)(param, 0, len)){
if(u2tframe(d, buf, len)) return (param->res = 21);
param->statscli64 += len;
param->nwrites++;
}
return 0;
}
static int udptotcpclient(struct udploop *u, struct udpsession *ss, unsigned char *buf, int len){
struct clientparam *param = ss->param;
struct u2t *d = ss->data;
if(param->bandlimfunc && (*param->bandlimfunc)(param, 0, len)) return 0;
/* the connection is not taking what it is given */
if(d->outlen - d->outoff > 65536) return (param->res = 487);
if(u2tframe(d, buf, len)) return (param->res = 21);
param->statscli64 += len;
param->nwrites++;
if(d->state == U2T_RUN){
if(u2tflush(param, d) < 0) return (param->res = 487);
u2tcompact(d);
ss->events = d->outoff < d->outlen? POLLIN | POLLOUT : POLLIN;
}
return 0;
}
static int udptotcpserver(struct udploop *u, struct udpsession *ss){
struct clientparam *param = ss->param;
struct u2t *d = ss->data;
int len, n, off, err;
SASIZETYPE elen;
if(d->state == U2T_CONNECTING){
err = 0;
elen = sizeof(err);
if(param->srv->so._getsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_ERROR, (char *)&err, &elen) || err)
return (param->res = 60);
d->state = d->mode == U2T_HTTP? U2T_ASKING : U2T_RUN;
/* the handshake and the datagrams after it */
if(u2tflush(param, d) < 0) return (param->res = 487);
u2tcompact(d);
if(d->state == U2T_RUN){
ss->idle = param->srv->timeouts[STRING_L];
ss->deadline = u->now + (uint64_t)ss->idle * 1000;
ss->events = d->outoff < d->outlen? POLLIN | POLLOUT : POLLIN;
}
else ss->events = POLLIN;
return 0;
}
if(d->state == U2T_ASKING){
/* ProxyGuard's answer: a header block, then the framing */
int i;
len = (int)param->srv->so._recv(param->sostate, param->remsock,
(char *)d->in + d->inlen, (int)sizeof(d->in) - d->inlen, 0);
if(len < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
if(len <= 0) return (param->res = 487);
d->inlen += len;
i = u2thdrend(d->in, (d->inlen - len > 3)? d->inlen - len - 3 : 0, d->inlen);
if(i < 0){
if(d->inlen >= UDPTUN_MAXHDR || d->inlen >= (int)sizeof(d->in)) return (param->res = 63);
return 0;
}
/* a 101 answer naming the protocol */
n = 0;
while(n < i && d->in[n] != ' ') n++;
if(n + 4 > i || memcmp(d->in + n + 1, "101", 3) || !udptunprotoin(d->in, i))
return (param->res = 63);
d->inlen -= i + 4;
if(d->inlen > 0) memmove(d->in, d->in + i + 4, d->inlen);
d->state = U2T_RUN;
ss->idle = param->srv->timeouts[STRING_L];
ss->deadline = u->now + (uint64_t)ss->idle * 1000;
ss->events = d->outoff < d->outlen? POLLIN | POLLOUT : POLLIN;
return 0;
}
/* U2T_RUN: first what waits, then what has come */
if(d->outoff < d->outlen){
if(u2tflush(param, d) < 0) return (param->res = 487);
u2tcompact(d);
ss->events = d->outoff < d->outlen? POLLIN | POLLOUT : POLLIN;
}
len = (int)param->srv->so._recv(param->sostate, param->remsock,
(char *)d->in + d->inlen, (int)sizeof(d->in) - d->inlen, 0);
if(len < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
if(len == 0) return 1; /* the target closed: over */
if(len < 0) return (param->res = 486);
d->inlen += len;
off = 0;
while(d->inlen - off >= UDPTUN_HDR){
n = udptunget(d->in + off);
if(n > UDPBUFSIZE) return (param->res = 483);
if(d->inlen - off < UDPTUN_HDR + n) break;
param->statssrv64 += n;
param->nreads++;
if(!param->bandlimfunc || !(*param->bandlimfunc)(param, n, 0))
udpanswer(u, param, d->in + off + UDPTUN_HDR, n);
off += UDPTUN_HDR + n;
}
if(off){
memmove(d->in, d->in + off, d->inlen - off);
d->inlen -= off;
}
/* half a datagram, and no room for the rest of it */
if(d->inlen == (int)sizeof(d->in)) return (param->res = 483);
return 0;
}
static void udptotcpend(struct udploop *u, struct udpsession *ss){
struct u2t *d = ss->data;
if(d){
free(d->out);
free(d);
ss->data = NULL;
}
dolog(ss->param, NULL);
}
const struct udpservice udptotcpservice = {
1,
udptotcpfirst,
udptotcpclient,
udptotcpserver,
udptotcpend,
92,
NULL
};
#ifdef WITHMAIN
struct proxydef childdef = {
NULL,
0,
1,
S_UDPTOTCP,
" -m - udptunnel handshake with the target, -m2 - ProxyGuard's, -m0 - none\n",
&udptotcpservice
};
#include "proxymain.c"
#endif
+69
View File
@@ -0,0 +1,69 @@
/*
3APA3A simplest proxy server
(c) 2002-2026 by Vladimir Dubrovin <vlad@3proxy.org>
please read License Agreement
*/
/* What the tunnels between TCP and UDP speak, tcptoudp and udptotcp:
datagrams on a TCP connection, each with its length, in network
order, in front of it. udptunnel (the rfc1036 one) and ProxyGuard's
UoTLV/1 (eduVPN) put datagrams on a connection the same way; what
they differ in is what comes first:
- nothing: the framing alone;
- udptunnel's handshake: 32 bytes beginning "udptunnel by ", which
the client sends and no answer follows;
- ProxyGuard's: an HTTP Upgrade, the client asking with "GET",
"Connection: Upgrade" and "Upgrade: UoTLV/1", the server answering
"101 Switching Protocols" before the framing begins.
Which of these a connection speaks is told by its first bytes, "GET"
or "udptunnel by ", so tcptoudp takes any of them from a client;
udptotcp sends the one it was configured to (-m: udptunnel's, -m2:
ProxyGuard's, -m0: none). */
#ifndef _UDPTUNNEL_H
#define _UDPTUNNEL_H
#include <ctype.h>
/* the length of the prefix a datagram carries on the connection */
#define UDPTUN_HDR 2
/* udptunnel's handshake: "udptunnel by md." of the rfc1036 udptunnel,
followed by zeroes and a counting sequence; any 32 bytes beginning
with the prefix are taken, the original Columbia one included */
#define UDPTUN_MAGIC_LEN 32
#define UDPTUN_PREFIX "udptunnel by "
#define UDPTUN_PREFIX_LEN 13
/* ProxyGuard's protocol, as the Upgrade: header names it */
#define UDPTUN_PROTO "UoTLV/1"
/* a header of a handshake is not longer */
#define UDPTUN_MAXHDR 2048
/* the length a datagram's prefix tells */
static int udptunget(const unsigned char *p){
return (p[0] << 8) | p[1];
}
/* the prefix of a datagram of this length */
static void udptunput(unsigned char *p, int n){
p[0] = (unsigned char)(n >> 8);
p[1] = (unsigned char)n;
}
/* whether the bytes of a handshake name the protocol, whatever the
case of the letters */
static int udptunprotoin(const unsigned char *b, int len){
int i, j;
for(i = 0; i + 7 <= len; i++){
for(j = 0; j < 7; j++)
if(tolower(b[i + j]) != tolower((unsigned char)UDPTUN_PROTO[j])) break;
if(j == 7) return 1;
}
return 0;
}
#endif
+3 -3
View File
@@ -1,14 +1,14 @@
#ifndef VERSION
#define VERSION "3proxy-1.1.0-pre1"
#define VERSION "3proxy-1.1.0-pre2"
#endif
#ifndef BUILDDATE
#define BUILDDATE "261024131856"
#define BUILDDATE "261120175134"
#endif
#define MAJOR3PROXY 1
#define SUBMAJOR3PROXY 1
#define MINOR3PROXY 0
#define SUBMINOR3PROXY 0
#define RELEASE3PROXY "3proxy-1.1.0-pre1(" BUILDDATE ")\0"
#define RELEASE3PROXY "3proxy-1.1.0-pre2(" BUILDDATE ")\0"
#ifndef YEAR3PROXY
#define YEAR3PROXY "2026"
#endif
+8
View File
@@ -13,6 +13,14 @@ skips itself when that is missing or the build has no TLS support. With no
`--bin` it looks in `bin/`, then `build/bin/`, then the per-configuration
directories a multi-configuration CMake generator uses.
The binary reports what it was built with in `3proxy --help` (a `built
with:` list), and the runner reads that before the first case: a case names
the features it needs with `if not t.skip_unless("ssl"): return`, and
skips on a build without them instead of failing. A binary too old to
report its features skips every case that needs one, and the cases with no
feature needs still run; some cases also probe at runtime, as a build can
leave a feature compiled in but unusable.
The proxy under test is also the origin server the tests talk to: the `http`
command's `echo` operation reports back how a request arrived - method, path,
query, host, and the source port it came from - and `data` generates a body
+49
View File
@@ -0,0 +1,49 @@
"""The mark command: a rule's connections carry a mark.
mark <number> extends the rule above it like nolog and weight; the
connection it lets through sends with the mark on its sockets towards
the destination. Where the system has no mark (Linux SO_MARK, FreeBSD
SO_USER_COOKIE) the command changes nothing, and what is checked here
is the flow: a rule with a mark serves as one without.
"""
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
t.start("mark_origin", f"""
log
auth iponly
allow *
http data * /data**
httpsrv -p{origin}
""", ports=[origin])
# a rule with a mark serves the connections it lets through
prox = t.free_port()
t.start("mark_rule", f"""
log
auth iponly
allow * * 192.168.0.0/16
allow * * 127.0.0.0/8
mark 20
proxy -p{prox}
""", ports=[prox])
t.eq(200, t.http(f"http://127.0.0.1:{origin}/data",
proxy=f"127.0.0.1:{prox}").status,
"a request matched by a rule with a mark is served")
# a mark of the rule above only: a rule of its own is refused
out = t.run_config("mark_alone", "log\nmark 20\nnot_a_command\n")
t.contains(out, "'mark' failed",
"a mark with no rule above it is refused")
t.not_contains(out, "'not_a_command'",
"and the file stops at the refused line")
# and so is a mark that is not a number
out = t.run_config("mark_word", "log\nallow *\nmark twenty\nnot_a_command\n")
t.contains(out, "Wrong mark",
"a mark that is not a number is refused")
+2
View File
@@ -4,6 +4,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
adm = t.free_port()
lim = t.free_port()
server = t.start("admin", f"""
+3 -1
View File
@@ -7,7 +7,9 @@ handshake and the service supplies the port.
def run(t):
certs = t.certs()
if not t.skip_unless("httpsrv"):
return
certs = t.certs() if t.has("ssl") else None
plain = t.free_port()
port = t.free_port()
secure = t.free_port() if certs else None
+2
View File
@@ -7,6 +7,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
proxy = t.free_port()
adm = t.free_port()
+108
View File
@@ -0,0 +1,108 @@
"""The FTP proxy logging in to its server: whatever the server answers the
login with reaches the client, which waits for the answer to its PASS."""
import socket
import threading
# what the server answers USER with, and PASS if it asks for one
LOGINS = {
"230 to USER": ([b"230 Anonymous user logged in"], None),
"multiline 230 to USER": ([b"230-Welcome", b"230-to the server", b"230 Login successful."], None),
"331 to USER, 230 to PASS": ([b"331 Please specify the password."], [b"230 Login successful."]),
"530 to USER": ([b"530 Not allowed here"], None),
"331 to USER, 530 to PASS": ([b"331 Please specify the password."], [b"530 Login incorrect."]),
}
def ftp_server(listener, user, password):
"""Greets, answers the login as told, then NOOP and QUIT."""
while True:
try:
c, _ = listener.accept()
except OSError:
return
try:
f = c.makefile("rb")
c.sendall(b"220 Fake FTP\r\n")
if not f.readline().upper().startswith(b"USER "):
continue
c.sendall(b"".join(line + b"\r\n" for line in user))
if password is not None:
if not f.readline().upper().startswith(b"PASS "):
continue
c.sendall(b"".join(line + b"\r\n" for line in password))
for line in f:
if line.upper().startswith(b"NOOP"):
c.sendall(b"200 NOOP ok\r\n")
elif line.upper().startswith(b"QUIT"):
c.sendall(b"221 Bye\r\n")
break
else:
c.sendall(b"502 Not implemented\r\n")
except OSError:
pass
finally:
c.close()
def reply(f):
"""The last line of a reply, multiline or not; empty at the end or on a
time out."""
while True:
try:
line = f.readline()
except OSError:
return b""
if not line:
return b""
if len(line) < 4 or line[3:4] != b"-":
return line.rstrip()
def run(t):
if not t.skip_unless("ftppr"):
return
servers = {}
for name, (user, password) in LOGINS.items():
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(5)
threading.Thread(target=ftp_server, args=(listener, user, password), daemon=True).start()
servers[name] = listener
port = t.free_port()
t.start("ftppr", f"""
log
auth none
ftppr -p{port}
""", ports=[port])
# without WITH_FTP the service closes the connection at once
s = socket.create_connection(("127.0.0.1", port), timeout=5)
built = reply(s.makefile("rb"))
s.close()
if not built:
t.skip("the FTP proxy (not built in this configuration)")
for listener in servers.values():
listener.close()
t.stop_all()
return
for name, listener in servers.items():
s = socket.create_connection(("127.0.0.1", port), timeout=5)
f = s.makefile("rb")
reply(f)
s.sendall(b"USER anonymous@127.0.0.1:%d\r\n" % listener.getsockname()[1])
reply(f)
s.sendall(b"PASS test@example.com\r\n")
got = reply(f)
ok = LOGINS[name][1] if LOGINS[name][1] is not None else LOGINS[name][0]
t.eq(ok[-1][:3], got[:3], f"{name}: the client gets the server's answer")
if got.startswith(b"230"):
s.sendall(b"NOOP\r\n")
t.eq(b"200", reply(f)[:3], f"{name}: and the session goes on")
s.close()
for listener in servers.values():
listener.close()
t.stop_all()
+20
View File
@@ -1,7 +1,11 @@
"""Authentication and access rules in front of the HTTP server."""
import base64
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
openport = t.free_port()
t.start("httpsrv_auth", f"""
@@ -47,3 +51,19 @@ def run(t):
t.contains(t.http(url + "/echo", auth=("alice", "secret")), "path=/echo",
"an authenticated request is dispatched")
# --- credentials do not outlive the request that carried them ------
# A kept connection answers a second request without credentials as
# unauthenticated: a reverse proxy reuses its upstreams between
# clients, so one client's login must not open another's way in.
creds = base64.b64encode(b"alice:secret").decode()
text, closed = t.raw_session(srv,
f"GET /echo HTTP/1.1\r\nHost: t\r\n"
f"Authorization: Basic {creds}\r\n\r\n"
f"GET /echo HTTP/1.1\r\nHost: t\r\nConnection: close\r\n\r\n")
parts = text.split("HTTP/1.")
t.eq(3, len(parts), "the kept connection answers both requests")
t.eq(True, parts[1].startswith("1 200"),
"the request with credentials is allowed")
t.eq(True, parts[2].startswith("0 401"),
"the request after it, without credentials, is refused")
+2
View File
@@ -8,6 +8,8 @@ import os
def run(t):
if not t.skip_unless("httpsrv"):
return
root = os.path.join(t.tmpdir, "web")
os.makedirs(os.path.join(root, "picts", "set"), exist_ok=True)
with open(os.path.join(root, "a.html"), "w") as fp:
+2
View File
@@ -10,6 +10,8 @@ import os
def run(t):
if not t.skip_unless("httpsrv"):
return
root = os.path.join(t.tmpdir, "ka")
os.makedirs(root, exist_ok=True)
with open(os.path.join(root, "a.html"), "w") as fp:
+2
View File
@@ -4,6 +4,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
t.start("httpsrv_ops", f"""
log
+2
View File
@@ -6,6 +6,8 @@ most of them away before they ever reached the server.
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
t.start("httpsrv_parsing", f"""
log
+2
View File
@@ -9,6 +9,8 @@ import os
def run(t):
if not t.skip_unless("httpsrv"):
return
root = os.path.join(t.tmpdir, "pp")
os.makedirs(root, exist_ok=True)
with open(os.path.join(root, "a.html"), "w") as fp:
+2
View File
@@ -2,6 +2,8 @@
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
srv2 = t.free_port()
t.start("httpsrv_rules", f"""
+2
View File
@@ -7,6 +7,8 @@ nscache6: nscache holds the IPv4 side and nothing else.
def run(t):
if not t.skip_unless("httpsrv", "ipv6"):
return
if not t.has_ipv6():
t.skip("IPv6 (this machine has no IPv6 loopback)")
return
+2
View File
@@ -8,6 +8,8 @@ data and the report, not that the kernel took it.
def run(t):
if not t.skip_unless("httpsrv", "ssl"):
return
certs = t.certs()
if not certs:
t.skip("kernel TLS (openssl is not available to generate certificates)")
+2
View File
@@ -130,6 +130,8 @@ def config(origin, p1, p2, p3, adm, main, shared=None):
def run(t):
if not t.skip_unless("httpsrv"):
return
origin, p1, p2, p3, adm = (t.free_port() for _ in range(5))
first = os.path.join(t.tmpdir, "logs-first.log")
second = os.path.join(t.tmpdir, "logs-second.log")
+2
View File
@@ -8,6 +8,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
# The origin runs in a process of its own, so the limit only applies to
# the mapper in front of it.
origin = t.free_port()
+88
View File
@@ -0,0 +1,88 @@
"""Name resolution: a server answering with an error is passed over, one
that says the name is not there ends the search.
A proxy resolves the destination by asking the configured name servers in
order. The first one here answers FORMERR to everything; the second answers
from a list. A request through the proxy reaches its destination, which
proves the second server was asked, and a name the second server says is
not there is not resolved by anyone else.
"""
import socket
import struct
import threading
class DnsServer:
"""Answers every query with a fixed rcode, and A records for names it
knows: the question is echoed, so the answer parses everywhere."""
def __init__(self, rcode, records):
self.rcode = rcode
self.records = records
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.thread = threading.Thread(target=self.serve, daemon=True)
def serve(self):
while True:
try:
data, addr = self.sock.recvfrom(65536)
except OSError:
return
if len(data) >= 12:
self.sock.sendto(self.reply(data), addr)
def reply(self, query):
if self.rcode:
return (query[:2] + struct.pack("!HHHHH", 0x8180 | self.rcode, 1, 0, 0, 0)
+ query[12:])
name = b""
pos = 12
while query[pos]:
name += query[pos + 1:pos + 1 + query[pos]] + b"."
pos += query[pos] + 1
name = name[:-1]
answer = self.records.get(name)
if not answer:
return (query[:2] + struct.pack("!HHHHH", 0x8183, 1, 0, 0, 0)
+ query[12:])
return (query[:2] + struct.pack("!HHHHH", 0x8180, 1, 1, 0, 0) + query[12:]
+ b"\xc0\x0c" + struct.pack("!HHIH", 1, 1, 60, 4)
+ socket.inet_aton(answer))
def start(self):
self.thread.start()
return self.port
def run(t):
broken = DnsServer(1, {}).start()
good = DnsServer(0, {b"here.test": "127.0.0.1"}).start()
# the destination the resolved name points at: a one-page origin
origin = t.free_port()
page = t.raw_server(origin, b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
b"\r\nok", close_after=True)
proxy = t.free_port()
t.start("nsfailover", f"""
log
flush
nserver 127.0.0.1:{broken}
nserver 127.0.0.1:{good}
auth iponly
allow *
proxy -p{proxy}
""", ports=[origin, proxy])
url = f"http://here.test:{origin}/"
t.eq(200, t.http(url, proxy=f"127.0.0.1:{proxy}").status,
"a name one server breaks is resolved by the next one")
r = t.http(f"http://gone.test:{origin}/", proxy=f"127.0.0.1:{proxy}")
t.ne(200, r.status if r else 0,
"a name the last server says is not there does not resolve")
page()
+99
View File
@@ -9,9 +9,22 @@ The number of attempts is bounded by parentretries, two by default, so each
case here needs at most one parent to fail before a working one is reached.
"""
import socket
import struct
import time
def recvall(sock, count):
"""Bytes from a socket, fewer only when the peer stops sending."""
data = b""
while len(data) < count:
chunk = sock.recv(count - len(data))
if not chunk:
break
data += chunk
return data
def served(server, needle, since=0):
"""How many log lines carrying needle a proxy wrote past offset since."""
return sum(1 for line in server.output()[since:].splitlines() if needle in line)
@@ -30,6 +43,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
good = t.free_port()
spare = t.free_port()
@@ -150,6 +165,90 @@ def run(t):
t.eq(1, wait_served(goodp, needle, 1, gmark),
"through the parent it names")
# --- UDP: a parent which is down is not replaced by a direct relay -------
# The association itself is allowed without its destination, but the
# datagram carrying one has to build the chain its rule demands. With
# the only parent gone the association has to fail: relaying the next
# datagram from the proxy's own address would be a way around the rule.
sudp = t.free_port()
t.start("failover_udp", f"""
log
auth iponly
allow *
parent 1000 socks5 127.0.0.1 {dead}
socks -p{sudp}
""", ports=[sudp])
echo1 = t.udp_echo()
echo2 = t.udp_echo()
ctrl = socket.create_connection(("127.0.0.1", sudp), t.timeout)
ctrl.settimeout(t.timeout)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.settimeout(1.0)
try:
ctrl.sendall(b"\x05\x01\x00")
greeted = recvall(ctrl, 2) == b"\x05\x00"
ctrl.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
reply = recvall(ctrl, 4)
bound = None
if greeted and len(reply) >= 4 and reply[1] == 0 and reply[3] == 1:
addr = recvall(ctrl, 6)
if len(addr) == 6:
bound = struct.unpack("!H", addr[4:6])[0]
def datagram(port, payload):
header = (b"\x00\x00\x00\x01" + socket.inet_aton("127.0.0.1") +
struct.pack("!H", port))
udp.sendto(header + payload, ("127.0.0.1", bound))
def silence(port, payload):
"""Whether nothing came back for the datagram sent."""
datagram(port, payload)
try:
udp.recvfrom(65536)
return False
except OSError:
return True
if bound is None:
t.fail("the association is granted", expected="a relay port",
actual=None)
else:
t.eq(True, silence(echo1, b"first"),
"the datagram to the dead parent is not delivered")
try:
closed = ctrl.recv(1) == b""
except OSError:
closed = False
t.eq(True, closed,
"the association does not survive its failed parent")
t.eq(True, silence(echo2, b"second"),
"no datagram after it is relayed direct")
finally:
ctrl.close()
udp.close()
# a parent which carries UDP is used for UDP: the failover above is the
# parent's failure, not the relay's refusal
suparent = t.free_port()
sup = t.free_port()
t.start("failover_udp_parent", f"""
log
auth iponly
allow *
socks -p{suparent}
""", ports=[suparent])
t.start("failover_udp_up", f"""
log
auth iponly
allow *
parent 1000 socks5 127.0.0.1 {suparent}
socks -p{sup}
""", ports=[sup])
reply, _ = t.socks_udp(f"127.0.0.1:{sup}", "127.0.0.1", echo1, b"udp")
t.eq(b"echo:udp", reply, "a datagram is carried by the working parent")
# --- what the parser still rejects --------------------------------------
out = t.run_config("failover_badweight", f"""
auth iponly
+2
View File
@@ -46,6 +46,8 @@ UNHONOURED = (1, 99)
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
prx = t.free_port()
sks = t.free_port()
+2
View File
@@ -37,6 +37,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
def run(t):
if not t.skip_unless("httpsrv"):
return
adm = t.free_port()
prx = t.free_port()
dummy = t.free_port()
+2
View File
@@ -20,6 +20,8 @@ def _has_pcre(t):
def run(t):
if not t.skip_unless("httpsrv", "pcre"):
return
if not _has_pcre(t):
t.skip("PCRE (this build has no PCRE support)")
return
+83
View File
@@ -0,0 +1,83 @@
"""A pcre action with ,log: what the pattern matched is written to the log.
dunno,log decides nothing, so a request it matches goes on as if the rule
was not there, and every match is a record of its own, carrying what the
pattern matched of what the client sent. The options apply to it as to
any other pattern, so a header can be watched whatever its case, and by
the line, wherever in the headers it comes.
"""
def _has_pcre(t):
"""Whether this build accepts the pcre commands at all.
The last line is nonsense on purpose: it makes 3proxy report and exit
instead of waiting, and what it says about the line above is the answer.
"""
out = t.run_config("pcre_probe",
'log\npcre request deny "x"\nnot_a_command\n')
return "'pcre'" not in out
def run(t):
if not t.skip_unless("httpsrv", "pcre"):
return
if not _has_pcre(t):
t.skip("PCRE (this build has no PCRE support)")
return
origin = t.free_port()
t.start("pcre_origin", f"""
log
auth iponly
allow *
http echo * /echo**
httpsrv -p{origin}
""", ports=[origin])
url = f"http://127.0.0.1:{origin}"
def proxy_with(name, *rules):
port = t.free_port()
server = t.start(name, "\n".join([
'logformat "%H:%M:%S %T"',
"log", "flush", "auth iponly", "allow *",
*rules, f"proxy -p{port}"]),
ports=[port])
return f"127.0.0.1:{port}", server
# --- dunno,log: decided nothing, watched something ---------------------
p, s = proxy_with("dunno_log", 'pcre cliheader dunno,log "X-Log-Marker:.*"')
t.eq(200, t.http(url + "/echo", proxy=p).status,
"a request without the header is served")
out = s.output()
t.not_contains(out, "watchme-123",
"and nothing about it is logged but the connection")
t.eq(200, t.http(url + "/echo", proxy=p,
headers={"X-Log-Marker": "watchme-123"}).status,
"a request a dunno,log rule matches is served all the same")
out = t.wait_output(s, "watchme-123")
t.contains(out, "X-Log-Marker: watchme-123",
"what the pattern matched is written to the log")
# --- deny,log: refused, and the refusal leaves its trace ----------------
p, s = proxy_with("deny_log", 'pcre cliheader deny,log "Forbidden-Marker:.*"')
t.eq(200, t.http(url + "/echo", proxy=p).status,
"a request without the header is served")
t.ne(200, t.http(url + "/echo", proxy=p,
headers={"Forbidden-Marker": "closed"}).status,
"a request a deny,log rule matches is denied")
out = t.wait_output(s, "Forbidden-Marker: closed")
t.contains(out, "Forbidden-Marker: closed",
"what the pattern matched is written to the log")
# --- the options apply: any case, any line of the headers ----------------
p, s = proxy_with("options_log",
"pcre_options PCRE2_CASELESS PCRE2_MULTILINE",
'pcre cliheader dunno,log "^x-log-marker:.*$"')
t.eq(200, t.http(url + "/echo", proxy=p,
headers={"X-Log-Marker": "cased-456"}).status,
"a header matches in lower case, on whatever line it comes")
out = t.wait_output(s, "cased-456")
t.contains(out, "X-Log-Marker: cased-456",
"and what it matched is written to the log")
+13 -3
View File
@@ -4,7 +4,7 @@ import socket
import threading
import time
HALFCLOSE_SIZE = 20000000
HALFCLOSE_SIZE = 4000000
def halfclose_origin(listener):
@@ -26,6 +26,8 @@ def halfclose_origin(listener):
def run(t):
if not t.skip_unless("httpsrv"):
return
# --- tcppm ---------------------------------------------------------
origin = t.free_port()
mapped = t.free_port()
@@ -79,8 +81,9 @@ def run(t):
""", ports=[halfclosed])
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32768)
s.settimeout(30)
s.settimeout(60)
got = 0
timedout = False
try:
s.connect(("127.0.0.1", halfclosed))
s.sendall(b"request")
@@ -91,11 +94,18 @@ def run(t):
if not d:
break
got += len(d)
except socket.timeout:
timedout = True
except OSError:
pass
s.close()
listener.close()
t.eq(HALFCLOSE_SIZE, got, "a half-closed client reading slowly gets the whole answer")
if timedout:
t.fail("a half-closed client reading slowly gets the whole answer",
f"{HALFCLOSE_SIZE} bytes", f"timed out with {got}")
else:
t.eq(HALFCLOSE_SIZE, got,
"a half-closed client reading slowly gets the whole answer")
t.stop_all()
+111
View File
@@ -0,0 +1,111 @@
"""The port command: a listening socket reserved where the configuration
is read, a service of the same address taking it over.
A privileged port is opened before setuid and chroot take the rights
away, and the service named after them runs on the socket that is
already open: what would be a bind() denied is a takeover instead. A
port no service takes stays reserved, its socket listening on its own.
"""
import time
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
t.start("port_origin", f"""
log
auth iponly
allow *
http data * /data**
httpsrv -p{origin}
""", ports=[origin])
# a port reserved and never taken: the socket listens by itself
solo = t.free_port()
t.start("port_solo", f"""
log
port tcp 127.0.0.1:{solo}
""", ports=[solo])
t.ok("a port with no service is kept listening") \
if t.wait_port(solo) else \
t.fail("a port with no service is kept listening",
f"port {solo} open", "closed")
# a service after the reservation takes the socket over
reserved = t.free_port()
adm = t.free_port()
server = t.start("port_taken", f"""
log
port tcp 127.0.0.1:{reserved}
auth iponly
allow *
proxy -p{reserved} -i127.0.0.1
admin -p{adm}
""", ports=[reserved, adm])
out = t.wait_output(server, "taken over")
t.contains(out, "taken over",
"the service runs on the socket the reservation opened")
t.eq(200, t.http(f"http://127.0.0.1:{origin}/data",
proxy=f"127.0.0.1:{reserved}").status,
"a request through the taken-over port is served")
# --- after chroot no reservation can be made again: a reload with
# the service alone, the port line left out, keeps the port -------
taken_before = server.output().count("taken over")
t.write_config("port_taken", f"""
log
auth iponly
allow *
proxy -p{reserved} -i127.0.0.1
admin -p{adm}
""")
t.http(f"http://127.0.0.1:{adm}/R")
out = t.wait_output(server, "taken over", since=len(server.output()))
t.ok("a reload with the service alone keeps the reserved port") \
if server.output().count("taken over") > taken_before else \
t.fail("a reload with the service alone keeps the reserved port",
"the socket taken over again", out)
t.eq(200, t.http(f"http://127.0.0.1:{origin}/data",
proxy=f"127.0.0.1:{reserved}").status,
"and it is served as before")
# a reload with neither the reservation nor a service drops the port
t.write_config("port_taken", f"""
log
auth iponly
allow *
admin -p{adm}
""")
t.http(f"http://127.0.0.1:{adm}/R")
deadline = time.time() + 5
while time.time() < deadline and t.wait_port(reserved, timeout=0.2):
time.sleep(0.2)
t.ok("a reload without the reservation and without a service drops it") \
if not t.wait_port(reserved, timeout=0.2) else \
t.fail("a reload without the reservation and without a service drops it",
f"port {reserved} closed", "open")
# a reserved UDP port is taken over the same way: bound by the
# reservation, answered by the service
udpp = t.free_port()
dns = t.start("port_udp", f"""
log
port udp 127.0.0.1:{udpp}
nserver 127.0.0.1
nscache 1024
nsrecord here.test 10.11.12.13
dnspr -p{udpp} -i127.0.0.1
""")
deadline = time.time() + 5
while time.time() < deadline:
if t.dns_query(udpp, "here.test"):
break
time.sleep(0.05)
t.eq(["10.11.12.13"], t.dns_query(udpp, "here.test"),
"a UDP service answers on its reserved port")
+19
View File
@@ -4,8 +4,12 @@ Access rules accumulate until "flush", so each service section here starts
from a clean list.
"""
import base64
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
other = t.free_port()
prx = t.free_port()
@@ -106,3 +110,18 @@ def run(t):
t.eq(407, t.http(origin + "/echo", proxy=needs_auth,
proxy_auth=("alice", "wrong")).status,
"wrong proxy credentials are refused")
# credentials do not outlive the request which carried them: a second
# request on the same connection, without them, is asked again
creds = base64.b64encode(b"alice:secret").decode()
text, closed = t.raw_session(auth,
f"GET {origin}/echo HTTP/1.1\r\nHost: 127.0.0.1:{srv}\r\n"
f"Proxy-Authorization: Basic {creds}\r\n\r\n"
f"GET {origin}/echo HTTP/1.1\r\nHost: 127.0.0.1:{srv}\r\n"
f"Connection: close\r\n\r\n")
parts = text.split("HTTP/1.")
t.eq(3, len(parts), "the kept connection answers both requests")
t.eq(True, parts[1].startswith("1 200"),
"the request with credentials is allowed")
t.eq(True, parts[2].startswith("0 407"),
"the request after it, without credentials, is refused")
+42
View File
@@ -0,0 +1,42 @@
"""The radius command: a server may be a name, an address, and carry a
port, with an IPv6 address in brackets.
The port was in the man page but not in the code before: a server with a
port was simply refused. A name is resolved when the configuration is
read, with the name servers in force or the system's.
"""
def run(t):
def accepted(config):
out = t.run_config("radius_cmd", config + "\nnot_a_command\n")
return "'radius' failed" not in out, out
ok, out = accepted("log\nradius s3cret 127.0.0.1:18120")
if ok:
t.ok("a server address with a port is accepted")
else:
t.fail("a server address with a port is accepted",
"'radius' not refused", out)
ok, out = accepted("log\nradius s3cret localhost")
if ok:
t.ok("a server name is accepted, resolved when the file is read")
else:
t.fail("a server name is accepted, resolved when the file is read",
"'radius' not refused", out)
if t.has_ipv6():
ok, out = accepted("log\nradius s3cret [::1]:18120")
if ok:
t.ok("an IPv6 server address in brackets, with a port, is accepted")
else:
t.fail("an IPv6 server address in brackets, with a port, is accepted",
"'radius' not refused", out)
out = t.run_config("radius_bad",
"log\nradius s3cret 999.999.999.999\nnot_a_command\n")
t.contains(out, "'radius' failed",
"an address that is none is refused")
t.not_contains(out, "'not_a_command'",
"and the file stops at the refused line")
+2
View File
@@ -10,6 +10,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
proxy = t.free_port()
adm = t.free_port()
+2
View File
@@ -29,6 +29,8 @@ def config(origin, proxy, adm, user, extra=""):
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
first = t.free_port()
second = t.free_port()
+91
View File
@@ -0,0 +1,91 @@
"""The SMTP proxy login: what it may be sent, and what may not be done."""
import base64
import socket
def recvline(sock):
"""One reply line, shorter only when the peer stops sending."""
data = b""
while not data.endswith(b"\n"):
chunk = sock.recv(1)
if not chunk:
break
data += chunk
return data
def drain_ehlo(sock):
"""Read the multi-line EHLO answer up to its last line."""
while True:
line = recvline(sock)
if not line or line.startswith(b"250 "):
return
def run(t):
if not t.skip_unless("smtpp"):
return
sp = t.free_port()
pp = t.free_port()
t.start("smtpp_login", f"""
log
auth iponly
allow *
proxy -p{pp}
flush
auth none
allow *
smtpp -p{sp}
""", ports=[pp, sp])
def auth_login(name):
"""The reply the login ends with for the given name."""
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
recvline(s)
s.sendall(b"EHLO case\r\n")
drain_ehlo(s)
s.sendall(b"AUTH LOGIN\r\n")
recvline(s)
s.sendall(base64.b64encode(name) + b"\r\n")
reply = recvline(s)
# the name carries the destination, so a refusal can come with
# the username already, before any password is asked for
if not reply.startswith(b"334"):
return reply
s.sendall(base64.b64encode(b"pw") + b"\r\n")
return recvline(s)
def auth_plain(name):
"""The reply of a one-line AUTH PLAIN carrying the given name."""
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
recvline(s)
s.sendall(b"EHLO case\r\n")
drain_ehlo(s)
s.sendall(b"AUTH PLAIN " +
base64.b64encode(b"\x00" + name + b"\x00pw") +
b"\r\n")
return recvline(s)
# A name of a port alone names no destination: the login is refused
# with a reply, and the daemon is left standing, its other listeners
# among them.
t.contains(auth_login(b"x@:25"), b"571",
"a login name of a port alone is refused")
t.contains(auth_plain(b"x@:25"), b"571",
"the same name over AUTH PLAIN is refused")
t.contains(auth_login(b"x@127.0.0.1:9"), b"571",
"a login name of a dead host is refused")
with socket.create_connection(("127.0.0.1", sp), t.timeout) as s:
s.settimeout(t.timeout)
t.eq(True, recvline(s).startswith(b"220"),
"the SMTP proxy answers again after the refused logins")
try:
with socket.create_connection(("127.0.0.1", pp), t.timeout):
t.ok("the other services of the process keep accepting")
except OSError:
t.fail("the other services of the process keep accepting")
+134
View File
@@ -1,7 +1,23 @@
"""The SOCKS proxy, reaching the built-in server."""
import socket
import struct
def recvall(sock, count):
"""Bytes from a socket, fewer only when the peer stops sending."""
data = b""
while len(data) < count:
chunk = sock.recv(count - len(data))
if not chunk:
break
data += chunk
return data
def run(t):
if not t.skip_unless("httpsrv"):
return
srv = t.free_port()
sks = t.free_port()
sauth = t.free_port()
@@ -94,3 +110,121 @@ def run(t):
"wrong SOCKS5 credentials are refused")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", srv),
"SOCKS5 without credentials is refused")
# --- names a client may not choose -------------------------------------
# A destination name travels into the request lines of parent protocols,
# so a control byte or a space in it could end the line early and name
# another destination. Such a name is refused where it is read, before
# anything is resolved or connected: reply 1, not the reply of a
# destination which does not answer.
sname = t.free_port()
standin = t.free_port()
t.start("socks_names", f"""
log
fakeresolve
auth iponly
allow *
socks -p{sname}
""", ports=[sname])
def socks5_name(name, port):
"""The reply code of a SOCKS5 CONNECT naming the given name."""
with socket.create_connection(("127.0.0.1", sname), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(b"\x05\x01\x00")
if recvall(s, 2) != b"\x05\x00":
return None
s.sendall(b"\x05\x01\x00\x03" + bytes([len(name)]) + name +
struct.pack("!H", port))
reply = recvall(s, 4)
return reply[1] if len(reply) > 1 else None
def socks4_name(name, port):
"""The reply code of a SOCKS4a CONNECT naming the given name."""
with socket.create_connection(("127.0.0.1", sname), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(struct.pack(">BBH", 4, 1, port) +
socket.inet_aton("0.0.0.0") + b"case\x00" + name +
b"\x00")
reply = recvall(s, 8)
return reply[1] if len(reply) > 1 else None
t.eq(1, socks5_name(b"127.0.0.1\r\nGET /other HTTP/1.1\r\n\r\nstand-in.example",
standin),
"a name with CR LF in it is refused")
t.eq(91, socks4_name(b"127.0.0.1\r\nGET /other HTTP/1.1\r\n\r\nstand-in.example",
standin),
"SOCKS4a refuses a name with CR LF in it")
t.eq(1, socks5_name(b"127.0.0.1 stand-in.example", standin),
"a name with a space in it is refused")
t.eq(1, socks5_name(b"stand-in\x7f.example", standin),
"a name with a control byte in it is refused")
# a well-formed name is let through, to the 127.0.0.2 fakeresolve maps
# every name to; where that address can be served, the tunnel has to be
# carried all the way to it
probe = socket.socket()
try:
probe.bind(("127.0.0.2", 0))
except OSError:
probe.close()
t.skip("the stand-in address 127.0.0.2 can not be bound here")
else:
probe.close()
stop = t.raw_server(standin, b"from the stand-in\r\n",
host="127.0.0.2")
t.eq(0, socks5_name(b"stand-in.example", standin),
"a well-formed name is connected by name")
t.eq(90, socks4_name(b"stand-in.example", standin),
"a well-formed name is connected by name over SOCKS4a")
stop()
# --- a pre-authorized association decides nothing for later ------------
# A UDP ASSOCIATE is allowed without looking at the destination its rules
# name, so that verdict may not be kept in the auth cache and returned
# for a CONNECT later.
scache = t.free_port()
allowed = t.free_port()
denied = t.free_port()
t.start("socks_cacheacl", f"""
log
authcache user,pass,dstport 60
auth cacheacl strong
users u:CL:p
allow u * * {allowed}
deny *
socks -p{scache}
""", ports=[scache])
# both destinations are alive: what decides between them is the rule
stop = t.raw_server(allowed, b"from the allowed stand-in\r\n")
refuse = t.raw_server(denied, b"from the refused stand-in\r\n")
def associate_declared():
"""The reply code of a UDP ASSOCIATE naming the refused destination."""
with socket.create_connection(("127.0.0.1", scache), t.timeout) as s:
s.settimeout(t.timeout)
s.sendall(b"\x05\x01\x02")
reply = recvall(s, 2)
if len(reply) < 2 or reply[1] != 0x02:
return None
s.sendall(b"\x01\x01u\x01p")
reply = recvall(s, 2)
if len(reply) < 2 or reply[1] != 0:
return None
s.sendall(b"\x05\x03\x00\x01" + socket.inet_aton("127.0.0.1") +
struct.pack("!H", denied))
reply = recvall(s, 4)
return reply[1] if len(reply) > 1 else None
guarded = f"127.0.0.1:{scache}"
t.eq(None, t.socks_connect(guarded, "127.0.0.1", allowed, auth=("u", "p")),
"a CONNECT the rules allow is connected")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", denied, auth=("u", "p")),
"a CONNECT the rules refuse is refused")
t.eq(0, associate_declared(),
"the association itself is allowed without its destination")
t.ne(None, t.socks_connect(guarded, "127.0.0.1", denied, auth=("u", "p")),
"a CONNECT after the association is refused all the same")
stop()
refuse()
+2
View File
@@ -61,6 +61,8 @@ def echo_through(port, data):
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+2
View File
@@ -11,6 +11,8 @@ def _no_tls(t, server):
def run(t):
if not t.skip_unless("httpsrv", "ssl"):
return
certs = t.certs()
if not certs:
t.skip("TLS (openssl is not available to generate certificates)")
+2
View File
@@ -49,6 +49,8 @@ def wait(t, port, name):
def run(t):
if not t.skip_unless("httpsrv"):
return
if not hosts_localhost() or not system_nameserver():
t.skip("no localhost in the hosts file, or no system name server")
return
+2
View File
@@ -9,6 +9,8 @@ import time
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
proxy = t.free_port()
adm = t.free_port()
+2
View File
@@ -2,6 +2,8 @@
def run(t):
if not t.skip_unless("httpsrv", "ssl"):
return
certs = t.certs()
if not certs:
t.skip("tlspr (openssl is not available to generate certificates)")
+2
View File
@@ -39,6 +39,8 @@ def _config(t, name, body):
def run(t):
if not t.skip_unless("httpsrv"):
return
# --- the command and its modes ------------------------------------
# These need no redirection, so they run wherever the feature is built.
out = _config(t, "transparent_probe", "log\ntransparent")
+106
View File
@@ -0,0 +1,106 @@
"""The UDP<->TCP tunnels: udptotcp takes datagrams to a TCP connection,
tcptoudp takes a TCP connection to datagrams, the datagrams on the
connection carrying their length, as udptunnel and ProxyGuard put them."""
import socket
import struct
import threading
UDP_MAGIC = b"udptunnel by md.\0\0\0\x01\x03\x06\x10\x15\x21\x28\x36\x45\x55\x66\x78\x91"
PG_GET = (b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nUser-Agent: test\r\n"
b"Connection: Upgrade\r\nUpgrade: UoTLV/1\r\n\r\n")
def frame(payload):
return struct.pack(">H", len(payload)) + payload
def read_frames(sock, state, count, timeout=10.0):
"""count length-prefixed datagrams from sock; state[0] is the bytes
already read and not yet used."""
out = []
sock.settimeout(timeout)
while len(out) < count:
while len(state[0]) >= 2:
need = 2 + struct.unpack(">H", state[0][:2])[0]
if len(state[0]) < need:
break
out.append(state[0][2:need])
state[0] = state[0][need:]
if len(out) >= count:
return out
data = sock.recv(65536)
if not data:
raise EOFError("the tunnel closed")
state[0] += data
return out
def run(t):
echo = t.udp_echo()
tunnel = t.free_port() # udptotcp listens here
tunnel_hs = t.free_port() # the same, udptunnel's handshake
server = t.free_port() # tcptoudp listens here
plain = t.free_port() # tcptoudp for the handshake clients
t.start("tunnels", f"""
log
auth iponly
allow *
udptotcp {tunnel} 127.0.0.1 {server}
udptotcp -m {tunnel_hs} 127.0.0.1 {server}
flush
auth iponly
allow *
tcptoudp {server} 127.0.0.1 {echo}
tcptoudp {plain} 127.0.0.1 {echo}
""", ports=[server, plain])
# a UDP service answers only once it is asked, so ask until it does
if t.wait_udp(tunnel):
t.ok("the UDP side of the tunnel is up")
else:
t.fail("the UDP side of the tunnel is up")
# --- a datagram each way, through both services ---------------
t.eq(b"echo:hello", t.udp_exchange(tunnel, b"hello"),
"a datagram reaches the target through the tunnel")
t.eq(b"echo:again", t.udp_exchange(tunnel, b"again"),
"a second datagram uses the same session")
big = b"x" * 4000
t.eq(b"echo:" + big, t.udp_exchange(tunnel, big),
"a larger datagram survives the round trip")
# --- udptunnel's handshake, accepted by tcptoudp ---------------
if t.wait_udp(tunnel_hs):
t.ok("the UDP side of the udptunnel-handshake tunnel is up")
t.eq(b"echo:with handshake", t.udp_exchange(tunnel_hs, b"with handshake"),
"a datagram with udptunnel's handshake before it is answered")
# --- a client speaking udptunnel, to tcptoudp ------------------
s = socket.create_connection(("127.0.0.1", plain), timeout=10)
s.sendall(UDP_MAGIC + frame(b"udptunnel asks"))
t.eq([b"echo:udptunnel asks"], read_frames(s, [b""], 1),
"a udptunnel client is answered")
s.close()
# --- a client speaking ProxyGuard, to tcptoudp -----------------
s = socket.create_connection(("127.0.0.1", plain), timeout=10)
s.sendall(PG_GET)
head = b""
while b"\r\n\r\n" not in head:
head += s.recv(4096)
t.eq(True, head.startswith(b"HTTP/1.1 101"),
"ProxyGuard's client is told the protocols are switched")
t.contains(head.decode("latin1"), "UoTLV/1", "the answer names the protocol")
s.sendall(frame(b"proxyguard asks"))
t.eq([b"echo:proxyguard asks"], read_frames(s, [b""], 1),
"ProxyGuard's datagram is answered")
s.close()
# --- a client that frames, two datagrams in one write ----------
s = socket.create_connection(("127.0.0.1", plain), timeout=10)
s.sendall(frame(b"first") + frame(b"second"))
t.eq([b"echo:first", b"echo:second"], read_frames(s, [b""], 2),
"two datagrams in one write are both answered")
s.close()
+2
View File
@@ -37,6 +37,8 @@ def unix_get(path, url, timeout=10):
def run(t):
if not t.skip_unless("httpsrv", "unix"):
return
if not hasattr(socket, "AF_UNIX") or sys.platform.startswith("win"):
t.skip("Unix domain sockets (not on this platform)")
return
+115
View File
@@ -0,0 +1,115 @@
"""A rule names, after one @, the service the request came through.
The rules of the limiters are shared by all the services, so there has
been no way to limit the connections of one service alone. The
targetlist names the service after its @ by the addresses it listens
on, the targetportlist by its ports — each side written as any other
list, a side left out standing for any. A deny so written closes one
service, a connlim so written caps one service, and neither touches
another service of the same configuration.
"""
import time
def run(t):
if not t.skip_unless("httpsrv"):
return
origin = t.free_port()
t.start("viaport_origin", f"""
auth iponly
allow *
http data * /data**
httpsrv -p{origin}
""", ports=[origin])
url = f"http://127.0.0.1:{origin}/data"
# a deny naming a service by its port closes that service alone
first, second = t.free_port(), t.free_port()
t.start("viaport_deny", f"""
log
auth iponly
deny * * * @{second}
allow *
proxy -p{first}
proxy -p{second}
""", ports=[first, second])
t.eq(200, t.http(url, proxy=f"127.0.0.1:{first}").status,
"the service the rule does not name is served")
t.ne(200, t.http(url, proxy=f"127.0.0.1:{second}").status,
"the service the rule names by its port is refused")
# a connlim naming a service by its port caps that service alone
third, fourth = t.free_port(), t.free_port()
t.start("viaport_connlim", f"""
log
auth iponly
connlim 1 0 * * * @{third}
allow *
proxy -p{third}
proxy -p{fourth}
""", ports=[third, fourth])
def slow(result):
# about two seconds: 400 KB in 8 KB blocks, 40 ms apart
r = t.http(f"http://127.0.0.1:{origin}"
f"/data?size=400000&block=8192&delay=40",
proxy=f"127.0.0.1:{third}")
result["status"] = r.status
result = {}
held = __import__("threading").Thread(target=slow, args=(result,))
held.start()
time.sleep(0.5)
t.ne(200, t.http(url, proxy=f"127.0.0.1:{third}").status,
"a second request of the service the rule names, while its first "
"is still going, is refused")
t.eq(200, t.http(url, proxy=f"127.0.0.1:{fourth}").status,
"another service is not counted in that limit")
held.join(60)
t.eq(200, result.get("status", 0),
"and the request the limit waited for finishes whole")
# a service named by its address, in the targetlist
if t.has_ipv6():
fifth, sixth = t.free_port(), t.free_port()
t.start("viaport_ip", f"""
log
auth iponly
deny * * *@::1 *
allow *
proxy -p{fifth} -i127.0.0.1
proxy -p{sixth} -i::1
""", ports=[fifth, ("::1", sixth)])
t.eq(200, t.http(url, proxy=f"127.0.0.1:{fifth}").status,
"the service on another address is served")
r = t.http(url, proxy=f"[::1]:{sixth}")
t.ne(200, r.status if r else 0,
"the service the rule names by its address is refused")
# several services named by one rule: the list after the @
sev1, sev2 = t.free_port(), t.free_port()
t.start("viaport_both", f"""
log
auth iponly
deny * * * @{sev1},{sev2}
allow *
proxy -p{sev1}
proxy -p{sev2}
""", ports=[sev1, sev2])
t.ne(200, t.http(url, proxy=f"127.0.0.1:{sev1}").status,
"the first service the rule names is refused")
t.ne(200, t.http(url, proxy=f"127.0.0.1:{sev2}").status,
"and so is the second")
# an @ with nothing after it is refused
out = t.run_config("viaport_bad",
"log\nallow * * * 443@\nnot_a_command\n")
t.contains(out, "Invalid port or port range",
"a service with nothing after the @ is refused")
+21 -1
View File
@@ -122,10 +122,11 @@ class Failure(Exception):
class Tester:
"""The API a case runs against: start servers, make requests, assert."""
def __init__(self, binary, tmpdir, case):
def __init__(self, binary, tmpdir, case, features=None):
self.binary = binary
self.tmpdir = tmpdir
self.case = case
self.features = features if features is not None else frozenset()
self.servers = []
self.checks = []
self.timeout = 10
@@ -135,6 +136,25 @@ class Tester:
self.logs = []
self.udp_servers = []
# ---- build features ----------------------------------------------
def has(self, *names):
"""Whether the binary reports every named feature."""
return all(name in self.features for name in names)
def skip_unless(self, *names):
"""Skip what needs a feature the binary was built without.
Returns False after recording the skip, so a case says
`if not t.skip_unless("ssl"): return` and keeps its checks out of
the failed count on a build that cannot pass them.
"""
missing = [name for name in names if name not in self.features]
if not missing:
return True
self.skip("built without: " + ", ".join(missing))
return False
# ---- servers -----------------------------------------------------
def has_ipv6(self):
+34 -1
View File
@@ -48,6 +48,37 @@ def load_case(path):
return name, module
def built_features(binary):
"""The features the binary reports in `3proxy --help`, as a set.
A binary too old to have the list, or one that cannot be run at all,
reports nothing: every case that needs a feature then skips, and the
ones that need none still run.
"""
import subprocess
try:
done = subprocess.run([binary, "--help"], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, timeout=15)
text = done.stdout.decode("utf-8", "replace")
except (OSError, subprocess.SubprocessError):
return frozenset()
features = set()
collecting = False
for line in text.splitlines():
stripped = line.strip()
if line.startswith("built with:"):
collecting = True
rest = stripped[len("built with:"):].strip()
if rest:
features.update(rest.split())
continue
if collecting:
if not line[:1].isspace() or not stripped:
break
features.update(stripped.split())
return frozenset(features)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("pattern", nargs="?", default="",
@@ -76,7 +107,9 @@ def main():
return 2
tmpdir = tempfile.mkdtemp(prefix="3proxy-tests.")
features = built_features(binary)
print(f"3proxy tests: {binary}")
print(f"built with: {' '.join(sorted(features)) or '(nothing reported)'}")
print(f"working in: {tmpdir}\n")
passed = failed = skipped = 0
@@ -86,7 +119,7 @@ def main():
for path in paths:
name, module = load_case(path)
print(f" {name}")
tester = Tester(binary, tmpdir, name)
tester = Tester(binary, tmpdir, name, features)
error = None
try:
module.run(tester)