summaryrefslogtreecommitdiffstats
path: root/contrib/pf/ftp-proxy/ftp-proxy.c
diff options
context:
space:
mode:
Diffstat (limited to 'contrib/pf/ftp-proxy/ftp-proxy.c')
-rw-r--r--contrib/pf/ftp-proxy/ftp-proxy.c2123
1 files changed, 927 insertions, 1196 deletions
diff --git a/contrib/pf/ftp-proxy/ftp-proxy.c b/contrib/pf/ftp-proxy/ftp-proxy.c
index ea4245a..06c8487 100644
--- a/contrib/pf/ftp-proxy/ftp-proxy.c
+++ b/contrib/pf/ftp-proxy/ftp-proxy.c
@@ -1,87 +1,39 @@
-/* $OpenBSD: ftp-proxy.c,v 1.41 2005/03/05 23:11:19 cloder Exp $ */
+/* $OpenBSD: ftp-proxy.c,v 1.13 2006/12/30 13:24:00 camield Exp $ */
/*
- * Copyright (c) 1996-2001
- * Obtuse Systems Corporation. All rights reserved.
+ * Copyright (c) 2004, 2005 Camiel Dobbelaar, <cd@sentia.nl>
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the Obtuse Systems nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY OBTUSE SYSTEMS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL OBTUSE SYSTEMS CORPORATION OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
*
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
-/*
- * ftp proxy, Originally based on juniper_ftp_proxy from the Obtuse
- * Systems juniper firewall, written by Dan Boulet <danny@obtuse.com>
- * and Bob Beck <beck@obtuse.com>
- *
- * This version basically passes everything through unchanged except
- * for the PORT and the * "227 Entering Passive Mode" reply.
- *
- * A PORT command is handled by noting the IP address and port number
- * specified and then configuring a listen port on some very high port
- * number and telling the server about it using a PORT message.
- * We then watch for an in-bound connection on the port from the server
- * and connect to the client's port when it happens.
- *
- * A "227 Entering Passive Mode" reply is handled by noting the IP address
- * and port number specified and then configuring a listen port on some
- * very high port number and telling the client about it using a
- * "227 Entering Passive Mode" reply.
- * We then watch for an in-bound connection on the port from the client
- * and connect to the server's port when it happens.
- *
- * supports tcp wrapper lookups/access control with the -w flag using
- * the real destination address - the tcp wrapper stuff is done after
- * the real destination address is retrieved from pf
- *
- */
-
-/*
- * TODO:
- * Plenty, this is very basic, with the idea to get it in clean first.
- *
- * - IPv6 and EPASV support
- * - Content filter support
- * - filename filter support
- * - per-user rules perhaps.
- */
-
-#include <sys/param.h>
+#include <sys/queue.h>
+#include <sys/types.h>
#include <sys/time.h>
+#include <sys/resource.h>
#include <sys/socket.h>
#include <net/if.h>
+#include <net/pfvar.h>
#include <netinet/in.h>
-
#include <arpa/inet.h>
-#include <ctype.h>
+#include <err.h>
#include <errno.h>
-#include <grp.h>
+#include <event.h>
+#include <fcntl.h>
#include <netdb.h>
#include <pwd.h>
#include <signal.h>
@@ -89,1288 +41,1067 @@ __FBSDID("$FreeBSD$");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sysexits.h>
#include <syslog.h>
#include <unistd.h>
-
-#include "util.h"
-
-#ifdef LIBWRAP
-#include <tcpd.h>
-int allow_severity = LOG_INFO;
-int deny_severity = LOG_NOTICE;
-#endif /* LIBWRAP */
-
-int min_port = IPPORT_HIFIRSTAUTO;
-int max_port = IPPORT_HILASTAUTO;
-
-#define STARTBUFSIZE 1024 /* Must be at least 3 */
-
-/*
- * Variables used to support PORT mode connections.
- *
- * This gets a bit complicated.
- *
- * If PORT mode is on then client_listen_sa describes the socket that
- * the real client is listening on and server_listen_sa describes the
- * socket that we are listening on (waiting for the real server to connect
- * with us).
- *
- * If PASV mode is on then client_listen_sa describes the socket that
- * we are listening on (waiting for the real client to connect to us on)
- * and server_listen_sa describes the socket that the real server is
- * listening on.
- *
- * If the socket we are listening on gets a connection then we connect
- * to the other side's socket. Similarly, if a connected socket is
- * shutdown then we shutdown the other side's socket.
- */
-
-double xfer_start_time;
-
-struct sockaddr_in real_server_sa;
-struct sockaddr_in client_listen_sa;
-struct sockaddr_in server_listen_sa;
-struct sockaddr_in proxy_sa;
-struct in_addr src_addr;
-
-int client_listen_socket = -1; /* Only used in PASV mode */
-int client_data_socket = -1; /* Connected socket to real client */
-int server_listen_socket = -1; /* Only used in PORT mode */
-int server_data_socket = -1; /* Connected socket to real server */
-int client_data_bytes, server_data_bytes;
-
-int AnonFtpOnly;
-int Verbose;
-int NatMode;
-int ReverseMode;
-
-char ClientName[NI_MAXHOST];
-char RealServerName[NI_MAXHOST];
-char OurName[NI_MAXHOST];
-
-const char *User = "proxy";
-const char *Group;
-
-extern int Debug_Level;
-extern int Use_Rdns;
-extern in_addr_t Bind_Addr;
+#include <vis.h>
+
+#include "filter.h"
+
+#define CONNECT_TIMEOUT 30
+#define MIN_PORT 1024
+#define MAX_LINE 500
+#define MAX_LOGLINE 300
+#define NTOP_BUFS 3
+#define TCP_BACKLOG 10
+
+#define CHROOT_DIR "/var/empty"
+#define NOPRIV_USER "proxy"
+
+/* pfctl standard NAT range. */
+#define PF_NAT_PROXY_PORT_LOW 50001
+#define PF_NAT_PROXY_PORT_HIGH 65535
+
+#define sstosa(ss) ((struct sockaddr *)(ss))
+
+enum { CMD_NONE = 0, CMD_PORT, CMD_EPRT, CMD_PASV, CMD_EPSV };
+
+struct session {
+ u_int32_t id;
+ struct sockaddr_storage client_ss;
+ struct sockaddr_storage proxy_ss;
+ struct sockaddr_storage server_ss;
+ struct sockaddr_storage orig_server_ss;
+ struct bufferevent *client_bufev;
+ struct bufferevent *server_bufev;
+ int client_fd;
+ int server_fd;
+ char cbuf[MAX_LINE];
+ size_t cbuf_valid;
+ char sbuf[MAX_LINE];
+ size_t sbuf_valid;
+ int cmd;
+ u_int16_t port;
+ u_int16_t proxy_port;
+ LIST_ENTRY(session) entry;
+};
+
+LIST_HEAD(, session) sessions = LIST_HEAD_INITIALIZER(sessions);
+
+void client_error(struct bufferevent *, short, void *);
+int client_parse(struct session *s);
+int client_parse_anon(struct session *s);
+int client_parse_cmd(struct session *s);
+void client_read(struct bufferevent *, void *);
+int drop_privs(void);
+void end_session(struct session *);
+int exit_daemon(void);
+int getline(char *, size_t *);
+void handle_connection(const int, short, void *);
+void handle_signal(int, short, void *);
+struct session * init_session(void);
+void logmsg(int, const char *, ...);
+u_int16_t parse_port(int);
+u_int16_t pick_proxy_port(void);
+void proxy_reply(int, struct sockaddr *, u_int16_t);
+void server_error(struct bufferevent *, short, void *);
+int server_parse(struct session *s);
+void server_read(struct bufferevent *, void *);
+const char *sock_ntop(struct sockaddr *);
+void usage(void);
+
+char linebuf[MAX_LINE + 1];
+size_t linelen;
+
+char ntop_buf[NTOP_BUFS][INET6_ADDRSTRLEN];
+
+struct sockaddr_storage fixed_server_ss, fixed_proxy_ss;
+char *fixed_server, *fixed_server_port, *fixed_proxy, *listen_ip, *listen_port,
+ *qname;
+int anonymous_only, daemonize, id_count, ipv6_mode, loglevel, max_sessions,
+ rfc_mode, session_count, timeout, verbose;
extern char *__progname;
-typedef enum {
- UNKNOWN_MODE,
- PORT_MODE,
- PASV_MODE,
- EPRT_MODE,
- EPSV_MODE
-} connection_mode_t;
-
-connection_mode_t connection_mode;
-
-extern void debuglog(int debug_level, const char *fmt, ...);
-double wallclock_time(void);
-void show_xfer_stats(void);
-void log_control_command (char *cmd, int client);
-int new_dataconn(int server);
-void do_client_cmd(struct csiob *client, struct csiob *server);
-void do_server_reply(struct csiob *server, struct csiob *client);
-static void
-usage(void)
+void
+client_error(struct bufferevent *bufev, short what, void *arg)
{
- syslog(LOG_NOTICE,
- "usage: %s [-AnrVw] [-a address] [-D debuglevel] [-g group]"
- " [-M maxport] [-m minport] [-R address[:port]] [-S address]"
- " [-t timeout] [-u user]", __progname);
- exit(EX_USAGE);
+ struct session *s = arg;
+
+ if (what & EVBUFFER_EOF)
+ logmsg(LOG_INFO, "#%d client close", s->id);
+ else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
+ logmsg(LOG_ERR, "#%d client reset connection", s->id);
+ else if (what & EVBUFFER_TIMEOUT)
+ logmsg(LOG_ERR, "#%d client timeout", s->id);
+ else if (what & EVBUFFER_WRITE)
+ logmsg(LOG_ERR, "#%d client write error: %d", s->id, what);
+ else
+ logmsg(LOG_ERR, "#%d abnormal client error: %d", s->id, what);
+
+ end_session(s);
}
-static void
-close_client_data(void)
+int
+client_parse(struct session *s)
{
- if (client_data_socket >= 0) {
- shutdown(client_data_socket, 2);
- close(client_data_socket);
- client_data_socket = -1;
- }
+ /* Reset any previous command. */
+ s->cmd = CMD_NONE;
+ s->port = 0;
+
+ /* Commands we are looking for are at least 4 chars long. */
+ if (linelen < 4)
+ return (1);
+
+ if (linebuf[0] == 'P' || linebuf[0] == 'p' ||
+ linebuf[0] == 'E' || linebuf[0] == 'e')
+ return (client_parse_cmd(s));
+
+ if (anonymous_only && (linebuf[0] == 'U' || linebuf[0] == 'u'))
+ return (client_parse_anon(s));
+
+ return (1);
}
-static void
-close_server_data(void)
+int
+client_parse_anon(struct session *s)
{
- if (server_data_socket >= 0) {
- shutdown(server_data_socket, 2);
- close(server_data_socket);
- server_data_socket = -1;
+ if (strcasecmp("USER ftp\r\n", linebuf) != 0 &&
+ strcasecmp("USER anonymous\r\n", linebuf) != 0) {
+ snprintf(linebuf, sizeof linebuf,
+ "500 Only anonymous FTP allowed\r\n");
+ logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
+
+ /* Talk back to the client ourself. */
+ linelen = strlen(linebuf);
+ bufferevent_write(s->client_bufev, linebuf, linelen);
+
+ /* Clear buffer so it's not sent to the server. */
+ linebuf[0] = '\0';
+ linelen = 0;
}
+
+ return (1);
}
-static void
-drop_privs(void)
+int
+client_parse_cmd(struct session *s)
{
- struct passwd *pw;
- struct group *gr;
- uid_t uid = 0;
- gid_t gid = 0;
-
- if (User != NULL) {
- pw = getpwnam(User);
- if (pw == NULL) {
- syslog(LOG_ERR, "cannot find user %s", User);
- exit(EX_USAGE);
- }
- uid = pw->pw_uid;
- gid = pw->pw_gid;
- }
+ if (strncasecmp("PASV", linebuf, 4) == 0)
+ s->cmd = CMD_PASV;
+ else if (strncasecmp("PORT ", linebuf, 5) == 0)
+ s->cmd = CMD_PORT;
+ else if (strncasecmp("EPSV", linebuf, 4) == 0)
+ s->cmd = CMD_EPSV;
+ else if (strncasecmp("EPRT ", linebuf, 5) == 0)
+ s->cmd = CMD_EPRT;
+ else
+ return (1);
- if (Group != NULL) {
- gr = getgrnam(Group);
- if (gr == NULL) {
- syslog(LOG_ERR, "cannot find group %s", Group);
- exit(EX_USAGE);
- }
- gid = gr->gr_gid;
+ if (ipv6_mode && (s->cmd == CMD_PASV || s->cmd == CMD_PORT)) {
+ logmsg(LOG_CRIT, "PASV and PORT not allowed with IPv6");
+ return (0);
}
- if (gid != 0 && (setegid(gid) == -1 || setgid(gid) == -1)) {
- syslog(LOG_ERR, "cannot drop group privs (%m)");
- exit(EX_CONFIG);
+ if (s->cmd == CMD_PORT || s->cmd == CMD_EPRT) {
+ s->port = parse_port(s->cmd);
+ if (s->port < MIN_PORT) {
+ logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
+ linebuf);
+ return (0);
+ }
+ s->proxy_port = pick_proxy_port();
+ proxy_reply(s->cmd, sstosa(&s->proxy_ss), s->proxy_port);
+ logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
}
- if (uid != 0 && (seteuid(uid) == -1 || setuid(uid) == -1)) {
- syslog(LOG_ERR, "cannot drop root privs (%m)");
- exit(EX_CONFIG);
- }
+ return (1);
}
-#ifdef LIBWRAP
-/*
- * Check a connection against the tcpwrapper, log if we're going to
- * reject it, returns: 0 -> reject, 1 -> accept. We add in hostnames
- * if we are set to do reverse DNS, otherwise no.
- */
-static int
-check_host(struct sockaddr_in *client_sin, struct sockaddr_in *server_sin)
+void
+client_read(struct bufferevent *bufev, void *arg)
{
- char cname[NI_MAXHOST];
- char sname[NI_MAXHOST];
- struct request_info request;
- int i;
-
- request_init(&request, RQ_DAEMON, __progname, RQ_CLIENT_SIN,
- client_sin, RQ_SERVER_SIN, server_sin, RQ_CLIENT_ADDR,
- inet_ntoa(client_sin->sin_addr), 0);
-
- if (Use_Rdns) {
- /*
- * We already looked these up, but we have to do it again
- * for tcp wrapper, to ensure that we get the DNS name, since
- * the tcp wrapper cares about these things, and we don't
- * want to pass in a printed address as a name.
- */
- i = getnameinfo((struct sockaddr *) &client_sin->sin_addr,
- sizeof(&client_sin->sin_addr), cname, sizeof(cname),
- NULL, 0, NI_NAMEREQD);
-
- if (i != 0 && i != EAI_NONAME && i != EAI_AGAIN)
- strlcpy(cname, STRING_UNKNOWN, sizeof(cname));
-
- i = getnameinfo((struct sockaddr *)&server_sin->sin_addr,
- sizeof(&server_sin->sin_addr), sname, sizeof(sname),
- NULL, 0, NI_NAMEREQD);
-
- if (i != 0 && i != EAI_NONAME && i != EAI_AGAIN)
- strlcpy(sname, STRING_UNKNOWN, sizeof(sname));
- } else {
- /*
- * ensure the TCP wrapper doesn't start doing
- * reverse DNS lookups if we aren't supposed to.
- */
- strlcpy(cname, STRING_UNKNOWN, sizeof(cname));
- strlcpy(sname, STRING_UNKNOWN, sizeof(sname));
- }
+ struct session *s = arg;
+ size_t buf_avail, read;
+ int n;
- request_set(&request, RQ_SERVER_ADDR, inet_ntoa(server_sin->sin_addr),
- 0);
- request_set(&request, RQ_CLIENT_NAME, cname, RQ_SERVER_NAME, sname, 0);
+ do {
+ buf_avail = sizeof s->cbuf - s->cbuf_valid;
+ read = bufferevent_read(bufev, s->cbuf + s->cbuf_valid,
+ buf_avail);
+ s->cbuf_valid += read;
+
+ while ((n = getline(s->cbuf, &s->cbuf_valid)) > 0) {
+ logmsg(LOG_DEBUG, "#%d client: %s", s->id, linebuf);
+ if (!client_parse(s)) {
+ end_session(s);
+ return;
+ }
+ bufferevent_write(s->server_bufev, linebuf, linelen);
+ }
- if (!hosts_access(&request)) {
- syslog(LOG_NOTICE, "tcpwrappers rejected: %s -> %s",
- ClientName, RealServerName);
- return(0);
- }
- return(1);
+ if (n == -1) {
+ logmsg(LOG_ERR, "#%d client command too long or not"
+ " clean", s->id);
+ end_session(s);
+ return;
+ }
+ } while (read == buf_avail);
}
-#endif /* LIBWRAP */
-double
-wallclock_time(void)
+int
+drop_privs(void)
{
- struct timeval tv;
+ struct passwd *pw;
+
+ pw = getpwnam(NOPRIV_USER);
+ if (pw == NULL)
+ return (0);
+
+ tzset();
+ if (chroot(CHROOT_DIR) != 0 || chdir("/") != 0 ||
+ setgroups(1, &pw->pw_gid) != 0 ||
+ setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0 ||
+ setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
+ return (0);
- gettimeofday(&tv, NULL);
- return(tv.tv_sec + tv.tv_usec / 1e6);
+ return (1);
}
-/*
- * Show the stats for this data transfer
- */
void
-show_xfer_stats(void)
+end_session(struct session *s)
{
- char tbuf[1000];
- double delta;
- size_t len;
- int i = -1;
-
- if (!Verbose)
- return;
-
- delta = wallclock_time() - xfer_start_time;
-
- if (delta < 0.001)
- delta = 0.001;
-
- if (client_data_bytes == 0 && server_data_bytes == 0) {
- syslog(LOG_INFO,
- "data transfer complete (no bytes transferred)");
- return;
+ int err;
+
+ logmsg(LOG_INFO, "#%d ending session", s->id);
+
+ if (s->client_fd != -1)
+ close(s->client_fd);
+ if (s->server_fd != -1)
+ close(s->server_fd);
+
+ if (s->client_bufev)
+ bufferevent_free(s->client_bufev);
+ if (s->server_bufev)
+ bufferevent_free(s->server_bufev);
+
+ /* Remove rulesets by commiting empty ones. */
+ err = 0;
+ if (prepare_commit(s->id) == -1)
+ err = errno;
+ else if (do_commit() == -1) {
+ err = errno;
+ do_rollback();
}
+ if (err)
+ logmsg(LOG_ERR, "#%d pf rule removal failed: %s", s->id,
+ strerror(err));
- len = sizeof(tbuf);
-
- if (delta >= 60) {
- int idelta;
+ LIST_REMOVE(s, entry);
+ free(s);
+ session_count--;
+}
- idelta = delta + 0.5;
- if (idelta >= 60*60) {
- i = snprintf(tbuf, len,
- "data transfer complete (%dh %dm %ds",
- idelta / (60*60), (idelta % (60*60)) / 60,
- idelta % 60);
- if (i == -1 || i >= len)
- goto logit;
- len -= i;
- } else {
- i = snprintf(tbuf, len,
- "data transfer complete (%dm %ds", idelta / 60,
- idelta % 60);
- if (i == -1 || i >= len)
- goto logit;
- len -= i;
- }
- } else {
- i = snprintf(tbuf, len, "data transfer complete (%.1fs",
- delta);
- if (i == -1 || i >= len)
- goto logit;
- len -= i;
- }
+int
+exit_daemon(void)
+{
+ struct session *s, *next;
- if (client_data_bytes > 0) {
- i = snprintf(&tbuf[strlen(tbuf)], len,
- ", %d bytes to server) (%.1fKB/s", client_data_bytes,
- (client_data_bytes / delta) / (double)1024);
- if (i == -1 || i >= len)
- goto logit;
- len -= i;
- }
- if (server_data_bytes > 0) {
- i = snprintf(&tbuf[strlen(tbuf)], len,
- ", %d bytes to client) (%.1fKB/s", server_data_bytes,
- (server_data_bytes / delta) / (double)1024);
- if (i == -1 || i >= len)
- goto logit;
- len -= i;
+#ifdef __FreeBSD__
+ LIST_FOREACH_SAFE(s, &sessions, entry, next) {
+#else
+ for (s = LIST_FIRST(&sessions); s != LIST_END(&sessions); s = next) {
+ next = LIST_NEXT(s, entry);
+#endif
+ end_session(s);
}
- strlcat(tbuf, ")", sizeof(tbuf));
- logit:
- if (i != -1)
- syslog(LOG_INFO, "%s", tbuf);
-}
-void
-log_control_command (char *cmd, int client)
-{
- /* log an ftp control command or reply */
- const char *logstring;
- int level = LOG_DEBUG;
+ if (daemonize)
+ closelog();
- if (!Verbose)
- return;
+ exit(0);
- /* don't log passwords */
- if (strncasecmp(cmd, "pass ", 5) == 0)
- logstring = "PASS XXXX";
- else
- logstring = cmd;
- if (client) {
- /* log interesting stuff at LOG_INFO, rest at LOG_DEBUG */
- if ((strncasecmp(cmd, "user ", 5) == 0) ||
- (strncasecmp(cmd, "retr ", 5) == 0) ||
- (strncasecmp(cmd, "cwd ", 4) == 0) ||
- (strncasecmp(cmd, "stor " ,5) == 0))
- level = LOG_INFO;
- }
- syslog(level, "%s %s", client ? "client:" : " server:",
- logstring);
+ /* NOTREACHED */
+ return (-1);
}
-/*
- * set ourselves up for a new data connection. Direction is toward client if
- * "server" is 0, towards server otherwise.
- */
int
-new_dataconn(int server)
+getline(char *buf, size_t *valid)
{
- /*
- * Close existing data conn.
- */
+ size_t i;
+
+ if (*valid > MAX_LINE)
+ return (-1);
- if (client_listen_socket != -1) {
- close(client_listen_socket);
- client_listen_socket = -1;
+ /* Copy to linebuf while searching for a newline. */
+ for (i = 0; i < *valid; i++) {
+ linebuf[i] = buf[i];
+ if (buf[i] == '\0')
+ return (-1);
+ if (buf[i] == '\n')
+ break;
}
- close_client_data();
- if (server_listen_socket != -1) {
- close(server_listen_socket);
- server_listen_socket = -1;
+ if (i == *valid) {
+ /* No newline found. */
+ linebuf[0] = '\0';
+ linelen = 0;
+ if (i < MAX_LINE)
+ return (0);
+ return (-1);
}
- close_server_data();
- if (server) {
- bzero(&server_listen_sa, sizeof(server_listen_sa));
- server_listen_socket = get_backchannel_socket(SOCK_STREAM,
- min_port, max_port, -1, 1, &server_listen_sa);
+ linelen = i + 1;
+ linebuf[linelen] = '\0';
+ *valid -= linelen;
+
+ /* Move leftovers to the start. */
+ if (*valid != 0)
+ bcopy(buf + linelen, buf, *valid);
- if (server_listen_socket == -1) {
- syslog(LOG_INFO, "server socket bind() failed (%m)");
- exit(EX_OSERR);
- }
- if (listen(server_listen_socket, 5) != 0) {
- syslog(LOG_INFO, "server socket listen() failed (%m)");
- exit(EX_OSERR);
- }
- } else {
- bzero(&client_listen_sa, sizeof(client_listen_sa));
- client_listen_socket = get_backchannel_socket(SOCK_STREAM,
- min_port, max_port, -1, 1, &client_listen_sa);
-
- if (client_listen_socket == -1) {
- syslog(LOG_NOTICE,
- "cannot get client listen socket (%m)");
- exit(EX_OSERR);
- }
- if (listen(client_listen_socket, 5) != 0) {
- syslog(LOG_NOTICE,
- "cannot listen on client socket (%m)");
- exit(EX_OSERR);
- }
- }
- return(0);
+ return ((int)linelen);
}
-static void
-connect_pasv_backchannel(void)
+void
+handle_connection(const int listen_fd, short event, void *ev)
{
- struct sockaddr_in listen_sa;
- socklen_t salen;
+ struct sockaddr_storage tmp_ss;
+ struct sockaddr *client_sa, *server_sa, *fixed_server_sa;
+ struct sockaddr *client_to_proxy_sa, *proxy_to_server_sa;
+ struct session *s;
+ socklen_t len;
+ int client_fd, fc, on;
/*
- * We are about to accept a connection from the client.
- * This is a PASV data connection.
+ * We _must_ accept the connection, otherwise libevent will keep
+ * coming back, and we will chew up all CPU.
*/
- debuglog(2, "client listen socket ready");
+ client_sa = sstosa(&tmp_ss);
+ len = sizeof(struct sockaddr_storage);
+ if ((client_fd = accept(listen_fd, client_sa, &len)) < 0) {
+ logmsg(LOG_CRIT, "accept failed: %s", strerror(errno));
+ return;
+ }
- close_server_data();
- close_client_data();
+ /* Refuse connection if the maximum is reached. */
+ if (session_count >= max_sessions) {
+ logmsg(LOG_ERR, "client limit (%d) reached, refusing "
+ "connection from %s", max_sessions, sock_ntop(client_sa));
+ close(client_fd);
+ return;
+ }
+
+ /* Allocate session and copy back the info from the accept(). */
+ s = init_session();
+ if (s == NULL) {
+ logmsg(LOG_CRIT, "init_session failed");
+ close(client_fd);
+ return;
+ }
+ s->client_fd = client_fd;
+ memcpy(sstosa(&s->client_ss), client_sa, client_sa->sa_len);
+
+ /* Cast it once, and be done with it. */
+ client_sa = sstosa(&s->client_ss);
+ server_sa = sstosa(&s->server_ss);
+ client_to_proxy_sa = sstosa(&tmp_ss);
+ proxy_to_server_sa = sstosa(&s->proxy_ss);
+ fixed_server_sa = sstosa(&fixed_server_ss);
- salen = sizeof(listen_sa);
- client_data_socket = accept(client_listen_socket,
- (struct sockaddr *)&listen_sa, &salen);
+ /* Log id/client early to ease debugging. */
+ logmsg(LOG_DEBUG, "#%d accepted connection from %s", s->id,
+ sock_ntop(client_sa));
- if (client_data_socket < 0) {
- syslog(LOG_NOTICE, "accept() failed (%m)");
- exit(EX_OSERR);
+ /*
+ * Find out the real server and port that the client wanted.
+ */
+ len = sizeof(struct sockaddr_storage);
+ if ((getsockname(s->client_fd, client_to_proxy_sa, &len)) < 0) {
+ logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
+ strerror(errno));
+ goto fail;
}
- close(client_listen_socket);
- client_listen_socket = -1;
- memset(&listen_sa, 0, sizeof(listen_sa));
-
- server_data_socket = get_backchannel_socket(SOCK_STREAM, min_port,
- max_port, -1, 1, &listen_sa);
- if (server_data_socket < 0) {
- syslog(LOG_NOTICE, "get_backchannel_socket() failed (%m)");
- exit(EX_OSERR);
+ if (server_lookup(client_sa, client_to_proxy_sa, server_sa) != 0) {
+ logmsg(LOG_CRIT, "#%d server lookup failed (no rdr?)", s->id);
+ goto fail;
}
- if (connect(server_data_socket, (struct sockaddr *) &server_listen_sa,
- sizeof(server_listen_sa)) != 0) {
- syslog(LOG_NOTICE, "connect() failed (%m)");
- exit(EX_NOHOST);
+ if (fixed_server) {
+ memcpy(sstosa(&s->orig_server_ss), server_sa,
+ server_sa->sa_len);
+ memcpy(server_sa, fixed_server_sa, fixed_server_sa->sa_len);
}
- client_data_bytes = 0;
- server_data_bytes = 0;
- xfer_start_time = wallclock_time();
-}
-static void
-connect_port_backchannel(void)
-{
- struct sockaddr_in listen_sa;
- socklen_t salen;
+ /* XXX: check we are not connecting to ourself. */
/*
- * We are about to accept a connection from the server.
- * This is a PORT or EPRT data connection.
+ * Setup socket and connect to server.
*/
- debuglog(2, "server listen socket ready");
-
- close_server_data();
- close_client_data();
-
- salen = sizeof(listen_sa);
- server_data_socket = accept(server_listen_socket,
- (struct sockaddr *)&listen_sa, &salen);
- if (server_data_socket < 0) {
- syslog(LOG_NOTICE, "accept() failed (%m)");
- exit(EX_OSERR);
+ if ((s->server_fd = socket(server_sa->sa_family, SOCK_STREAM,
+ IPPROTO_TCP)) < 0) {
+ logmsg(LOG_CRIT, "#%d server socket failed: %s", s->id,
+ strerror(errno));
+ goto fail;
+ }
+ if (fixed_proxy && bind(s->server_fd, sstosa(&fixed_proxy_ss),
+ fixed_proxy_ss.ss_len) != 0) {
+ logmsg(LOG_CRIT, "#%d cannot bind fixed proxy address: %s",
+ s->id, strerror(errno));
+ goto fail;
}
- close(server_listen_socket);
- server_listen_socket = -1;
-
- if (getuid() != 0) {
- /*
- * We're not running as root, so we get a backchannel
- * socket bound in our designated range, instead of
- * getting one bound to port 20 - This is deliberately
- * not RFC compliant.
- */
- bcopy(&src_addr, &listen_sa.sin_addr, sizeof(struct in_addr));
- client_data_socket = get_backchannel_socket(SOCK_STREAM,
- min_port, max_port, -1, 1, &listen_sa);
- if (client_data_socket < 0) {
- syslog(LOG_NOTICE, "get_backchannel_socket() failed (%m)");
- exit(EX_OSERR);
- }
- } else {
+ /* Use non-blocking connect(), see CONNECT_TIMEOUT below. */
+ if ((fc = fcntl(s->server_fd, F_GETFL)) == -1 ||
+ fcntl(s->server_fd, F_SETFL, fc | O_NONBLOCK) == -1) {
+ logmsg(LOG_CRIT, "#%d cannot mark socket non-blocking: %s",
+ s->id, strerror(errno));
+ goto fail;
+ }
+ if (connect(s->server_fd, server_sa, server_sa->sa_len) < 0 &&
+ errno != EINPROGRESS) {
+ logmsg(LOG_CRIT, "#%d proxy cannot connect to server %s: %s",
+ s->id, sock_ntop(server_sa), strerror(errno));
+ goto fail;
+ }
- /*
- * We're root, get our backchannel socket bound to port
- * 20 here, so we're fully RFC compliant.
- */
- client_data_socket = socket(AF_INET, SOCK_STREAM, 0);
+ len = sizeof(struct sockaddr_storage);
+ if ((getsockname(s->server_fd, proxy_to_server_sa, &len)) < 0) {
+ logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
+ strerror(errno));
+ goto fail;
+ }
- salen = 1;
- listen_sa.sin_family = AF_INET;
- bcopy(&src_addr, &listen_sa.sin_addr, sizeof(struct in_addr));
- listen_sa.sin_port = htons(20);
+ logmsg(LOG_INFO, "#%d FTP session %d/%d started: client %s to server "
+ "%s via proxy %s ", s->id, session_count, max_sessions,
+ sock_ntop(client_sa), sock_ntop(server_sa),
+ sock_ntop(proxy_to_server_sa));
- if (setsockopt(client_data_socket, SOL_SOCKET, SO_REUSEADDR,
- &salen, sizeof(salen)) == -1) {
- syslog(LOG_NOTICE, "setsockopt() failed (%m)");
- exit(EX_OSERR);
- }
+ /* Keepalive is nice, but don't care if it fails. */
+ on = 1;
+ setsockopt(s->client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
+ sizeof on);
+ setsockopt(s->server_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
+ sizeof on);
- if (bind(client_data_socket, (struct sockaddr *)&listen_sa,
- sizeof(listen_sa)) == - 1) {
- syslog(LOG_NOTICE, "data channel bind() failed (%m)");
- exit(EX_OSERR);
- }
+ /*
+ * Setup buffered events.
+ */
+ s->client_bufev = bufferevent_new(s->client_fd, &client_read, NULL,
+ &client_error, s);
+ if (s->client_bufev == NULL) {
+ logmsg(LOG_CRIT, "#%d bufferevent_new client failed", s->id);
+ goto fail;
}
-
- if (connect(client_data_socket, (struct sockaddr *) &client_listen_sa,
- sizeof(client_listen_sa)) != 0) {
- syslog(LOG_INFO, "cannot connect data channel (%m)");
- exit(EX_NOHOST);
+ bufferevent_settimeout(s->client_bufev, timeout, 0);
+ bufferevent_enable(s->client_bufev, EV_READ | EV_TIMEOUT);
+
+ s->server_bufev = bufferevent_new(s->server_fd, &server_read, NULL,
+ &server_error, s);
+ if (s->server_bufev == NULL) {
+ logmsg(LOG_CRIT, "#%d bufferevent_new server failed", s->id);
+ goto fail;
}
+ bufferevent_settimeout(s->server_bufev, CONNECT_TIMEOUT, 0);
+ bufferevent_enable(s->server_bufev, EV_READ | EV_TIMEOUT);
- client_data_bytes = 0;
- server_data_bytes = 0;
- xfer_start_time = wallclock_time();
+ return;
+
+ fail:
+ end_session(s);
}
void
-do_client_cmd(struct csiob *client, struct csiob *server)
+handle_signal(int sig, short event, void *arg)
{
- int i, j, rv;
- char tbuf[100];
- char *sendbuf = NULL;
-
- log_control_command((char *)client->line_buffer, 1);
-
- /* client->line_buffer is an ftp control command.
- * There is no reason for these to be very long.
- * In the interest of limiting buffer overrun attempts,
- * we catch them here.
- */
- if (strlen((char *)client->line_buffer) > 512) {
- syslog(LOG_NOTICE, "excessively long control command");
- exit(EX_DATAERR);
- }
-
/*
- * Check the client user provided if needed
+ * Signal handler rules don't apply, libevent decouples for us.
*/
- if (AnonFtpOnly && strncasecmp((char *)client->line_buffer, "user ",
- strlen("user ")) == 0) {
- char *cp;
-
- cp = (char *) client->line_buffer + strlen("user ");
- if ((strcasecmp(cp, "ftp\r\n") != 0) &&
- (strcasecmp(cp, "anonymous\r\n") != 0)) {
- /*
- * this isn't anonymous - give the client an
- * error before they send a password
- */
- snprintf(tbuf, sizeof(tbuf),
- "500 Only anonymous FTP is allowed\r\n");
- j = 0;
- i = strlen(tbuf);
- do {
- rv = send(client->fd, tbuf + j, i - j, 0);
- if (rv == -1 && errno != EAGAIN &&
- errno != EINTR)
- break;
- else if (rv != -1)
- j += rv;
- } while (j >= 0 && j < i);
- sendbuf = NULL;
- } else
- sendbuf = (char *)client->line_buffer;
- } else if ((strncasecmp((char *)client->line_buffer, "eprt ",
- strlen("eprt ")) == 0)) {
-
- /* Watch out for EPRT commands */
- char *line = NULL, *q, *p, *result[3], delim;
- struct addrinfo hints, *res = NULL;
- unsigned long proto;
-
- j = 0;
- line = strdup((char *)client->line_buffer+strlen("eprt "));
- if (line == NULL) {
- syslog(LOG_ERR, "insufficient memory");
- exit(EX_UNAVAILABLE);
- }
- p = line;
- delim = p[0];
- p++;
-
- memset(result,0, sizeof(result));
- for (i = 0; i < 3; i++) {
- q = strchr(p, delim);
- if (!q || *q != delim)
- goto parsefail;
- *q++ = '\0';
- result[i] = p;
- p = q;
- }
-
- proto = strtoul(result[0], &p, 10);
- if (!*result[0] || *p)
- goto protounsupp;
-
- memset(&hints, 0, sizeof(hints));
- if (proto != 1) /* 1 == AF_INET - all we support for now */
- goto protounsupp;
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags = AI_NUMERICHOST; /*no DNS*/
- if (getaddrinfo(result[1], result[2], &hints, &res))
- goto parsefail;
- if (res->ai_next)
- goto parsefail;
- if (sizeof(client_listen_sa) < res->ai_addrlen)
- goto parsefail;
- memcpy(&client_listen_sa, res->ai_addr, res->ai_addrlen);
-
- debuglog(1, "client wants us to use %s:%u",
- inet_ntoa(client_listen_sa.sin_addr),
- htons(client_listen_sa.sin_port));
-
- /*
- * Configure our own listen socket and tell the server about it
- */
- new_dataconn(1);
- connection_mode = EPRT_MODE;
-
- debuglog(1, "we want server to use %s:%u",
- inet_ntoa(server->sa.sin_addr),
- ntohs(server_listen_sa.sin_port));
-
- snprintf(tbuf, sizeof(tbuf), "EPRT |%d|%s|%u|\r\n", 1,
- inet_ntoa(server->sa.sin_addr),
- ntohs(server_listen_sa.sin_port));
- debuglog(1, "to server (modified): %s", tbuf);
- sendbuf = tbuf;
- goto out;
-parsefail:
- snprintf(tbuf, sizeof(tbuf),
- "500 Invalid argument; rejected\r\n");
- sendbuf = NULL;
- goto out;
-protounsupp:
- /* we only support AF_INET for now */
- if (proto == 2)
- snprintf(tbuf, sizeof(tbuf),
- "522 Protocol not supported, use (1)\r\n");
- else
- snprintf(tbuf, sizeof(tbuf),
- "501 Protocol not supported\r\n");
- sendbuf = NULL;
-out:
- if (line)
- free(line);
- if (res)
- freeaddrinfo(res);
- if (sendbuf == NULL) {
- debuglog(1, "to client (modified): %s", tbuf);
- i = strlen(tbuf);
- do {
- rv = send(client->fd, tbuf + j, i - j, 0);
- if (rv == -1 && errno != EAGAIN &&
- errno != EINTR)
- break;
- else if (rv != -1)
- j += rv;
- } while (j >= 0 && j < i);
- }
- } else if (!NatMode && (strncasecmp((char *)client->line_buffer,
- "epsv", strlen("epsv")) == 0)) {
-
- /*
- * If we aren't in NAT mode, deal with EPSV.
- * EPSV is a problem - Unlike PASV, the reply from the
- * server contains *only* a port, we can't modify the reply
- * to the client and get the client to connect to us without
- * resorting to using a dynamic rdr rule we have to add in
- * for the reply to this connection, and take away afterwards.
- * so this will wait until we have the right solution for rule
- * additions/deletions in pf.
- *
- * in the meantime we just tell the client we don't do it,
- * and most clients should fall back to using PASV.
- */
-
- snprintf(tbuf, sizeof(tbuf),
- "500 EPSV command not understood\r\n");
- debuglog(1, "to client (modified): %s", tbuf);
- j = 0;
- i = strlen(tbuf);
- do {
- rv = send(client->fd, tbuf + j, i - j, 0);
- if (rv == -1 && errno != EAGAIN && errno != EINTR)
- break;
- else if (rv != -1)
- j += rv;
- } while (j >= 0 && j < i);
- sendbuf = NULL;
- } else if (strncasecmp((char *)client->line_buffer, "port ",
- strlen("port ")) == 0) {
- unsigned int values[6];
- char *tailptr;
-
- debuglog(1, "Got a PORT command");
-
- tailptr = (char *)&client->line_buffer[strlen("port ")];
- values[0] = 0;
-
- i = sscanf(tailptr, "%u,%u,%u,%u,%u,%u", &values[0],
- &values[1], &values[2], &values[3], &values[4],
- &values[5]);
- if (i != 6) {
- syslog(LOG_INFO, "malformed PORT command (%s)",
- client->line_buffer);
- exit(EX_DATAERR);
- }
- for (i = 0; i<6; i++) {
- if (values[i] > 255) {
- syslog(LOG_INFO,
- "malformed PORT command (%s)",
- client->line_buffer);
- exit(EX_DATAERR);
- }
- }
+ logmsg(LOG_ERR, "%s exiting on signal %d", __progname, sig);
- client_listen_sa.sin_family = AF_INET;
- client_listen_sa.sin_addr.s_addr = htonl((values[0] << 24) |
- (values[1] << 16) | (values[2] << 8) |
- (values[3] << 0));
-
- client_listen_sa.sin_port = htons((values[4] << 8) |
- values[5]);
- debuglog(1, "client wants us to use %u.%u.%u.%u:%u",
- values[0], values[1], values[2], values[3],
- (values[4] << 8) | values[5]);
-
- /*
- * Configure our own listen socket and tell the server about it
- */
- new_dataconn(1);
- connection_mode = PORT_MODE;
-
- debuglog(1, "we want server to use %s:%u",
- inet_ntoa(server->sa.sin_addr),
- ntohs(server_listen_sa.sin_port));
-
- snprintf(tbuf, sizeof(tbuf), "PORT %u,%u,%u,%u,%u,%u\r\n",
- ((u_char *)&server->sa.sin_addr.s_addr)[0],
- ((u_char *)&server->sa.sin_addr.s_addr)[1],
- ((u_char *)&server->sa.sin_addr.s_addr)[2],
- ((u_char *)&server->sa.sin_addr.s_addr)[3],
- ((u_char *)&server_listen_sa.sin_port)[0],
- ((u_char *)&server_listen_sa.sin_port)[1]);
-
- debuglog(1, "to server (modified): %s", tbuf);
-
- sendbuf = tbuf;
- } else
- sendbuf = (char *)client->line_buffer;
+ exit_daemon();
+}
+
- /*
- *send our (possibly modified) control command in sendbuf
- * on it's way to the server
- */
- if (sendbuf != NULL) {
- j = 0;
- i = strlen(sendbuf);
- do {
- rv = send(server->fd, sendbuf + j, i - j, 0);
- if (rv == -1 && errno != EAGAIN && errno != EINTR)
- break;
- else if (rv != -1)
- j += rv;
- } while (j >= 0 && j < i);
- }
+struct session *
+init_session(void)
+{
+ struct session *s;
+
+ s = calloc(1, sizeof(struct session));
+ if (s == NULL)
+ return (NULL);
+
+ s->id = id_count++;
+ s->client_fd = -1;
+ s->server_fd = -1;
+ s->cbuf[0] = '\0';
+ s->cbuf_valid = 0;
+ s->sbuf[0] = '\0';
+ s->sbuf_valid = 0;
+ s->client_bufev = NULL;
+ s->server_bufev = NULL;
+ s->cmd = CMD_NONE;
+ s->port = 0;
+
+ LIST_INSERT_HEAD(&sessions, s, entry);
+ session_count++;
+
+ return (s);
}
void
-do_server_reply(struct csiob *server, struct csiob *client)
+logmsg(int pri, const char *message, ...)
{
- int code, i, j, rv;
- struct in_addr *iap;
- static int continuing = 0;
- char tbuf[100], *sendbuf, *p;
-
- log_control_command((char *)server->line_buffer, 0);
-
- if (strlen((char *)server->line_buffer) > 512) {
- /*
- * someone's playing games. Have a cow in the syslogs and
- * exit - we don't pass this on for fear of hurting
- * our other end, which might be poorly implemented.
- */
- syslog(LOG_NOTICE, "long FTP control reply");
- exit(EX_DATAERR);
- }
-
- /*
- * Watch out for "227 Entering Passive Mode ..." replies
- */
- code = strtol((char *)server->line_buffer, &p, 10);
- if (isspace(server->line_buffer[0]))
- code = 0;
- if (!*(server->line_buffer) || (*p != ' ' && *p != '-')) {
- if (continuing)
- goto sendit;
- syslog(LOG_INFO, "malformed control reply");
- exit(EX_DATAERR);
- }
- if (code <= 0 || code > 999) {
- if (continuing)
- goto sendit;
- syslog(LOG_INFO, "invalid server reply code %d", code);
- exit(EX_DATAERR);
- }
- if (*p == '-')
- continuing = 1;
- else
- continuing = 0;
- if (code == 227 && !NatMode) {
- unsigned int values[6];
- char *tailptr;
-
- debuglog(1, "Got a PASV reply");
- debuglog(1, "{%s}", (char *)server->line_buffer);
-
- tailptr = (char *)strchr((char *)server->line_buffer, '(');
- if (tailptr == NULL) {
- tailptr = strrchr((char *)server->line_buffer, ' ');
- if (tailptr == NULL) {
- syslog(LOG_NOTICE, "malformed 227 reply");
- exit(EX_DATAERR);
- }
- }
- tailptr++; /* skip past space or ( */
-
- values[0] = 0;
+ va_list ap;
- i = sscanf(tailptr, "%u,%u,%u,%u,%u,%u", &values[0],
- &values[1], &values[2], &values[3], &values[4],
- &values[5]);
- if (i != 6) {
- syslog(LOG_INFO, "malformed PASV reply (%s)",
- client->line_buffer);
- exit(EX_DATAERR);
- }
- for (i = 0; i<6; i++)
- if (values[i] > 255) {
- syslog(LOG_INFO, "malformed PASV reply(%s)",
- client->line_buffer);
- exit(EX_DATAERR);
- }
+ if (pri > loglevel)
+ return;
- server_listen_sa.sin_family = AF_INET;
- server_listen_sa.sin_addr.s_addr = htonl((values[0] << 24) |
- (values[1] << 16) | (values[2] << 8) | (values[3] << 0));
- server_listen_sa.sin_port = htons((values[4] << 8) |
- values[5]);
-
- debuglog(1, "server wants us to use %s:%u",
- inet_ntoa(server_listen_sa.sin_addr), (values[4] << 8) |
- values[5]);
-
- new_dataconn(0);
- connection_mode = PASV_MODE;
- if (ReverseMode)
- iap = &(proxy_sa.sin_addr);
- else
- iap = &(server->sa.sin_addr);
-
- debuglog(1, "we want client to use %s:%u", inet_ntoa(*iap),
- htons(client_listen_sa.sin_port));
-
- snprintf(tbuf, sizeof(tbuf),
- "227 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n",
- ((u_char *)iap)[0], ((u_char *)iap)[1],
- ((u_char *)iap)[2], ((u_char *)iap)[3],
- ((u_char *)&client_listen_sa.sin_port)[0],
- ((u_char *)&client_listen_sa.sin_port)[1]);
- debuglog(1, "to client (modified): %s", tbuf);
- sendbuf = tbuf;
- } else {
- sendit:
- sendbuf = (char *)server->line_buffer;
+ va_start(ap, message);
+
+ if (daemonize)
+ /* syslog does its own vissing. */
+ vsyslog(pri, message, ap);
+ else {
+ char buf[MAX_LOGLINE];
+ char visbuf[2 * MAX_LOGLINE];
+
+ /* We don't care about truncation. */
+ vsnprintf(buf, sizeof buf, message, ap);
+#ifdef __FreeBSD__
+ /* XXX: strnvis might be nice to have */
+ strvisx(visbuf, buf,
+ MIN((sizeof(visbuf) / 4) - 1, strlen(buf)),
+ VIS_CSTYLE | VIS_NL);
+#else
+ strnvis(visbuf, buf, sizeof visbuf, VIS_CSTYLE | VIS_NL);
+#endif
+ fprintf(stderr, "%s\n", visbuf);
}
- /*
- * send our (possibly modified) control command in sendbuf
- * on it's way to the client
- */
- j = 0;
- i = strlen(sendbuf);
- do {
- rv = send(client->fd, sendbuf + j, i - j, 0);
- if (rv == -1 && errno != EAGAIN && errno != EINTR)
- break;
- else if (rv != -1)
- j += rv;
- } while (j >= 0 && j < i);
-
+ va_end(ap);
}
int
main(int argc, char *argv[])
{
- struct csiob client_iob, server_iob;
- struct sigaction new_sa, old_sa;
- int sval, ch, flags, i;
- socklen_t salen;
- int one = 1;
- long timeout_seconds = 0;
- struct timeval tv;
-#ifdef LIBWRAP
- int use_tcpwrapper = 0;
-#endif /* LIBWRAP */
-
- while ((ch = getopt(argc, argv, "a:D:g:m:M:R:S:t:u:AnVwr")) != -1) {
- char *p;
+ struct rlimit rlp;
+ struct addrinfo hints, *res;
+ struct event ev, ev_sighup, ev_sigint, ev_sigterm;
+ int ch, error, listenfd, on;
+ const char *errstr;
+
+ /* Defaults. */
+ anonymous_only = 0;
+ daemonize = 1;
+ fixed_proxy = NULL;
+ fixed_server = NULL;
+ fixed_server_port = "21";
+ ipv6_mode = 0;
+ listen_ip = NULL;
+ listen_port = "8021";
+ loglevel = LOG_NOTICE;
+ max_sessions = 100;
+ qname = NULL;
+ rfc_mode = 0;
+ timeout = 24 * 3600;
+ verbose = 0;
+
+ /* Other initialization. */
+ id_count = 1;
+ session_count = 0;
+
+ while ((ch = getopt(argc, argv, "6Aa:b:D:dm:P:p:q:R:rt:v")) != -1) {
switch (ch) {
- case 'a':
- if (!*optarg)
- usage();
- if ((Bind_Addr = inet_addr(optarg)) == INADDR_NONE) {
- syslog(LOG_NOTICE,
- "%s: invalid address", optarg);
- usage();
- }
+ case '6':
+ ipv6_mode = 1;
break;
case 'A':
- AnonFtpOnly = 1; /* restrict to anon usernames only */
+ anonymous_only = 1;
+ break;
+ case 'a':
+ fixed_proxy = optarg;
+ break;
+ case 'b':
+ listen_ip = optarg;
break;
case 'D':
- Debug_Level = strtol(optarg, &p, 10);
- if (!*optarg || *p)
- usage();
+ loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
+ &errstr);
+ if (errstr)
+ errx(1, "loglevel %s", errstr);
break;
- case 'g':
- Group = optarg;
+ case 'd':
+ daemonize = 0;
break;
case 'm':
- min_port = strtol(optarg, &p, 10);
- if (!*optarg || *p)
- usage();
- if (min_port < 0 || min_port > USHRT_MAX)
- usage();
+ max_sessions = strtonum(optarg, 1, 500, &errstr);
+ if (errstr)
+ errx(1, "max sessions %s", errstr);
break;
- case 'M':
- max_port = strtol(optarg, &p, 10);
- if (!*optarg || *p)
- usage();
- if (max_port < 0 || max_port > USHRT_MAX)
- usage();
+ case 'P':
+ fixed_server_port = optarg;
break;
- case 'n':
- NatMode = 1; /* pass all passives, we're using NAT */
+ case 'p':
+ listen_port = optarg;
break;
- case 'r':
- Use_Rdns = 1; /* look up hostnames */
+ case 'q':
+ if (strlen(optarg) >= PF_QNAME_SIZE)
+ errx(1, "queuename too long");
+ qname = optarg;
break;
- case 'R': {
- char *s, *t;
-
- if (!*optarg)
- usage();
- if ((s = strdup(optarg)) == NULL) {
- syslog (LOG_NOTICE,
- "Insufficient memory (malloc failed)");
- exit(EX_UNAVAILABLE);
- }
- memset(&real_server_sa, 0, sizeof(real_server_sa));
- real_server_sa.sin_len = sizeof(struct sockaddr_in);
- real_server_sa.sin_family = AF_INET;
- t = strchr(s, ':');
- if (t == NULL)
- real_server_sa.sin_port = htons(21);
- else {
- long port = strtol(t + 1, &p, 10);
-
- if (*p || port <= 0 || port > 65535)
- usage();
- real_server_sa.sin_port = htons(port);
- *t = 0;
- }
- real_server_sa.sin_addr.s_addr = inet_addr(s);
- if (real_server_sa.sin_addr.s_addr == INADDR_NONE)
- usage();
- free(s);
- ReverseMode = 1;
+ case 'R':
+ fixed_server = optarg;
break;
- }
- case 'S':
- if (!inet_aton(optarg, &src_addr))
- usage();
+ case 'r':
+ rfc_mode = 1;
break;
case 't':
- timeout_seconds = strtol(optarg, &p, 10);
- if (!*optarg || *p)
- usage();
+ timeout = strtonum(optarg, 0, 86400, &errstr);
+ if (errstr)
+ errx(1, "timeout %s", errstr);
break;
- case 'u':
- User = optarg;
- break;
- case 'V':
- Verbose = 1;
- break;
-#ifdef LIBWRAP
- case 'w':
- use_tcpwrapper = 1; /* do the libwrap thing */
+ case 'v':
+ verbose++;
+ if (verbose > 2)
+ usage();
break;
-#endif /* LIBWRAP */
default:
usage();
- /* NOTREACHED */
}
}
- argc -= optind;
- argv += optind;
-
- if (max_port < min_port)
- usage();
- openlog(__progname, LOG_NDELAY|LOG_PID, LOG_DAEMON);
+ if (listen_ip == NULL)
+ listen_ip = ipv6_mode ? "::1" : "127.0.0.1";
- setlinebuf(stdout);
- setlinebuf(stderr);
+ /* Check for root to save the user from cryptic failure messages. */
+ if (getuid() != 0)
+ errx(1, "needs to start as root");
- memset(&client_iob, 0, sizeof(client_iob));
- memset(&server_iob, 0, sizeof(server_iob));
+ /* Raise max. open files limit to satisfy max. sessions. */
+ rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
+ if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
+ err(1, "setrlimit");
- if (get_proxy_env(0, &real_server_sa, &client_iob.sa,
- &proxy_sa) == -1)
- exit(EX_PROTOCOL);
+ if (fixed_proxy) {
+ memset(&hints, 0, sizeof hints);
+ hints.ai_flags = AI_NUMERICHOST;
+ hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
+ if (error)
+ errx(1, "getaddrinfo fixed proxy address failed: %s",
+ gai_strerror(error));
+ memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
+ logmsg(LOG_INFO, "using %s to connect to servers",
+ sock_ntop(sstosa(&fixed_proxy_ss)));
+ freeaddrinfo(res);
+ }
- /*
- * We may now drop root privs, as we have done our ioctl for
- * pf. If we do drop root, we can't make backchannel connections
- * for PORT and EPRT come from port 20, which is not strictly
- * RFC compliant. This shouldn't cause problems for all but
- * the stupidest ftp clients and the stupidest packet filters.
- */
- drop_privs();
+ if (fixed_server) {
+ memset(&hints, 0, sizeof hints);
+ hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ error = getaddrinfo(fixed_server, fixed_server_port, &hints,
+ &res);
+ if (error)
+ errx(1, "getaddrinfo fixed server address failed: %s",
+ gai_strerror(error));
+ memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
+ logmsg(LOG_INFO, "using fixed server %s",
+ sock_ntop(sstosa(&fixed_server_ss)));
+ freeaddrinfo(res);
+ }
- /*
- * We check_host after get_proxy_env so that checks are done
- * against the original destination endpoint, not the endpoint
- * of our side of the rdr. This allows the use of tcpwrapper
- * rules to restrict destinations as well as sources of connections
- * for ftp.
- */
- if (Use_Rdns)
- flags = 0;
- else
- flags = NI_NUMERICHOST | NI_NUMERICSERV;
+ /* Setup listener. */
+ memset(&hints, 0, sizeof hints);
+ hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
+ hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ error = getaddrinfo(listen_ip, listen_port, &hints, &res);
+ if (error)
+ errx(1, "getaddrinfo listen address failed: %s",
+ gai_strerror(error));
+ if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
+ errx(1, "socket failed");
+ on = 1;
+ if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
+ sizeof on) != 0)
+ err(1, "setsockopt failed");
+ if (bind(listenfd, (struct sockaddr *)res->ai_addr,
+ (socklen_t)res->ai_addrlen) != 0)
+ err(1, "bind failed");
+ if (listen(listenfd, TCP_BACKLOG) != 0)
+ err(1, "listen failed");
+ freeaddrinfo(res);
+
+ /* Initialize pf. */
+ init_filter(qname, verbose);
+
+ if (daemonize) {
+ if (daemon(0, 0) == -1)
+ err(1, "cannot daemonize");
+ openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
+ }
- i = getnameinfo((struct sockaddr *)&client_iob.sa,
- sizeof(client_iob.sa), ClientName, sizeof(ClientName), NULL, 0,
- flags);
+ /* Use logmsg for output from here on. */
- if (i != 0 && i != EAI_NONAME && i != EAI_AGAIN) {
- debuglog(2, "name resolution failure (client)");
- exit(EX_OSERR);
+ if (!drop_privs()) {
+ logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
+ exit(1);
}
+
+ event_init();
- i = getnameinfo((struct sockaddr *)&real_server_sa,
- sizeof(real_server_sa), RealServerName, sizeof(RealServerName),
- NULL, 0, flags);
+ /* Setup signal handler. */
+ signal(SIGPIPE, SIG_IGN);
+ signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
+ signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
+ signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
+ signal_add(&ev_sighup, NULL);
+ signal_add(&ev_sigint, NULL);
+ signal_add(&ev_sigterm, NULL);
- if (i != 0 && i != EAI_NONAME && i != EAI_AGAIN) {
- debuglog(2, "name resolution failure (server)");
- exit(EX_OSERR);
- }
+ event_set(&ev, listenfd, EV_READ | EV_PERSIST, handle_connection, &ev);
+ event_add(&ev, NULL);
-#ifdef LIBWRAP
- if (use_tcpwrapper && !check_host(&client_iob.sa, &real_server_sa))
- exit(EX_NOPERM);
-#endif
+ logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);
- client_iob.fd = 0;
+ /* Vroom, vroom. */
+ event_dispatch();
- syslog(LOG_INFO, "accepted connection from %s:%u to %s:%u", ClientName,
- ntohs(client_iob.sa.sin_port), RealServerName,
- ntohs(real_server_sa.sin_port));
+ logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
+ exit_daemon();
- server_iob.fd = get_backchannel_socket(SOCK_STREAM, min_port, max_port,
- -1, 1, &server_iob.sa);
+ /* NOTREACHED */
+ return (1);
+}
+
+u_int16_t
+parse_port(int mode)
+{
+ unsigned int port, v[6];
+ int n;
+ char *p;
- if (connect(server_iob.fd, (struct sockaddr *)&real_server_sa,
- sizeof(real_server_sa)) != 0) {
- syslog(LOG_INFO, "cannot connect to %s:%u (%m)", RealServerName,
- ntohs(real_server_sa.sin_port));
- exit(EX_NOHOST);
+ /* Find the last space or left-parenthesis. */
+ for (p = linebuf + linelen; p > linebuf; p--)
+ if (*p == ' ' || *p == '(')
+ break;
+ if (p == linebuf)
+ return (0);
+
+ switch (mode) {
+ case CMD_PORT:
+ n = sscanf(p, " %u,%u,%u,%u,%u,%u", &v[0], &v[1], &v[2],
+ &v[3], &v[4], &v[5]);
+ if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
+ v[3] < 256 && v[4] < 256 && v[5] < 256)
+ return ((v[4] << 8) | v[5]);
+ break;
+ case CMD_PASV:
+ n = sscanf(p, "(%u,%u,%u,%u,%u,%u)", &v[0], &v[1], &v[2],
+ &v[3], &v[4], &v[5]);
+ if (n == 6 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
+ v[3] < 256 && v[4] < 256 && v[5] < 256)
+ return ((v[4] << 8) | v[5]);
+ break;
+ case CMD_EPSV:
+ n = sscanf(p, "(|||%u|)", &port);
+ if (n == 1 && port < 65536)
+ return (port);
+ break;
+ case CMD_EPRT:
+ n = sscanf(p, " |1|%u.%u.%u.%u|%u|", &v[0], &v[1], &v[2],
+ &v[3], &port);
+ if (n == 5 && v[0] < 256 && v[1] < 256 && v[2] < 256 &&
+ v[3] < 256 && port < 65536)
+ return (port);
+ n = sscanf(p, " |2|%*[a-fA-F0-9:]|%u|", &port);
+ if (n == 1 && port < 65536)
+ return (port);
+ break;
+ default:
+ return (0);
}
- /*
- * Now that we are connected to the real server, get the name
- * of our end of the server socket so we know our IP address
- * from the real server's perspective.
- */
- salen = sizeof(server_iob.sa);
- getsockname(server_iob.fd, (struct sockaddr *)&server_iob.sa, &salen);
+ return (0);
+}
- i = getnameinfo((struct sockaddr *)&server_iob.sa,
- sizeof(server_iob.sa), OurName, sizeof(OurName), NULL, 0, flags);
+u_int16_t
+pick_proxy_port(void)
+{
+ /* Random should be good enough for avoiding port collisions. */
+ return (IPPORT_HIFIRSTAUTO + (arc4random() %
+ (IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO)));
+}
- if (i != 0 && i != EAI_NONAME && i != EAI_AGAIN) {
- debuglog(2, "name resolution failure (local)");
- exit(EX_OSERR);
+void
+proxy_reply(int cmd, struct sockaddr *sa, u_int16_t port)
+{
+ int i, r;
+
+ switch (cmd) {
+ case CMD_PORT:
+ r = snprintf(linebuf, sizeof linebuf,
+ "PORT %s,%u,%u\r\n", sock_ntop(sa), port / 256,
+ port % 256);
+ break;
+ case CMD_PASV:
+ r = snprintf(linebuf, sizeof linebuf,
+ "227 Entering Passive Mode (%s,%u,%u)\r\n", sock_ntop(sa),
+ port / 256, port % 256);
+ break;
+ case CMD_EPRT:
+ if (sa->sa_family == AF_INET)
+ r = snprintf(linebuf, sizeof linebuf,
+ "EPRT |1|%s|%u|\r\n", sock_ntop(sa), port);
+ else if (sa->sa_family == AF_INET6)
+ r = snprintf(linebuf, sizeof linebuf,
+ "EPRT |2|%s|%u|\r\n", sock_ntop(sa), port);
+ break;
+ case CMD_EPSV:
+ r = snprintf(linebuf, sizeof linebuf,
+ "229 Entering Extended Passive Mode (|||%u|)\r\n", port);
+ break;
}
- debuglog(1, "local socket is %s:%u", OurName,
- ntohs(server_iob.sa.sin_port));
-
- /* ignore SIGPIPE */
- bzero(&new_sa, sizeof(new_sa));
- new_sa.sa_handler = SIG_IGN;
- (void)sigemptyset(&new_sa.sa_mask);
- new_sa.sa_flags = SA_RESTART;
- if (sigaction(SIGPIPE, &new_sa, &old_sa) != 0) {
- syslog(LOG_ERR, "sigaction() failed (%m)");
- exit(EX_OSERR);
+ if (r < 0 || r >= sizeof linebuf) {
+ logmsg(LOG_ERR, "proxy_reply failed: %d", r);
+ linebuf[0] = '\0';
+ linelen = 0;
+ return;
}
+ linelen = (size_t)r;
- if (setsockopt(client_iob.fd, SOL_SOCKET, SO_OOBINLINE, (char *)&one,
- sizeof(one)) == -1) {
- syslog(LOG_NOTICE, "cannot set SO_OOBINLINE (%m)");
- exit(EX_OSERR);
+ if (cmd == CMD_PORT || cmd == CMD_PASV) {
+ /* Replace dots in IP address with commas. */
+ for (i = 0; i < linelen; i++)
+ if (linebuf[i] == '.')
+ linebuf[i] = ',';
}
+}
- client_iob.line_buffer_size = STARTBUFSIZE;
- client_iob.line_buffer = malloc(client_iob.line_buffer_size);
- client_iob.io_buffer_size = STARTBUFSIZE;
- client_iob.io_buffer = malloc(client_iob.io_buffer_size);
- client_iob.next_byte = 0;
- client_iob.io_buffer_len = 0;
- client_iob.alive = 1;
- client_iob.who = "client";
- client_iob.send_oob_flags = 0;
- client_iob.real_sa = client_iob.sa;
-
- server_iob.line_buffer_size = STARTBUFSIZE;
- server_iob.line_buffer = malloc(server_iob.line_buffer_size);
- server_iob.io_buffer_size = STARTBUFSIZE;
- server_iob.io_buffer = malloc(server_iob.io_buffer_size);
- server_iob.next_byte = 0;
- server_iob.io_buffer_len = 0;
- server_iob.alive = 1;
- server_iob.who = "server";
- server_iob.send_oob_flags = MSG_OOB;
- server_iob.real_sa = real_server_sa;
-
- if (client_iob.line_buffer == NULL || client_iob.io_buffer == NULL ||
- server_iob.line_buffer == NULL || server_iob.io_buffer == NULL) {
- syslog (LOG_NOTICE, "insufficient memory");
- exit(EX_UNAVAILABLE);
- }
+void
+server_error(struct bufferevent *bufev, short what, void *arg)
+{
+ struct session *s = arg;
+
+ if (what & EVBUFFER_EOF)
+ logmsg(LOG_INFO, "#%d server close", s->id);
+ else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
+ logmsg(LOG_ERR, "#%d server refused connection", s->id);
+ else if (what & EVBUFFER_WRITE)
+ logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
+ else if (what & EVBUFFER_TIMEOUT)
+ logmsg(LOG_NOTICE, "#%d server timeout", s->id);
+ else
+ logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);
- while (client_iob.alive || server_iob.alive) {
- int maxfd = 0;
- fd_set *fdsp;
-
- if (client_iob.fd > maxfd)
- maxfd = client_iob.fd;
- if (client_listen_socket > maxfd)
- maxfd = client_listen_socket;
- if (client_data_socket > maxfd)
- maxfd = client_data_socket;
- if (server_iob.fd > maxfd)
- maxfd = server_iob.fd;
- if (server_listen_socket > maxfd)
- maxfd = server_listen_socket;
- if (server_data_socket > maxfd)
- maxfd = server_data_socket;
-
- debuglog(3, "client is %s; server is %s",
- client_iob.alive ? "alive" : "dead",
- server_iob.alive ? "alive" : "dead");
-
- fdsp = (fd_set *)calloc(howmany(maxfd + 1, NFDBITS),
- sizeof(fd_mask));
- if (fdsp == NULL) {
- syslog(LOG_NOTICE, "insufficient memory");
- exit(EX_UNAVAILABLE);
+ end_session(s);
+}
+
+int
+server_parse(struct session *s)
+{
+ struct sockaddr *client_sa, *orig_sa, *proxy_sa, *server_sa;
+ int prepared = 0;
+
+ if (s->cmd == CMD_NONE || linelen < 4 || linebuf[0] != '2')
+ goto out;
+
+ /*
+ * The pf rules below do quite some NAT rewriting, to keep up
+ * appearances. Points to keep in mind:
+ * 1) The client must think it's talking to the real server,
+ * for both control and data connections. Transparently.
+ * 2) The server must think that the proxy is the client.
+ * 3) Source and destination ports are rewritten to minimize
+ * port collisions, to aid security (some systems pick weak
+ * ports) or to satisfy RFC requirements (source port 20).
+ */
+
+ /* Cast this once, to make code below it more readable. */
+ client_sa = sstosa(&s->client_ss);
+ server_sa = sstosa(&s->server_ss);
+ proxy_sa = sstosa(&s->proxy_ss);
+ if (fixed_server)
+ /* Fixed server: data connections must appear to come
+ from / go to the original server, not the fixed one. */
+ orig_sa = sstosa(&s->orig_server_ss);
+ else
+ /* Server not fixed: orig_server == server. */
+ orig_sa = sstosa(&s->server_ss);
+
+ /* Passive modes. */
+ if ((s->cmd == CMD_PASV && strncmp("227 ", linebuf, 4) == 0) ||
+ (s->cmd == CMD_EPSV && strncmp("229 ", linebuf, 4) == 0)) {
+ s->port = parse_port(s->cmd);
+ if (s->port < MIN_PORT) {
+ logmsg(LOG_CRIT, "#%d bad port in '%s'", s->id,
+ linebuf);
+ return (0);
}
+ s->proxy_port = pick_proxy_port();
+ logmsg(LOG_INFO, "#%d passive: client to server port %d"
+ " via port %d", s->id, s->port, s->proxy_port);
+
+ if (prepare_commit(s->id) == -1)
+ goto fail;
+ prepared = 1;
+
+ proxy_reply(s->cmd, orig_sa, s->proxy_port);
+ logmsg(LOG_DEBUG, "#%d proxy: %s", s->id, linebuf);
+
+ /* rdr from $client to $orig_server port $proxy_port -> $server
+ port $port */
+ if (add_rdr(s->id, client_sa, orig_sa, s->proxy_port,
+ server_sa, s->port) == -1)
+ goto fail;
+
+ /* nat from $client to $server port $port -> $proxy */
+ if (add_nat(s->id, client_sa, server_sa, s->port, proxy_sa,
+ PF_NAT_PROXY_PORT_LOW, PF_NAT_PROXY_PORT_HIGH) == -1)
+ goto fail;
+
+ /* pass in from $client to $server port $port */
+ if (add_filter(s->id, PF_IN, client_sa, server_sa,
+ s->port) == -1)
+ goto fail;
+
+ /* pass out from $proxy to $server port $port */
+ if (add_filter(s->id, PF_OUT, proxy_sa, server_sa,
+ s->port) == -1)
+ goto fail;
+ }
- if (client_iob.alive && telnet_getline(&client_iob,
- &server_iob)) {
- debuglog(3, "client line buffer is \"%s\"",
- (char *)client_iob.line_buffer);
- if (client_iob.line_buffer[0] != '\0')
- do_client_cmd(&client_iob, &server_iob);
- } else if (server_iob.alive && telnet_getline(&server_iob,
- &client_iob)) {
- debuglog(3, "server line buffer is \"%s\"",
- (char *)server_iob.line_buffer);
- if (server_iob.line_buffer[0] != '\0')
- do_server_reply(&server_iob, &client_iob);
+ /* Active modes. */
+ if ((s->cmd == CMD_PORT || s->cmd == CMD_EPRT) &&
+ strncmp("200 ", linebuf, 4) == 0) {
+ logmsg(LOG_INFO, "#%d active: server to client port %d"
+ " via port %d", s->id, s->port, s->proxy_port);
+
+ if (prepare_commit(s->id) == -1)
+ goto fail;
+ prepared = 1;
+
+ /* rdr from $server to $proxy port $proxy_port -> $client port
+ $port */
+ if (add_rdr(s->id, server_sa, proxy_sa, s->proxy_port,
+ client_sa, s->port) == -1)
+ goto fail;
+
+ /* nat from $server to $client port $port -> $orig_server port
+ $natport */
+ if (rfc_mode && s->cmd == CMD_PORT) {
+ /* Rewrite sourceport to RFC mandated 20. */
+ if (add_nat(s->id, server_sa, client_sa, s->port,
+ orig_sa, 20, 20) == -1)
+ goto fail;
} else {
- if (client_iob.alive) {
- FD_SET(client_iob.fd, fdsp);
- if (client_listen_socket >= 0)
- FD_SET(client_listen_socket, fdsp);
- if (client_data_socket >= 0)
- FD_SET(client_data_socket, fdsp);
- }
- if (server_iob.alive) {
- FD_SET(server_iob.fd, fdsp);
- if (server_listen_socket >= 0)
- FD_SET(server_listen_socket, fdsp);
- if (server_data_socket >= 0)
- FD_SET(server_data_socket, fdsp);
- }
- tv.tv_sec = timeout_seconds;
- tv.tv_usec = 0;
-
- doselect:
- sval = select(maxfd + 1, fdsp, NULL, NULL,
- (tv.tv_sec == 0) ? NULL : &tv);
- if (sval == 0) {
- /*
- * This proxy has timed out. Expire it
- * quietly with an obituary in the syslogs
- * for any passing mourners.
- */
- syslog(LOG_INFO,
- "timeout: no data for %ld seconds",
- timeout_seconds);
- exit(EX_OK);
- }
- if (sval == -1) {
- if (errno == EINTR || errno == EAGAIN)
- goto doselect;
- syslog(LOG_NOTICE,
- "select() failed (%m)");
- exit(EX_OSERR);
- }
- if (client_data_socket >= 0 &&
- FD_ISSET(client_data_socket, fdsp)) {
- int rval;
-
- debuglog(3, "transfer: client to server");
- rval = xfer_data("client to server",
- client_data_socket,
- server_data_socket,
- client_iob.sa.sin_addr,
- real_server_sa.sin_addr);
- if (rval <= 0) {
- close_client_data();
- close_server_data();
- show_xfer_stats();
- } else
- client_data_bytes += rval;
- }
- if (server_data_socket >= 0 &&
- FD_ISSET(server_data_socket, fdsp)) {
- int rval;
-
- debuglog(3, "transfer: server to client");
- rval = xfer_data("server to client",
- server_data_socket,
- client_data_socket,
- real_server_sa.sin_addr,
- client_iob.sa.sin_addr);
- if (rval <= 0) {
- close_client_data();
- close_server_data();
- show_xfer_stats();
- } else
- server_data_bytes += rval;
- }
- if (server_listen_socket >= 0 &&
- FD_ISSET(server_listen_socket, fdsp)) {
- connect_port_backchannel();
- }
- if (client_listen_socket >= 0 &&
- FD_ISSET(client_listen_socket, fdsp)) {
- connect_pasv_backchannel();
- }
- if (client_iob.alive &&
- FD_ISSET(client_iob.fd, fdsp)) {
- client_iob.data_available = 1;
- }
- if (server_iob.alive &&
- FD_ISSET(server_iob.fd, fdsp)) {
- server_iob.data_available = 1;
- }
+ /* Let pf pick a source port from the standard range. */
+ if (add_nat(s->id, server_sa, client_sa, s->port,
+ orig_sa, PF_NAT_PROXY_PORT_LOW,
+ PF_NAT_PROXY_PORT_HIGH) == -1)
+ goto fail;
}
- free(fdsp);
- if (client_iob.got_eof) {
- shutdown(server_iob.fd, 1);
- shutdown(client_iob.fd, 0);
- client_iob.got_eof = 0;
- client_iob.alive = 0;
+
+ /* pass in from $server to $client port $port */
+ if (add_filter(s->id, PF_IN, server_sa, client_sa, s->port) ==
+ -1)
+ goto fail;
+
+ /* pass out from $orig_server to $client port $port */
+ if (add_filter(s->id, PF_OUT, orig_sa, client_sa, s->port) ==
+ -1)
+ goto fail;
+ }
+
+ /* Commit rules if they were prepared. */
+ if (prepared && (do_commit() == -1)) {
+ if (errno != EBUSY)
+ goto fail;
+ /* One more try if busy. */
+ usleep(5000);
+ if (do_commit() == -1)
+ goto fail;
+ }
+
+ out:
+ s->cmd = CMD_NONE;
+ s->port = 0;
+
+ return (1);
+
+ fail:
+ logmsg(LOG_CRIT, "#%d pf operation failed: %s", s->id, strerror(errno));
+ if (prepared)
+ do_rollback();
+ return (0);
+}
+
+void
+server_read(struct bufferevent *bufev, void *arg)
+{
+ struct session *s = arg;
+ size_t buf_avail, read;
+ int n;
+
+ bufferevent_settimeout(bufev, timeout, 0);
+
+ do {
+ buf_avail = sizeof s->sbuf - s->sbuf_valid;
+ read = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
+ buf_avail);
+ s->sbuf_valid += read;
+
+ while ((n = getline(s->sbuf, &s->sbuf_valid)) > 0) {
+ logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
+ if (!server_parse(s)) {
+ end_session(s);
+ return;
+ }
+ bufferevent_write(s->client_bufev, linebuf, linelen);
}
- if (server_iob.got_eof) {
- shutdown(client_iob.fd, 1);
- shutdown(server_iob.fd, 0);
- server_iob.got_eof = 0;
- server_iob.alive = 0;
+
+ if (n == -1) {
+ logmsg(LOG_ERR, "#%d server reply too long or not"
+ " clean", s->id);
+ end_session(s);
+ return;
}
+ } while (read == buf_avail);
+}
+
+const char *
+sock_ntop(struct sockaddr *sa)
+{
+ static int n = 0;
+
+ /* Cycle to next buffer. */
+ n = (n + 1) % NTOP_BUFS;
+ ntop_buf[n][0] = '\0';
+
+ if (sa->sa_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+
+ return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
+ sizeof ntop_buf[0]));
+ }
+
+ if (sa->sa_family == AF_INET6) {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+
+ return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
+ sizeof ntop_buf[0]));
}
- if (Verbose)
- syslog(LOG_INFO, "session ended");
+ return (NULL);
+}
- exit(EX_OK);
+void
+usage(void)
+{
+ fprintf(stderr, "usage: %s [-6Adrv] [-a address] [-b address]"
+ " [-D level] [-m maxsessions]\n [-P port]"
+ " [-p port] [-q queue] [-R address] [-t timeout]\n", __progname);
+ exit(1);
}
OpenPOWER on IntegriCloud