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