Compare commits

...
14 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
22 changed files with 1044 additions and 107 deletions

No files matched your search

+86 -4
View File
@@ -588,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,
@@ -600,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.
@@ -610,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.
@@ -910,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 *
@@ -1243,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
@@ -1500,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
@@ -1797,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.
+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;
+7
View File
@@ -349,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;
+20
View File
@@ -758,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;
@@ -807,6 +826,7 @@ 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 */
+172 -56
View File
@@ -439,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;
@@ -1263,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){
@@ -1323,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;
@@ -1358,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;
@@ -1403,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])) {
@@ -1818,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;
@@ -2138,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},
@@ -2146,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},
@@ -2414,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;
@@ -2564,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;
@@ -2631,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;
}
+2
View File
@@ -1209,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,
+13 -1
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,6 +216,7 @@ struct pcre_filter_data {
pcre2_match_data * match_data;
pcre2_match_context * match_context;
int action;
int log;
char * replace;
struct ace *acl;
};
@@ -300,6 +301,7 @@ 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;
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
#define pcrefd (pcd->pcrefd)
@@ -319,6 +321,14 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
if(count <= 0) break;
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];
@@ -494,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;
@@ -608,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;
+3
View File
@@ -630,6 +630,9 @@ 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);
+7 -1
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++) {
}
+15 -3
View File
@@ -449,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;
};
@@ -850,6 +853,7 @@ struct clientparam {
int pwtype,
weight,
nolog,
mark,
nolongdatfilter,
nosplice, /* a TLS socket of the connection is not in the kernel */
nooverwritefilter,
@@ -965,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;
};
@@ -1022,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 {
+13 -10
View File
@@ -301,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);
@@ -322,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);
}
@@ -351,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){
+1
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
+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")
+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()
+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")
+11 -3
View File
@@ -4,7 +4,7 @@ import socket
import threading
import time
HALFCLOSE_SIZE = 20000000
HALFCLOSE_SIZE = 4000000
def halfclose_origin(listener):
@@ -81,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")
@@ -93,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")
+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")
+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")