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