Home | History | Annotate | Line # | Download | only in ftp-proxy
      1 /*	$NetBSD: ftp-proxy.c,v 1.5 2025/01/07 21:15:40 joe Exp $ */
      2 /*	$OpenBSD: ftp-proxy.c,v 1.15 2007/08/15 15:18:02 camield Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2004, 2005 Camiel Dobbelaar, <cd (at) sentia.nl>
      6  *
      7  * Permission to use, copy, modify, and distribute this software for any
      8  * purpose with or without fee is hereby granted, provided that the above
      9  * copyright notice and this permission notice appear in all copies.
     10  *
     11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18  */
     19 
     20 #include <sys/queue.h>
     21 #include <sys/types.h>
     22 #include <sys/time.h>
     23 #include <sys/resource.h>
     24 #include <sys/socket.h>
     25 
     26 #include <net/if.h>
     27 #include <net/pfvar.h>
     28 #include <netinet/in.h>
     29 #include <arpa/inet.h>
     30 
     31 #include <err.h>
     32 #include <errno.h>
     33 #include <event.h>
     34 #include <fcntl.h>
     35 #include <netdb.h>
     36 #include <pwd.h>
     37 #include <signal.h>
     38 #include <stdarg.h>
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <string.h>
     42 #include <syslog.h>
     43 #include <unistd.h>
     44 #include <vis.h>
     45 
     46 #include "filter.h"
     47 
     48 #define CONNECT_TIMEOUT	30
     49 #define MIN_PORT	1024
     50 #define MAX_LINE	500
     51 #define MAX_LOGLINE	300
     52 #define NTOP_BUFS	3
     53 #define TCP_BACKLOG	10
     54 
     55 #define CHROOT_DIR	"/var/chroot/ftp-proxy"
     56 #define NOPRIV_USER	"_proxy"
     57 
     58 /* pfctl standard NAT range. */
     59 #define PF_NAT_PROXY_PORT_LOW	50001
     60 #define PF_NAT_PROXY_PORT_HIGH	65535
     61 
     62 #ifndef sstosa
     63 #define	sstosa(ss)	((struct sockaddr *)(ss))
     64 #endif /* sstosa */
     65 
     66 #ifndef IPPORT_HIFIRSTAUTO
     67 #define IPPORT_HIFIRSTAUTO	IPPORT_ANONMIN
     68 #endif /* IPPORT_HIFIRSTAUTO */
     69 
     70 #ifndef IPPORT_HILASTAUTO
     71 #define IPPORT_HILASTAUTO	IPPORT_ANONMAX
     72 #endif /* IPPORT_HILASTAUTO */
     73 
     74 enum { CMD_NONE = 0, CMD_PORT, CMD_EPRT, CMD_PASV, CMD_EPSV };
     75 
     76 struct session {
     77 	u_int32_t		 id;
     78 	struct sockaddr_storage  client_ss;
     79 	struct sockaddr_storage  proxy_ss;
     80 	struct sockaddr_storage  server_ss;
     81 	struct sockaddr_storage  orig_server_ss;
     82 	struct bufferevent	*client_bufev;
     83 	struct bufferevent	*server_bufev;
     84 	int			 client_fd;
     85 	int			 server_fd;
     86 	char			 cbuf[MAX_LINE];
     87 	size_t			 cbuf_valid;
     88 	char			 sbuf[MAX_LINE];
     89 	size_t			 sbuf_valid;
     90 	int			 cmd;
     91 	u_int16_t		 port;
     92 	u_int16_t		 proxy_port;
     93 	LIST_ENTRY(session)	 entry;
     94 };
     95 
     96 LIST_HEAD(, session) sessions = LIST_HEAD_INITIALIZER(sessions);
     97 
     98 void	client_error(struct bufferevent *, short, void *);
     99 int	client_parse(struct session *s);
    100 int	client_parse_anon(struct session *s);
    101 int	client_parse_cmd(struct session *s);
    102 void	client_read(struct bufferevent *, void *);
    103 int	drop_privs(void);
    104 void	end_session(struct session *);
    105 int	exit_daemon(void);
    106 int	get_line(char *, size_t *);
    107 void	handle_connection(const int, short, void *);
    108 void	handle_signal(int, short, void *);
    109 struct session * init_session(void);
    110 void	logmsg(int, const char *, ...);
    111 u_int16_t parse_port(int);
    112 u_int16_t pick_proxy_port(void);
    113 void	proxy_reply(int, struct sockaddr *, u_int16_t);
    114 void	server_error(struct bufferevent *, short, void *);
    115 int	server_parse(struct session *s);
    116 int	allow_data_connection(struct session *s);
    117 void	server_read(struct bufferevent *, void *);
    118 const char *sock_ntop(struct sockaddr *);
    119 void	usage(void);
    120 
    121 char linebuf[MAX_LINE + 1];
    122 size_t linelen;
    123 
    124 char ntop_buf[NTOP_BUFS][INET6_ADDRSTRLEN];
    125 
    126 struct sockaddr_storage fixed_server_ss, fixed_proxy_ss;
    127 char *fixed_server, *fixed_server_port, *fixed_proxy, *listen_ip, *listen_port,
    128     *qname, *tagname;
    129 int anonymous_only, daemonize, id_count, ipv6_mode, loglevel, max_sessions,
    130     rfc_mode, session_count, timeout, verbose;
    131 extern char *__progname;
    132 
    133 /* Default: PF operations. */
    134 static const ftp_proxy_ops_t *	fops = &pf_fprx_ops;
    135 
    136 void
    137 client_error(struct bufferevent *bufev, short what, void *arg)
    138 {
    139 	struct session *s = arg;
    140 
    141 	if (what & EVBUFFER_EOF)
    142 		logmsg(LOG_INFO, "#%d client close", s->id);
    143 	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
    144 		logmsg(LOG_ERR, "#%d client reset connection", s->id);
    145 	else if (what & EVBUFFER_TIMEOUT)
    146 		logmsg(LOG_ERR, "#%d client timeout", s->id);
    147 	else if (what & EVBUFFER_WRITE)
    148 		logmsg(LOG_ERR, "#%d client write error: %d", s->id, what);
    149 	else
    150 		logmsg(LOG_ERR, "#%d abnormal client error: %d", s->id, what);
    151 
    152 	end_session(s);
    153 }
    154 
    155 int
    156 client_parse(struct session *s)
    157 {
    158 	/* Reset any previous command. */
    159 	s->cmd = CMD_NONE;
    160 	s->port = 0;
    161 
    162 	/* Commands we are looking for are at least 4 chars long. */
    163 	if (linelen < 4)
    164 		return (1);
    165 
    166 	if (linebuf[0] == 'P' || linebuf[0] == 'p' ||
    167 	    linebuf[0] == 'E' || linebuf[0] == 'e') {
    168 		if (!client_parse_cmd(s))
    169 			return (0);
    170 
    171 		/*
    172 		 * Allow active mode connections immediately, instead of
    173 		 * waiting for a positive reply from the server.  Some
    174 		 * rare servers/proxies try to probe or setup the data
    175 		 * connection before an actual transfer request.
    176 		 */
    177 		if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT)
    178 			return (allow_data_connection(s));
    179 	}
    180 
    181 	if (anonymous_only && (linebuf[0] == 'U' || linebuf[0] == 'u'))
    182 		return (client_parse_anon(s));
    183 
    184 	return (1);
    185 }
    186 
    187 int
    188 client_parse_anon(struct session *s)
    189 {
    190 	if (strcasecmp("USER ftp\r\n", linebuf) != 0 &&
    191 	    strcasecmp("USER anonymous\r\n", linebuf) != 0) {
    192 		snprintf(linebuf, sizeof linebuf,
    193 		    "500 Only anonymous FTP allowed\r\n");
    194 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
    195 
    196 		/* Talk back to the client ourself. */
    197 		linelen = strlen(linebuf);
    198 		bufferevent_write(s->client_bufev, linebuf, linelen);
    199 
    200 		/* Clear buffer so it's not sent to the server. */
    201 		linebuf[0] = '\0';
    202 		linelen = 0;
    203 	}
    204 
    205 	return (1);
    206 }
    207 
    208 int
    209 client_parse_cmd(struct session *s)
    210 {
    211 	if (strncasecmp("PASV", linebuf, 4) == 0)
    212 		s->cmd = CMD_PASV;
    213 	else if (strncasecmp("PORT ", linebuf, 5) == 0)
    214 		s->cmd = CMD_PORT;
    215 	else if (strncasecmp("EPSV", linebuf, 4) == 0)
    216 		s->cmd = CMD_EPSV;
    217 	else if (strncasecmp("EPRT ", linebuf, 5) == 0)
    218 		s->cmd = CMD_EPRT;
    219 	else
    220 		return (1);
    221 
    222 	if (ipv6_mode && (s->cmd == CMD_PASV || s->cmd == CMD_PORT)) {
    223 		logmsg(LOG_CRIT, "PASV and PORT not allowed with IPv6");
    224 		return (0);
    225 	}
    226 
    227 	if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
    228 		s->port = parse_port(s->cmd);
    229 		if (s->port < MIN_PORT) {
    230 			logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
    231 			    linebuf);
    232 			return (0);
    233 		}
    234 		s->proxy_port = pick_proxy_port();
    235 		proxy_reply(s->cmd, sstosa(&s->proxy_ss), s->proxy_port);
    236 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
    237 	}
    238 
    239 	return (1);
    240 }
    241 
    242 void
    243 client_read(struct bufferevent *bufev, void *arg)
    244 {
    245 	struct session	*s = arg;
    246 	size_t		 buf_avail, nread;
    247 	int		 n;
    248 
    249 	do {
    250 		buf_avail = sizeof s->cbuf - s->cbuf_valid;
    251 		nread = bufferevent_read(bufev, s->cbuf + s->cbuf_valid,
    252 		    buf_avail);
    253 		s->cbuf_valid += nread;
    254 
    255 		while ((n = get_line(s->cbuf, &s->cbuf_valid)) > 0) {
    256 			logmsg(LOG_DEBUG, "#%d client: %s", s->id, linebuf);
    257 			if (!client_parse(s)) {
    258 				end_session(s);
    259 				return;
    260 			}
    261 			bufferevent_write(s->server_bufev, linebuf, linelen);
    262 		}
    263 
    264 		if (n == -1) {
    265 			logmsg(LOG_ERR, "#%d client command too long or not"
    266 			    " clean", s->id);
    267 			end_session(s);
    268 			return;
    269 		}
    270 	} while (nread == buf_avail);
    271 }
    272 
    273 int
    274 drop_privs(void)
    275 {
    276 	struct passwd *pw;
    277 
    278 	pw = getpwnam(NOPRIV_USER);
    279 	if (pw == NULL)
    280 		return (0);
    281 
    282 	tzset();
    283 #ifdef __NetBSD__
    284 	if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
    285 	    setgroups(1, &pw->pw_gid) != 0 ||
    286 	    setgid(pw->pw_gid) != 0 ||
    287 	    setuid(pw->pw_uid) != 0)
    288 		return (0);
    289 #else
    290 	if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
    291 	    setgroups(1, &pw->pw_gid) != 0 ||
    292 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0 ||
    293 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
    294 		return (0);
    295 #endif /* !__NetBSD__ */
    296 
    297 	return (1);
    298 }
    299 
    300 void
    301 end_session(struct session *s)
    302 {
    303 	int error;
    304 
    305 	logmsg(LOG_INFO, "#%d ending session", s->id);
    306 
    307 	if (s->client_fd != -1)
    308 		close(s->client_fd);
    309 	if (s->server_fd != -1)
    310 		close(s->server_fd);
    311 
    312 	if (s->client_bufev)
    313 		bufferevent_free(s->client_bufev);
    314 	if (s->server_bufev)
    315 		bufferevent_free(s->server_bufev);
    316 
    317 	/* Remove rulesets by commiting empty ones. */
    318 	error = 0;
    319 	if (fops->prepare_commit(s->id) == -1)
    320 		error = errno;
    321 	else if (fops->do_commit() == -1) {
    322 		error = errno;
    323 		fops->do_rollback();
    324 	}
    325 	if (error)
    326 		logmsg(LOG_ERR, "#%d pf rule removal failed: %s", s->id,
    327 		    strerror(error));
    328 
    329 	LIST_REMOVE(s, entry);
    330 	free(s);
    331 	session_count--;
    332 }
    333 
    334 int
    335 exit_daemon(void)
    336 {
    337 	struct session *s, *next;
    338 
    339 	for (s = LIST_FIRST(&sessions); s != LIST_END(&sessions); s = next) {
    340 		next = LIST_NEXT(s, entry);
    341 		end_session(s);
    342 	}
    343 
    344 	if (daemonize)
    345 		closelog();
    346 
    347 	exit(0);
    348 
    349 	/* NOTREACHED */
    350 	return (-1);
    351 }
    352 
    353 int
    354 get_line(char *buf, size_t *valid)
    355 {
    356 	size_t i;
    357 
    358 	if (*valid > MAX_LINE)
    359 		return (-1);
    360 
    361 	/* Copy to linebuf while searching for a newline. */
    362 	for (i = 0; i < *valid; i++) {
    363 		linebuf[i] = buf[i];
    364 		if (buf[i] == '\0')
    365 			return (-1);
    366 		if (buf[i] == '\n')
    367 			break;
    368 	}
    369 
    370 	if (i == *valid) {
    371 		/* No newline found. */
    372 		linebuf[0] = '\0';
    373 		linelen = 0;
    374 		if (i < MAX_LINE)
    375 			return (0);
    376 		return (-1);
    377 	}
    378 
    379 	linelen = i + 1;
    380 	linebuf[linelen] = '\0';
    381 	*valid -= linelen;
    382 
    383 	/* Move leftovers to the start. */
    384 	if (*valid != 0)
    385 		bcopy(buf + linelen, buf, *valid);
    386 
    387 	return ((int)linelen);
    388 }
    389 
    390 void
    391 handle_connection(const int listen_fd, short event, void *ev)
    392 {
    393 	struct sockaddr_storage tmp_ss;
    394 	struct sockaddr *client_sa, *server_sa, *fixed_server_sa;
    395 	struct sockaddr *client_to_proxy_sa, *proxy_to_server_sa;
    396 	struct session *s;
    397 	socklen_t len;
    398 	int client_fd, fc, on;
    399 
    400 	/*
    401 	 * We _must_ accept the connection, otherwise libevent will keep
    402 	 * coming back, and we will chew up all CPU.
    403 	 */
    404 	client_sa = sstosa(&tmp_ss);
    405 	len = sizeof(struct sockaddr_storage);
    406 	if ((client_fd = accept(listen_fd, client_sa, &len)) < 0) {
    407 		logmsg(LOG_CRIT, "accept failed: %s", strerror(errno));
    408 		return;
    409 	}
    410 
    411 	/* Refuse connection if the maximum is reached. */
    412 	if (session_count >= max_sessions) {
    413 		logmsg(LOG_ERR, "client limit (%d) reached, refusing "
    414 		    "connection from %s", max_sessions, sock_ntop(client_sa));
    415 		close(client_fd);
    416 		return;
    417 	}
    418 
    419 	/* Allocate session and copy back the info from the accept(). */
    420 	s = init_session();
    421 	if (s == NULL) {
    422 		logmsg(LOG_CRIT, "init_session failed");
    423 		close(client_fd);
    424 		return;
    425 	}
    426 	s->client_fd = client_fd;
    427 	memcpy(sstosa(&s->client_ss), client_sa, client_sa->sa_len);
    428 
    429 	/* Cast it once, and be done with it. */
    430 	client_sa = sstosa(&s->client_ss);
    431 	server_sa = sstosa(&s->server_ss);
    432 	client_to_proxy_sa = sstosa(&tmp_ss);
    433 	proxy_to_server_sa = sstosa(&s->proxy_ss);
    434 	fixed_server_sa = sstosa(&fixed_server_ss);
    435 
    436 	/* Log id/client early to ease debugging. */
    437 	logmsg(LOG_DEBUG, "#%d accepted connection from %s", s->id,
    438 	    sock_ntop(client_sa));
    439 
    440 	/*
    441 	 * Find out the real server and port that the client wanted.
    442 	 */
    443 	len = sizeof(struct sockaddr_storage);
    444 	if ((getsockname(s->client_fd, client_to_proxy_sa, &len)) < 0) {
    445 		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
    446 		    strerror(errno));
    447 		goto fail;
    448 	}
    449 	if (fops->server_lookup(client_sa, client_to_proxy_sa, server_sa)) {
    450 	    	logmsg(LOG_CRIT, "#%d server lookup failed (no rdr?)", s->id);
    451 		goto fail;
    452 	}
    453 	if (fixed_server) {
    454 		memcpy(sstosa(&s->orig_server_ss), server_sa,
    455 		    server_sa->sa_len);
    456 		memcpy(server_sa, fixed_server_sa, fixed_server_sa->sa_len);
    457 	}
    458 
    459 	/* XXX: check we are not connecting to ourself. */
    460 
    461 	/*
    462 	 * Setup socket and connect to server.
    463 	 */
    464 	if ((s->server_fd = socket(server_sa->sa_family, SOCK_STREAM,
    465 	    IPPROTO_TCP)) < 0) {
    466 		logmsg(LOG_CRIT, "#%d server socket failed: %s", s->id,
    467 		    strerror(errno));
    468 		goto fail;
    469 	}
    470 	if (fixed_proxy && bind(s->server_fd, sstosa(&fixed_proxy_ss),
    471 	    fixed_proxy_ss.ss_len) != 0) {
    472 		logmsg(LOG_CRIT, "#%d cannot bind fixed proxy address: %s",
    473 		    s->id, strerror(errno));
    474 		goto fail;
    475 	}
    476 
    477 	/* Use non-blocking connect(), see CONNECT_TIMEOUT below. */
    478 	if ((fc = fcntl(s->server_fd, F_GETFL)) == -1 ||
    479 	    fcntl(s->server_fd, F_SETFL, fc | O_NONBLOCK) == -1) {
    480 		logmsg(LOG_CRIT, "#%d cannot mark socket non-blocking: %s",
    481 		    s->id, strerror(errno));
    482 		goto fail;
    483 	}
    484 	if (connect(s->server_fd, server_sa, server_sa->sa_len) < 0 &&
    485 	    errno != EINPROGRESS) {
    486 		logmsg(LOG_CRIT, "#%d proxy cannot connect to server %s: %s",
    487 		    s->id, sock_ntop(server_sa), strerror(errno));
    488 		goto fail;
    489 	}
    490 
    491 	len = sizeof(struct sockaddr_storage);
    492 	if ((getsockname(s->server_fd, proxy_to_server_sa, &len)) < 0) {
    493 		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
    494 		    strerror(errno));
    495 		goto fail;
    496 	}
    497 
    498 	logmsg(LOG_INFO, "#%d FTP session %d/%d started: client %s to server "
    499 	    "%s via proxy %s ", s->id, session_count, max_sessions,
    500 	    sock_ntop(client_sa), sock_ntop(server_sa),
    501 	    sock_ntop(proxy_to_server_sa));
    502 
    503 	/* Keepalive is nice, but don't care if it fails. */
    504 	on = 1;
    505 	setsockopt(s->client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
    506 	    sizeof on);
    507 	setsockopt(s->server_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
    508 	    sizeof on);
    509 
    510 	/*
    511 	 * Setup buffered events.
    512 	 */
    513 	s->client_bufev = bufferevent_new(s->client_fd, &client_read, NULL,
    514 	    &client_error, s);
    515 	if (s->client_bufev == NULL) {
    516 		logmsg(LOG_CRIT, "#%d bufferevent_new client failed", s->id);
    517 		goto fail;
    518 	}
    519 	bufferevent_settimeout(s->client_bufev, timeout, 0);
    520 	bufferevent_enable(s->client_bufev, EV_READ | EV_TIMEOUT);
    521 
    522 	s->server_bufev = bufferevent_new(s->server_fd, &server_read, NULL,
    523 	    &server_error, s);
    524 	if (s->server_bufev == NULL) {
    525 		logmsg(LOG_CRIT, "#%d bufferevent_new server failed", s->id);
    526 		goto fail;
    527 	}
    528 	bufferevent_settimeout(s->server_bufev, CONNECT_TIMEOUT, 0);
    529 	bufferevent_enable(s->server_bufev, EV_READ | EV_TIMEOUT);
    530 
    531 	return;
    532 
    533  fail:
    534 	end_session(s);
    535 }
    536 
    537 void
    538 handle_signal(int sig, short event, void *arg)
    539 {
    540 	/*
    541 	 * Signal handler rules don't apply, libevent decouples for us.
    542 	 */
    543 
    544 	logmsg(LOG_ERR, "%s exiting on signal %d", __progname, sig);
    545 
    546 	exit_daemon();
    547 }
    548 
    549 struct session *
    550 init_session(void)
    551 {
    552 	struct session *s;
    553 
    554 	s = calloc(1, sizeof(struct session));
    555 	if (s == NULL)
    556 		return (NULL);
    557 
    558 	s->id = id_count++;
    559 	s->client_fd = -1;
    560 	s->server_fd = -1;
    561 	s->cbuf[0] = '\0';
    562 	s->cbuf_valid = 0;
    563 	s->sbuf[0] = '\0';
    564 	s->sbuf_valid = 0;
    565 	s->client_bufev = NULL;
    566 	s->server_bufev = NULL;
    567 	s->cmd = CMD_NONE;
    568 	s->port = 0;
    569 
    570 	LIST_INSERT_HEAD(&sessions, s, entry);
    571 	session_count++;
    572 
    573 	return (s);
    574 }
    575 
    576 void
    577 logmsg(int pri, const char *message, ...)
    578 {
    579 	va_list	ap;
    580 
    581 	if (pri > loglevel)
    582 		return;
    583 
    584 	va_start(ap, message);
    585 
    586 	if (daemonize)
    587 		/* syslog does its own vissing. */
    588 		vsyslog(pri, message, ap);
    589 	else {
    590 		char buf[MAX_LOGLINE];
    591 		char visbuf[2 * MAX_LOGLINE];
    592 
    593 		/* We don't care about truncation. */
    594 		vsnprintf(buf, sizeof buf, message, ap);
    595 #ifdef __NetBSD__
    596 		size_t len = strlen(buf);
    597 		if (len > sizeof visbuf) {
    598 			len = sizeof visbuf;
    599 		}
    600 		strvisx(visbuf, buf, len, VIS_CSTYLE | VIS_NL);
    601 #else
    602 		strnvis(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
    603 #endif /* !__NetBSD__ */
    604 		fprintf(stderr, "%s\n", visbuf);
    605 	}
    606 
    607 	va_end(ap);
    608 }
    609 
    610 int
    611 main(int argc, char *argv[])
    612 {
    613 	struct rlimit rlp;
    614 	struct addrinfo hints, *res;
    615 	struct event ev, ev_sighup, ev_sigint, ev_sigterm;
    616 	int ch, error, listenfd, on;
    617 	const char *errstr = NULL; /* XXX gcc */
    618 
    619 	/* Defaults. */
    620 	anonymous_only	= 0;
    621 	daemonize	= 1;
    622 	fixed_proxy	= NULL;
    623 	fixed_server	= NULL;
    624 	fixed_server_port = "21";
    625 	ipv6_mode	= 0;
    626 	listen_ip	= NULL;
    627 	listen_port	= "8021";
    628 	loglevel	= LOG_NOTICE;
    629 	max_sessions	= 100;
    630 	qname		= NULL;
    631 	rfc_mode	= 0;
    632 	tagname		= NULL;
    633 	timeout		= 24 * 3600;
    634 	verbose		= 0;
    635 
    636 	/* Other initialization. */
    637 	id_count	= 1;
    638 	session_count	= 0;
    639 
    640 #if defined(__NetBSD__)
    641 /* Note: both for IPFilter and NPF. */
    642 #define	NBSD_OPTS	"i:N:"
    643 #endif
    644 	while ((ch = getopt(argc, argv,
    645 	    "6Aa:b:D:d" NBSD_OPTS "m:P:p:q:R:rT:t:v")) != -1) {
    646 		switch (ch) {
    647 		case '6':
    648 			ipv6_mode = 1;
    649 			break;
    650 		case 'A':
    651 			anonymous_only = 1;
    652 			break;
    653 		case 'a':
    654 			fixed_proxy = optarg;
    655 			break;
    656 		case 'b':
    657 			listen_ip = optarg;
    658 			break;
    659 		case 'D':
    660 			loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
    661 			    &errstr);
    662 			if (errstr)
    663 				errx(1, "loglevel %s", errstr);
    664 			break;
    665 		case 'd':
    666 			daemonize = 0;
    667 			break;
    668 		case 'i':
    669 #if defined(__NetBSD__) && defined(WITH_IPF)
    670 			fops = &ipf_fprx_ops;
    671 			netif = optarg;
    672 #endif
    673 			break;
    674 		case 'm':
    675 			max_sessions = strtonum(optarg, 1, 500, &errstr);
    676 			if (errstr)
    677 				errx(1, "max sessions %s", errstr);
    678 			break;
    679 		case 'N':
    680 #if defined(__NetBSD__) && defined(WITH_NPF)
    681 			fops = &npf_fprx_ops;
    682 			npfopts = optarg;
    683 #endif
    684 			break;
    685 		case 'P':
    686 			fixed_server_port = optarg;
    687 			break;
    688 		case 'p':
    689 			listen_port = optarg;
    690 			break;
    691 		case 'q':
    692 			if (strlen(optarg) >= PF_QNAME_SIZE)
    693 				errx(1, "queuename too long");
    694 			qname = optarg;
    695 			break;
    696 		case 'R':
    697 			fixed_server = optarg;
    698 			break;
    699 		case 'r':
    700 			rfc_mode = 1;
    701 			break;
    702 		case 'T':
    703 			if (strlen(optarg) >= PF_TAG_NAME_SIZE)
    704 				errx(1, "tagname too long");
    705 			tagname = optarg;
    706 			break;
    707 		case 't':
    708 			timeout = strtonum(optarg, 0, 86400, &errstr);
    709 			if (errstr)
    710 				errx(1, "timeout %s", errstr);
    711 			break;
    712 		case 'v':
    713 			verbose++;
    714 			if (verbose > 2)
    715 				usage();
    716 			break;
    717 		default:
    718 			usage();
    719 		}
    720 	}
    721 
    722 	if (listen_ip == NULL)
    723 		listen_ip = ipv6_mode ? "::1" : "127.0.0.1";
    724 
    725 	/* Check for root to save the user from cryptic failure messages. */
    726 	if (getuid() != 0)
    727 		errx(1, "needs to start as root");
    728 
    729 	/* Raise max. open files limit to satisfy max. sessions. */
    730 	rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
    731 	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
    732 		err(1, "setrlimit");
    733 
    734 	if (fixed_proxy) {
    735 		memset(&hints, 0, sizeof hints);
    736 		hints.ai_flags = AI_NUMERICHOST;
    737 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    738 		hints.ai_socktype = SOCK_STREAM;
    739 		error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
    740 		if (error)
    741 			errx(1, "getaddrinfo fixed proxy address failed: %s",
    742 			    gai_strerror(error));
    743 		memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
    744 		logmsg(LOG_INFO, "using %s to connect to servers",
    745 		    sock_ntop(sstosa(&fixed_proxy_ss)));
    746 		freeaddrinfo(res);
    747 	}
    748 
    749 	if (fixed_server) {
    750 		memset(&hints, 0, sizeof hints);
    751 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    752 		hints.ai_socktype = SOCK_STREAM;
    753 		error = getaddrinfo(fixed_server, fixed_server_port, &hints,
    754 		    &res);
    755 		if (error)
    756 			errx(1, "getaddrinfo fixed server address failed: %s",
    757 			    gai_strerror(error));
    758 		memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
    759 		logmsg(LOG_INFO, "using fixed server %s",
    760 		    sock_ntop(sstosa(&fixed_server_ss)));
    761 		freeaddrinfo(res);
    762 	}
    763 
    764 	/* Setup listener. */
    765 	memset(&hints, 0, sizeof hints);
    766 	hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
    767 	hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
    768 	hints.ai_socktype = SOCK_STREAM;
    769 	error = getaddrinfo(listen_ip, listen_port, &hints, &res);
    770 	if (error)
    771 		errx(1, "getaddrinfo listen address failed: %s",
    772 		    gai_strerror(error));
    773 	if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
    774 		errx(1, "socket failed");
    775 	on = 1;
    776 	if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
    777 	    sizeof on) != 0)
    778 		err(1, "setsockopt failed");
    779 	if (bind(listenfd, (struct sockaddr *)res->ai_addr,
    780 	    (socklen_t)res->ai_addrlen) != 0)
    781 	    	err(1, "bind failed");
    782 	if (listen(listenfd, TCP_BACKLOG) != 0)
    783 		err(1, "listen failed");
    784 	freeaddrinfo(res);
    785 
    786 	/* Initialize pf. */
    787 	fops->init_filter(qname, tagname, verbose);
    788 
    789 	if (daemonize) {
    790 		if (daemon(0, 0) == -1)
    791 			err(1, "cannot daemonize");
    792 		openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
    793 	}
    794 
    795 	/* Use logmsg for output from here on. */
    796 
    797 	if (!drop_privs()) {
    798 		logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
    799 		exit(1);
    800 	}
    801 
    802 	event_init();
    803 
    804 	/* Setup signal handler. */
    805 	signal(SIGPIPE, SIG_IGN);
    806 	signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
    807 	signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
    808 	signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
    809 	signal_add(&ev_sighup, NULL);
    810 	signal_add(&ev_sigint, NULL);
    811 	signal_add(&ev_sigterm, NULL);
    812 
    813 	event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev);
    814 	event_add(&ev, NULL);
    815 
    816 	logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);
    817 
    818 	/*  Vroom, vroom.  */
    819 	event_dispatch();
    820 
    821 	logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
    822 	exit_daemon();
    823 
    824 	/* NOTREACHED */
    825 	return (1);
    826 }
    827 
    828 u_int16_t
    829 parse_port(int mode)
    830 {
    831 	unsigned int	 port, v[6];
    832 	int		 n;
    833 	char		*p;
    834 
    835 	/* Find the last space or left-parenthesis. */
    836 	for (p = linebuf + linelen; p > linebuf; p--)
    837 		if (*p == ' ' || *p == '(')
    838 			break;
    839 	if (p == linebuf)
    840 		return (0);
    841 
    842 	switch (mode) {
    843 	case CMD_PORT:
    844 		n = sscanf(p, " %u,%u,%u,%u,%u,%u", &v[0], &v[1], &v[2],
    845 		    &v[3], &v[4], &v[5]);
    846 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    847 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
    848 			return ((v[4] << 8) | v[5]);
    849 		break;
    850 	case CMD_PASV:
    851 		n = sscanf(p, "(%u,%u,%u,%u,%u,%u)", &v[0], &v[1], &v[2],
    852 		    &v[3], &v[4], &v[5]);
    853 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    854 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
    855 			return ((v[4] << 8) | v[5]);
    856 		break;
    857 	case CMD_EPSV:
    858 		n = sscanf(p, "(|||%u|)", &port);
    859 		if (n == 1 && port < 65536)
    860 			return (port);
    861 		break;
    862 	case CMD_EPRT:
    863 		n = sscanf(p, " |1|%u.%u.%u.%u|%u|", &v[0], &v[1], &v[2],
    864 		    &v[3], &port);
    865 		if (n == 5 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
    866 		    v[3] < 256 && port < 65536)
    867 			return (port);
    868 		n = sscanf(p, " |2|%*[a-fA-F0-9:]|%u|", &port);
    869 		if (n == 1 && port < 65536)
    870 			return (port);
    871 		break;
    872 	default:
    873 		return (0);
    874 	}
    875 
    876 	return (0);
    877 }
    878 
    879 u_int16_t
    880 pick_proxy_port(void)
    881 {
    882 	/* Random should be good enough for avoiding port collisions. */
    883 	return (IPPORT_HIFIRSTAUTO + (arc4random() %
    884 	    (IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO)));
    885 }
    886 
    887 void
    888 proxy_reply(int cmd, struct sockaddr *sa, u_int16_t port)
    889 {
    890 	int i, r = -1;
    891 
    892 	switch (cmd) {
    893 	case CMD_PORT:
    894 		r = snprintf(linebuf, sizeof linebuf,
    895 		    "PORT %s,%u,%u\r\n", sock_ntop(sa), port / 256,
    896 		    port % 256);
    897 		break;
    898 	case CMD_PASV:
    899 		r = snprintf(linebuf, sizeof linebuf,
    900 		    "227 Entering Passive Mode (%s,%u,%u)\r\n", sock_ntop(sa),
    901 		        port / 256, port % 256);
    902 		break;
    903 	case CMD_EPRT:
    904 		if (sa->sa_family == AF_INET)
    905 			r = snprintf(linebuf, sizeof linebuf,
    906 			    "EPRT |1|%s|%u|\r\n", sock_ntop(sa), port);
    907 		else if (sa->sa_family == AF_INET6)
    908 			r = snprintf(linebuf, sizeof linebuf,
    909 			    "EPRT |2|%s|%u|\r\n", sock_ntop(sa), port);
    910 		break;
    911 	case CMD_EPSV:
    912 		r = snprintf(linebuf, sizeof linebuf,
    913 		    "229 Entering Extended Passive Mode (|||%u|)\r\n", port);
    914 		break;
    915 	}
    916 
    917 	if (r < 0 || r >= sizeof linebuf) {
    918 		logmsg(LOG_ERR, "proxy_reply failed: %d", r);
    919 		linebuf[0] = '\0';
    920 		linelen = 0;
    921 		return;
    922 	}
    923 	linelen = (size_t)r;
    924 
    925 	if (cmd == CMD_PORT || cmd == CMD_PASV) {
    926 		/* Replace dots in IP address with commas. */
    927 		for (i = 0; i < linelen; i++)
    928 			if (linebuf[i] == '.')
    929 				linebuf[i] = ',';
    930 	}
    931 }
    932 
    933 void
    934 server_error(struct bufferevent *bufev, short what, void *arg)
    935 {
    936 	struct session *s = arg;
    937 
    938 	if (what & EVBUFFER_EOF)
    939 		logmsg(LOG_INFO, "#%d server close", s->id);
    940 	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
    941 		logmsg(LOG_ERR, "#%d server refused connection", s->id);
    942 	else if (what & EVBUFFER_WRITE)
    943 		logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
    944 	else if (what & EVBUFFER_TIMEOUT)
    945 		logmsg(LOG_NOTICE, "#%d server timeout", s->id);
    946 	else
    947 		logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);
    948 
    949 	end_session(s);
    950 }
    951 
    952 int
    953 server_parse(struct session *s)
    954 {
    955 	if (s->cmd == CMD_NONE || linelen < 4 || linebuf[0] != '2')
    956 		goto out;
    957 
    958 	if ((s->cmd == CMD_PASV && strncmp("227 ", linebuf, 4) == 0) ||
    959 	    (s->cmd == CMD_EPSV && strncmp("229 ", linebuf, 4) == 0))
    960 		return (allow_data_connection(s));
    961 
    962  out:
    963 	s->cmd = CMD_NONE;
    964 	s->port = 0;
    965 
    966 	return (1);
    967 }
    968 
    969 int
    970 allow_data_connection(struct session *s)
    971 {
    972 	struct sockaddr *client_sa, *orig_sa, *proxy_sa, *server_sa;
    973 	int prepared = 0;
    974 
    975 	/*
    976 	 * The pf rules below do quite some NAT rewriting, to keep up
    977 	 * appearances.  Points to keep in mind:
    978 	 * 1)  The client must think it's talking to the real server,
    979 	 *     for both control and data connections.  Transparently.
    980 	 * 2)  The server must think that the proxy is the client.
    981 	 * 3)  Source and destination ports are rewritten to minimize
    982 	 *     port collisions, to aid security (some systems pick weak
    983 	 *     ports) or to satisfy RFC requirements (source port 20).
    984 	 */
    985 
    986 	/* Cast this once, to make code below it more readable. */
    987 	client_sa = sstosa(&s->client_ss);
    988 	server_sa = sstosa(&s->server_ss);
    989 	proxy_sa = sstosa(&s->proxy_ss);
    990 	if (fixed_server)
    991 		/* Fixed server: data connections must appear to come
    992 		   from / go to the original server, not the fixed one. */
    993 		orig_sa = sstosa(&s->orig_server_ss);
    994 	else
    995 		/* Server not fixed: orig_server == server. */
    996 		orig_sa = sstosa(&s->server_ss);
    997 
    998 	/* Passive modes. */
    999 	if (s->cmd == CMD_PASV || s->cmd == CMD_EPSV) {
   1000 		s->port = parse_port(s->cmd);
   1001 		if (s->port < MIN_PORT) {
   1002 			logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
   1003 			    linebuf);
   1004 			return (0);
   1005 		}
   1006 		s->proxy_port = pick_proxy_port();
   1007 		logmsg(LOG_INFO, "#%d passive: client to server port %d"
   1008 		    " via port %d", s->id, s->port, s->proxy_port);
   1009 
   1010 		if (fops->prepare_commit(s->id) == -1)
   1011 			goto fail;
   1012 		prepared = 1;
   1013 
   1014 		proxy_reply(s->cmd, orig_sa, s->proxy_port);
   1015 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
   1016 
   1017 		/* rdr from $client to $orig_server port $proxy_port -> $server
   1018 		    port $port */
   1019 		if (fops->add_rdr(s->id, client_sa, orig_sa, s->proxy_port,
   1020 		    server_sa, s->port) == -1)
   1021 			goto fail;
   1022 
   1023 		/* nat from $client to $server port $port -> $proxy */
   1024 		if (fops->add_nat(s->id, client_sa, server_sa, s->port,
   1025 		    proxy_sa, PF_NAT_PROXY_PORT_LOW, PF_NAT_PROXY_PORT_HIGH)
   1026 		    == -1)
   1027 			goto fail;
   1028 
   1029 		/* pass in from $client to $server port $port */
   1030 		if (fops->add_filter(s->id, PF_IN, client_sa, server_sa,
   1031 		    s->port) == -1)
   1032 			goto fail;
   1033 
   1034 		/* pass out from $proxy to $server port $port */
   1035 		if (fops->add_filter(s->id, PF_OUT, proxy_sa, server_sa,
   1036 		    s->port) == -1)
   1037 			goto fail;
   1038 	}
   1039 
   1040 	/* Active modes. */
   1041 	if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
   1042 		logmsg(LOG_INFO, "#%d active: server to client port %d"
   1043 		    " via port %d", s->id, s->port, s->proxy_port);
   1044 
   1045 		if (fops->prepare_commit(s->id) == -1)
   1046 			goto fail;
   1047 		prepared = 1;
   1048 
   1049 		/* rdr from $server to $proxy port $proxy_port -> $client port
   1050 		    $port */
   1051 		if (fops->add_rdr(s->id, server_sa, proxy_sa,
   1052 		    s->proxy_port, client_sa, s->port) == -1)
   1053 			goto fail;
   1054 
   1055 		/* nat from $server to $client port $port -> $orig_server port
   1056 		    $natport */
   1057 		if (rfc_mode && s->cmd == CMD_PORT) {
   1058 			/* Rewrite sourceport to RFC mandated 20. */
   1059 			if (fops->add_nat(s->id, server_sa, client_sa,
   1060 			    s->port, orig_sa, 20, 20) == -1)
   1061 				goto fail;
   1062 		} else {
   1063 			/* Let pf pick a source port from the standard range. */
   1064 			if (fops->add_nat(s->id, server_sa, client_sa,
   1065 			    s->port, orig_sa, PF_NAT_PROXY_PORT_LOW,
   1066 			    PF_NAT_PROXY_PORT_HIGH) == -1)
   1067 			    	goto fail;
   1068 		}
   1069 
   1070 		/* pass in from $server to $client port $port */
   1071 		if (fops->add_filter(s->id, PF_IN, server_sa, client_sa,
   1072 		    s->port) == -1)
   1073 			goto fail;
   1074 
   1075 		/* pass out from $orig_server to $client port $port */
   1076 		if (fops->add_filter(s->id, PF_OUT, orig_sa, client_sa,
   1077 		    s->port) == -1)
   1078 			goto fail;
   1079 	}
   1080 
   1081 	/* Commit rules if they were prepared. */
   1082 	if (prepared && (fops->do_commit() == -1)) {
   1083 		if (errno != EBUSY)
   1084 			goto fail;
   1085 		/* One more try if busy. */
   1086 		usleep(5000);
   1087 		if (fops->do_commit() == -1)
   1088 			goto fail;
   1089 	}
   1090 
   1091 	s->cmd = CMD_NONE;
   1092 	s->port = 0;
   1093 
   1094 	return (1);
   1095 
   1096  fail:
   1097 	logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
   1098 	if (prepared)
   1099 		fops->do_rollback();
   1100 	return (0);
   1101 }
   1102 
   1103 void
   1104 server_read(struct bufferevent *bufev, void *arg)
   1105 {
   1106 	struct session	*s = arg;
   1107 	size_t		 buf_avail, nread;
   1108 	int		 n;
   1109 
   1110 	bufferevent_settimeout(bufev, timeout, 0);
   1111 
   1112 	do {
   1113 		buf_avail = sizeof s->sbuf - s->sbuf_valid;
   1114 		nread = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
   1115 		    buf_avail);
   1116 		s->sbuf_valid += nread;
   1117 
   1118 		while ((n = get_line(s->sbuf, &s->sbuf_valid)) > 0) {
   1119 			logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
   1120 			if (!server_parse(s)) {
   1121 				end_session(s);
   1122 				return;
   1123 			}
   1124 			bufferevent_write(s->client_bufev, linebuf, linelen);
   1125 		}
   1126 
   1127 		if (n == -1) {
   1128 			logmsg(LOG_ERR, "#%d server reply too long or not"
   1129 			    " clean", s->id);
   1130 			end_session(s);
   1131 			return;
   1132 		}
   1133 	} while (nread == buf_avail);
   1134 }
   1135 
   1136 const char *
   1137 sock_ntop(struct sockaddr *sa)
   1138 {
   1139 	static int n = 0;
   1140 
   1141 	/* Cycle to next buffer. */
   1142 	n = (n + 1) % NTOP_BUFS;
   1143 	ntop_buf[n][0] = '\0';
   1144 
   1145 	if (sa->sa_family == AF_INET) {
   1146 		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
   1147 
   1148 		return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
   1149 		    sizeof ntop_buf[0]));
   1150 	}
   1151 
   1152 	if (sa->sa_family == AF_INET6) {
   1153 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
   1154 
   1155 		return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
   1156 		    sizeof ntop_buf[0]));
   1157 	}
   1158 
   1159 	return (NULL);
   1160 }
   1161 
   1162 void
   1163 usage(void)
   1164 {
   1165 	fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
   1166 	    " [-D level] [-m maxsessions]\n                 [-P port]"
   1167 #if defined(__NetBSD__)
   1168 #if defined(WITH_IPF)
   1169 	    " [-i netif]"
   1170 #endif
   1171 #if defined(WITH_NPF)
   1172 	    " [-N netif:addr:port]"
   1173 #endif
   1174 #endif
   1175 	    " [-p port] [-q queue] [-R address] [-T tag] [-t timeout]\n",
   1176 	    __progname);
   1177 
   1178 	exit(1);
   1179 }
   1180