ftp-proxy.c revision 1.1.2.1 1 /* $NetBSD: ftp-proxy.c,v 1.1.2.1 2008/04/26 12:57:42 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 strvisx(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
595 #else
596 strnvis(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
597 #endif /* !__NetBSD__ */
598 fprintf(stderr, "%s\n", visbuf);
599 }
600
601 va_end(ap);
602 }
603
604 int
605 main(int argc, char *argv[])
606 {
607 struct rlimit rlp;
608 struct addrinfo hints, *res;
609 struct event ev, ev_sighup, ev_sigint, ev_sigterm;
610 int ch, error, listenfd, on;
611 const char *errstr = NULL; /* XXX gcc */
612
613 /* Defaults. */
614 anonymous_only = 0;
615 daemonize = 1;
616 fixed_proxy = NULL;
617 fixed_server = NULL;
618 fixed_server_port = "21";
619 ipv6_mode = 0;
620 listen_ip = NULL;
621 listen_port = "8021";
622 loglevel = LOG_NOTICE;
623 max_sessions = 100;
624 qname = NULL;
625 rfc_mode = 0;
626 tagname = NULL;
627 timeout = 24 * 3600;
628 verbose = 0;
629
630 /* Other initialization. */
631 id_count = 1;
632 session_count = 0;
633
634 while ((ch = getopt(argc, argv, "6Aa:b:D:dm:P:p:q:R:rT:t:v")) != -1) {
635 switch (ch) {
636 case '6':
637 ipv6_mode = 1;
638 break;
639 case 'A':
640 anonymous_only = 1;
641 break;
642 case 'a':
643 fixed_proxy = optarg;
644 break;
645 case 'b':
646 listen_ip = optarg;
647 break;
648 case 'D':
649 loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
650 &errstr);
651 if (errstr)
652 errx(1, "loglevel %s", errstr);
653 break;
654 case 'd':
655 daemonize = 0;
656 break;
657 case 'm':
658 max_sessions = strtonum(optarg, 1, 500, &errstr);
659 if (errstr)
660 errx(1, "max sessions %s", errstr);
661 break;
662 case 'P':
663 fixed_server_port = optarg;
664 break;
665 case 'p':
666 listen_port = optarg;
667 break;
668 case 'q':
669 if (strlen(optarg) >= PF_QNAME_SIZE)
670 errx(1, "queuename too long");
671 qname = optarg;
672 break;
673 case 'R':
674 fixed_server = optarg;
675 break;
676 case 'r':
677 rfc_mode = 1;
678 break;
679 case 'T':
680 if (strlen(optarg) >= PF_TAG_NAME_SIZE)
681 errx(1, "tagname too long");
682 tagname = optarg;
683 break;
684 case 't':
685 timeout = strtonum(optarg, 0, 86400, &errstr);
686 if (errstr)
687 errx(1, "timeout %s", errstr);
688 break;
689 case 'v':
690 verbose++;
691 if (verbose > 2)
692 usage();
693 break;
694 default:
695 usage();
696 }
697 }
698
699 if (listen_ip == NULL)
700 listen_ip = ipv6_mode ? "::1" : "127.0.0.1";
701
702 /* Check for root to save the user from cryptic failure messages. */
703 if (getuid() != 0)
704 errx(1, "needs to start as root");
705
706 /* Raise max. open files limit to satisfy max. sessions. */
707 rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
708 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
709 err(1, "setrlimit");
710
711 if (fixed_proxy) {
712 memset(&hints, 0, sizeof hints);
713 hints.ai_flags = AI_NUMERICHOST;
714 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
715 hints.ai_socktype = SOCK_STREAM;
716 error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
717 if (error)
718 errx(1, "getaddrinfo fixed proxy address failed: %s",
719 gai_strerror(error));
720 memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
721 logmsg(LOG_INFO, "using %s to connect to servers",
722 sock_ntop(sstosa(&fixed_proxy_ss)));
723 freeaddrinfo(res);
724 }
725
726 if (fixed_server) {
727 memset(&hints, 0, sizeof hints);
728 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
729 hints.ai_socktype = SOCK_STREAM;
730 error = getaddrinfo(fixed_server, fixed_server_port, &hints,
731 &res);
732 if (error)
733 errx(1, "getaddrinfo fixed server address failed: %s",
734 gai_strerror(error));
735 memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
736 logmsg(LOG_INFO, "using fixed server %s",
737 sock_ntop(sstosa(&fixed_server_ss)));
738 freeaddrinfo(res);
739 }
740
741 /* Setup listener. */
742 memset(&hints, 0, sizeof hints);
743 hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
744 hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
745 hints.ai_socktype = SOCK_STREAM;
746 error = getaddrinfo(listen_ip, listen_port, &hints, &res);
747 if (error)
748 errx(1, "getaddrinfo listen address failed: %s",
749 gai_strerror(error));
750 if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
751 errx(1, "socket failed");
752 on = 1;
753 if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
754 sizeof on) != 0)
755 err(1, "setsockopt failed");
756 if (bind(listenfd, (struct sockaddr *)res->ai_addr,
757 (socklen_t)res->ai_addrlen) != 0)
758 err(1, "bind failed");
759 if (listen(listenfd, TCP_BACKLOG) != 0)
760 err(1, "listen failed");
761 freeaddrinfo(res);
762
763 /* Initialize pf. */
764 init_filter(qname, tagname, verbose);
765
766 if (daemonize) {
767 if (daemon(0, 0) == -1)
768 err(1, "cannot daemonize");
769 openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
770 }
771
772 /* Use logmsg for output from here on. */
773
774 if (!drop_privs()) {
775 logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
776 exit(1);
777 }
778
779 event_init();
780
781 /* Setup signal handler. */
782 signal(SIGPIPE, SIG_IGN);
783 signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
784 signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
785 signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
786 signal_add(&ev_sighup, NULL);
787 signal_add(&ev_sigint, NULL);
788 signal_add(&ev_sigterm, NULL);
789
790 event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev);
791 event_add(&ev, NULL);
792
793 logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);
794
795 /* Vroom, vroom. */
796 event_dispatch();
797
798 logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
799 exit_daemon();
800
801 /* NOTREACHED */
802 return (1);
803 }
804
805 u_int16_t
806 parse_port(int mode)
807 {
808 unsigned int port, v[6];
809 int n;
810 char *p;
811
812 /* Find the last space or left-parenthesis. */
813 for (p = linebuf + linelen; p > linebuf; p--)
814 if (*p == ' ' || *p == '(')
815 break;
816 if (p == linebuf)
817 return (0);
818
819 switch (mode) {
820 case CMD_PORT:
821 n = sscanf(p, " %u,%u,%u,%u,%u,%u", &v[0], &v[1], &v[2],
822 &v[3], &v[4], &v[5]);
823 if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
824 v[3] < 256 && v[4] < 256 && v[5] < 256)
825 return ((v[4] << 8) | v[5]);
826 break;
827 case CMD_PASV:
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_EPSV:
835 n = sscanf(p, "(|||%u|)", &port);
836 if (n == 1 && port < 65536)
837 return (port);
838 break;
839 case CMD_EPRT:
840 n = sscanf(p, " |1|%u.%u.%u.%u|%u|", &v[0], &v[1], &v[2],
841 &v[3], &port);
842 if (n == 5 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
843 v[3] < 256 && port < 65536)
844 return (port);
845 n = sscanf(p, " |2|%*[a-fA-F0-9:]|%u|", &port);
846 if (n == 1 && port < 65536)
847 return (port);
848 break;
849 default:
850 return (0);
851 }
852
853 return (0);
854 }
855
856 u_int16_t
857 pick_proxy_port(void)
858 {
859 /* Random should be good enough for avoiding port collisions. */
860 return (IPPORT_HIFIRSTAUTO + (arc4random() %
861 (IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO)));
862 }
863
864 void
865 proxy_reply(int cmd, struct sockaddr *sa, u_int16_t port)
866 {
867 int i, r = -1;
868
869 switch (cmd) {
870 case CMD_PORT:
871 r = snprintf(linebuf, sizeof linebuf,
872 "PORT %s,%u,%u\r\n", sock_ntop(sa), port / 256,
873 port % 256);
874 break;
875 case CMD_PASV:
876 r = snprintf(linebuf, sizeof linebuf,
877 "227 Entering Passive Mode (%s,%u,%u)\r\n", sock_ntop(sa),
878 port / 256, port % 256);
879 break;
880 case CMD_EPRT:
881 if (sa->sa_family == AF_INET)
882 r = snprintf(linebuf, sizeof linebuf,
883 "EPRT |1|%s|%u|\r\n", sock_ntop(sa), port);
884 else if (sa->sa_family == AF_INET6)
885 r = snprintf(linebuf, sizeof linebuf,
886 "EPRT |2|%s|%u|\r\n", sock_ntop(sa), port);
887 break;
888 case CMD_EPSV:
889 r = snprintf(linebuf, sizeof linebuf,
890 "229 Entering Extended Passive Mode (|||%u|)\r\n", port);
891 break;
892 }
893
894 if (r < 0 || r >= sizeof linebuf) {
895 logmsg(LOG_ERR, "proxy_reply failed: %d", r);
896 linebuf[0] = '\0';
897 linelen = 0;
898 return;
899 }
900 linelen = (size_t)r;
901
902 if (cmd == CMD_PORT || cmd == CMD_PASV) {
903 /* Replace dots in IP address with commas. */
904 for (i = 0; i < linelen; i++)
905 if (linebuf[i] == '.')
906 linebuf[i] = ',';
907 }
908 }
909
910 void
911 server_error(struct bufferevent *bufev, short what, void *arg)
912 {
913 struct session *s = arg;
914
915 if (what & EVBUFFER_EOF)
916 logmsg(LOG_INFO, "#%d server close", s->id);
917 else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
918 logmsg(LOG_ERR, "#%d server refused connection", s->id);
919 else if (what & EVBUFFER_WRITE)
920 logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
921 else if (what & EVBUFFER_TIMEOUT)
922 logmsg(LOG_NOTICE, "#%d server timeout", s->id);
923 else
924 logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);
925
926 end_session(s);
927 }
928
929 int
930 server_parse(struct session *s)
931 {
932 if (s->cmd == CMD_NONE || linelen < 4 || linebuf[0] != '2')
933 goto out;
934
935 if ((s->cmd == CMD_PASV && strncmp("227 ", linebuf, 4) == 0) ||
936 (s->cmd == CMD_EPSV && strncmp("229 ", linebuf, 4) == 0))
937 return (allow_data_connection(s));
938
939 out:
940 s->cmd = CMD_NONE;
941 s->port = 0;
942
943 return (1);
944 }
945
946 int
947 allow_data_connection(struct session *s)
948 {
949 struct sockaddr *client_sa, *orig_sa, *proxy_sa, *server_sa;
950 int prepared = 0;
951
952 /*
953 * The pf rules below do quite some NAT rewriting, to keep up
954 * appearances. Points to keep in mind:
955 * 1) The client must think it's talking to the real server,
956 * for both control and data connections. Transparently.
957 * 2) The server must think that the proxy is the client.
958 * 3) Source and destination ports are rewritten to minimize
959 * port collisions, to aid security (some systems pick weak
960 * ports) or to satisfy RFC requirements (source port 20).
961 */
962
963 /* Cast this once, to make code below it more readable. */
964 client_sa = sstosa(&s->client_ss);
965 server_sa = sstosa(&s->server_ss);
966 proxy_sa = sstosa(&s->proxy_ss);
967 if (fixed_server)
968 /* Fixed server: data connections must appear to come
969 from / go to the original server, not the fixed one. */
970 orig_sa = sstosa(&s->orig_server_ss);
971 else
972 /* Server not fixed: orig_server == server. */
973 orig_sa = sstosa(&s->server_ss);
974
975 /* Passive modes. */
976 if (s->cmd == CMD_PASV || s->cmd == CMD_EPSV) {
977 s->port = parse_port(s->cmd);
978 if (s->port < MIN_PORT) {
979 logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
980 linebuf);
981 return (0);
982 }
983 s->proxy_port = pick_proxy_port();
984 logmsg(LOG_INFO, "#%d passive: client to server port %d"
985 " via port %d", s->id, s->port, s->proxy_port);
986
987 if (prepare_commit(s->id) == -1)
988 goto fail;
989 prepared = 1;
990
991 proxy_reply(s->cmd, orig_sa, s->proxy_port);
992 logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
993
994 /* rdr from $client to $orig_server port $proxy_port -> $server
995 port $port */
996 if (add_rdr(s->id, client_sa, orig_sa, s->proxy_port,
997 server_sa, s->port) == -1)
998 goto fail;
999
1000 /* nat from $client to $server port $port -> $proxy */
1001 if (add_nat(s->id, client_sa, server_sa, s->port, proxy_sa,
1002 PF_NAT_PROXY_PORT_LOW, PF_NAT_PROXY_PORT_HIGH) == -1)
1003 goto fail;
1004
1005 /* pass in from $client to $server port $port */
1006 if (add_filter(s->id, PF_IN, client_sa, server_sa,
1007 s->port) == -1)
1008 goto fail;
1009
1010 /* pass out from $proxy to $server port $port */
1011 if (add_filter(s->id, PF_OUT, proxy_sa, server_sa,
1012 s->port) == -1)
1013 goto fail;
1014 }
1015
1016 /* Active modes. */
1017 if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
1018 logmsg(LOG_INFO, "#%d active: server to client port %d"
1019 " via port %d", s->id, s->port, s->proxy_port);
1020
1021 if (prepare_commit(s->id) == -1)
1022 goto fail;
1023 prepared = 1;
1024
1025 /* rdr from $server to $proxy port $proxy_port -> $client port
1026 $port */
1027 if (add_rdr(s->id, server_sa, proxy_sa, s->proxy_port,
1028 client_sa, s->port) == -1)
1029 goto fail;
1030
1031 /* nat from $server to $client port $port -> $orig_server port
1032 $natport */
1033 if (rfc_mode && s->cmd == CMD_PORT) {
1034 /* Rewrite sourceport to RFC mandated 20. */
1035 if (add_nat(s->id, server_sa, client_sa, s->port,
1036 orig_sa, 20, 20) == -1)
1037 goto fail;
1038 } else {
1039 /* Let pf pick a source port from the standard range. */
1040 if (add_nat(s->id, server_sa, client_sa, s->port,
1041 orig_sa, PF_NAT_PROXY_PORT_LOW,
1042 PF_NAT_PROXY_PORT_HIGH) == -1)
1043 goto fail;
1044 }
1045
1046 /* pass in from $server to $client port $port */
1047 if (add_filter(s->id, PF_IN, server_sa, client_sa, s->port) ==
1048 -1)
1049 goto fail;
1050
1051 /* pass out from $orig_server to $client port $port */
1052 if (add_filter(s->id, PF_OUT, orig_sa, client_sa, s->port) ==
1053 -1)
1054 goto fail;
1055 }
1056
1057 /* Commit rules if they were prepared. */
1058 if (prepared && (do_commit() == -1)) {
1059 if (errno != EBUSY)
1060 goto fail;
1061 /* One more try if busy. */
1062 usleep(5000);
1063 if (do_commit() == -1)
1064 goto fail;
1065 }
1066
1067 s->cmd = CMD_NONE;
1068 s->port = 0;
1069
1070 return (1);
1071
1072 fail:
1073 logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
1074 if (prepared)
1075 do_rollback();
1076 return (0);
1077 }
1078
1079 void
1080 server_read(struct bufferevent *bufev, void *arg)
1081 {
1082 struct session *s = arg;
1083 size_t buf_avail, read;
1084 int n;
1085
1086 bufferevent_settimeout(bufev, timeout, 0);
1087
1088 do {
1089 buf_avail = sizeof s->sbuf - s->sbuf_valid;
1090 read = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
1091 buf_avail);
1092 s->sbuf_valid += read;
1093
1094 while ((n = getline(s->sbuf, &s->sbuf_valid)) > 0) {
1095 logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
1096 if (!server_parse(s)) {
1097 end_session(s);
1098 return;
1099 }
1100 bufferevent_write(s->client_bufev, linebuf, linelen);
1101 }
1102
1103 if (n == -1) {
1104 logmsg(LOG_ERR, "#%d server reply too long or not"
1105 " clean", s->id);
1106 end_session(s);
1107 return;
1108 }
1109 } while (read == buf_avail);
1110 }
1111
1112 const char *
1113 sock_ntop(struct sockaddr *sa)
1114 {
1115 static int n = 0;
1116
1117 /* Cycle to next buffer. */
1118 n = (n + 1) % NTOP_BUFS;
1119 ntop_buf[n][0] = '\0';
1120
1121 if (sa->sa_family == AF_INET) {
1122 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1123
1124 return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
1125 sizeof ntop_buf[0]));
1126 }
1127
1128 if (sa->sa_family == AF_INET6) {
1129 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
1130
1131 return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
1132 sizeof ntop_buf[0]));
1133 }
1134
1135 return (NULL);
1136 }
1137
1138 void
1139 usage(void)
1140 {
1141 fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
1142 " [-D level] [-m maxsessions]\n [-P port]"
1143 " [-p port] [-q queue] [-R address] [-T tag] [-t timeout]\n", __progname);
1144 exit(1);
1145 }
1146