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