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