1 /* 2 * Copyright (c) 1983, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #ifndef lint 35 static const char copyright[] = 36 "@(#) Copyright (c) 1983, 1993\n\ 37 The Regents of the University of California. All rights reserved.\n"; 38 #endif /* not lint */ 39 40 #ifndef lint 41 #if 0 42 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93"; 43 #endif 44 static const char rcsid[] = 45 "$Id: tftpd.c,v 1.11 1998/04/12 11:15:54 phk Exp $"; 46 #endif /* not lint */ 47 48 /* 49 * Trivial file transfer protocol server. 50 * 51 * This version includes many modifications by Jim Guyton 52 * <guyton@rand-unix>. 53 */ 54 55 #include <sys/param.h> 56 #include <sys/ioctl.h> 57 #include <sys/stat.h> 58 #include <sys/socket.h> 59 #include <sys/types.h> 60 61 #include <netinet/in.h> 62 #include <arpa/tftp.h> 63 #include <arpa/inet.h> 64 65 #include <ctype.h> 66 #include <errno.h> 67 #include <fcntl.h> 68 #include <netdb.h> 69 #include <pwd.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 #define TIMEOUT 5 81 82 int peer; 83 int rexmtval = TIMEOUT; 84 int maxtimeout = 5*TIMEOUT; 85 86 #define PKTSIZE SEGSIZE+4 87 char buf[PKTSIZE]; 88 char ackbuf[PKTSIZE]; 89 struct sockaddr_in from; 90 int fromlen; 91 92 void tftp __P((struct tftphdr *, int)); 93 94 /* 95 * Null-terminated directory prefix list for absolute pathname requests and 96 * search list for relative pathname requests. 97 * 98 * MAXDIRS should be at least as large as the number of arguments that 99 * inetd allows (currently 20). 100 */ 101 #define MAXDIRS 20 102 static struct dirlist { 103 char *name; 104 int len; 105 } dirs[MAXDIRS+1]; 106 static int suppress_naks; 107 static int logging; 108 109 static char *errtomsg __P((int)); 110 static void nak __P((int)); 111 static char *verifyhost __P((struct sockaddr_in *)); 112 113 int 114 main(argc, argv) 115 int argc; 116 char *argv[]; 117 { 118 register struct tftphdr *tp; 119 register int n; 120 int ch, on; 121 struct sockaddr_in sin; 122 char *chroot_dir = NULL; 123 struct passwd *nobody; 124 125 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP); 126 while ((ch = getopt(argc, argv, "lns:")) != -1) { 127 switch (ch) { 128 case 'l': 129 logging = 1; 130 break; 131 case 'n': 132 suppress_naks = 1; 133 break; 134 case 's': 135 chroot_dir = optarg; 136 break; 137 default: 138 syslog(LOG_WARNING, "ignoring unknown option -%c", ch); 139 } 140 } 141 if (optind < argc) { 142 struct dirlist *dirp; 143 144 /* Get list of directory prefixes. Skip relative pathnames. */ 145 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS]; 146 optind++) { 147 if (argv[optind][0] == '/') { 148 dirp->name = argv[optind]; 149 dirp->len = strlen(dirp->name); 150 dirp++; 151 } 152 } 153 } 154 else if (chroot_dir) { 155 dirs->name = "/"; 156 dirs->len = 1; 157 } 158 159 on = 1; 160 if (ioctl(0, FIONBIO, &on) < 0) { 161 syslog(LOG_ERR, "ioctl(FIONBIO): %m"); 162 exit(1); 163 } 164 fromlen = sizeof (from); 165 n = recvfrom(0, buf, sizeof (buf), 0, 166 (struct sockaddr *)&from, &fromlen); 167 if (n < 0) { 168 syslog(LOG_ERR, "recvfrom: %m"); 169 exit(1); 170 } 171 /* 172 * Now that we have read the message out of the UDP 173 * socket, we fork and exit. Thus, inetd will go back 174 * to listening to the tftp port, and the next request 175 * to come in will start up a new instance of tftpd. 176 * 177 * We do this so that inetd can run tftpd in "wait" mode. 178 * The problem with tftpd running in "nowait" mode is that 179 * inetd may get one or more successful "selects" on the 180 * tftp port before we do our receive, so more than one 181 * instance of tftpd may be started up. Worse, if tftpd 182 * break before doing the above "recvfrom", inetd would 183 * spawn endless instances, clogging the system. 184 */ 185 { 186 int pid; 187 int i, j; 188 189 for (i = 1; i < 20; i++) { 190 pid = fork(); 191 if (pid < 0) { 192 sleep(i); 193 /* 194 * flush out to most recently sent request. 195 * 196 * This may drop some request, but those 197 * will be resent by the clients when 198 * they timeout. The positive effect of 199 * this flush is to (try to) prevent more 200 * than one tftpd being started up to service 201 * a single request from a single client. 202 */ 203 j = sizeof from; 204 i = recvfrom(0, buf, sizeof (buf), 0, 205 (struct sockaddr *)&from, &j); 206 if (i > 0) { 207 n = i; 208 fromlen = j; 209 } 210 } else { 211 break; 212 } 213 } 214 if (pid < 0) { 215 syslog(LOG_ERR, "fork: %m"); 216 exit(1); 217 } else if (pid != 0) { 218 exit(0); 219 } 220 } 221 222 /* 223 * Since we exit here, we should do that only after the above 224 * recvfrom to keep inetd from constantly forking should there 225 * be a problem. See the above comment about system clogging. 226 */ 227 if (chroot_dir) { 228 /* Must get this before chroot because /etc might go away */ 229 if ((nobody = getpwnam("nobody")) == NULL) { 230 syslog(LOG_ERR, "nobody: no such user"); 231 exit(1); 232 } 233 if (chroot(chroot_dir)) { 234 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir); 235 exit(1); 236 } 237 chdir( "/" ); 238 setuid(nobody->pw_uid); 239 } 240 241 from.sin_family = AF_INET; 242 alarm(0); 243 close(0); 244 close(1); 245 peer = socket(AF_INET, SOCK_DGRAM, 0); 246 if (peer < 0) { 247 syslog(LOG_ERR, "socket: %m"); 248 exit(1); 249 } 250 memset(&sin, 0, sizeof(sin)); 251 sin.sin_family = AF_INET; 252 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) { 253 syslog(LOG_ERR, "bind: %m"); 254 exit(1); 255 } 256 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) { 257 syslog(LOG_ERR, "connect: %m"); 258 exit(1); 259 } 260 tp = (struct tftphdr *)buf; 261 tp->th_opcode = ntohs(tp->th_opcode); 262 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) 263 tftp(tp, n); 264 exit(1); 265 } 266 267 struct formats; 268 int validate_access __P((char **, int)); 269 void xmitfile __P((struct formats *)); 270 void recvfile __P((struct formats *)); 271 272 struct formats { 273 char *f_mode; 274 int (*f_validate) __P((char **, int)); 275 void (*f_send) __P((struct formats *)); 276 void (*f_recv) __P((struct formats *)); 277 int f_convert; 278 } formats[] = { 279 { "netascii", validate_access, xmitfile, recvfile, 1 }, 280 { "octet", validate_access, xmitfile, recvfile, 0 }, 281 #ifdef notdef 282 { "mail", validate_user, sendmail, recvmail, 1 }, 283 #endif 284 { 0 } 285 }; 286 287 /* 288 * Handle initial connection protocol. 289 */ 290 void 291 tftp(tp, size) 292 struct tftphdr *tp; 293 int size; 294 { 295 register char *cp; 296 int first = 1, ecode; 297 register struct formats *pf; 298 char *filename, *mode; 299 300 filename = cp = tp->th_stuff; 301 again: 302 while (cp < buf + size) { 303 if (*cp == '\0') 304 break; 305 cp++; 306 } 307 if (*cp != '\0') { 308 nak(EBADOP); 309 exit(1); 310 } 311 if (first) { 312 mode = ++cp; 313 first = 0; 314 goto again; 315 } 316 for (cp = mode; *cp; cp++) 317 if (isupper(*cp)) 318 *cp = tolower(*cp); 319 for (pf = formats; pf->f_mode; pf++) 320 if (strcmp(pf->f_mode, mode) == 0) 321 break; 322 if (pf->f_mode == 0) { 323 nak(EBADOP); 324 exit(1); 325 } 326 ecode = (*pf->f_validate)(&filename, tp->th_opcode); 327 if (logging) { 328 syslog(LOG_INFO, "%s: %s request for %s: %s", 329 verifyhost(&from), 330 tp->th_opcode == WRQ ? "write" : "read", 331 filename, errtomsg(ecode)); 332 } 333 if (ecode) { 334 /* 335 * Avoid storms of naks to a RRQ broadcast for a relative 336 * bootfile pathname from a diskless Sun. 337 */ 338 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND) 339 exit(0); 340 nak(ecode); 341 exit(1); 342 } 343 if (tp->th_opcode == WRQ) 344 (*pf->f_recv)(pf); 345 else 346 (*pf->f_send)(pf); 347 exit(0); 348 } 349 350 351 FILE *file; 352 353 /* 354 * Validate file access. Since we 355 * have no uid or gid, for now require 356 * file to exist and be publicly 357 * readable/writable. 358 * If we were invoked with arguments 359 * from inetd then the file must also be 360 * in one of the given directory prefixes. 361 * Note also, full path name must be 362 * given as we have no login directory. 363 */ 364 int 365 validate_access(filep, mode) 366 char **filep; 367 int mode; 368 { 369 struct stat stbuf; 370 int fd; 371 struct dirlist *dirp; 372 static char pathname[MAXPATHLEN]; 373 char *filename = *filep; 374 375 /* 376 * Prevent tricksters from getting around the directory restrictions 377 */ 378 if (strstr(filename, "/../")) 379 return (EACCESS); 380 381 if (*filename == '/') { 382 /* 383 * Allow the request if it's in one of the approved locations. 384 * Special case: check the null prefix ("/") by looking 385 * for length = 1 and relying on the arg. processing that 386 * it's a /. 387 */ 388 for (dirp = dirs; dirp->name != NULL; dirp++) { 389 if (dirp->len == 1 || 390 (!strncmp(filename, dirp->name, dirp->len) && 391 filename[dirp->len] == '/')) 392 break; 393 } 394 /* If directory list is empty, allow access to any file */ 395 if (dirp->name == NULL && dirp != dirs) 396 return (EACCESS); 397 if (stat(filename, &stbuf) < 0) 398 return (errno == ENOENT ? ENOTFOUND : EACCESS); 399 if ((stbuf.st_mode & S_IFMT) != S_IFREG) 400 return (ENOTFOUND); 401 if (mode == RRQ) { 402 if ((stbuf.st_mode & S_IROTH) == 0) 403 return (EACCESS); 404 } else { 405 if ((stbuf.st_mode & S_IWOTH) == 0) 406 return (EACCESS); 407 } 408 } else { 409 int err; 410 411 /* 412 * Relative file name: search the approved locations for it. 413 * Don't allow write requests that avoid directory 414 * restrictions. 415 */ 416 417 if (!strncmp(filename, "../", 3)) 418 return (EACCESS); 419 420 /* 421 * If the file exists in one of the directories and isn't 422 * readable, continue looking. However, change the error code 423 * to give an indication that the file exists. 424 */ 425 err = ENOTFOUND; 426 for (dirp = dirs; dirp->name != NULL; dirp++) { 427 snprintf(pathname, sizeof(pathname), "%s/%s", 428 dirp->name, filename); 429 if (stat(pathname, &stbuf) == 0 && 430 (stbuf.st_mode & S_IFMT) == S_IFREG) { 431 if ((stbuf.st_mode & S_IROTH) != 0) { 432 break; 433 } 434 err = EACCESS; 435 } 436 } 437 if (dirp->name == NULL) 438 return (err); 439 *filep = filename = pathname; 440 } 441 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC); 442 if (fd < 0) 443 return (errno + 100); 444 file = fdopen(fd, (mode == RRQ)? "r":"w"); 445 if (file == NULL) { 446 return errno+100; 447 } 448 return (0); 449 } 450 451 int timeout; 452 jmp_buf timeoutbuf; 453 454 void 455 timer() 456 { 457 458 timeout += rexmtval; 459 if (timeout >= maxtimeout) 460 exit(1); 461 longjmp(timeoutbuf, 1); 462 } 463 464 /* 465 * Send the requested file. 466 */ 467 void 468 xmitfile(pf) 469 struct formats *pf; 470 { 471 struct tftphdr *dp, *r_init(); 472 register struct tftphdr *ap; /* ack packet */ 473 register int size, n; 474 volatile int block; 475 476 signal(SIGALRM, timer); 477 dp = r_init(); 478 ap = (struct tftphdr *)ackbuf; 479 block = 1; 480 do { 481 size = readit(file, &dp, pf->f_convert); 482 if (size < 0) { 483 nak(errno + 100); 484 goto abort; 485 } 486 dp->th_opcode = htons((u_short)DATA); 487 dp->th_block = htons((u_short)block); 488 timeout = 0; 489 (void)setjmp(timeoutbuf); 490 491 send_data: 492 if (send(peer, dp, size + 4, 0) != size + 4) { 493 syslog(LOG_ERR, "write: %m"); 494 goto abort; 495 } 496 read_ahead(file, pf->f_convert); 497 for ( ; ; ) { 498 alarm(rexmtval); /* read the ack */ 499 n = recv(peer, ackbuf, sizeof (ackbuf), 0); 500 alarm(0); 501 if (n < 0) { 502 syslog(LOG_ERR, "read: %m"); 503 goto abort; 504 } 505 ap->th_opcode = ntohs((u_short)ap->th_opcode); 506 ap->th_block = ntohs((u_short)ap->th_block); 507 508 if (ap->th_opcode == ERROR) 509 goto abort; 510 511 if (ap->th_opcode == ACK) { 512 if (ap->th_block == block) 513 break; 514 /* Re-synchronize with the other side */ 515 (void) synchnet(peer); 516 if (ap->th_block == (block -1)) 517 goto send_data; 518 } 519 520 } 521 block++; 522 } while (size == SEGSIZE); 523 abort: 524 (void) fclose(file); 525 } 526 527 void 528 justquit() 529 { 530 exit(0); 531 } 532 533 534 /* 535 * Receive a file. 536 */ 537 void 538 recvfile(pf) 539 struct formats *pf; 540 { 541 struct tftphdr *dp, *w_init(); 542 register struct tftphdr *ap; /* ack buffer */ 543 register int n, size; 544 volatile int block; 545 546 signal(SIGALRM, timer); 547 dp = w_init(); 548 ap = (struct tftphdr *)ackbuf; 549 block = 0; 550 do { 551 timeout = 0; 552 ap->th_opcode = htons((u_short)ACK); 553 ap->th_block = htons((u_short)block); 554 block++; 555 (void) setjmp(timeoutbuf); 556 send_ack: 557 if (send(peer, ackbuf, 4, 0) != 4) { 558 syslog(LOG_ERR, "write: %m"); 559 goto abort; 560 } 561 write_behind(file, pf->f_convert); 562 for ( ; ; ) { 563 alarm(rexmtval); 564 n = recv(peer, dp, PKTSIZE, 0); 565 alarm(0); 566 if (n < 0) { /* really? */ 567 syslog(LOG_ERR, "read: %m"); 568 goto abort; 569 } 570 dp->th_opcode = ntohs((u_short)dp->th_opcode); 571 dp->th_block = ntohs((u_short)dp->th_block); 572 if (dp->th_opcode == ERROR) 573 goto abort; 574 if (dp->th_opcode == DATA) { 575 if (dp->th_block == block) { 576 break; /* normal */ 577 } 578 /* Re-synchronize with the other side */ 579 (void) synchnet(peer); 580 if (dp->th_block == (block-1)) 581 goto send_ack; /* rexmit */ 582 } 583 } 584 /* size = write(file, dp->th_data, n - 4); */ 585 size = writeit(file, &dp, n - 4, pf->f_convert); 586 if (size != (n-4)) { /* ahem */ 587 if (size < 0) nak(errno + 100); 588 else nak(ENOSPACE); 589 goto abort; 590 } 591 } while (size == SEGSIZE); 592 write_behind(file, pf->f_convert); 593 (void) fclose(file); /* close data file */ 594 595 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */ 596 ap->th_block = htons((u_short)(block)); 597 (void) send(peer, ackbuf, 4, 0); 598 599 signal(SIGALRM, justquit); /* just quit on timeout */ 600 alarm(rexmtval); 601 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */ 602 alarm(0); 603 if (n >= 4 && /* if read some data */ 604 dp->th_opcode == DATA && /* and got a data block */ 605 block == dp->th_block) { /* then my last ack was lost */ 606 (void) send(peer, ackbuf, 4, 0); /* resend final ack */ 607 } 608 abort: 609 return; 610 } 611 612 struct errmsg { 613 int e_code; 614 char *e_msg; 615 } errmsgs[] = { 616 { EUNDEF, "Undefined error code" }, 617 { ENOTFOUND, "File not found" }, 618 { EACCESS, "Access violation" }, 619 { ENOSPACE, "Disk full or allocation exceeded" }, 620 { EBADOP, "Illegal TFTP operation" }, 621 { EBADID, "Unknown transfer ID" }, 622 { EEXISTS, "File already exists" }, 623 { ENOUSER, "No such user" }, 624 { -1, 0 } 625 }; 626 627 static char * 628 errtomsg(error) 629 int error; 630 { 631 static char buf[20]; 632 register struct errmsg *pe; 633 if (error == 0) 634 return "success"; 635 for (pe = errmsgs; pe->e_code >= 0; pe++) 636 if (pe->e_code == error) 637 return pe->e_msg; 638 snprintf(buf, sizeof(buf), "error %d", error); 639 return buf; 640 } 641 642 /* 643 * Send a nak packet (error message). 644 * Error code passed in is one of the 645 * standard TFTP codes, or a UNIX errno 646 * offset by 100. 647 */ 648 static void 649 nak(error) 650 int error; 651 { 652 register struct tftphdr *tp; 653 int length; 654 register struct errmsg *pe; 655 656 tp = (struct tftphdr *)buf; 657 tp->th_opcode = htons((u_short)ERROR); 658 tp->th_code = htons((u_short)error); 659 for (pe = errmsgs; pe->e_code >= 0; pe++) 660 if (pe->e_code == error) 661 break; 662 if (pe->e_code < 0) { 663 pe->e_msg = strerror(error - 100); 664 tp->th_code = EUNDEF; /* set 'undef' errorcode */ 665 } 666 strcpy(tp->th_msg, pe->e_msg); 667 length = strlen(pe->e_msg); 668 tp->th_msg[length] = '\0'; 669 length += 5; 670 if (send(peer, buf, length, 0) != length) 671 syslog(LOG_ERR, "nak: %m"); 672 } 673 674 static char * 675 verifyhost(fromp) 676 struct sockaddr_in *fromp; 677 { 678 struct hostent *hp; 679 680 hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (fromp->sin_addr), 681 fromp->sin_family); 682 if (hp) 683 return hp->h_name; 684 else 685 return inet_ntoa(fromp->sin_addr); 686 } 687