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