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