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