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