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