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