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