xref: /freebsd-13-stable/libexec/tftpd/tftpd.c (revision 3d497e17ebd33fe0f58d773e35ab994d750258d6)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
41 #endif
42 #endif /* not lint */
43 #include <sys/cdefs.h>
44 /*
45  * Trivial file transfer protocol server.
46  *
47  * This version includes many modifications by Jim Guyton
48  * <guyton@rand-unix>.
49  */
50 
51 #include <sys/param.h>
52 #include <sys/ioctl.h>
53 #include <sys/stat.h>
54 #include <sys/socket.h>
55 
56 #include <netinet/in.h>
57 #include <arpa/tftp.h>
58 
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #include <pwd.h>
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <syslog.h>
69 #include <unistd.h>
70 
71 #include "tftp-file.h"
72 #include "tftp-io.h"
73 #include "tftp-utils.h"
74 #include "tftp-transfer.h"
75 #include "tftp-options.h"
76 
77 #ifdef	LIBWRAP
78 #include <tcpd.h>
79 #endif
80 
81 static void	tftp_wrq(int peer, char *, ssize_t);
82 static void	tftp_rrq(int peer, char *, ssize_t);
83 
84 /*
85  * Null-terminated directory prefix list for absolute pathname requests and
86  * search list for relative pathname requests.
87  *
88  * MAXDIRS should be at least as large as the number of arguments that
89  * inetd allows (currently 20).
90  */
91 #define MAXDIRS	20
92 static struct dirlist {
93 	const char	*name;
94 	int	len;
95 } dirs[MAXDIRS+1];
96 static int	suppress_naks;
97 static int	logging;
98 static int	ipchroot;
99 static int	check_woth = 1;
100 static int	create_new = 0;
101 static const char *newfile_format = "%Y%m%d";
102 static int	increase_name = 0;
103 static mode_t	mask = S_IWGRP | S_IWOTH;
104 
105 struct formats;
106 static void	tftp_recvfile(int peer, const char *mode);
107 static void	tftp_xmitfile(int peer, const char *mode);
108 static int	validate_access(int peer, char **, int);
109 static char	peername[NI_MAXHOST];
110 
111 static FILE *file;
112 
113 static struct formats {
114 	const char	*f_mode;
115 	int	f_convert;
116 } formats[] = {
117 	{ "netascii",	1 },
118 	{ "octet",	0 },
119 	{ NULL,		0 }
120 };
121 
122 int
main(int argc,char * argv[])123 main(int argc, char *argv[])
124 {
125 	struct tftphdr *tp;
126 	int		peer;
127 	socklen_t	peerlen, len;
128 	ssize_t		n;
129 	int		ch;
130 	char		*chroot_dir = NULL;
131 	struct passwd	*nobody;
132 	const char	*chuser = "nobody";
133 	char		recvbuffer[MAXPKTSIZE];
134 	int		allow_ro = 1, allow_wo = 1;
135 
136 	tzset();			/* syslog in localtime */
137 	acting_as_client = 0;
138 
139 	tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
140 	while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:Su:U:wW")) != -1) {
141 		switch (ch) {
142 		case 'c':
143 			ipchroot = 1;
144 			break;
145 		case 'C':
146 			ipchroot = 2;
147 			break;
148 		case 'd':
149 			if (atoi(optarg) != 0)
150 				debug += atoi(optarg);
151 			else
152 				debug |= debug_finds(optarg);
153 			break;
154 		case 'F':
155 			newfile_format = optarg;
156 			break;
157 		case 'l':
158 			logging = 1;
159 			break;
160 		case 'n':
161 			suppress_naks = 1;
162 			break;
163 		case 'o':
164 			options_rfc_enabled = 0;
165 			break;
166 		case 'O':
167 			options_extra_enabled = 0;
168 			break;
169 		case 'p':
170 			packetdroppercentage = atoi(optarg);
171 			tftp_log(LOG_INFO,
172 			    "Randomly dropping %d out of 100 packets",
173 			    packetdroppercentage);
174 			break;
175 		case 's':
176 			chroot_dir = optarg;
177 			break;
178 		case 'S':
179 			check_woth = -1;
180 			break;
181 		case 'u':
182 			chuser = optarg;
183 			break;
184 		case 'U':
185 			mask = strtol(optarg, NULL, 0);
186 			break;
187 		case 'w':
188 			create_new = 1;
189 			break;
190 		case 'W':
191 			create_new = 1;
192 			increase_name = 1;
193 			break;
194 		default:
195 			tftp_log(LOG_WARNING,
196 				"ignoring unknown option -%c", ch);
197 		}
198 	}
199 	if (optind < argc) {
200 		struct dirlist *dirp;
201 
202 		/* Get list of directory prefixes. Skip relative pathnames. */
203 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
204 		     optind++) {
205 			if (argv[optind][0] == '/') {
206 				dirp->name = argv[optind];
207 				dirp->len  = strlen(dirp->name);
208 				dirp++;
209 			}
210 		}
211 	}
212 	else if (chroot_dir) {
213 		dirs->name = "/";
214 		dirs->len = 1;
215 	}
216 	if (ipchroot > 0 && chroot_dir == NULL) {
217 		tftp_log(LOG_ERR, "-c requires -s");
218 		exit(1);
219 	}
220 
221 	umask(mask);
222 
223 	{
224 		int on = 1;
225 		if (ioctl(0, FIONBIO, &on) < 0) {
226 			tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
227 			exit(1);
228 		}
229 	}
230 
231 	/* Find out who we are talking to and what we are going to do */
232 	peerlen = sizeof(peer_sock);
233 	n = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
234 	    (struct sockaddr *)&peer_sock, &peerlen);
235 	if (n < 0) {
236 		tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
237 		exit(1);
238 	}
239 	getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
240 	    peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
241 
242 	/*
243 	 * Now that we have read the message out of the UDP
244 	 * socket, we fork and exit.  Thus, inetd will go back
245 	 * to listening to the tftp port, and the next request
246 	 * to come in will start up a new instance of tftpd.
247 	 *
248 	 * We do this so that inetd can run tftpd in "wait" mode.
249 	 * The problem with tftpd running in "nowait" mode is that
250 	 * inetd may get one or more successful "selects" on the
251 	 * tftp port before we do our receive, so more than one
252 	 * instance of tftpd may be started up.  Worse, if tftpd
253 	 * break before doing the above "recvfrom", inetd would
254 	 * spawn endless instances, clogging the system.
255 	 */
256 	{
257 		int i, pid;
258 
259 		for (i = 1; i < 20; i++) {
260 		    pid = fork();
261 		    if (pid < 0) {
262 				sleep(i);
263 				/*
264 				 * flush out to most recently sent request.
265 				 *
266 				 * This may drop some request, but those
267 				 * will be resent by the clients when
268 				 * they timeout.  The positive effect of
269 				 * this flush is to (try to) prevent more
270 				 * than one tftpd being started up to service
271 				 * a single request from a single client.
272 				 */
273 				peerlen = sizeof peer_sock;
274 				i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
275 				    (struct sockaddr *)&peer_sock, &peerlen);
276 				if (i > 0) {
277 					n = i;
278 				}
279 		    } else {
280 				break;
281 		    }
282 		}
283 		if (pid < 0) {
284 			tftp_log(LOG_ERR, "fork: %s", strerror(errno));
285 			exit(1);
286 		} else if (pid != 0) {
287 			exit(0);
288 		}
289 	}
290 
291 #ifdef	LIBWRAP
292 	/*
293 	 * See if the client is allowed to talk to me.
294 	 * (This needs to be done before the chroot())
295 	 */
296 	{
297 		struct request_info req;
298 
299 		request_init(&req, RQ_CLIENT_ADDR, peername, 0);
300 		request_set(&req, RQ_DAEMON, "tftpd", 0);
301 
302 		if (hosts_access(&req) == 0) {
303 			if (debug&DEBUG_ACCESS)
304 				tftp_log(LOG_WARNING,
305 				    "Access denied by 'tftpd' entry "
306 				    "in /etc/hosts.allow");
307 
308 			/*
309 			 * Full access might be disabled, but maybe the
310 			 * client is allowed to do read-only access.
311 			 */
312 			request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
313 			allow_ro = hosts_access(&req);
314 
315 			request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
316 			allow_wo = hosts_access(&req);
317 
318 			if (allow_ro == 0 && allow_wo == 0) {
319 				tftp_log(LOG_WARNING,
320 				    "Unauthorized access from %s", peername);
321 				exit(1);
322 			}
323 
324 			if (debug&DEBUG_ACCESS) {
325 				if (allow_ro)
326 					tftp_log(LOG_WARNING,
327 					    "But allowed readonly access "
328 					    "via 'tftpd-ro' entry");
329 				if (allow_wo)
330 					tftp_log(LOG_WARNING,
331 					    "But allowed writeonly access "
332 					    "via 'tftpd-wo' entry");
333 			}
334 		} else
335 			if (debug&DEBUG_ACCESS)
336 				tftp_log(LOG_WARNING,
337 				    "Full access allowed"
338 				    "in /etc/hosts.allow");
339 	}
340 #endif
341 
342 	/*
343 	 * Since we exit here, we should do that only after the above
344 	 * recvfrom to keep inetd from constantly forking should there
345 	 * be a problem.  See the above comment about system clogging.
346 	 */
347 	if (chroot_dir) {
348 		if (ipchroot > 0) {
349 			char *tempchroot;
350 			struct stat sb;
351 			int statret;
352 			struct sockaddr_storage ss;
353 			char hbuf[NI_MAXHOST];
354 
355 			statret = -1;
356 			memcpy(&ss, &peer_sock, peer_sock.ss_len);
357 			unmappedaddr((struct sockaddr_in6 *)&ss);
358 			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
359 				    hbuf, sizeof(hbuf), NULL, 0,
360 				    NI_NUMERICHOST);
361 			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
362 			if (ipchroot == 2)
363 				statret = stat(tempchroot, &sb);
364 			if (ipchroot == 1 ||
365 			    (statret == 0 && (sb.st_mode & S_IFDIR)))
366 				chroot_dir = tempchroot;
367 		}
368 		/* Must get this before chroot because /etc might go away */
369 		if ((nobody = getpwnam(chuser)) == NULL) {
370 			tftp_log(LOG_ERR, "%s: no such user", chuser);
371 			exit(1);
372 		}
373 		if (chroot(chroot_dir)) {
374 			tftp_log(LOG_ERR, "chroot: %s: %s",
375 			    chroot_dir, strerror(errno));
376 			exit(1);
377 		}
378 		if (chdir("/") != 0) {
379 			tftp_log(LOG_ERR, "chdir: %s", strerror(errno));
380 			exit(1);
381 		}
382 		if (setgroups(1, &nobody->pw_gid) != 0) {
383 			tftp_log(LOG_ERR, "setgroups failed");
384 			exit(1);
385 		}
386 		if (setuid(nobody->pw_uid) != 0) {
387 			tftp_log(LOG_ERR, "setuid failed");
388 			exit(1);
389 		}
390 		if (check_woth == -1)
391 			check_woth = 0;
392 	}
393 	if (check_woth == -1)
394 		check_woth = 1;
395 
396 	len = sizeof(me_sock);
397 	if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
398 		switch (me_sock.ss_family) {
399 		case AF_INET:
400 			((struct sockaddr_in *)&me_sock)->sin_port = 0;
401 			break;
402 		case AF_INET6:
403 			((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
404 			break;
405 		default:
406 			/* unsupported */
407 			break;
408 		}
409 	} else {
410 		memset(&me_sock, 0, sizeof(me_sock));
411 		me_sock.ss_family = peer_sock.ss_family;
412 		me_sock.ss_len = peer_sock.ss_len;
413 	}
414 	close(0);
415 	close(1);
416 	peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
417 	if (peer < 0) {
418 		tftp_log(LOG_ERR, "socket: %s", strerror(errno));
419 		exit(1);
420 	}
421 	if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
422 		tftp_log(LOG_ERR, "bind: %s", strerror(errno));
423 		exit(1);
424 	}
425 
426 	tp = (struct tftphdr *)recvbuffer;
427 	tp->th_opcode = ntohs(tp->th_opcode);
428 	if (tp->th_opcode == RRQ) {
429 		if (allow_ro)
430 			tftp_rrq(peer, tp->th_stuff, n - 1);
431 		else {
432 			tftp_log(LOG_WARNING,
433 			    "%s read access denied", peername);
434 			exit(1);
435 		}
436 	} else if (tp->th_opcode == WRQ) {
437 		if (allow_wo)
438 			tftp_wrq(peer, tp->th_stuff, n - 1);
439 		else {
440 			tftp_log(LOG_WARNING,
441 			    "%s write access denied", peername);
442 			exit(1);
443 		}
444 	} else
445 		send_error(peer, EBADOP);
446 	exit(1);
447 }
448 
449 static void
reduce_path(char * fn)450 reduce_path(char *fn)
451 {
452 	char *slash, *ptr;
453 
454 	/* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
455 	while ((slash = strstr(fn, "/./")) != NULL) {
456 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
457 			;
458 		slash += 2;
459 		while (*slash)
460 			*++ptr = *++slash;
461 	}
462 
463 	/* Now reduce all "/something/+../" to "/" */
464 	while ((slash = strstr(fn, "/../")) != NULL) {
465 		if (slash == fn)
466 			break;
467 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
468 			;
469 		for (ptr--; ptr >= fn; ptr--)
470 			if (*ptr == '/')
471 				break;
472 		if (ptr < fn)
473 			break;
474 		slash += 3;
475 		while (*slash)
476 			*++ptr = *++slash;
477 	}
478 }
479 
480 static char *
parse_header(int peer,char * recvbuffer,ssize_t size,char ** filename,char ** mode)481 parse_header(int peer, char *recvbuffer, ssize_t size,
482 	char **filename, char **mode)
483 {
484 	char	*cp;
485 	int	i;
486 	struct formats *pf;
487 
488 	*mode = NULL;
489 	cp = recvbuffer;
490 
491 	i = get_field(peer, recvbuffer, size);
492 	if (i >= PATH_MAX) {
493 		tftp_log(LOG_ERR, "Bad option - filename too long");
494 		send_error(peer, EBADOP);
495 		exit(1);
496 	}
497 	*filename = recvbuffer;
498 	tftp_log(LOG_INFO, "Filename: '%s'", *filename);
499 	cp += i;
500 
501 	i = get_field(peer, cp, size);
502 	*mode = cp;
503 	cp += i;
504 
505 	/* Find the file transfer mode */
506 	for (cp = *mode; *cp; cp++)
507 		if (isupper(*cp))
508 			*cp = tolower(*cp);
509 	for (pf = formats; pf->f_mode; pf++)
510 		if (strcmp(pf->f_mode, *mode) == 0)
511 			break;
512 	if (pf->f_mode == NULL) {
513 		tftp_log(LOG_ERR,
514 		    "Bad option - Unknown transfer mode (%s)", *mode);
515 		send_error(peer, EBADOP);
516 		exit(1);
517 	}
518 	tftp_log(LOG_INFO, "Mode: '%s'", *mode);
519 
520 	return (cp + 1);
521 }
522 
523 /*
524  * WRQ - receive a file from the client
525  */
526 void
tftp_wrq(int peer,char * recvbuffer,ssize_t size)527 tftp_wrq(int peer, char *recvbuffer, ssize_t size)
528 {
529 	char *cp;
530 	int has_options = 0, ecode;
531 	char *filename, *mode;
532 	char fnbuf[PATH_MAX];
533 
534 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
535 	size -= (cp - recvbuffer) + 1;
536 
537 	strlcpy(fnbuf, filename, sizeof(fnbuf));
538 	reduce_path(fnbuf);
539 	filename = fnbuf;
540 
541 	if (size > 0) {
542 		if (options_rfc_enabled)
543 			has_options = !parse_options(peer, cp, size);
544 		else
545 			tftp_log(LOG_INFO, "Options found but not enabled");
546 	}
547 
548 	ecode = validate_access(peer, &filename, WRQ);
549 	if (ecode == 0) {
550 		if (has_options)
551 			send_oack(peer);
552 		else
553 			send_ack(peer, 0);
554 	}
555 	if (logging) {
556 		tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
557 			    filename, errtomsg(ecode));
558 	}
559 
560 	if (ecode) {
561 		send_error(peer, ecode);
562 		exit(1);
563 	}
564 	tftp_recvfile(peer, mode);
565 	exit(0);
566 }
567 
568 /*
569  * RRQ - send a file to the client
570  */
571 void
tftp_rrq(int peer,char * recvbuffer,ssize_t size)572 tftp_rrq(int peer, char *recvbuffer, ssize_t size)
573 {
574 	char *cp;
575 	int has_options = 0, ecode;
576 	char *filename, *mode;
577 	char	fnbuf[PATH_MAX];
578 
579 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
580 	size -= (cp - recvbuffer) + 1;
581 
582 	strlcpy(fnbuf, filename, sizeof(fnbuf));
583 	reduce_path(fnbuf);
584 	filename = fnbuf;
585 
586 	if (size > 0) {
587 		if (options_rfc_enabled)
588 			has_options = !parse_options(peer, cp, size);
589 		else
590 			tftp_log(LOG_INFO, "Options found but not enabled");
591 	}
592 
593 	ecode = validate_access(peer, &filename, RRQ);
594 	if (ecode == 0) {
595 		if (has_options) {
596 			int n;
597 			char lrecvbuffer[MAXPKTSIZE];
598 			struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
599 
600 			send_oack(peer);
601 			n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
602 				NULL, timeoutpacket);
603 			if (n < 0) {
604 				if (debug&DEBUG_SIMPLE)
605 					tftp_log(LOG_DEBUG, "Aborting: %s",
606 					    rp_strerror(n));
607 				return;
608 			}
609 			if (rp->th_opcode != ACK) {
610 				if (debug&DEBUG_SIMPLE)
611 					tftp_log(LOG_DEBUG,
612 					    "Expected ACK, got %s on OACK",
613 					    packettype(rp->th_opcode));
614 				return;
615 			}
616 		}
617 	}
618 
619 	if (logging)
620 		tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
621 			    filename, errtomsg(ecode));
622 
623 	if (ecode) {
624 		/*
625 		 * Avoid storms of naks to a RRQ broadcast for a relative
626 		 * bootfile pathname from a diskless Sun.
627 		 */
628 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
629 			exit(0);
630 		send_error(peer, ecode);
631 		exit(1);
632 	}
633 	tftp_xmitfile(peer, mode);
634 }
635 
636 /*
637  * Find the next value for YYYYMMDD.nn when the file to be written should
638  * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
639  * Besides, that is four updates per hour on a file, which is kind of
640  * execessive anyway.
641  */
642 static int
find_next_name(char * filename,int * fd)643 find_next_name(char *filename, int *fd)
644 {
645 	int i;
646 	time_t tval;
647 	size_t len;
648 	struct tm lt;
649 	char yyyymmdd[MAXPATHLEN];
650 	char newname[MAXPATHLEN];
651 
652 	/* Create the YYYYMMDD part of the filename */
653 	time(&tval);
654 	lt = *localtime(&tval);
655 	len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
656 	if (len == 0) {
657 		syslog(LOG_WARNING,
658 			"Filename suffix too long (%d characters maximum)",
659 			MAXPATHLEN);
660 		return (EACCESS);
661 	}
662 
663 	/* Make sure the new filename is not too long */
664 	if (strlen(filename) > MAXPATHLEN - len - 5) {
665 		syslog(LOG_WARNING,
666 			"Filename too long (%zd characters, %zd maximum)",
667 			strlen(filename), MAXPATHLEN - len - 5);
668 		return (EACCESS);
669 	}
670 
671 	/* Find the first file which doesn't exist */
672 	for (i = 0; i < 100; i++) {
673 		sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
674 		*fd = open(newname,
675 		    O_WRONLY | O_CREAT | O_EXCL,
676 		    S_IRUSR | S_IWUSR | S_IRGRP |
677 		    S_IWGRP | S_IROTH | S_IWOTH);
678 		if (*fd > 0)
679 			return 0;
680 	}
681 
682 	return (EEXIST);
683 }
684 
685 /*
686  * Validate file access.  Since we
687  * have no uid or gid, for now require
688  * file to exist and be publicly
689  * readable/writable.
690  * If we were invoked with arguments
691  * from inetd then the file must also be
692  * in one of the given directory prefixes.
693  * Note also, full path name must be
694  * given as we have no login directory.
695  */
696 int
validate_access(int peer,char ** filep,int mode)697 validate_access(int peer, char **filep, int mode)
698 {
699 	struct stat stbuf;
700 	int	fd;
701 	int	error;
702 	struct dirlist *dirp;
703 	static char pathname[MAXPATHLEN];
704 	char *filename = *filep;
705 
706 	/*
707 	 * Prevent tricksters from getting around the directory restrictions
708 	 */
709 	if (strstr(filename, "/../"))
710 		return (EACCESS);
711 
712 	if (*filename == '/') {
713 		/*
714 		 * Allow the request if it's in one of the approved locations.
715 		 * Special case: check the null prefix ("/") by looking
716 		 * for length = 1 and relying on the arg. processing that
717 		 * it's a /.
718 		 */
719 		for (dirp = dirs; dirp->name != NULL; dirp++) {
720 			if (dirp->len == 1 ||
721 			    (!strncmp(filename, dirp->name, dirp->len) &&
722 			     filename[dirp->len] == '/'))
723 				    break;
724 		}
725 		/* If directory list is empty, allow access to any file */
726 		if (dirp->name == NULL && dirp != dirs)
727 			return (EACCESS);
728 		if (stat(filename, &stbuf) < 0)
729 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
730 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
731 			return (ENOTFOUND);
732 		if (mode == RRQ) {
733 			if ((stbuf.st_mode & S_IROTH) == 0)
734 				return (EACCESS);
735 		} else {
736 			if (check_woth && ((stbuf.st_mode & S_IWOTH) == 0))
737 				return (EACCESS);
738 		}
739 	} else {
740 		int err;
741 
742 		/*
743 		 * Relative file name: search the approved locations for it.
744 		 * Don't allow write requests that avoid directory
745 		 * restrictions.
746 		 */
747 
748 		if (!strncmp(filename, "../", 3))
749 			return (EACCESS);
750 
751 		/*
752 		 * If the file exists in one of the directories and isn't
753 		 * readable, continue looking. However, change the error code
754 		 * to give an indication that the file exists.
755 		 */
756 		err = ENOTFOUND;
757 		for (dirp = dirs; dirp->name != NULL; dirp++) {
758 			snprintf(pathname, sizeof(pathname), "%s/%s",
759 				dirp->name, filename);
760 			if (stat(pathname, &stbuf) == 0 &&
761 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
762 				if (mode == RRQ) {
763 					if ((stbuf.st_mode & S_IROTH) != 0)
764 						break;
765 				} else {
766 					if (!check_woth || ((stbuf.st_mode & S_IWOTH) != 0))
767 						break;
768 				}
769 				err = EACCESS;
770 			}
771 		}
772 		if (dirp->name != NULL)
773 			*filep = filename = pathname;
774 		else if (mode == RRQ)
775 			return (err);
776 		else if (err != ENOTFOUND || !create_new)
777 			return (err);
778 	}
779 
780 	/*
781 	 * This option is handled here because it (might) require(s) the
782 	 * size of the file.
783 	 */
784 	option_tsize(peer, NULL, mode, &stbuf);
785 
786 	if (mode == RRQ)
787 		fd = open(filename, O_RDONLY);
788 	else {
789 		if (create_new) {
790 			if (increase_name) {
791 				error = find_next_name(filename, &fd);
792 				if (error > 0)
793 					return (error + 100);
794 			} else
795 				fd = open(filename,
796 				    O_WRONLY | O_TRUNC | O_CREAT,
797 				    S_IRUSR | S_IWUSR | S_IRGRP |
798 				    S_IWGRP | S_IROTH | S_IWOTH );
799 		} else
800 			fd = open(filename, O_WRONLY | O_TRUNC);
801 	}
802 	if (fd < 0)
803 		return (errno + 100);
804 	file = fdopen(fd, (mode == RRQ)? "r":"w");
805 	if (file == NULL) {
806 		close(fd);
807 		return (errno + 100);
808 	}
809 	return (0);
810 }
811 
812 static void
tftp_xmitfile(int peer,const char * mode)813 tftp_xmitfile(int peer, const char *mode)
814 {
815 	uint16_t block;
816 	time_t now;
817 	struct tftp_stats ts;
818 
819 	memset(&ts, 0, sizeof(ts));
820 	now = time(NULL);
821 	if (debug&DEBUG_SIMPLE)
822 		tftp_log(LOG_DEBUG, "Transmitting file");
823 
824 	read_init(0, file, mode);
825 	block = 1;
826 	tftp_send(peer, &block, &ts);
827 	read_close();
828 	if (debug&DEBUG_SIMPLE)
829 		tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
830 		    (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
831 }
832 
833 static void
tftp_recvfile(int peer,const char * mode)834 tftp_recvfile(int peer, const char *mode)
835 {
836 	uint16_t block;
837 	struct timeval now1, now2;
838 	struct tftp_stats ts;
839 
840 	gettimeofday(&now1, NULL);
841 	if (debug&DEBUG_SIMPLE)
842 		tftp_log(LOG_DEBUG, "Receiving file");
843 
844 	write_init(0, file, mode);
845 
846 	block = 0;
847 	tftp_receive(peer, &block, &ts, NULL, 0);
848 
849 	gettimeofday(&now2, NULL);
850 
851 	if (debug&DEBUG_SIMPLE) {
852 		double f;
853 		if (now1.tv_usec > now2.tv_usec) {
854 			now2.tv_usec += 1000000;
855 			now2.tv_sec--;
856 		}
857 
858 		f = now2.tv_sec - now1.tv_sec +
859 		    (now2.tv_usec - now1.tv_usec) / 100000.0;
860 		tftp_log(LOG_INFO,
861 		    "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
862 		    (intmax_t)ts.amount, block, f);
863 	}
864 
865 	return;
866 }
867