tftpd.c revision 1.14 1 /* $NetBSD: tftpd.c,v 1.14 1998/07/29 11:31:22 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
41 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
42 #else
43 __RCSID("$NetBSD: tftpd.c,v 1.14 1998/07/29 11:31:22 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 <grp.h>
70 #include <netdb.h>
71 #include <pwd.h>
72 #include <setjmp.h>
73 #include <signal.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <syslog.h>
78 #include <unistd.h>
79
80 #include "tftpsubs.h"
81
82 #define DEFAULTUSER "nobody"
83
84 #define TIMEOUT 5
85
86 extern char *__progname;
87 int peer;
88 int rexmtval = TIMEOUT;
89 int maxtimeout = 5*TIMEOUT;
90
91 #define PKTSIZE SEGSIZE+4
92 char buf[PKTSIZE];
93 char ackbuf[PKTSIZE];
94 struct sockaddr_in from;
95 int 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
105 static struct dirlist {
106 char *name;
107 int len;
108 } dirs[MAXDIRS+1];
109 static int suppress_naks;
110 static int logging;
111 static int secure;
112 static char *securedir;
113
114 struct formats;
115
116 static void tftp __P((struct tftphdr *, int));
117 static const char *errtomsg __P((int));
118 static void nak __P((int));
119 static char *verifyhost __P((struct sockaddr_in *));
120 static void usage __P((void));
121 void timer __P((int));
122 void sendfile __P((struct formats *));
123 void recvfile __P((struct formats *));
124 void justquit __P((int));
125 int validate_access __P((char **, int));
126 int main __P((int, char **));
127
128 struct 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 { 0 }
138 };
139
140 static void
141 usage()
142 {
143 syslog(LOG_ERR,
144 "Usage: %s [-ln] [-u user] [-g group] [-s directory] [directory ...]",
145 __progname);
146 exit(1);
147 }
148
149 int
150 main(argc, argv)
151 int argc;
152 char **argv;
153 {
154 struct passwd *pwent;
155 struct group *grent;
156 struct tftphdr *tp;
157 int n = 0;
158 int ch, on;
159 int fd = 0;
160 struct sockaddr_in sin;
161 char *tgtuser, *tgtgroup, *ep;
162 uid_t curuid, tgtuid;
163 gid_t curgid, tgtgid;
164 long nid;
165
166 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
167 tgtuser = DEFAULTUSER;
168 tgtgroup = NULL;
169 curuid = getuid();
170 curgid = getgid();
171
172 while ((ch = getopt(argc, argv, "g:lns:u:")) != -1)
173 switch (ch) {
174
175 case 'g':
176 tgtgroup = optarg;
177 break;
178
179 case 'l':
180 logging = 1;
181 break;
182
183 case 'n':
184 suppress_naks = 1;
185 break;
186
187 case 's':
188 secure = 1;
189 securedir = optarg;
190 break;
191
192 case 'u':
193 tgtuser = optarg;
194 break;
195
196 default:
197 usage();
198 break;
199 }
200
201 if (optind < argc) {
202 struct dirlist *dirp;
203
204 /* Get list of directory prefixes. Skip relative pathnames. */
205 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
206 optind++) {
207 if (argv[optind][0] == '/') {
208 dirp->name = argv[optind];
209 dirp->len = strlen(dirp->name);
210 dirp++;
211 }
212 }
213 }
214
215 if (*tgtuser == '\0' || (tgtgroup != NULL && *tgtgroup == '\0'))
216 usage();
217
218 nid = (strtol(tgtuser, &ep, 10));
219 if (*ep == '\0') {
220 if (nid > UID_MAX) {
221 syslog(LOG_ERR, "uid %ld is too large", nid);
222 exit(1);
223 }
224 pwent = getpwuid((uid_t)nid);
225 } else
226 pwent = getpwnam(tgtuser);
227 if (pwent == NULL) {
228 syslog(LOG_ERR, "unknown user `%s'", tgtuser);
229 exit(1);
230 }
231 tgtuid = pwent->pw_uid;
232 tgtgid = pwent->pw_gid;
233
234 if (tgtgroup != NULL) {
235 nid = (strtol(tgtgroup, &ep, 10));
236 if (*ep == '\0') {
237 if (nid > GID_MAX) {
238 syslog(LOG_ERR, "gid %ld is too large", nid);
239 exit(1);
240 }
241 grent = getgrgid((gid_t)nid);
242 } else
243 grent = getgrnam(tgtgroup);
244 if (grent != NULL)
245 tgtgid = grent->gr_gid;
246 else {
247 syslog(LOG_ERR, "unknown group `%s'", tgtgroup);
248 exit(1);
249 }
250 }
251
252 if (secure) {
253 if (chdir(securedir) < 0) {
254 syslog(LOG_ERR, "chdir %s: %m", securedir);
255 exit(1);
256 }
257 if (chroot(".")) {
258 syslog(LOG_ERR, "chroot: %m");
259 exit(1);
260 }
261 }
262
263 syslog(LOG_DEBUG, "running as user `%s' (%d), group `%s' (%d)",
264 tgtuser, tgtuid, tgtgroup ? tgtgroup : "(unspecified)" , tgtgid);
265 if (curgid != tgtgid) {
266 if (setgid(tgtgid)) {
267 syslog(LOG_ERR, "setgid to %d: %m", (int)tgtgid);
268 exit(1);
269 }
270 if (setgroups(0, NULL)) {
271 syslog(LOG_ERR, "setgroups: %m");
272 exit(1);
273 }
274 }
275
276 if (curuid != tgtuid) {
277 if (setuid(tgtuid)) {
278 syslog(LOG_ERR, "setuid to %d: %m", (int)tgtuid);
279 exit(1);
280 }
281 }
282
283 on = 1;
284 if (ioctl(fd, FIONBIO, &on) < 0) {
285 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
286 exit(1);
287 }
288 fromlen = sizeof (from);
289 n = recvfrom(fd, buf, sizeof (buf), 0,
290 (struct sockaddr *)&from, &fromlen);
291 if (n < 0) {
292 syslog(LOG_ERR, "recvfrom: %m");
293 exit(1);
294 }
295 /*
296 * Now that we have read the message out of the UDP
297 * socket, we fork and exit. Thus, inetd will go back
298 * to listening to the tftp port, and the next request
299 * to come in will start up a new instance of tftpd.
300 *
301 * We do this so that inetd can run tftpd in "wait" mode.
302 * The problem with tftpd running in "nowait" mode is that
303 * inetd may get one or more successful "selects" on the
304 * tftp port before we do our receive, so more than one
305 * instance of tftpd may be started up. Worse, if tftpd
306 * break before doing the above "recvfrom", inetd would
307 * spawn endless instances, clogging the system.
308 */
309 {
310 int pid;
311 int i, j;
312
313 for (i = 1; i < 20; i++) {
314 pid = fork();
315 if (pid < 0) {
316 sleep(i);
317 /*
318 * flush out to most recently sent request.
319 *
320 * This may drop some request, but those
321 * will be resent by the clients when
322 * they timeout. The positive effect of
323 * this flush is to (try to) prevent more
324 * than one tftpd being started up to service
325 * a single request from a single client.
326 */
327 j = sizeof from;
328 i = recvfrom(fd, buf, sizeof (buf), 0,
329 (struct sockaddr *)&from, &j);
330 if (i > 0) {
331 n = i;
332 fromlen = j;
333 }
334 } else {
335 break;
336 }
337 }
338 if (pid < 0) {
339 syslog(LOG_ERR, "fork: %m");
340 exit(1);
341 } else if (pid != 0) {
342 exit(0);
343 }
344 }
345 from.sin_len = sizeof(struct sockaddr_in);
346 from.sin_family = AF_INET;
347 alarm(0);
348 close(fd);
349 close(1);
350 peer = socket(AF_INET, SOCK_DGRAM, 0);
351 if (peer < 0) {
352 syslog(LOG_ERR, "socket: %m");
353 exit(1);
354 }
355 memset(&sin, 0, sizeof(sin));
356 sin.sin_family = AF_INET;
357 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
358 syslog(LOG_ERR, "bind: %m");
359 exit(1);
360 }
361 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
362 syslog(LOG_ERR, "connect: %m");
363 exit(1);
364 }
365 tp = (struct tftphdr *)buf;
366 tp->th_opcode = ntohs(tp->th_opcode);
367 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
368 tftp(tp, n);
369 exit(1);
370 }
371
372 /*
373 * Handle initial connection protocol.
374 */
375 static void
376 tftp(tp, size)
377 struct tftphdr *tp;
378 int size;
379 {
380 char *cp;
381 int first = 1, ecode;
382 struct formats *pf;
383 char *filename, *mode = NULL; /* XXX gcc */
384
385 filename = cp = tp->th_stuff;
386 again:
387 while (cp < buf + size) {
388 if (*cp == '\0')
389 break;
390 cp++;
391 }
392 if (*cp != '\0') {
393 nak(EBADOP);
394 exit(1);
395 }
396 if (first) {
397 mode = ++cp;
398 first = 0;
399 goto again;
400 }
401 for (cp = mode; *cp; cp++)
402 if (isupper(*cp))
403 *cp = tolower(*cp);
404 for (pf = formats; pf->f_mode; pf++)
405 if (strcmp(pf->f_mode, mode) == 0)
406 break;
407 if (pf->f_mode == 0) {
408 nak(EBADOP);
409 exit(1);
410 }
411 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
412 if (logging) {
413 syslog(LOG_INFO, "%s: %s request for %s: %s",
414 verifyhost(&from),
415 tp->th_opcode == WRQ ? "write" : "read",
416 filename, errtomsg(ecode));
417 }
418 if (ecode) {
419 /*
420 * Avoid storms of naks to a RRQ broadcast for a relative
421 * bootfile pathname from a diskless Sun.
422 */
423 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
424 exit(0);
425 nak(ecode);
426 exit(1);
427 }
428 if (tp->th_opcode == WRQ)
429 (*pf->f_recv)(pf);
430 else
431 (*pf->f_send)(pf);
432 exit(0);
433 }
434
435
436 FILE *file;
437
438 /*
439 * Validate file access. Since we
440 * have no uid or gid, for now require
441 * file to exist and be publicly
442 * readable/writable.
443 * If we were invoked with arguments
444 * from inetd then the file must also be
445 * in one of the given directory prefixes.
446 * Note also, full path name must be
447 * given as we have no login directory.
448 */
449 int
450 validate_access(filep, mode)
451 char **filep;
452 int mode;
453 {
454 struct stat stbuf;
455 int fd;
456 struct dirlist *dirp;
457 static char pathname[MAXPATHLEN];
458 char *filename = *filep;
459
460 /*
461 * Prevent tricksters from getting around the directory restrictions
462 */
463 if (strstr(filename, "/../"))
464 return (EACCESS);
465
466 if (*filename == '/') {
467 /*
468 * Allow the request if it's in one of the approved locations.
469 * Special case: check the null prefix ("/") by looking
470 * for length = 1 and relying on the arg. processing that
471 * it's a /.
472 */
473 for (dirp = dirs; dirp->name != NULL; dirp++) {
474 if (dirp->len == 1 ||
475 (!strncmp(filename, dirp->name, dirp->len) &&
476 filename[dirp->len] == '/'))
477 break;
478 }
479 /* If directory list is empty, allow access to any file */
480 if (dirp->name == NULL && dirp != dirs)
481 return (EACCESS);
482 if (stat(filename, &stbuf) < 0)
483 return (errno == ENOENT ? ENOTFOUND : EACCESS);
484 if (!S_ISREG(stbuf.st_mode))
485 return (ENOTFOUND);
486 if (mode == RRQ) {
487 if ((stbuf.st_mode & S_IROTH) == 0)
488 return (EACCESS);
489 } else {
490 if ((stbuf.st_mode & S_IWOTH) == 0)
491 return (EACCESS);
492 }
493 } else {
494 int err;
495
496 /*
497 * Relative file name: search the approved locations for it.
498 * Don't allow write requests or ones that avoid directory
499 * restrictions.
500 */
501
502 if (mode != RRQ || !strncmp(filename, "../", 3))
503 return (EACCESS);
504
505 /*
506 * If the file exists in one of the directories and isn't
507 * readable, continue looking. However, change the error code
508 * to give an indication that the file exists.
509 */
510 err = ENOTFOUND;
511 if (dirs[0].name != NULL) {
512 for (dirp = dirs; dirp->name != NULL; dirp++) {
513 snprintf(pathname, sizeof pathname, "%s/%s",
514 dirp->name, filename);
515 if (stat(pathname, &stbuf) == 0 &&
516 (stbuf.st_mode & S_IFMT) == S_IFREG) {
517 if ((stbuf.st_mode & S_IROTH) != 0)
518 break;
519 err = EACCESS;
520 }
521 }
522 if (dirp->name == NULL)
523 return (err);
524 *filep = filename = pathname;
525 } else
526 *filep = filename;
527 }
528 fd = open(filename, mode == RRQ ? 0 : 1);
529 if (fd < 0)
530 return (errno + 100);
531 file = fdopen(fd, (mode == RRQ)? "r":"w");
532 if (file == NULL) {
533 return errno+100;
534 }
535 return (0);
536 }
537
538 int timeout;
539 jmp_buf timeoutbuf;
540
541 void
542 timer(dummy)
543 int dummy;
544 {
545
546 timeout += rexmtval;
547 if (timeout >= maxtimeout)
548 exit(1);
549 longjmp(timeoutbuf, 1);
550 }
551
552 /*
553 * Send the requested file.
554 */
555 void
556 sendfile(pf)
557 struct formats *pf;
558 {
559 struct tftphdr *dp;
560 struct tftphdr *ap; /* ack packet */
561 int size, n;
562 volatile int block;
563
564 signal(SIGALRM, timer);
565 dp = r_init();
566 ap = (struct tftphdr *)ackbuf;
567 block = 1;
568 do {
569 size = readit(file, &dp, pf->f_convert);
570 if (size < 0) {
571 nak(errno + 100);
572 goto abort;
573 }
574 dp->th_opcode = htons((u_short)DATA);
575 dp->th_block = htons((u_short)block);
576 timeout = 0;
577 (void)setjmp(timeoutbuf);
578
579 send_data:
580 if (send(peer, dp, size + 4, 0) != size + 4) {
581 syslog(LOG_ERR, "tftpd: write: %m");
582 goto abort;
583 }
584 read_ahead(file, pf->f_convert);
585 for ( ; ; ) {
586 alarm(rexmtval); /* read the ack */
587 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
588 alarm(0);
589 if (n < 0) {
590 syslog(LOG_ERR, "tftpd: read: %m");
591 goto abort;
592 }
593 ap->th_opcode = ntohs((u_short)ap->th_opcode);
594 ap->th_block = ntohs((u_short)ap->th_block);
595
596 if (ap->th_opcode == ERROR)
597 goto abort;
598
599 if (ap->th_opcode == ACK) {
600 if (ap->th_block == block)
601 break;
602 /* Re-synchronize with the other side */
603 (void) synchnet(peer);
604 if (ap->th_block == (block -1))
605 goto send_data;
606 }
607
608 }
609 block++;
610 } while (size == SEGSIZE);
611 abort:
612 (void) fclose(file);
613 }
614
615 void
616 justquit(dummy)
617 int dummy;
618 {
619 exit(0);
620 }
621
622 /*
623 * Receive a file.
624 */
625 void
626 recvfile(pf)
627 struct formats *pf;
628 {
629 struct tftphdr *dp;
630 struct tftphdr *ap; /* ack buffer */
631 int n, size;
632 volatile int block;
633
634 signal(SIGALRM, timer);
635 dp = w_init();
636 ap = (struct tftphdr *)ackbuf;
637 block = 0;
638 do {
639 timeout = 0;
640 ap->th_opcode = htons((u_short)ACK);
641 ap->th_block = htons((u_short)block);
642 block++;
643 (void) setjmp(timeoutbuf);
644 send_ack:
645 if (send(peer, ackbuf, 4, 0) != 4) {
646 syslog(LOG_ERR, "tftpd: write: %m");
647 goto abort;
648 }
649 write_behind(file, pf->f_convert);
650 for ( ; ; ) {
651 alarm(rexmtval);
652 n = recv(peer, dp, PKTSIZE, 0);
653 alarm(0);
654 if (n < 0) { /* really? */
655 syslog(LOG_ERR, "tftpd: read: %m");
656 goto abort;
657 }
658 dp->th_opcode = ntohs((u_short)dp->th_opcode);
659 dp->th_block = ntohs((u_short)dp->th_block);
660 if (dp->th_opcode == ERROR)
661 goto abort;
662 if (dp->th_opcode == DATA) {
663 if (dp->th_block == block) {
664 break; /* normal */
665 }
666 /* Re-synchronize with the other side */
667 (void) synchnet(peer);
668 if (dp->th_block == (block-1))
669 goto send_ack; /* rexmit */
670 }
671 }
672 /* size = write(file, dp->th_data, n - 4); */
673 size = writeit(file, &dp, n - 4, pf->f_convert);
674 if (size != (n-4)) { /* ahem */
675 if (size < 0) nak(errno + 100);
676 else nak(ENOSPACE);
677 goto abort;
678 }
679 } while (size == SEGSIZE);
680 write_behind(file, pf->f_convert);
681 (void) fclose(file); /* close data file */
682
683 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
684 ap->th_block = htons((u_short)(block));
685 (void) send(peer, ackbuf, 4, 0);
686
687 signal(SIGALRM, justquit); /* just quit on timeout */
688 alarm(rexmtval);
689 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
690 alarm(0);
691 if (n >= 4 && /* if read some data */
692 dp->th_opcode == DATA && /* and got a data block */
693 block == dp->th_block) { /* then my last ack was lost */
694 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
695 }
696 abort:
697 return;
698 }
699
700 const struct errmsg {
701 int e_code;
702 const char *e_msg;
703 } errmsgs[] = {
704 { EUNDEF, "Undefined error code" },
705 { ENOTFOUND, "File not found" },
706 { EACCESS, "Access violation" },
707 { ENOSPACE, "Disk full or allocation exceeded" },
708 { EBADOP, "Illegal TFTP operation" },
709 { EBADID, "Unknown transfer ID" },
710 { EEXISTS, "File already exists" },
711 { ENOUSER, "No such user" },
712 { -1, 0 }
713 };
714
715 static const char *
716 errtomsg(error)
717 int error;
718 {
719 static char buf[20];
720 const struct errmsg *pe;
721
722 if (error == 0)
723 return "success";
724 for (pe = errmsgs; pe->e_code >= 0; pe++)
725 if (pe->e_code == error)
726 return pe->e_msg;
727 sprintf(buf, "error %d", error);
728 return buf;
729 }
730
731 /*
732 * Send a nak packet (error message).
733 * Error code passed in is one of the
734 * standard TFTP codes, or a UNIX errno
735 * offset by 100.
736 */
737 static void
738 nak(error)
739 int error;
740 {
741 struct tftphdr *tp;
742 int length;
743 const struct errmsg *pe;
744
745 tp = (struct tftphdr *)buf;
746 tp->th_opcode = htons((u_short)ERROR);
747 for (pe = errmsgs; pe->e_code >= 0; pe++)
748 if (pe->e_code == error)
749 break;
750 if (pe->e_code < 0) {
751 tp->th_code = EUNDEF; /* set 'undef' errorcode */
752 strcpy(tp->th_msg, strerror(error - 100));
753 } else {
754 tp->th_code = htons((u_short)error);
755 strcpy(tp->th_msg, pe->e_msg);
756 }
757 length = strlen(pe->e_msg);
758 tp->th_msg[length] = '\0';
759 length += 5;
760 if (send(peer, buf, length, 0) != length)
761 syslog(LOG_ERR, "nak: %m");
762 }
763
764 static char *
765 verifyhost(fromp)
766 struct sockaddr_in *fromp;
767 {
768 struct hostent *hp;
769
770 hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (fromp->sin_addr),
771 fromp->sin_family);
772 if (hp)
773 return hp->h_name;
774 else
775 return inet_ntoa(fromp->sin_addr);
776 }
777