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