Home | History | Annotate | Line # | Download | only in tftp-proxy
tftp-proxy.c revision 1.1.1.1
      1 /*	$NetBSD: tftp-proxy.c,v 1.1.1.1 2009/12/01 07:03:10 martti Exp $	*/
      2 /* $OpenBSD: tftp-proxy.c,v 1.2 2006/12/20 03:33:38 joel Exp $
      3  *
      4  * Copyright (c) 2005 DLS Internet Services
      5  * Copyright (c) 2004, 2005 Camiel Dobbelaar, <cd (at) sentia.nl>
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  *
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. The name of the author may not be used to endorse or promote products
     17  *    derived from this software without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 #include <sys/types.h>
     32 #include <sys/ioctl.h>
     33 #include <sys/uio.h>
     34 #include <unistd.h>
     35 
     36 #include <netinet/in.h>
     37 #include <arpa/inet.h>
     38 #include <arpa/tftp.h>
     39 #include <sys/socket.h>
     40 #include <net/if.h>
     41 #include <net/pfvar.h>
     42 
     43 #include <errno.h>
     44 #include <pwd.h>
     45 #include <stdio.h>
     46 #include <syslog.h>
     47 #include <string.h>
     48 #include <stdlib.h>
     49 
     50 #include "filter.h"
     51 
     52 #define CHROOT_DIR	"/var/empty"
     53 #define NOPRIV_USER	"proxy"
     54 
     55 #define PF_NAT_PROXY_PORT_LOW	50001
     56 #define PF_NAT_PROXY_PORT_HIGH	65535
     57 
     58 #define DEFTRANSWAIT	2
     59 #define NTOP_BUFS	4
     60 #define PKTSIZE		SEGSIZE+4
     61 
     62 const char *opcode(int);
     63 const char *sock_ntop(struct sockaddr *);
     64 u_int16_t pick_proxy_port(void);
     65 static void usage(void);
     66 
     67 extern	char *__progname;
     68 char	ntop_buf[NTOP_BUFS][INET6_ADDRSTRLEN];
     69 int	verbose = 0;
     70 
     71 int
     72 main(int argc, char *argv[])
     73 {
     74 	int c, fd = 0, on = 1, out_fd = 0, peer, reqsize = 0;
     75 	int transwait = DEFTRANSWAIT;
     76 	char *p;
     77 	struct tftphdr *tp;
     78 	struct passwd *pw;
     79 
     80 	char cbuf[CMSG_SPACE(sizeof(struct sockaddr_storage))];
     81 	char req[PKTSIZE];
     82 	struct cmsghdr *cmsg;
     83 	struct msghdr msg;
     84 	struct iovec iov;
     85 
     86 	struct sockaddr_storage from, proxy, server, proxy_to_server, s_in;
     87 	struct sockaddr_in sock_out;
     88 	socklen_t j;
     89 	in_port_t bindport;
     90 
     91 	openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
     92 
     93 	while ((c = getopt(argc, argv, "vw:")) != -1)
     94 		switch (c) {
     95 		case 'v':
     96 			verbose++;
     97 			break;
     98 		case 'w':
     99 			transwait = strtoll(optarg, &p, 10);
    100 			if (transwait < 1) {
    101 				syslog(LOG_ERR, "invalid -w value");
    102 				exit(1);
    103 			}
    104 			break;
    105 		default:
    106 			usage();
    107 			break;
    108 		}
    109 
    110 	/* open /dev/pf */
    111 	init_filter(NULL, verbose);
    112 
    113 	tzset();
    114 
    115 	pw = getpwnam(NOPRIV_USER);
    116 	if (!pw) {
    117 		syslog(LOG_ERR, "no such user %s: %m", NOPRIV_USER);
    118 		exit(1);
    119 	}
    120 	if (chroot(CHROOT_DIR) || chdir("/")) {
    121 		syslog(LOG_ERR, "chroot %s: %m", CHROOT_DIR);
    122 		exit(1);
    123 	}
    124 	if (setgroups(1, &pw->pw_gid) ||
    125 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
    126 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) {
    127 		syslog(LOG_ERR, "can't revoke privs: %m");
    128 		exit(1);
    129 	}
    130 
    131 	/* non-blocking io */
    132 	if (ioctl(fd, FIONBIO, &on) < 0) {
    133 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
    134 		exit(1);
    135 	}
    136 
    137 	if (setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, &on, sizeof(on)) == -1) {
    138 		syslog(LOG_ERR, "setsockopt(IP_RECVDSTADDR): %m");
    139 		exit(1);
    140 	}
    141 
    142 	j = sizeof(s_in);
    143 	if (getsockname(fd, (struct sockaddr *)&s_in, &j) == -1) {
    144 		syslog(LOG_ERR, "getsockname: %m");
    145 		exit(1);
    146 	}
    147 
    148 	bindport = ((struct sockaddr_in *)&s_in)->sin_port;
    149 
    150 	/* req will be pushed back out at the end, unchanged */
    151 	j = sizeof(from);
    152 	if ((reqsize = recvfrom(fd, req, sizeof(req), MSG_PEEK,
    153 	    (struct sockaddr *)&from, &j)) < 0) {
    154 		syslog(LOG_ERR, "recvfrom: %m");
    155 		exit(1);
    156 	}
    157 
    158 	bzero(&msg, sizeof(msg));
    159 	iov.iov_base = req;
    160 	iov.iov_len = sizeof(req);
    161 	msg.msg_name = &from;
    162 	msg.msg_namelen = sizeof(from);
    163 	msg.msg_iov = &iov;
    164 	msg.msg_iovlen = 1;
    165 	msg.msg_control = cbuf;
    166 	msg.msg_controllen = CMSG_LEN(sizeof(struct sockaddr_storage));
    167 
    168 	if (recvmsg(fd, &msg, 0) < 0) {
    169 		syslog(LOG_ERR, "recvmsg: %m");
    170 		exit(1);
    171 	}
    172 
    173 	close(fd);
    174 	close(1);
    175 
    176 	peer = socket(from.ss_family, SOCK_DGRAM, 0);
    177 	if (peer < 0) {
    178 		syslog(LOG_ERR, "socket: %m");
    179 		exit(1);
    180 	}
    181 	memset(&s_in, 0, sizeof(s_in));
    182 	s_in.ss_family = from.ss_family;
    183 	s_in.ss_len = from.ss_len;
    184 
    185 	/* get local address if possible */
    186 	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
    187 	    cmsg = CMSG_NXTHDR(&msg, cmsg)) {
    188 		if (cmsg->cmsg_level == IPPROTO_IP &&
    189 		    cmsg->cmsg_type == IP_RECVDSTADDR) {
    190 			memcpy(&((struct sockaddr_in *)&s_in)->sin_addr,
    191 			    CMSG_DATA(cmsg), sizeof(struct in_addr));
    192 			break;
    193 		}
    194 	}
    195 
    196 	if (bind(peer, (struct sockaddr *)&s_in, s_in.ss_len) < 0) {
    197 		syslog(LOG_ERR, "bind: %m");
    198 		exit(1);
    199 	}
    200 	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
    201 		syslog(LOG_ERR, "connect: %m");
    202 		exit(1);
    203 	}
    204 
    205 	tp = (struct tftphdr *)req;
    206 	if (!(ntohs(tp->th_opcode) == RRQ || ntohs(tp->th_opcode) == WRQ)) {
    207 		/* not a tftp request, bail */
    208 		if (verbose) {
    209 			syslog(LOG_WARNING, "not a valid tftp request");
    210 			exit(1);
    211 		} else
    212 			/* exit 0 so inetd doesn't log anything */
    213 			exit(0);
    214 	}
    215 
    216 	j = sizeof(struct sockaddr_storage);
    217 	if (getsockname(fd, (struct sockaddr *)&proxy, &j) == -1) {
    218 		syslog(LOG_ERR, "getsockname: %m");
    219 		exit(1);
    220 	}
    221 
    222 	((struct sockaddr_in *)&proxy)->sin_port = bindport;
    223 
    224 	/* find the un-rdr'd server and port the client wanted */
    225 	if (server_lookup((struct sockaddr *)&from,
    226 	    (struct sockaddr *)&proxy, (struct sockaddr *)&server,
    227 	    IPPROTO_UDP) != 0) {
    228 		syslog(LOG_ERR, "pf connection lookup failed (no rdr?)");
    229 		exit(1);
    230 	}
    231 
    232 	/* establish a new outbound connection to the remote server */
    233 	if ((out_fd = socket(((struct sockaddr *)&from)->sa_family,
    234 	    SOCK_DGRAM, IPPROTO_UDP)) < 0) {
    235 		syslog(LOG_ERR, "couldn't create new socket");
    236 		exit(1);
    237 	}
    238 
    239 	bzero((char *)&sock_out, sizeof(sock_out));
    240 	sock_out.sin_family = from.ss_family;
    241 	sock_out.sin_port = htons(pick_proxy_port());
    242 	if (bind(out_fd, (struct sockaddr *)&sock_out, sizeof(sock_out)) < 0) {
    243 		syslog(LOG_ERR, "couldn't bind to new socket: %m");
    244 		exit(1);
    245 	}
    246 
    247 	if (connect(out_fd, (struct sockaddr *)&server,
    248 	    ((struct sockaddr *)&server)->sa_len) < 0 && errno != EINPROGRESS) {
    249 		syslog(LOG_ERR, "couldn't connect to remote server: %m");
    250 		exit(1);
    251 	}
    252 
    253 	j = sizeof(struct sockaddr_storage);
    254 	if ((getsockname(out_fd, (struct sockaddr *)&proxy_to_server,
    255 	    &j)) < 0) {
    256 		syslog(LOG_ERR, "getsockname: %m");
    257 		exit(1);
    258 	}
    259 
    260 	if (verbose)
    261 		syslog(LOG_INFO, "%s:%d -> %s:%d/%s:%d -> %s:%d \"%s %s\"",
    262 			sock_ntop((struct sockaddr *)&from),
    263 			ntohs(((struct sockaddr_in *)&from)->sin_port),
    264 			sock_ntop((struct sockaddr *)&proxy),
    265 			ntohs(((struct sockaddr_in *)&proxy)->sin_port),
    266 			sock_ntop((struct sockaddr *)&proxy_to_server),
    267 			ntohs(((struct sockaddr_in *)&proxy_to_server)->sin_port),
    268 			sock_ntop((struct sockaddr *)&server),
    269 			ntohs(((struct sockaddr_in *)&server)->sin_port),
    270 			opcode(ntohs(tp->th_opcode)),
    271 			tp->th_stuff);
    272 
    273 	/* get ready to add rdr and pass rules */
    274 	if (prepare_commit(1) == -1) {
    275 		syslog(LOG_ERR, "couldn't prepare pf commit");
    276 		exit(1);
    277 	}
    278 
    279 	/* rdr from server to us on our random port -> client on its port */
    280 	if (add_rdr(1, (struct sockaddr *)&server,
    281 	    (struct sockaddr *)&proxy_to_server, ntohs(sock_out.sin_port),
    282 	    (struct sockaddr *)&from,
    283 	    ntohs(((struct sockaddr_in *)&from)->sin_port),
    284 	    IPPROTO_UDP) == -1) {
    285 		syslog(LOG_ERR, "couldn't add rdr");
    286 		exit(1);
    287 	}
    288 
    289 	/* explicitly allow the packets to return back to the client (which pf
    290 	 * will see post-rdr) */
    291 	if (add_filter(1, PF_IN, (struct sockaddr *)&server,
    292 	    (struct sockaddr *)&from,
    293 	    ntohs(((struct sockaddr_in *)&from)->sin_port),
    294 	    IPPROTO_UDP) == -1) {
    295 		syslog(LOG_ERR, "couldn't add pass in");
    296 		exit(1);
    297 	}
    298 	if (add_filter(1, PF_OUT, (struct sockaddr *)&server,
    299 	    (struct sockaddr *)&from,
    300 	    ntohs(((struct sockaddr_in *)&from)->sin_port),
    301 	    IPPROTO_UDP) == -1) {
    302 		syslog(LOG_ERR, "couldn't add pass out");
    303 		exit(1);
    304 	}
    305 
    306 	/* and just in case, to pass out from us to the server */
    307 	if (add_filter(1, PF_OUT, (struct sockaddr *)&proxy_to_server,
    308 	    (struct sockaddr *)&server,
    309 	    ntohs(((struct sockaddr_in *)&server)->sin_port),
    310 	    IPPROTO_UDP) == -1) {
    311 		syslog(LOG_ERR, "couldn't add pass out");
    312 		exit(1);
    313 	}
    314 
    315 	if (do_commit() == -1) {
    316 		syslog(LOG_ERR, "couldn't commit pf rules");
    317 		exit(1);
    318 	}
    319 
    320 	/* forward the initial tftp request and start the insanity */
    321 	if (send(out_fd, tp, reqsize, 0) < 0) {
    322 		syslog(LOG_ERR, "couldn't forward tftp packet: %m");
    323 		exit(1);
    324 	}
    325 
    326 	/* allow the transfer to start to establish a state */
    327 	sleep(transwait);
    328 
    329 	/* delete our rdr rule and clean up */
    330 	prepare_commit(1);
    331 	do_commit();
    332 
    333 	return(0);
    334 }
    335 
    336 const char *
    337 opcode(int code)
    338 {
    339 	static char str[6];
    340 
    341 	switch (code) {
    342 	case 1:
    343 		(void)snprintf(str, sizeof(str), "RRQ");
    344 		break;
    345 	case 2:
    346 		(void)snprintf(str, sizeof(str), "WRQ");
    347 		break;
    348 	default:
    349 		(void)snprintf(str, sizeof(str), "(%d)", code);
    350 		break;
    351 	}
    352 
    353 	return (str);
    354 }
    355 
    356 const char *
    357 sock_ntop(struct sockaddr *sa)
    358 {
    359 	static int n = 0;
    360 
    361 	/* Cycle to next buffer. */
    362 	n = (n + 1) % NTOP_BUFS;
    363 	ntop_buf[n][0] = '\0';
    364 
    365 	if (sa->sa_family == AF_INET) {
    366 		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
    367 
    368 		return (inet_ntop(AF_INET, &sin->sin_addr, ntop_buf[n],
    369 		    sizeof ntop_buf[0]));
    370 	}
    371 
    372 	if (sa->sa_family == AF_INET6) {
    373 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
    374 
    375 		return (inet_ntop(AF_INET6, &sin6->sin6_addr, ntop_buf[n],
    376 		    sizeof ntop_buf[0]));
    377 	}
    378 
    379 	return (NULL);
    380 }
    381 
    382 u_int16_t
    383 pick_proxy_port(void)
    384 {
    385 	return (IPPORT_HIFIRSTAUTO + (arc4random() %
    386 	    (IPPORT_HILASTAUTO - IPPORT_HIFIRSTAUTO)));
    387 }
    388 
    389 static void
    390 usage(void)
    391 {
    392 	syslog(LOG_ERR, "usage: %s [-v] [-w transwait]", __progname);
    393 	exit(1);
    394 }
    395