xref: /freebsd/libexec/tftpd/tftpd.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 /*
49  * Trivial file transfer protocol server.
50  *
51  * This version includes many modifications by Jim Guyton
52  * <guyton@rand-unix>.
53  */
54 
55 #include <sys/param.h>
56 #include <sys/ioctl.h>
57 #include <sys/stat.h>
58 #include <sys/socket.h>
59 #include <sys/types.h>
60 
61 #include <netinet/in.h>
62 #include <arpa/tftp.h>
63 #include <arpa/inet.h>
64 
65 #include <ctype.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <libutil.h>
69 #include <netdb.h>
70 #include <pwd.h>
71 #include <setjmp.h>
72 #include <signal.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <syslog.h>
77 #include <unistd.h>
78 
79 #include "tftpsubs.h"
80 
81 #define	TIMEOUT		5
82 
83 int	peer;
84 int	rexmtval = TIMEOUT;
85 int	maxtimeout = 5*TIMEOUT;
86 
87 #define	PKTSIZE	SEGSIZE+4
88 char	buf[PKTSIZE];
89 char	ackbuf[PKTSIZE];
90 struct	sockaddr_in from;
91 int	fromlen;
92 
93 void	tftp __P((struct tftphdr *, int));
94 
95 /*
96  * Null-terminated directory prefix list for absolute pathname requests and
97  * search list for relative pathname requests.
98  *
99  * MAXDIRS should be at least as large as the number of arguments that
100  * inetd allows (currently 20).
101  */
102 #define MAXDIRS	20
103 static struct dirlist {
104 	char	*name;
105 	int	len;
106 } dirs[MAXDIRS+1];
107 static int	suppress_naks;
108 static int	logging;
109 
110 static char *errtomsg __P((int));
111 static void  nak __P((int));
112 
113 int
114 main(argc, argv)
115 	int argc;
116 	char *argv[];
117 {
118 	register struct tftphdr *tp;
119 	register int n;
120 	int ch, on;
121 	struct sockaddr_in sin;
122 	char *chroot_dir = NULL;
123 	struct passwd *nobody;
124 
125 	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
126 	while ((ch = getopt(argc, argv, "lns:")) != -1) {
127 		switch (ch) {
128 		case 'l':
129 			logging = 1;
130 			break;
131 		case 'n':
132 			suppress_naks = 1;
133 			break;
134 		case 's':
135 			chroot_dir = optarg;
136 			break;
137 		default:
138 			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
139 		}
140 	}
141 	if (optind < argc) {
142 		struct dirlist *dirp;
143 
144 		/* Get list of directory prefixes. Skip relative pathnames. */
145 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
146 		     optind++) {
147 			if (argv[optind][0] == '/') {
148 				dirp->name = argv[optind];
149 				dirp->len  = strlen(dirp->name);
150 				dirp++;
151 			}
152 		}
153 	}
154 	else if (chroot_dir) {
155 		dirs->name = "/";
156 		dirs->len = 1;
157 	}
158 
159 	on = 1;
160 	if (ioctl(0, FIONBIO, &on) < 0) {
161 		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
162 		exit(1);
163 	}
164 	fromlen = sizeof (from);
165 	n = recvfrom(0, buf, sizeof (buf), 0,
166 	    (struct sockaddr *)&from, &fromlen);
167 	if (n < 0) {
168 		syslog(LOG_ERR, "recvfrom: %m");
169 		exit(1);
170 	}
171 	/*
172 	 * Now that we have read the message out of the UDP
173 	 * socket, we fork and exit.  Thus, inetd will go back
174 	 * to listening to the tftp port, and the next request
175 	 * to come in will start up a new instance of tftpd.
176 	 *
177 	 * We do this so that inetd can run tftpd in "wait" mode.
178 	 * The problem with tftpd running in "nowait" mode is that
179 	 * inetd may get one or more successful "selects" on the
180 	 * tftp port before we do our receive, so more than one
181 	 * instance of tftpd may be started up.  Worse, if tftpd
182 	 * break before doing the above "recvfrom", inetd would
183 	 * spawn endless instances, clogging the system.
184 	 */
185 	{
186 		int pid;
187 		int i, j;
188 
189 		for (i = 1; i < 20; i++) {
190 		    pid = fork();
191 		    if (pid < 0) {
192 				sleep(i);
193 				/*
194 				 * flush out to most recently sent request.
195 				 *
196 				 * This may drop some request, but those
197 				 * will be resent by the clients when
198 				 * they timeout.  The positive effect of
199 				 * this flush is to (try to) prevent more
200 				 * than one tftpd being started up to service
201 				 * a single request from a single client.
202 				 */
203 				j = sizeof from;
204 				i = recvfrom(0, buf, sizeof (buf), 0,
205 				    (struct sockaddr *)&from, &j);
206 				if (i > 0) {
207 					n = i;
208 					fromlen = j;
209 				}
210 		    } else {
211 				break;
212 		    }
213 		}
214 		if (pid < 0) {
215 			syslog(LOG_ERR, "fork: %m");
216 			exit(1);
217 		} else if (pid != 0) {
218 			exit(0);
219 		}
220 	}
221 
222 	/*
223 	 * Since we exit here, we should do that only after the above
224 	 * recvfrom to keep inetd from constantly forking should there
225 	 * be a problem.  See the above comment about system clogging.
226 	 */
227 	if (chroot_dir) {
228 		/* Must get this before chroot because /etc might go away */
229 		if ((nobody = getpwnam("nobody")) == NULL) {
230 			syslog(LOG_ERR, "nobody: no such user");
231 			exit(1);
232 		}
233 		if (chroot(chroot_dir)) {
234 			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
235 			exit(1);
236 		}
237 		chdir( "/" );
238 		setuid(nobody->pw_uid);
239 	}
240 
241 	from.sin_family = AF_INET;
242 	alarm(0);
243 	close(0);
244 	close(1);
245 	peer = socket(AF_INET, SOCK_DGRAM, 0);
246 	if (peer < 0) {
247 		syslog(LOG_ERR, "socket: %m");
248 		exit(1);
249 	}
250 	memset(&sin, 0, sizeof(sin));
251 	sin.sin_family = AF_INET;
252 	if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
253 		syslog(LOG_ERR, "bind: %m");
254 		exit(1);
255 	}
256 	if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
257 		syslog(LOG_ERR, "connect: %m");
258 		exit(1);
259 	}
260 	tp = (struct tftphdr *)buf;
261 	tp->th_opcode = ntohs(tp->th_opcode);
262 	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
263 		tftp(tp, n);
264 	exit(1);
265 }
266 
267 struct formats;
268 int	validate_access __P((char **, int));
269 void	xmitfile __P((struct formats *));
270 void	recvfile __P((struct formats *));
271 
272 struct formats {
273 	char	*f_mode;
274 	int	(*f_validate) __P((char **, int));
275 	void	(*f_send) __P((struct formats *));
276 	void	(*f_recv) __P((struct formats *));
277 	int	f_convert;
278 } formats[] = {
279 	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
280 	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
281 #ifdef notdef
282 	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
283 #endif
284 	{ 0 }
285 };
286 
287 /*
288  * Handle initial connection protocol.
289  */
290 void
291 tftp(tp, size)
292 	struct tftphdr *tp;
293 	int size;
294 {
295 	register char *cp;
296 	int first = 1, ecode;
297 	register struct formats *pf;
298 	char *filename, *mode;
299 
300 	filename = cp = tp->th_stuff;
301 again:
302 	while (cp < buf + size) {
303 		if (*cp == '\0')
304 			break;
305 		cp++;
306 	}
307 	if (*cp != '\0') {
308 		nak(EBADOP);
309 		exit(1);
310 	}
311 	if (first) {
312 		mode = ++cp;
313 		first = 0;
314 		goto again;
315 	}
316 	for (cp = mode; *cp; cp++)
317 		if (isupper(*cp))
318 			*cp = tolower(*cp);
319 	for (pf = formats; pf->f_mode; pf++)
320 		if (strcmp(pf->f_mode, mode) == 0)
321 			break;
322 	if (pf->f_mode == 0) {
323 		nak(EBADOP);
324 		exit(1);
325 	}
326 	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
327 	if (logging) {
328 		char host[MAXHOSTNAMELEN];
329 
330 		realhostname(host, sizeof(host) - 1, &from.sin_addr);
331 		host[sizeof(host) - 1] = '\0';
332 		syslog(LOG_INFO, "%s: %s request for %s: %s", host,
333 			tp->th_opcode == WRQ ? "write" : "read",
334 			filename, errtomsg(ecode));
335 	}
336 	if (ecode) {
337 		/*
338 		 * Avoid storms of naks to a RRQ broadcast for a relative
339 		 * bootfile pathname from a diskless Sun.
340 		 */
341 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
342 			exit(0);
343 		nak(ecode);
344 		exit(1);
345 	}
346 	if (tp->th_opcode == WRQ)
347 		(*pf->f_recv)(pf);
348 	else
349 		(*pf->f_send)(pf);
350 	exit(0);
351 }
352 
353 
354 FILE *file;
355 
356 /*
357  * Validate file access.  Since we
358  * have no uid or gid, for now require
359  * file to exist and be publicly
360  * readable/writable.
361  * If we were invoked with arguments
362  * from inetd then the file must also be
363  * in one of the given directory prefixes.
364  * Note also, full path name must be
365  * given as we have no login directory.
366  */
367 int
368 validate_access(filep, mode)
369 	char **filep;
370 	int mode;
371 {
372 	struct stat stbuf;
373 	int	fd;
374 	struct dirlist *dirp;
375 	static char pathname[MAXPATHLEN];
376 	char *filename = *filep;
377 
378 	/*
379 	 * Prevent tricksters from getting around the directory restrictions
380 	 */
381 	if (strstr(filename, "/../"))
382 		return (EACCESS);
383 
384 	if (*filename == '/') {
385 		/*
386 		 * Allow the request if it's in one of the approved locations.
387 		 * Special case: check the null prefix ("/") by looking
388 		 * for length = 1 and relying on the arg. processing that
389 		 * it's a /.
390 		 */
391 		for (dirp = dirs; dirp->name != NULL; dirp++) {
392 			if (dirp->len == 1 ||
393 			    (!strncmp(filename, dirp->name, dirp->len) &&
394 			     filename[dirp->len] == '/'))
395 				    break;
396 		}
397 		/* If directory list is empty, allow access to any file */
398 		if (dirp->name == NULL && dirp != dirs)
399 			return (EACCESS);
400 		if (stat(filename, &stbuf) < 0)
401 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
402 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
403 			return (ENOTFOUND);
404 		if (mode == RRQ) {
405 			if ((stbuf.st_mode & S_IROTH) == 0)
406 				return (EACCESS);
407 		} else {
408 			if ((stbuf.st_mode & S_IWOTH) == 0)
409 				return (EACCESS);
410 		}
411 	} else {
412 		int err;
413 
414 		/*
415 		 * Relative file name: search the approved locations for it.
416 		 * Don't allow write requests that avoid directory
417 		 * restrictions.
418 		 */
419 
420 		if (!strncmp(filename, "../", 3))
421 			return (EACCESS);
422 
423 		/*
424 		 * If the file exists in one of the directories and isn't
425 		 * readable, continue looking. However, change the error code
426 		 * to give an indication that the file exists.
427 		 */
428 		err = ENOTFOUND;
429 		for (dirp = dirs; dirp->name != NULL; dirp++) {
430 			snprintf(pathname, sizeof(pathname), "%s/%s",
431 				dirp->name, filename);
432 			if (stat(pathname, &stbuf) == 0 &&
433 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
434 				if ((stbuf.st_mode & S_IROTH) != 0) {
435 					break;
436 				}
437 				err = EACCESS;
438 			}
439 		}
440 		if (dirp->name == NULL)
441 			return (err);
442 		*filep = filename = pathname;
443 	}
444 	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
445 	if (fd < 0)
446 		return (errno + 100);
447 	file = fdopen(fd, (mode == RRQ)? "r":"w");
448 	if (file == NULL) {
449 		return errno+100;
450 	}
451 	return (0);
452 }
453 
454 int	timeout;
455 jmp_buf	timeoutbuf;
456 
457 void
458 timer()
459 {
460 
461 	timeout += rexmtval;
462 	if (timeout >= maxtimeout)
463 		exit(1);
464 	longjmp(timeoutbuf, 1);
465 }
466 
467 /*
468  * Send the requested file.
469  */
470 void
471 xmitfile(pf)
472 	struct formats *pf;
473 {
474 	struct tftphdr *dp, *r_init();
475 	register struct tftphdr *ap;    /* ack packet */
476 	register int size, n;
477 	volatile int block;
478 
479 	signal(SIGALRM, timer);
480 	dp = r_init();
481 	ap = (struct tftphdr *)ackbuf;
482 	block = 1;
483 	do {
484 		size = readit(file, &dp, pf->f_convert);
485 		if (size < 0) {
486 			nak(errno + 100);
487 			goto abort;
488 		}
489 		dp->th_opcode = htons((u_short)DATA);
490 		dp->th_block = htons((u_short)block);
491 		timeout = 0;
492 		(void)setjmp(timeoutbuf);
493 
494 send_data:
495 		if (send(peer, dp, size + 4, 0) != size + 4) {
496 			syslog(LOG_ERR, "write: %m");
497 			goto abort;
498 		}
499 		read_ahead(file, pf->f_convert);
500 		for ( ; ; ) {
501 			alarm(rexmtval);        /* read the ack */
502 			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
503 			alarm(0);
504 			if (n < 0) {
505 				syslog(LOG_ERR, "read: %m");
506 				goto abort;
507 			}
508 			ap->th_opcode = ntohs((u_short)ap->th_opcode);
509 			ap->th_block = ntohs((u_short)ap->th_block);
510 
511 			if (ap->th_opcode == ERROR)
512 				goto abort;
513 
514 			if (ap->th_opcode == ACK) {
515 				if (ap->th_block == block)
516 					break;
517 				/* Re-synchronize with the other side */
518 				(void) synchnet(peer);
519 				if (ap->th_block == (block -1))
520 					goto send_data;
521 			}
522 
523 		}
524 		block++;
525 	} while (size == SEGSIZE);
526 abort:
527 	(void) fclose(file);
528 }
529 
530 void
531 justquit()
532 {
533 	exit(0);
534 }
535 
536 
537 /*
538  * Receive a file.
539  */
540 void
541 recvfile(pf)
542 	struct formats *pf;
543 {
544 	struct tftphdr *dp, *w_init();
545 	register struct tftphdr *ap;    /* ack buffer */
546 	register int n, size;
547 	volatile int block;
548 
549 	signal(SIGALRM, timer);
550 	dp = w_init();
551 	ap = (struct tftphdr *)ackbuf;
552 	block = 0;
553 	do {
554 		timeout = 0;
555 		ap->th_opcode = htons((u_short)ACK);
556 		ap->th_block = htons((u_short)block);
557 		block++;
558 		(void) setjmp(timeoutbuf);
559 send_ack:
560 		if (send(peer, ackbuf, 4, 0) != 4) {
561 			syslog(LOG_ERR, "write: %m");
562 			goto abort;
563 		}
564 		write_behind(file, pf->f_convert);
565 		for ( ; ; ) {
566 			alarm(rexmtval);
567 			n = recv(peer, dp, PKTSIZE, 0);
568 			alarm(0);
569 			if (n < 0) {            /* really? */
570 				syslog(LOG_ERR, "read: %m");
571 				goto abort;
572 			}
573 			dp->th_opcode = ntohs((u_short)dp->th_opcode);
574 			dp->th_block = ntohs((u_short)dp->th_block);
575 			if (dp->th_opcode == ERROR)
576 				goto abort;
577 			if (dp->th_opcode == DATA) {
578 				if (dp->th_block == block) {
579 					break;   /* normal */
580 				}
581 				/* Re-synchronize with the other side */
582 				(void) synchnet(peer);
583 				if (dp->th_block == (block-1))
584 					goto send_ack;          /* rexmit */
585 			}
586 		}
587 		/*  size = write(file, dp->th_data, n - 4); */
588 		size = writeit(file, &dp, n - 4, pf->f_convert);
589 		if (size != (n-4)) {                    /* ahem */
590 			if (size < 0) nak(errno + 100);
591 			else nak(ENOSPACE);
592 			goto abort;
593 		}
594 	} while (size == SEGSIZE);
595 	write_behind(file, pf->f_convert);
596 	(void) fclose(file);            /* close data file */
597 
598 	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
599 	ap->th_block = htons((u_short)(block));
600 	(void) send(peer, ackbuf, 4, 0);
601 
602 	signal(SIGALRM, justquit);      /* just quit on timeout */
603 	alarm(rexmtval);
604 	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
605 	alarm(0);
606 	if (n >= 4 &&                   /* if read some data */
607 	    dp->th_opcode == DATA &&    /* and got a data block */
608 	    block == dp->th_block) {	/* then my last ack was lost */
609 		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
610 	}
611 abort:
612 	return;
613 }
614 
615 struct errmsg {
616 	int	e_code;
617 	char	*e_msg;
618 } errmsgs[] = {
619 	{ EUNDEF,	"Undefined error code" },
620 	{ ENOTFOUND,	"File not found" },
621 	{ EACCESS,	"Access violation" },
622 	{ ENOSPACE,	"Disk full or allocation exceeded" },
623 	{ EBADOP,	"Illegal TFTP operation" },
624 	{ EBADID,	"Unknown transfer ID" },
625 	{ EEXISTS,	"File already exists" },
626 	{ ENOUSER,	"No such user" },
627 	{ -1,		0 }
628 };
629 
630 static char *
631 errtomsg(error)
632 	int error;
633 {
634 	static char buf[20];
635 	register struct errmsg *pe;
636 	if (error == 0)
637 		return "success";
638 	for (pe = errmsgs; pe->e_code >= 0; pe++)
639 		if (pe->e_code == error)
640 			return pe->e_msg;
641 	snprintf(buf, sizeof(buf), "error %d", error);
642 	return buf;
643 }
644 
645 /*
646  * Send a nak packet (error message).
647  * Error code passed in is one of the
648  * standard TFTP codes, or a UNIX errno
649  * offset by 100.
650  */
651 static void
652 nak(error)
653 	int error;
654 {
655 	register struct tftphdr *tp;
656 	int length;
657 	register struct errmsg *pe;
658 
659 	tp = (struct tftphdr *)buf;
660 	tp->th_opcode = htons((u_short)ERROR);
661 	tp->th_code = htons((u_short)error);
662 	for (pe = errmsgs; pe->e_code >= 0; pe++)
663 		if (pe->e_code == error)
664 			break;
665 	if (pe->e_code < 0) {
666 		pe->e_msg = strerror(error - 100);
667 		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
668 	}
669 	strcpy(tp->th_msg, pe->e_msg);
670 	length = strlen(pe->e_msg);
671 	tp->th_msg[length] = '\0';
672 	length += 5;
673 	if (send(peer, buf, length, 0) != length)
674 		syslog(LOG_ERR, "nak: %m");
675 }
676