2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 * Trivial file transfer protocol server.
49 * This version includes many modifications by Jim Guyton
53 #include <sys/param.h>
54 #include <sys/ioctl.h>
55 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <arpa/tftp.h>
75 #include "tftp-file.h"
77 #include "tftp-utils.h"
78 #include "tftp-transfer.h"
79 #include "tftp-options.h"
85 static void tftp_wrq(int peer, char *, ssize_t);
86 static void tftp_rrq(int peer, char *, ssize_t);
89 * Null-terminated directory prefix list for absolute pathname requests and
90 * search list for relative pathname requests.
92 * MAXDIRS should be at least as large as the number of arguments that
93 * inetd allows (currently 20).
96 static struct dirlist {
100 static int suppress_naks;
103 static int create_new = 0;
104 static const char *newfile_format = "%Y%m%d";
105 static int increase_name = 0;
106 static mode_t mask = S_IWGRP | S_IWOTH;
109 static void tftp_recvfile(int peer, const char *mode);
110 static void tftp_xmitfile(int peer, const char *mode);
111 static int validate_access(int peer, char **, int);
112 static char peername[NI_MAXHOST];
116 static struct formats {
126 main(int argc, char *argv[])
130 socklen_t peerlen, len;
133 char *chroot_dir = NULL;
134 struct passwd *nobody;
135 const char *chuser = "nobody";
136 char recvbuffer[MAXPKTSIZE];
137 int allow_ro = 1, allow_wo = 1;
139 tzset(); /* syslog in localtime */
140 acting_as_client = 0;
142 tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
143 while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:u:U:wW")) != -1) {
152 if (atoi(optarg) != 0)
153 debug += atoi(optarg);
155 debug |= debug_finds(optarg);
158 newfile_format = optarg;
167 options_rfc_enabled = 0;
170 options_extra_enabled = 0;
173 packetdroppercentage = atoi(optarg);
175 "Randomly dropping %d out of 100 packets",
176 packetdroppercentage);
185 mask = strtol(optarg, NULL, 0);
195 tftp_log(LOG_WARNING,
196 "ignoring unknown option -%c", ch);
200 struct dirlist *dirp;
202 /* Get list of directory prefixes. Skip relative pathnames. */
203 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
205 if (argv[optind][0] == '/') {
206 dirp->name = argv[optind];
207 dirp->len = strlen(dirp->name);
212 else if (chroot_dir) {
216 if (ipchroot > 0 && chroot_dir == NULL) {
217 tftp_log(LOG_ERR, "-c requires -s");
225 if (ioctl(0, FIONBIO, &on) < 0) {
226 tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
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);
236 tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
239 getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
240 peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
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.
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.
259 for (i = 1; i < 20; i++) {
264 * flush out to most recently sent request.
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.
273 peerlen = sizeof peer_sock;
274 i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
275 (struct sockaddr *)&peer_sock, &peerlen);
284 tftp_log(LOG_ERR, "fork: %s", strerror(errno));
286 } else if (pid != 0) {
293 * See if the client is allowed to talk to me.
294 * (This needs to be done before the chroot())
297 struct request_info req;
299 request_init(&req, RQ_CLIENT_ADDR, peername, 0);
300 request_set(&req, RQ_DAEMON, "tftpd", 0);
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");
309 * Full access might be disabled, but maybe the
310 * client is allowed to do read-only access.
312 request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
313 allow_ro = hosts_access(&req);
315 request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
316 allow_wo = hosts_access(&req);
318 if (allow_ro == 0 && allow_wo == 0) {
319 tftp_log(LOG_WARNING,
320 "Unauthorized access from %s", peername);
324 if (debug & DEBUG_ACCESS) {
326 tftp_log(LOG_WARNING,
327 "But allowed readonly access "
328 "via 'tftpd-ro' entry");
330 tftp_log(LOG_WARNING,
331 "But allowed writeonly access "
332 "via 'tftpd-wo' entry");
335 if (debug & DEBUG_ACCESS)
336 tftp_log(LOG_WARNING,
337 "Full access allowed"
338 "in /etc/hosts.allow");
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.
352 struct sockaddr_storage ss;
353 char hbuf[NI_MAXHOST];
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,
361 asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
363 statret = stat(tempchroot, &sb);
365 (statret == 0 && (sb.st_mode & S_IFDIR)))
366 chroot_dir = tempchroot;
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);
373 if (chroot(chroot_dir)) {
374 tftp_log(LOG_ERR, "chroot: %s: %s",
375 chroot_dir, strerror(errno));
378 if (chdir("/") != 0) {
379 tftp_log(LOG_ERR, "chdir: %s", strerror(errno));
382 if (setgroups(1, &nobody->pw_gid) != 0) {
383 tftp_log(LOG_ERR, "setgroups failed");
386 if (setuid(nobody->pw_uid) != 0) {
387 tftp_log(LOG_ERR, "setuid failed");
392 len = sizeof(me_sock);
393 if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
394 switch (me_sock.ss_family) {
396 ((struct sockaddr_in *)&me_sock)->sin_port = 0;
399 ((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
406 memset(&me_sock, 0, sizeof(me_sock));
407 me_sock.ss_family = peer_sock.ss_family;
408 me_sock.ss_len = peer_sock.ss_len;
412 peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
414 tftp_log(LOG_ERR, "socket: %s", strerror(errno));
417 if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
418 tftp_log(LOG_ERR, "bind: %s", strerror(errno));
422 tp = (struct tftphdr *)recvbuffer;
423 tp->th_opcode = ntohs(tp->th_opcode);
424 if (tp->th_opcode == RRQ) {
426 tftp_rrq(peer, tp->th_stuff, n - 1);
428 tftp_log(LOG_WARNING,
429 "%s read access denied", peername);
432 } else if (tp->th_opcode == WRQ) {
434 tftp_wrq(peer, tp->th_stuff, n - 1);
436 tftp_log(LOG_WARNING,
437 "%s write access denied", peername);
441 send_error(peer, EBADOP);
446 reduce_path(char *fn)
450 /* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
451 while ((slash = strstr(fn, "/./")) != NULL) {
452 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
459 /* Now reduce all "/something/+../" to "/" */
460 while ((slash = strstr(fn, "/../")) != NULL) {
463 for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
465 for (ptr--; ptr >= fn; ptr--)
477 parse_header(int peer, char *recvbuffer, ssize_t size,
478 char **filename, char **mode)
487 i = get_field(peer, recvbuffer, size);
489 tftp_log(LOG_ERR, "Bad option - filename too long");
490 send_error(peer, EBADOP);
493 *filename = recvbuffer;
494 tftp_log(LOG_INFO, "Filename: '%s'", *filename);
497 i = get_field(peer, cp, size);
501 /* Find the file transfer mode */
502 for (cp = *mode; *cp; cp++)
505 for (pf = formats; pf->f_mode; pf++)
506 if (strcmp(pf->f_mode, *mode) == 0)
508 if (pf->f_mode == NULL) {
510 "Bad option - Unknown transfer mode (%s)", *mode);
511 send_error(peer, EBADOP);
514 tftp_log(LOG_INFO, "Mode: '%s'", *mode);
520 * WRQ - receive a file from the client
523 tftp_wrq(int peer, char *recvbuffer, ssize_t size)
526 int has_options = 0, ecode;
527 char *filename, *mode;
528 char fnbuf[PATH_MAX];
530 cp = parse_header(peer, recvbuffer, size, &filename, &mode);
531 size -= (cp - recvbuffer) + 1;
533 strlcpy(fnbuf, filename, sizeof(fnbuf));
538 if (options_rfc_enabled)
539 has_options = !parse_options(peer, cp, size);
541 tftp_log(LOG_INFO, "Options found but not enabled");
544 ecode = validate_access(peer, &filename, WRQ);
552 tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
553 filename, errtomsg(ecode));
557 send_error(peer, ecode);
560 tftp_recvfile(peer, mode);
565 * RRQ - send a file to the client
568 tftp_rrq(int peer, char *recvbuffer, ssize_t size)
571 int has_options = 0, ecode;
572 char *filename, *mode;
573 char fnbuf[PATH_MAX];
575 cp = parse_header(peer, recvbuffer, size, &filename, &mode);
576 size -= (cp - recvbuffer) + 1;
578 strlcpy(fnbuf, filename, sizeof(fnbuf));
583 if (options_rfc_enabled)
584 has_options = !parse_options(peer, cp, size);
586 tftp_log(LOG_INFO, "Options found but not enabled");
589 ecode = validate_access(peer, &filename, RRQ);
593 char lrecvbuffer[MAXPKTSIZE];
594 struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
597 n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
598 NULL, timeoutpacket);
600 if (debug & DEBUG_SIMPLE)
601 tftp_log(LOG_DEBUG, "Aborting: %s",
605 if (rp->th_opcode != ACK) {
606 if (debug & DEBUG_SIMPLE)
608 "Expected ACK, got %s on OACK",
609 packettype(rp->th_opcode));
616 tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
617 filename, errtomsg(ecode));
621 * Avoid storms of naks to a RRQ broadcast for a relative
622 * bootfile pathname from a diskless Sun.
624 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
626 send_error(peer, ecode);
629 tftp_xmitfile(peer, mode);
633 * Find the next value for YYYYMMDD.nn when the file to be written should
634 * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
635 * Besides, that is four updates per hour on a file, which is kind of
639 find_next_name(char *filename, int *fd)
645 char yyyymmdd[MAXPATHLEN];
646 char newname[MAXPATHLEN];
648 /* Create the YYYYMMDD part of the filename */
650 lt = *localtime(&tval);
651 len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, <);
654 "Filename suffix too long (%d characters maximum)",
659 /* Make sure the new filename is not too long */
660 if (strlen(filename) > MAXPATHLEN - len - 5) {
662 "Filename too long (%zd characters, %zd maximum)",
663 strlen(filename), MAXPATHLEN - len - 5);
667 /* Find the first file which doesn't exist */
668 for (i = 0; i < 100; i++) {
669 sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
671 O_WRONLY | O_CREAT | O_EXCL,
672 S_IRUSR | S_IWUSR | S_IRGRP |
673 S_IWGRP | S_IROTH | S_IWOTH);
682 * Validate file access. Since we
683 * have no uid or gid, for now require
684 * file to exist and be publicly
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.
693 validate_access(int peer, char **filep, int mode)
698 struct dirlist *dirp;
699 static char pathname[MAXPATHLEN];
700 char *filename = *filep;
703 * Prevent tricksters from getting around the directory restrictions
705 if (strstr(filename, "/../"))
708 if (*filename == '/') {
710 * Allow the request if it's in one of the approved locations.
711 * Special case: check the null prefix ("/") by looking
712 * for length = 1 and relying on the arg. processing that
715 for (dirp = dirs; dirp->name != NULL; dirp++) {
716 if (dirp->len == 1 ||
717 (!strncmp(filename, dirp->name, dirp->len) &&
718 filename[dirp->len] == '/'))
721 /* If directory list is empty, allow access to any file */
722 if (dirp->name == NULL && dirp != dirs)
724 if (stat(filename, &stbuf) < 0)
725 return (errno == ENOENT ? ENOTFOUND : EACCESS);
726 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
729 if ((stbuf.st_mode & S_IROTH) == 0)
732 if ((stbuf.st_mode & S_IWOTH) == 0)
739 * Relative file name: search the approved locations for it.
740 * Don't allow write requests that avoid directory
744 if (!strncmp(filename, "../", 3))
748 * If the file exists in one of the directories and isn't
749 * readable, continue looking. However, change the error code
750 * to give an indication that the file exists.
753 for (dirp = dirs; dirp->name != NULL; dirp++) {
754 snprintf(pathname, sizeof(pathname), "%s/%s",
755 dirp->name, filename);
756 if (stat(pathname, &stbuf) == 0 &&
757 (stbuf.st_mode & S_IFMT) == S_IFREG) {
759 if ((stbuf.st_mode & S_IROTH) != 0)
762 if ((stbuf.st_mode & S_IWOTH) != 0)
768 if (dirp->name != NULL)
769 *filep = filename = pathname;
770 else if (mode == RRQ)
772 else if (err != ENOTFOUND || !create_new)
777 * This option is handled here because it (might) require(s) the
780 option_tsize(peer, NULL, mode, &stbuf);
783 fd = open(filename, O_RDONLY);
787 error = find_next_name(filename, &fd);
789 return (error + 100);
792 O_WRONLY | O_TRUNC | O_CREAT,
793 S_IRUSR | S_IWUSR | S_IRGRP |
794 S_IWGRP | S_IROTH | S_IWOTH );
796 fd = open(filename, O_WRONLY | O_TRUNC);
799 return (errno + 100);
800 file = fdopen(fd, (mode == RRQ)? "r":"w");
803 return (errno + 100);
809 tftp_xmitfile(int peer, const char *mode)
813 struct tftp_stats ts;
815 memset(&ts, 0, sizeof(ts));
817 if (debug & DEBUG_SIMPLE)
818 tftp_log(LOG_DEBUG, "Transmitting file");
820 read_init(0, file, mode);
822 tftp_send(peer, &block, &ts);
824 if (debug & DEBUG_SIMPLE)
825 tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
826 (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
830 tftp_recvfile(int peer, const char *mode)
833 struct timeval now1, now2;
834 struct tftp_stats ts;
836 gettimeofday(&now1, NULL);
837 if (debug & DEBUG_SIMPLE)
838 tftp_log(LOG_DEBUG, "Receiving file");
840 write_init(0, file, mode);
843 tftp_receive(peer, &block, &ts, NULL, 0);
845 gettimeofday(&now2, NULL);
847 if (debug & DEBUG_SIMPLE) {
849 if (now1.tv_usec > now2.tv_usec) {
850 now2.tv_usec += 1000000;
854 f = now2.tv_sec - now1.tv_sec +
855 (now2.tv_usec - now1.tv_usec) / 100000.0;
857 "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
858 (intmax_t)ts.amount, block, f);