ftp-proxy.c revision 1.1.2.2 1 /* $NetBSD: ftp-proxy.c,v 1.1.2.2 2008/05/01 11:45:35 peter Exp $ */
2 /* $OpenBSD: ftp-proxy.c,v 1.15 2007/08/15 15:18:02 camield Exp $ */
3
4 /*
5 * Copyright (c) 2004, 2005 Camiel Dobbelaar, <cd (at) sentia.nl>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20 #include <sys/queue.h>
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/resource.h>
24 #include <sys/socket.h>
25
26 #include <net/if.h>
27 #include <net/pfvar.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30
31 #include <err.h>
32 #include <errno.h>
33 #include <event.h>
34 #include <fcntl.h>
35 #include <netdb.h>
36 #include <pwd.h>
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <syslog.h>
43 #include <unistd.h>
44 #include <vis.h>
45
46 #include "filter.h"
47
48 #define CONNECT_TIMEOUT 30
49 #define MIN_PORT 1024
50 #define MAX_LINE 500
51 #define MAX_LOGLINE 300
52 #define NTOP_BUFS 3
53 #define TCP_BACKLOG 10
54
55 #define CHROOT_DIR "/var/chroot/ftp-proxy"
56 #define NOPRIV_USER "_proxy"
57
58 /* pfctl standard NAT range. */
59 #define PF_NAT_PROXY_PORT_LOW 50001
60 #define PF_NAT_PROXY_PORT_HIGH 65535
61
62 #ifndef sstosa
63 #define sstosa(ss) ((struct sockaddr *)(ss))
64 #endif /* sstosa */
65
66 #ifndef IPPORT_HIFIRSTAUTO
67 #define IPPORT_HIFIRSTAUTO IPPORT_ANONMIN
68 #endif /* IPPORT_HIFIRSTAUTO */
69
70 #ifndef IPPORT_HILASTAUTO
71 #define IPPORT_HILASTAUTO IPPORT_ANONMAX
72 #endif /* IPPORT_HILASTAUTO */
73
74 enum { CMD_NONE = 0, CMD_PORT, CMD_EPRT, CMD_PASV, CMD_EPSV };
75
76 struct session {
77 u_int32_t id;
78 struct sockaddr_storage client_ss;
79 struct sockaddr_storage proxy_ss;
80 struct sockaddr_storage server_ss;
81 struct sockaddr_storage orig_server_ss;
82 struct bufferevent *client_bufev;
83 struct bufferevent *server_bufev;
84 int client_fd;
85 int server_fd;
86 char cbuf[MAX_LINE];
87 size_t cbuf_valid;
88 char sbuf[MAX_LINE];
89 size_t sbuf_valid;
90 int cmd;
91 u_int16_t port;
92 u_int16_t proxy_port;
93 LIST_ENTRY(session) entry;
94 };
95
96 LIST_HEAD(, session) sessions = LIST_HEAD_INITIALIZER(sessions);
97
98 void client_error(struct bufferevent *, short, void *);
99 int client_parse(struct session *s);
100 int client_parse_anon(struct session *s);
101 int client_parse_cmd(struct session *s);
102 void client_read(struct bufferevent *, void *);
103 int drop_privs(void);
104 void end_session(struct session *);
105 int exit_daemon(void);
106 int getline(char *, size_t *);
107 void handle_connection(const int, short, void *);
108 void handle_signal(int, short, void *);
109 struct session * init_session(void);
110 void logmsg(int, const char *, ...);
111 u_int16_t parse_port(int);
112 u_int16_t pick_proxy_port(void);
113 void proxy_reply(int, struct sockaddr *, u_int16_t);
114 void server_error(struct bufferevent *, short, void *);
115 int server_parse(struct session *s);
116 int allow_data_connection(struct session *s);
117 void server_read(struct bufferevent *, void *);
118 const char *sock_ntop(struct sockaddr *);
119 void usage(void);
120
121 char linebuf[MAX_LINE + 1];
122 size_t linelen;
123
124 char ntop_buf[NTOP_BUFS][INET6_ADDRSTRLEN];
125
126 struct sockaddr_storage fixed_server_ss, fixed_proxy_ss;
127 char *fixed_server, *fixed_server_port, *fixed_proxy, *listen_ip, *listen_port,
128 *qname, *tagname;
129 int anonymous_only, daemonize, id_count, ipv6_mode, loglevel, max_sessions,
130 rfc_mode, session_count, timeout, verbose;
131 extern char *__progname;
132
133 void
134 client_error(struct bufferevent *bufev, short what, void *arg)
135 {
136 struct session *s = arg;
137
138 if (what & EVBUFFER_EOF)
139 logmsg(LOG_INFO, "#%d client close", s->id);
140 else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
141 logmsg(LOG_ERR, "#%d client reset connection", s->id);
142 else if (what & EVBUFFER_TIMEOUT)
143 logmsg(LOG_ERR, "#%d client timeout", s->id);
144 else if (what & EVBUFFER_WRITE)
145 logmsg(LOG_ERR, "#%d client write error: %d", s->id, what);
146 else
147 logmsg(LOG_ERR, "#%d abnormal client error: %d", s->id, what);
148
149 end_session(s);
150 }
151
152 int
153 client_parse(struct session *s)
154 {
155 /* Reset any previous command. */
156 s->cmd = CMD_NONE;
157 s->port = 0;
158
159 /* Commands we are looking for are at least 4 chars long. */
160 if (linelen < 4)
161 return (1);
162
163 if (linebuf[0] == 'P' || linebuf[0] == 'p' ||
164 linebuf[0] == 'E' || linebuf[0] == 'e') {
165 if (!client_parse_cmd(s))
166 return (0);
167
168 /*
169 * Allow active mode connections immediately, instead of
170 * waiting for a positive reply from the server. Some
171 * rare servers/proxies try to probe or setup the data
172 * connection before an actual transfer request.
173 */
174 if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT)
175 return (allow_data_connection(s));
176 }
177
178 if (anonymous_only && (linebuf[0] == 'U' || linebuf[0] == 'u'))
179 return (client_parse_anon(s));
180
181 return (1);
182 }
183
184 int
185 client_parse_anon(struct session *s)
186 {
187 if (strcasecmp("USER ftp\r\n", linebuf) != 0 &&
188 strcasecmp("USER anonymous\r\n", linebuf) != 0) {
189 snprintf(linebuf, sizeof linebuf,
190 "500 Only anonymous FTP allowed\r\n");
191 logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
192
193 /* Talk back to the client ourself. */
194 linelen = strlen(linebuf);
195 bufferevent_write(s->client_bufev, linebuf, linelen);
196
197 /* Clear buffer so it's not sent to the server. */
198 linebuf[0] = '\0';
199 linelen = 0;
200 }
201
202 return (1);
203 }
204
205 int
206 client_parse_cmd(struct session *s)
207 {
208 if (strncasecmp("PASV", linebuf, 4) == 0)
209 s->cmd = CMD_PASV;
210 else if (strncasecmp("PORT ", linebuf, 5) == 0)
211 s->cmd = CMD_PORT;
212 else if (strncasecmp("EPSV", linebuf, 4) == 0)
213 s->cmd = CMD_EPSV;
214 else if (strncasecmp("EPRT ", linebuf, 5) == 0)
215 s->cmd = CMD_EPRT;
216 else
217 return (1);
218
219 if (ipv6_mode && (s->cmd == CMD_PASV || s->cmd == CMD_PORT)) {
220 logmsg(LOG_CRIT, "PASV and PORT not allowed with IPv6");
221 return (0);
222 }
223
224 if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
225 s->port = parse_port(s->cmd);
226 if (s->port < MIN_PORT) {
227 logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
228 linebuf);
229 return (0);
230 }
231 s->proxy_port = pick_proxy_port();
232 proxy_reply(s->cmd, sstosa(&s->proxy_ss), s->proxy_port);
233 logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
234 }
235
236 return (1);
237 }
238
239 void
240 client_read(struct bufferevent *bufev, void *arg)
241 {
242 struct session *s = arg;
243 size_t buf_avail, read;
244 int n;
245
246 do {
247 buf_avail = sizeof s->cbuf - s->cbuf_valid;
248 read = bufferevent_read(bufev, s->cbuf + s->cbuf_valid,
249 buf_avail);
250 s->cbuf_valid += read;
251
252 while ((n = getline(s->cbuf, &s->cbuf_valid)) > 0) {
253 logmsg(LOG_DEBUG, "#%d client: %s", s->id, linebuf);
254 if (!client_parse(s)) {
255 end_session(s);
256 return;
257 }
258 bufferevent_write(s->server_bufev, linebuf, linelen);
259 }
260
261 if (n == -1) {
262 logmsg(LOG_ERR, "#%d client command too long or not"
263 " clean", s->id);
264 end_session(s);
265 return;
266 }
267 } while (read == buf_avail);
268 }
269
270 int
271 drop_privs(void)
272 {
273 struct passwd *pw;
274
275 pw = getpwnam(NOPRIV_USER);
276 if (pw == NULL)
277 return (0);
278
279 tzset();
280 #ifdef __NetBSD__
281 if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
282 setgroups(1, &pw->pw_gid) != 0 ||
283 setgid(pw->pw_gid) != 0 ||
284 setuid(pw->pw_uid) != 0)
285 return (0);
286 #else
287 if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
288 setgroups(1, &pw->pw_gid) != 0 ||
289 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0 ||
290 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
291 return (0);
292 #endif /* !__NetBSD__ */
293
294 return (1);
295 }
296
297 void
298 end_session(struct session *s)
299 {
300 int err;
301
302 logmsg(LOG_INFO, "#%d ending session", s->id);
303
304 if (s->client_fd != -1)
305 close(s->client_fd);
306 if (s->server_fd != -1)
307 close(s->server_fd);
308
309 if (s->client_bufev)
310 bufferevent_free(s->client_bufev);
311 if (s->server_bufev)
312 bufferevent_free(s->server_bufev);
313
314 /* Remove rulesets by commiting empty ones. */
315 err = 0;
316 if (prepare_commit(s->id) == -1)
317 err = errno;
318 else if (do_commit() == -1) {
319 err = errno;
320 do_rollback();
321 }
322 if (err)
323 logmsg(LOG_ERR, "#%d pf rule removal failed: %s", s->id,
324 strerror(err));
325
326 LIST_REMOVE(s, entry);
327 free(s);
328 session_count--;
329 }
330
331 int
332 exit_daemon(void)
333 {
334 struct session *s, *next;
335
336 for (s = LIST_FIRST(&sessions); s != LIST_END(&sessions); s = next) {
337 next = LIST_NEXT(s, entry);
338 end_session(s);
339 }
340
341 if (daemonize)
342 closelog();
343
344 exit(0);
345
346 /* NOTREACHED */
347 return (-1);
348 }
349
350 int
351 getline(char *buf, size_t *valid)
352 {
353 size_t i;
354
355 if (*valid > MAX_LINE)
356 return (-1);
357
358 /* Copy to linebuf while searching for a newline. */
359 for (i = 0; i < *valid; i++) {
360 linebuf[i] = buf[i];
361 if (buf[i] == '\0')
362 return (-1);
363 if (buf[i] == '\n')
364 break;
365 }
366
367 if (i == *valid) {
368 /* No newline found. */
369 linebuf[0] = '\0';
370 linelen = 0;
371 if (i < MAX_LINE)
372 return (0);
373 return (-1);
374 }
375
376 linelen = i + 1;
377 linebuf[linelen] = '\0';
378 *valid -= linelen;
379
380 /* Move leftovers to the start. */
381 if (*valid != 0)
382 bcopy(buf + linelen, buf, *valid);
383
384 return ((int)linelen);
385 }
386
387 void
388 handle_connection(const int listen_fd, short event, void *ev)
389 {
390 struct sockaddr_storage tmp_ss;
391 struct sockaddr *client_sa, *server_sa, *fixed_server_sa;
392 struct sockaddr *client_to_proxy_sa, *proxy_to_server_sa;
393 struct session *s;
394 socklen_t len;
395 int client_fd, fc, on;
396
397 /*
398 * We _must_ accept the connection, otherwise libevent will keep
399 * coming back, and we will chew up all CPU.
400 */
401 client_sa = sstosa(&tmp_ss);
402 len = sizeof(struct sockaddr_storage);
403 if ((client_fd = accept(listen_fd, client_sa, &len)) < 0) {
404 logmsg(LOG_CRIT, "accept failed: %s", strerror(errno));
405 return;
406 }
407
408 /* Refuse connection if the maximum is reached. */
409 if (session_count >= max_sessions) {
410 logmsg(LOG_ERR, "client limit (%d) reached, refusing "
411 "connection from %s", max_sessions, sock_ntop(client_sa));
412 close(client_fd);
413 return;
414 }
415
416 /* Allocate session and copy back the info from the accept(). */
417 s = init_session();
418 if (s == NULL) {
419 logmsg(LOG_CRIT, "init_session failed");
420 close(client_fd);
421 return;
422 }
423 s->client_fd = client_fd;
424 memcpy(sstosa(&s->client_ss), client_sa, client_sa->sa_len);
425
426 /* Cast it once, and be done with it. */
427 client_sa = sstosa(&s->client_ss);
428 server_sa = sstosa(&s->server_ss);
429 client_to_proxy_sa = sstosa(&tmp_ss);
430 proxy_to_server_sa = sstosa(&s->proxy_ss);
431 fixed_server_sa = sstosa(&fixed_server_ss);
432
433 /* Log id/client early to ease debugging. */
434 logmsg(LOG_DEBUG, "#%d accepted connection from %s", s->id,
435 sock_ntop(client_sa));
436
437 /*
438 * Find out the real server and port that the client wanted.
439 */
440 len = sizeof(struct sockaddr_storage);
441 if ((getsockname(s->client_fd, client_to_proxy_sa, &len)) < 0) {
442 logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
443 strerror(errno));
444 goto fail;
445 }
446 if (server_lookup(client_sa, client_to_proxy_sa, server_sa) != 0) {
447 logmsg(LOG_CRIT, "#%d server lookup failed (no rdr?)", s->id);
448 goto fail;
449 }
450 if (fixed_server) {
451 memcpy(sstosa(&s->orig_server_ss), server_sa,
452 server_sa->sa_len);
453 memcpy(server_sa, fixed_server_sa, fixed_server_sa->sa_len);
454 }
455
456 /* XXX: check we are not connecting to ourself. */
457
458 /*
459 * Setup socket and connect to server.
460 */
461 if ((s->server_fd = socket(server_sa->sa_family, SOCK_STREAM,
462 IPPROTO_TCP)) < 0) {
463 logmsg(LOG_CRIT, "#%d server socket failed: %s", s->id,
464 strerror(errno));
465 goto fail;
466 }
467 if (fixed_proxy && bind(s->server_fd, sstosa(&fixed_proxy_ss),
468 fixed_proxy_ss.ss_len) != 0) {
469 logmsg(LOG_CRIT, "#%d cannot bind fixed proxy address: %s",
470 s->id, strerror(errno));
471 goto fail;
472 }
473
474 /* Use non-blocking connect(), see CONNECT_TIMEOUT below. */
475 if ((fc = fcntl(s->server_fd, F_GETFL)) == -1 ||
476 fcntl(s->server_fd, F_SETFL, fc | O_NONBLOCK) == -1) {
477 logmsg(LOG_CRIT, "#%d cannot mark socket non-blocking: %s",
478 s->id, strerror(errno));
479 goto fail;
480 }
481 if (connect(s->server_fd, server_sa, server_sa->sa_len) < 0 &&
482 errno != EINPROGRESS) {
483 logmsg(LOG_CRIT, "#%d proxy cannot connect to server %s: %s",
484 s->id, sock_ntop(server_sa), strerror(errno));
485 goto fail;
486 }
487
488 len = sizeof(struct sockaddr_storage);
489 if ((getsockname(s->server_fd, proxy_to_server_sa, &len)) < 0) {
490 logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
491 strerror(errno));
492 goto fail;
493 }
494
495 logmsg(LOG_INFO, "#%d FTP session %d/%d started: client %s to server "
496 "%s via proxy %s ", s->id, session_count, max_sessions,
497 sock_ntop(client_sa), sock_ntop(server_sa),
498 sock_ntop(proxy_to_server_sa));
499
500 /* Keepalive is nice, but don't care if it fails. */
501 on = 1;
502 setsockopt(s->client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
503 sizeof on);
504 setsockopt(s->server_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
505 sizeof on);
506
507 /*
508 * Setup buffered events.
509 */
510 s->client_bufev = bufferevent_new(s->client_fd, &client_read, NULL,
511 &client_error, s);
512 if (s->client_bufev == NULL) {
513 logmsg(LOG_CRIT, "#%d bufferevent_new client failed", s->id);
514 goto fail;
515 }
516 bufferevent_settimeout(s->client_bufev, timeout, 0);
517 bufferevent_enable(s->client_bufev, EV_READ | EV_TIMEOUT);
518
519 s->server_bufev = bufferevent_new(s->server_fd, &server_read, NULL,
520 &server_error, s);
521 if (s->server_bufev == NULL) {
522 logmsg(LOG_CRIT, "#%d bufferevent_new server failed", s->id);
523 goto fail;
524 }
525 bufferevent_settimeout(s->server_bufev, CONNECT_TIMEOUT, 0);
526 bufferevent_enable(s->server_bufev, EV_READ | EV_TIMEOUT);
527
528 return;
529
530 fail:
531 end_session(s);
532 }
533
534 void
535 handle_signal(int sig, short event, void *arg)
536 {
537 /*
538 * Signal handler rules don't apply, libevent decouples for us.
539 */
540
541 logmsg(LOG_ERR, "%s exiting on signal %d", __progname, sig);
542
543 exit_daemon();
544 }
545
546
547 struct session *
548 init_session(void)
549 {
550 struct session *s;
551
552 s = calloc(1, sizeof(struct session));
553 if (s == NULL)
554 return (NULL);
555
556 s->id = id_count++;
557 s->client_fd = -1;
558 s->server_fd = -1;
559 s->cbuf[0] = '\0';
560 s->cbuf_valid = 0;
561 s->sbuf[0] = '\0';
562 s->sbuf_valid = 0;
563 s->client_bufev = NULL;
564 s->server_bufev = NULL;
565 s->cmd = CMD_NONE;
566 s->port = 0;
567
568 LIST_INSERT_HEAD(&sessions, s, entry);
569 session_count++;
570
571 return (s);
572 }
573
574 void
575 logmsg(int pri, const char *message, ...)
576 {
577 va_list ap;
578
579 if (pri > loglevel)
580 return;
581
582 va_start(ap, message);
583
584 if (daemonize)
585 /* syslog does its own vissing. */
586 vsyslog(pri, message, ap);
587 else {
588 char buf[MAX_LOGLINE];
589 char visbuf[2 * MAX_LOGLINE];
590
591 /* We don't care about truncation. */
592 vsnprintf(buf, sizeof buf, message, ap);
593 #ifdef __NetBSD__
594 size_t len = strlen(buf);
595 if (len > sizeof visbuf) {
596 len = sizeof visbuf;
597 }
598 strvisx(visbuf, buf, len, VIS_CSTYLE | VIS_NL);
599 #else
600 strnvis(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
601 #endif /* !__NetBSD__ */
602 fprintf(stderr, "%s\n", visbuf);
603 }
604
605 va_end(ap);
606 }
607
608 int
609 main(int argc, char *argv[])
610 {
611 struct rlimit rlp;
612 struct addrinfo hints, *res;
613 struct event ev, ev_sighup, ev_sigint, ev_sigterm;
614 int ch, error, listenfd, on;
615 const char *errstr = NULL; /* XXX gcc */
616
617 /* Defaults. */
618 anonymous_only = 0;
619 daemonize = 1;
620 fixed_proxy = NULL;
621 fixed_server = NULL;
622 fixed_server_port = "21";
623 ipv6_mode = 0;
624 listen_ip = NULL;
625 listen_port = "8021";
626 loglevel = LOG_NOTICE;
627 max_sessions = 100;
628 qname = NULL;
629 rfc_mode = 0;
630 tagname = NULL;
631 timeout = 24 * 3600;
632 verbose = 0;
633
634 /* Other initialization. */
635 id_count = 1;
636 session_count = 0;
637
638 while ((ch = getopt(argc, argv, "6Aa:b:D:dm:P:p:q:R:rT:t:v")) != -1) {
639 switch (ch) {
640 case '6':
641 ipv6_mode = 1;
642 break;
643 case 'A':
644 anonymous_only = 1;
645 break;
646 case 'a':
647 fixed_proxy = optarg;
648 break;
649 case 'b':
650 listen_ip = optarg;
651 break;
652 case 'D':
653 loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
654 &errstr);
655 if (errstr)
656 errx(1, "loglevel %s", errstr);
657 break;
658 case 'd':
659 daemonize = 0;
660 break;
661 case 'm':
662 max_sessions = strtonum(optarg, 1, 500, &errstr);
663 if (errstr)
664 errx(1, "max sessions %s", errstr);
665 break;
666 case 'P':
667 fixed_server_port = optarg;
668 break;
669 case 'p':
670 listen_port = optarg;
671 break;
672 case 'q':
673 if (strlen(optarg) >= PF_QNAME_SIZE)
674 errx(1, "queuename too long");
675 qname = optarg;
676 break;
677 case 'R':
678 fixed_server = optarg;
679 break;
680 case 'r':
681 rfc_mode = 1;
682 break;
683 case 'T':
684 if (strlen(optarg) >= PF_TAG_NAME_SIZE)
685 errx(1, "tagname too long");
686 tagname = optarg;
687 break;
688 case 't':
689 timeout = strtonum(optarg, 0, 86400, &errstr);
690 if (errstr)
691 errx(1, "timeout %s", errstr);
692 break;
693 case 'v':
694 verbose++;
695 if (verbose > 2)
696 usage();
697 break;
698 default:
699 usage();
700 }
701 }
702
703 if (listen_ip == NULL)
704 listen_ip = ipv6_mode ? "::1" : "127.0.0.1";
705
706 /* Check for root to save the user from cryptic failure messages. */
707 if (getuid() != 0)
708 errx(1, "needs to start as root");
709
710 /* Raise max. open files limit to satisfy max. sessions. */
711 rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
712 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
713 err(1, "setrlimit");
714
715 if (fixed_proxy) {
716 memset(&hints, 0, sizeof hints);
717 hints.ai_flags = AI_NUMERICHOST;
718 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
719 hints.ai_socktype = SOCK_STREAM;
720 error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
721 if (error)
722 errx(1, "getaddrinfo fixed proxy address failed: %s",
723 gai_strerror(error));
724 memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
725 logmsg(LOG_INFO, "using %s to connect to servers",
726 sock_ntop(sstosa(&fixed_proxy_ss)));
727 freeaddrinfo(res);
728 }
729
730 if (fixed_server) {
731 memset(&hints, 0, sizeof hints);
732 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
733 hints.ai_socktype = SOCK_STREAM;
734 error = getaddrinfo(fixed_server, fixed_server_port, &hints,
735 &res);
736 if (error)
737 errx(1, "getaddrinfo fixed server address failed: %s",
738 gai_strerror(error));
739 memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
740 logmsg(LOG_INFO, "using fixed server %s",
741 sock_ntop(sstosa(&fixed_server_ss)));
742 freeaddrinfo(res);
743 }
744
745 /* Setup listener. */
746 memset(&hints, 0, sizeof hints);
747 hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
748 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
749 hints.ai_socktype = SOCK_STREAM;
750 error = getaddrinfo(listen_ip, listen_port, &hints, &res);
751 if (error)
752 errx(1, "getaddrinfo listen address failed: %s",
753 gai_strerror(error));
754 if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
755 errx(1, "socket failed");
756 on = 1;
757 if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
758 sizeof on) != 0)
759 err(1, "setsockopt failed");
760 if (bind(listenfd, (struct sockaddr *)res->ai_addr,
761 (socklen_t)res->ai_addrlen) != 0)
762 err(1, "bind failed");
763 if (listen(listenfd, TCP_BACKLOG) != 0)
764 err(1, "listen failed");
765 freeaddrinfo(res);
766
767 /* Initialize pf. */
768 init_filter(qname, tagname, verbose);
769
770 if (daemonize) {
771 if (daemon(0, 0) == -1)
772 err(1, "cannot daemonize");
773 openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
774 }
775
776 /* Use logmsg for output from here on. */
777
778 if (!drop_privs()) {
779 logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
780 exit(1);
781 }
782
783 event_init();
784
785 /* Setup signal handler. */
786 signal(SIGPIPE, SIG_IGN);
787 signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
788 signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
789 signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
790 signal_add(&ev_sighup, NULL);
791 signal_add(&ev_sigint, NULL);
792 signal_add(&ev_sigterm, NULL);
793
794 event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev);
795 event_add(&ev, 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 + (arc4random() %
865 (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 = -1;
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 /* rdr from $client to $orig_server port $proxy_port -> $server
999 port $port */
1000 if (add_rdr(s->id, client_sa, orig_sa, s->proxy_port,
1001 server_sa, s->port) == -1)
1002 goto fail;
1003
1004 /* nat from $client to $server port $port -> $proxy */
1005 if (add_nat(s->id, client_sa, server_sa, s->port, proxy_sa,
1006 PF_NAT_PROXY_PORT_LOW, PF_NAT_PROXY_PORT_HIGH) == -1)
1007 goto fail;
1008
1009 /* pass in from $client to $server port $port */
1010 if (add_filter(s->id, PF_IN, client_sa, server_sa,
1011 s->port) == -1)
1012 goto fail;
1013
1014 /* pass out from $proxy to $server port $port */
1015 if (add_filter(s->id, PF_OUT, proxy_sa, server_sa,
1016 s->port) == -1)
1017 goto fail;
1018 }
1019
1020 /* Active modes. */
1021 if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
1022 logmsg(LOG_INFO, "#%d active: server to client port %d"
1023 " via port %d", s->id, s->port, s->proxy_port);
1024
1025 if (prepare_commit(s->id) == -1)
1026 goto fail;
1027 prepared = 1;
1028
1029 /* rdr from $server to $proxy port $proxy_port -> $client port
1030 $port */
1031 if (add_rdr(s->id, server_sa, proxy_sa, s->proxy_port,
1032 client_sa, s->port) == -1)
1033 goto fail;
1034
1035 /* nat from $server to $client port $port -> $orig_server port
1036 $natport */
1037 if (rfc_mode && s->cmd == CMD_PORT) {
1038 /* Rewrite sourceport to RFC mandated 20. */
1039 if (add_nat(s->id, server_sa, client_sa, s->port,
1040 orig_sa, 20, 20) == -1)
1041 goto fail;
1042 } else {
1043 /* Let pf pick a source port from the standard range. */
1044 if (add_nat(s->id, server_sa, client_sa, s->port,
1045 orig_sa, PF_NAT_PROXY_PORT_LOW,
1046 PF_NAT_PROXY_PORT_HIGH) == -1)
1047 goto fail;
1048 }
1049
1050 /* pass in from $server to $client port $port */
1051 if (add_filter(s->id, PF_IN, server_sa, client_sa, s->port) ==
1052 -1)
1053 goto fail;
1054
1055 /* pass out from $orig_server to $client port $port */
1056 if (add_filter(s->id, PF_OUT, orig_sa, client_sa, s->port) ==
1057 -1)
1058 goto fail;
1059 }
1060
1061 /* Commit rules if they were prepared. */
1062 if (prepared && (do_commit() == -1)) {
1063 if (errno != EBUSY)
1064 goto fail;
1065 /* One more try if busy. */
1066 usleep(5000);
1067 if (do_commit() == -1)
1068 goto fail;
1069 }
1070
1071 s->cmd = CMD_NONE;
1072 s->port = 0;
1073
1074 return (1);
1075
1076 fail:
1077 logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
1078 if (prepared)
1079 do_rollback();
1080 return (0);
1081 }
1082
1083 void
1084 server_read(struct bufferevent *bufev, void *arg)
1085 {
1086 struct session *s = arg;
1087 size_t buf_avail, read;
1088 int n;
1089
1090 bufferevent_settimeout(bufev, timeout, 0);
1091
1092 do {
1093 buf_avail = sizeof s->sbuf - s->sbuf_valid;
1094 read = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
1095 buf_avail);
1096 s->sbuf_valid += read;
1097
1098 while ((n = getline(s->sbuf, &s->sbuf_valid)) > 0) {
1099 logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
1100 if (!server_parse(s)) {
1101 end_session(s);
1102 return;
1103 }
1104 bufferevent_write(s->client_bufev, linebuf, linelen);
1105 }
1106
1107 if (n == -1) {
1108 logmsg(LOG_ERR, "#%d server reply too long or not"
1109 " clean", s->id);
1110 end_session(s);
1111 return;
1112 }
1113 } while (read == buf_avail);
1114 }
1115
1116 const char *
1117 sock_ntop(struct sockaddr *sa)
1118 {
1119 static int n = 0;
1120
1121 /* Cycle to next buffer. */
1122 n = (n + 1) % NTOP_BUFS;
1123 ntop_buf[n][0] = '\0';
1124
1125 if (sa->sa_family == AF_INET) {
1126 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1127
1128 return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
1129 sizeof ntop_buf[0]));
1130 }
1131
1132 if (sa->sa_family == AF_INET6) {
1133 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
1134
1135 return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
1136 sizeof ntop_buf[0]));
1137 }
1138
1139 return (NULL);
1140 }
1141
1142 void
1143 usage(void)
1144 {
1145 fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
1146 " [-D level] [-m maxsessions]\n [-P port]"
1147 " [-p port] [-q queue] [-R address] [-T tag] [-t timeout]\n", __progname);
1148 exit(1);
1149 }
1150