xref: /openbsd-src/usr.sbin/ftp-proxy/ftp-proxy.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /*	$OpenBSD: ftp-proxy.c,v 1.34 2016/02/12 08:12:48 ajacoutot 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	"_ftp_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 committing 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 	if (getpwnam(NOPRIV_USER) == NULL)
710 		errx(1, "unknown user %s", NOPRIV_USER);
711 
712 	/* Raise max. open files limit to satisfy max. sessions. */
713 	rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
714 	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
715 		err(1, "setrlimit");
716 
717 	if (fixed_proxy) {
718 		memset(&hints, 0, sizeof hints);
719 		hints.ai_flags = AI_NUMERICHOST;
720 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
721 		hints.ai_socktype = SOCK_STREAM;
722 		error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
723 		if (error)
724 			errx(1, "getaddrinfo fixed proxy address failed: %s",
725 			    gai_strerror(error));
726 		memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
727 		logmsg(LOG_INFO, "using %s to connect to servers",
728 		    sock_ntop(sstosa(&fixed_proxy_ss)));
729 		freeaddrinfo(res);
730 	}
731 
732 	if (fixed_server) {
733 		memset(&hints, 0, sizeof hints);
734 		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
735 		hints.ai_socktype = SOCK_STREAM;
736 		error = getaddrinfo(fixed_server, fixed_server_port, &hints,
737 		    &res);
738 		if (error)
739 			errx(1, "getaddrinfo fixed server address failed: %s",
740 			    gai_strerror(error));
741 		memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
742 		logmsg(LOG_INFO, "using fixed server %s",
743 		    sock_ntop(sstosa(&fixed_server_ss)));
744 		freeaddrinfo(res);
745 	}
746 
747 	/* Setup listener. */
748 	memset(&hints, 0, sizeof hints);
749 	hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
750 	hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
751 	hints.ai_socktype = SOCK_STREAM;
752 	error = getaddrinfo(listen_ip, listen_port, &hints, &res);
753 	if (error)
754 		errx(1, "getaddrinfo listen address failed: %s",
755 		    gai_strerror(error));
756 	if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
757 		errx(1, "socket failed");
758 	on = 1;
759 	if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
760 	    sizeof on) != 0)
761 		err(1, "setsockopt failed");
762 	if (bind(listenfd, (struct sockaddr *)res->ai_addr,
763 	    (socklen_t)res->ai_addrlen) != 0)
764 	    	err(1, "bind failed");
765 	if (listen(listenfd, TCP_BACKLOG) != 0)
766 		err(1, "listen failed");
767 	freeaddrinfo(res);
768 
769 	/* Initialize pf. */
770 	init_filter(qname, tagname, verbose);
771 
772 	if (daemonize) {
773 		if (daemon(0, 0) == -1)
774 			err(1, "cannot daemonize");
775 		openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
776 	}
777 
778 	/* Use logmsg for output from here on. */
779 
780 	if (!drop_privs()) {
781 		logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
782 		exit(1);
783 	}
784 
785 	event_init();
786 
787 	/* Setup signal handler. */
788 	signal(SIGPIPE, SIG_IGN);
789 	signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
790 	signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
791 	signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
792 	signal_add(&ev_sighup, NULL);
793 	signal_add(&ev_sigint, NULL);
794 	signal_add(&ev_sigterm, NULL);
795 
796 	event_set(&listen_ev, listenfd, EV_READ, handle_connection, NULL);
797 	event_add(&listen_ev, NULL);
798 	evtimer_set(&pause_accept_ev, handle_connection, NULL);
799 
800 	logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);
801 
802 	/*  Vroom, vroom.  */
803 	event_dispatch();
804 
805 	logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
806 	exit_daemon();
807 
808 	/* NOTREACHED */
809 	return (1);
810 }
811 
812 u_int16_t
813 parse_port(int mode)
814 {
815 	unsigned int	 port, v[6];
816 	int		 n;
817 	char		*p;
818 
819 	/* Find the last space or left-parenthesis. */
820 	for (p = linebuf + linelen; p > linebuf; p--)
821 		if (*p == ' ' || *p == '(')
822 			break;
823 	if (p == linebuf)
824 		return (0);
825 
826 	switch (mode) {
827 	case CMD_PORT:
828 		n = sscanf(p, " %u,%u,%u,%u,%u,%u", &v[0], &v[1], &v[2],
829 		    &v[3], &v[4], &v[5]);
830 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
831 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
832 			return ((v[4] << 8) | v[5]);
833 		break;
834 	case CMD_PASV:
835 		n = sscanf(p, "(%u,%u,%u,%u,%u,%u)", &v[0], &v[1], &v[2],
836 		    &v[3], &v[4], &v[5]);
837 		if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
838 		    v[3] < 256 && v[4] < 256 && v[5] < 256)
839 			return ((v[4] << 8) | v[5]);
840 		break;
841 	case CMD_EPSV:
842 		n = sscanf(p, "(|||%u|)", &port);
843 		if (n == 1 && port < 65536)
844 			return (port);
845 		break;
846 	case CMD_EPRT:
847 		n = sscanf(p, " |1|%u.%u.%u.%u|%u|", &v[0], &v[1], &v[2],
848 		    &v[3], &port);
849 		if (n == 5 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
850 		    v[3] < 256 && port < 65536)
851 			return (port);
852 		n = sscanf(p, " |2|%*[a-fA-F0-9:]|%u|", &port);
853 		if (n == 1 && port < 65536)
854 			return (port);
855 		break;
856 	default:
857 		return (0);
858 	}
859 
860 	return (0);
861 }
862 
863 u_int16_t
864 pick_proxy_port(void)
865 {
866 	/* Random should be good enough for avoiding port collisions. */
867 	return (IPPORT_HIFIRSTAUTO +
868 	    arc4random_uniform(IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO));
869 }
870 
871 void
872 proxy_reply(int cmd, struct sockaddr *sa, u_int16_t port)
873 {
874 	int i, r;
875 
876 	switch (cmd) {
877 	case CMD_PORT:
878 		r = snprintf(linebuf, sizeof linebuf,
879 		    "PORT %s,%u,%u\r\n", sock_ntop(sa), port / 256,
880 		    port % 256);
881 		break;
882 	case CMD_PASV:
883 		r = snprintf(linebuf, sizeof linebuf,
884 		    "227 Entering Passive Mode (%s,%u,%u)\r\n", sock_ntop(sa),
885 		        port / 256, port % 256);
886 		break;
887 	case CMD_EPRT:
888 		if (sa->sa_family == AF_INET)
889 			r = snprintf(linebuf, sizeof linebuf,
890 			    "EPRT |1|%s|%u|\r\n", sock_ntop(sa), port);
891 		else if (sa->sa_family == AF_INET6)
892 			r = snprintf(linebuf, sizeof linebuf,
893 			    "EPRT |2|%s|%u|\r\n", sock_ntop(sa), port);
894 		break;
895 	case CMD_EPSV:
896 		r = snprintf(linebuf, sizeof linebuf,
897 		    "229 Entering Extended Passive Mode (|||%u|)\r\n", port);
898 		break;
899 	}
900 
901 	if (r < 0 || r >= sizeof linebuf) {
902 		logmsg(LOG_ERR, "proxy_reply failed: %d", r);
903 		linebuf[0] = '\0';
904 		linelen = 0;
905 		return;
906 	}
907 	linelen = (size_t)r;
908 
909 	if (cmd == CMD_PORT || cmd == CMD_PASV) {
910 		/* Replace dots in IP address with commas. */
911 		for (i = 0; i < linelen; i++)
912 			if (linebuf[i] == '.')
913 				linebuf[i] = ',';
914 	}
915 }
916 
917 void
918 server_error(struct bufferevent *bufev, short what, void *arg)
919 {
920 	struct session *s = arg;
921 
922 	if (what & EVBUFFER_EOF)
923 		logmsg(LOG_INFO, "#%d server close", s->id);
924 	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
925 		logmsg(LOG_ERR, "#%d server refused connection", s->id);
926 	else if (what & EVBUFFER_WRITE)
927 		logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
928 	else if (what & EVBUFFER_TIMEOUT)
929 		logmsg(LOG_NOTICE, "#%d server timeout", s->id);
930 	else
931 		logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);
932 
933 	end_session(s);
934 }
935 
936 int
937 server_parse(struct session *s)
938 {
939 	if (s->cmd == CMD_NONE || linelen < 4 || linebuf[0] != '2')
940 		goto out;
941 
942 	if ((s->cmd == CMD_PASV && strncmp("227 ", linebuf, 4) == 0) ||
943 	    (s->cmd == CMD_EPSV && strncmp("229 ", linebuf, 4) == 0))
944 		return (allow_data_connection(s));
945 
946  out:
947 	s->cmd = CMD_NONE;
948 	s->port = 0;
949 
950 	return (1);
951 }
952 
953 int
954 allow_data_connection(struct session *s)
955 {
956 	struct sockaddr *client_sa, *orig_sa, *proxy_sa, *server_sa;
957 	int prepared = 0;
958 
959 	/*
960 	 * The pf rules below do quite some NAT rewriting, to keep up
961 	 * appearances.  Points to keep in mind:
962 	 * 1)  The client must think it's talking to the real server,
963 	 *     for both control and data connections.  Transparently.
964 	 * 2)  The server must think that the proxy is the client.
965 	 * 3)  Source and destination ports are rewritten to minimize
966 	 *     port collisions, to aid security (some systems pick weak
967 	 *     ports) or to satisfy RFC requirements (source port 20).
968 	 */
969 
970 	/* Cast this once, to make code below it more readable. */
971 	client_sa = sstosa(&s->client_ss);
972 	server_sa = sstosa(&s->server_ss);
973 	proxy_sa = sstosa(&s->proxy_ss);
974 	if (fixed_server)
975 		/* Fixed server: data connections must appear to come
976 		   from / go to the original server, not the fixed one. */
977 		orig_sa = sstosa(&s->orig_server_ss);
978 	else
979 		/* Server not fixed: orig_server == server. */
980 		orig_sa = sstosa(&s->server_ss);
981 
982 	/* Passive modes. */
983 	if (s->cmd == CMD_PASV || s->cmd == CMD_EPSV) {
984 		s->port = parse_port(s->cmd);
985 		if (s->port < MIN_PORT) {
986 			logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
987 			    linebuf);
988 			return (0);
989 		}
990 		s->proxy_port = pick_proxy_port();
991 		logmsg(LOG_INFO, "#%d passive: client to server port %d"
992 		    " via port %d", s->id, s->port, s->proxy_port);
993 
994 		if (prepare_commit(s->id) == -1)
995 			goto fail;
996 		prepared = 1;
997 
998 		proxy_reply(s->cmd, orig_sa, s->proxy_port);
999 		logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
1000 
1001 		/* pass in from $client to $orig_server port $proxy_port
1002 		    rdr-to $server port $port */
1003 		if (add_rdr(s->id, client_sa, s->client_rd, orig_sa,
1004 		    s->proxy_port, server_sa, s->port, getrtable()) == -1)
1005 			goto fail;
1006 
1007 		/* pass out from $client to $server port $port nat-to $proxy */
1008 		if (add_nat(s->id, client_sa, getrtable(), server_sa,
1009 		    s->port, proxy_sa, PF_NAT_PROXY_PORT_LOW,
1010 		    PF_NAT_PROXY_PORT_HIGH) == -1)
1011 			goto fail;
1012 	}
1013 
1014 	/* Active modes. */
1015 	if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
1016 		logmsg(LOG_INFO, "#%d active: server to client port %d"
1017 		    " via port %d", s->id, s->port, s->proxy_port);
1018 
1019 		if (prepare_commit(s->id) == -1)
1020 			goto fail;
1021 		prepared = 1;
1022 
1023 		/* pass in from $server to $proxy port $proxy_port
1024 		    rdr-to $client port $port */
1025 		if (add_rdr(s->id, server_sa, getrtable(), proxy_sa,
1026 		    s->proxy_port, client_sa, s->port, s->client_rd) == -1)
1027 			goto fail;
1028 
1029 		/* pass out from $server to $client port $port
1030 		    nat-to $orig_server port $natport */
1031 		if (rfc_mode && s->cmd == CMD_PORT) {
1032 			/* Rewrite sourceport to RFC mandated 20. */
1033 			if (add_nat(s->id, server_sa, s->client_rd, client_sa,
1034 			    s->port, orig_sa, 20, 20) == -1)
1035 				goto fail;
1036 		} else {
1037 			/* Let pf pick a source port from the standard range. */
1038 			if (add_nat(s->id, server_sa, s->client_rd, client_sa,
1039 			    s->port, orig_sa, PF_NAT_PROXY_PORT_LOW,
1040 			    PF_NAT_PROXY_PORT_HIGH) == -1)
1041 			    	goto fail;
1042 		}
1043 	}
1044 
1045 	/* Commit rules if they were prepared. */
1046 	if (prepared && (do_commit() == -1)) {
1047 		if (errno != EBUSY)
1048 			goto fail;
1049 		/* One more try if busy. */
1050 		usleep(5000);
1051 		if (do_commit() == -1)
1052 			goto fail;
1053 	}
1054 
1055 	s->cmd = CMD_NONE;
1056 	s->port = 0;
1057 
1058 	return (1);
1059 
1060  fail:
1061 	logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
1062 	if (prepared)
1063 		do_rollback();
1064 	return (0);
1065 }
1066 
1067 void
1068 server_read(struct bufferevent *bufev, void *arg)
1069 {
1070 	struct session	*s = arg;
1071 	size_t		 buf_avail, read;
1072 	int		 n;
1073 
1074 	bufferevent_settimeout(bufev, timeout, 0);
1075 
1076 	do {
1077 		buf_avail = sizeof s->sbuf - s->sbuf_valid;
1078 		read = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
1079 		    buf_avail);
1080 		s->sbuf_valid += read;
1081 
1082 		while ((n = get_line(s->sbuf, &s->sbuf_valid)) > 0) {
1083 			logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
1084 			if (!server_parse(s)) {
1085 				end_session(s);
1086 				return;
1087 			}
1088 			bufferevent_write(s->client_bufev, linebuf, linelen);
1089 		}
1090 
1091 		if (n == -1) {
1092 			logmsg(LOG_ERR, "#%d server reply too long or not"
1093 			    " clean", s->id);
1094 			end_session(s);
1095 			return;
1096 		}
1097 	} while (read == buf_avail);
1098 }
1099 
1100 const char *
1101 sock_ntop(struct sockaddr *sa)
1102 {
1103 	static int n = 0;
1104 
1105 	/* Cycle to next buffer. */
1106 	n = (n + 1) % NTOP_BUFS;
1107 	ntop_buf[n][0] = '\0';
1108 
1109 	if (sa->sa_family == AF_INET) {
1110 		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1111 
1112 		return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
1113 		    sizeof ntop_buf[0]));
1114 	}
1115 
1116 	if (sa->sa_family == AF_INET6) {
1117 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
1118 
1119 		return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
1120 		    sizeof ntop_buf[0]));
1121 	}
1122 
1123 	return (NULL);
1124 }
1125 
1126 void
1127 usage(void)
1128 {
1129 	fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
1130 	    " [-D level] [-m maxsessions]\n                 [-P port]"
1131 	    " [-p port] [-q queue] [-R address] [-T tag]\n"
1132             "                 [-t timeout]\n", __progname);
1133 	exit(1);
1134 }
1135