1 /* $OpenBSD: ftpd.c,v 1.112 2001/12/18 00:27:57 millert Exp $ */ 2 /* $NetBSD: ftpd.c,v 1.15 1995/06/03 22:46:47 mycroft Exp $ */ 3 4 /* 5 * Copyright (C) 1997 and 1998 WIDE Project. 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. Neither the name of the project nor the names of its contributors 17 * may be used to endorse or promote products derived from this software 18 * without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND 21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE 24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 * SUCH DAMAGE. 31 */ 32 33 /* 34 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 35 * The Regents of the University of California. All rights reserved. 36 * 37 * Redistribution and use in source and binary forms, with or without 38 * modification, are permitted provided that the following conditions 39 * are met: 40 * 1. Redistributions of source code must retain the above copyright 41 * notice, this list of conditions and the following disclaimer. 42 * 2. Redistributions in binary form must reproduce the above copyright 43 * notice, this list of conditions and the following disclaimer in the 44 * documentation and/or other materials provided with the distribution. 45 * 3. All advertising materials mentioning features or use of this software 46 * must display the following acknowledgement: 47 * This product includes software developed by the University of 48 * California, Berkeley and its contributors. 49 * 4. Neither the name of the University nor the names of its contributors 50 * may be used to endorse or promote products derived from this software 51 * without specific prior written permission. 52 * 53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 63 * SUCH DAMAGE. 64 */ 65 66 #ifndef lint 67 static char copyright[] = 68 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\ 69 The Regents of the University of California. All rights reserved.\n"; 70 #endif /* not lint */ 71 72 #ifndef lint 73 #if 0 74 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94"; 75 #else 76 static char rcsid[] = "$OpenBSD: ftpd.c,v 1.112 2001/12/18 00:27:57 millert Exp $"; 77 #endif 78 #endif /* not lint */ 79 80 /* 81 * FTP server. 82 */ 83 #include <sys/param.h> 84 #include <sys/stat.h> 85 #include <sys/ioctl.h> 86 #include <sys/socket.h> 87 #include <sys/wait.h> 88 #include <sys/mman.h> 89 90 #include <netinet/in.h> 91 #include <netinet/in_systm.h> 92 #include <netinet/ip.h> 93 #include <netinet/tcp.h> 94 95 #define FTP_NAMES 96 #include <arpa/ftp.h> 97 #include <arpa/inet.h> 98 #include <arpa/telnet.h> 99 100 #include <ctype.h> 101 #include <dirent.h> 102 #include <err.h> 103 #include <errno.h> 104 #include <fcntl.h> 105 #include <glob.h> 106 #include <limits.h> 107 #include <login_cap.h> 108 #include <netdb.h> 109 #include <pwd.h> 110 #include <signal.h> 111 #include <stdio.h> 112 #include <stdlib.h> 113 #include <string.h> 114 #include <syslog.h> 115 #include <time.h> 116 #include <vis.h> 117 #include <unistd.h> 118 #include <util.h> 119 #include <utmp.h> 120 #include <bsd_auth.h> 121 122 #if defined(TCPWRAPPERS) 123 #include <tcpd.h> 124 #endif /* TCPWRAPPERS */ 125 126 #include "pathnames.h" 127 #include "extern.h" 128 129 #ifdef __STDC__ 130 #include <stdarg.h> 131 #else 132 #include <varargs.h> 133 #endif 134 135 static char version[] = "Version 6.5/OpenBSD"; 136 137 extern off_t restart_point; 138 extern char cbuf[]; 139 140 union sockunion server_addr; 141 union sockunion ctrl_addr; 142 union sockunion data_source; 143 union sockunion data_dest; 144 union sockunion his_addr; 145 union sockunion pasv_addr; 146 147 sigset_t allsigs; 148 149 int daemon_mode = 0; 150 int data; 151 int logged_in; 152 struct passwd *pw; 153 int debug = 0; 154 int timeout = 900; /* timeout after 15 minutes of inactivity */ 155 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ 156 int logging; 157 int high_data_ports = 0; 158 int anon_only = 0; 159 int multihome = 0; 160 int guest; 161 int stats; 162 int statfd = -1; 163 int portcheck = 1; 164 int dochroot; 165 int type; 166 int form; 167 int stru; /* avoid C keyword */ 168 int mode; 169 int doutmp = 0; /* update utmp file */ 170 int usedefault = 1; /* for data transfers */ 171 int pdata = -1; /* for passive mode */ 172 int family = AF_INET; 173 volatile sig_atomic_t transflag; 174 off_t file_size; 175 off_t byte_count; 176 #if !defined(CMASK) || CMASK == 0 177 #undef CMASK 178 #define CMASK 022 179 #endif 180 int defumask = CMASK; /* default umask value */ 181 int umaskchange = 1; /* allow user to change umask value. */ 182 char tmpline[7]; 183 char hostname[MAXHOSTNAMELEN]; 184 char remotehost[MAXHOSTNAMELEN]; 185 char dhostname[MAXHOSTNAMELEN]; 186 char *guestpw; 187 static char ttyline[20]; 188 char *tty = ttyline; /* for klogin */ 189 static struct utmp utmp; /* for utmp */ 190 static login_cap_t *lc; 191 static auth_session_t *as; 192 static volatile sig_atomic_t recvurg; 193 194 #if defined(TCPWRAPPERS) 195 int allow_severity = LOG_INFO; 196 int deny_severity = LOG_NOTICE; 197 #endif /* TCPWRAPPERS */ 198 199 char *ident = NULL; 200 201 202 int epsvall = 0; 203 204 /* 205 * Timeout intervals for retrying connections 206 * to hosts that don't accept PORT cmds. This 207 * is a kludge, but given the problems with TCP... 208 */ 209 #define SWAITMAX 90 /* wait at most 90 seconds */ 210 #define SWAITINT 5 /* interval between retries */ 211 212 int swaitmax = SWAITMAX; 213 int swaitint = SWAITINT; 214 215 #ifdef HASSETPROCTITLE 216 char proctitle[BUFSIZ]; /* initial part of title */ 217 #endif /* HASSETPROCTITLE */ 218 219 #define LOGCMD(cmd, file) \ 220 if (logging > 1) \ 221 syslog(LOG_INFO,"%s %s%s", cmd, \ 222 *(file) == '/' ? "" : curdir(), file); 223 #define LOGCMD2(cmd, file1, file2) \ 224 if (logging > 1) \ 225 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \ 226 *(file1) == '/' ? "" : curdir(), file1, \ 227 *(file2) == '/' ? "" : curdir(), file2); 228 #define LOGBYTES(cmd, file, cnt) \ 229 if (logging > 1) { \ 230 if (cnt == (off_t)-1) \ 231 syslog(LOG_INFO,"%s %s%s", cmd, \ 232 *(file) == '/' ? "" : curdir(), file); \ 233 else \ 234 syslog(LOG_INFO, "%s %s%s = %qd bytes", \ 235 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \ 236 } 237 238 static void ack __P((char *)); 239 static void sigurg __P((int)); 240 static void myoob __P((void)); 241 static int checkuser __P((char *, char *)); 242 static FILE *dataconn __P((char *, off_t, char *)); 243 static void dolog __P((struct sockaddr *)); 244 static char *copy_dir __P((char *, struct passwd *)); 245 static char *curdir __P((void)); 246 static void end_login __P((void)); 247 static FILE *getdatasock __P((char *)); 248 static int guniquefd __P((char *, char **)); 249 static void lostconn __P((int)); 250 static void sigquit __P((int)); 251 static int receive_data __P((FILE *, FILE *)); 252 static void replydirname __P((const char *, const char *)); 253 static int send_data __P((FILE *, FILE *, off_t, off_t, int)); 254 static struct passwd * 255 sgetpwnam __P((char *)); 256 static void reapchild __P((int)); 257 static int check_host __P((struct sockaddr *)); 258 static void usage __P((void)); 259 260 void logxfer __P((char *, off_t, time_t)); 261 262 static char * 263 curdir() 264 { 265 static char path[MAXPATHLEN+1]; /* path + '/' */ 266 267 if (getcwd(path, sizeof(path)-1) == NULL) 268 return (""); 269 if (path[1] != '\0') /* special case for root dir. */ 270 strcat(path, "/"); 271 /* For guest account, skip / since it's chrooted */ 272 return (guest ? path+1 : path); 273 } 274 275 char *argstr = "AdDhlMSt:T:u:UvP46"; 276 277 static void 278 usage() 279 { 280 syslog(LOG_ERR, 281 "usage: ftpd [-AdDhlMSUv] [-t timeout] [-T maxtimeout] [-u mask]"); 282 exit(2); 283 } 284 285 int 286 main(argc, argv, envp) 287 int argc; 288 char *argv[]; 289 char **envp; 290 { 291 int addrlen, ch, on = 1, tos; 292 char *cp, line[LINE_MAX]; 293 FILE *fp; 294 struct hostent *hp; 295 struct sigaction sa; 296 297 tzset(); /* in case no timezone database in ~ftp */ 298 sigfillset(&allsigs); /* used to block signals while root */ 299 sigemptyset(&sa.sa_mask); 300 sa.sa_flags = SA_RESTART; 301 302 while ((ch = getopt(argc, argv, argstr)) != -1) { 303 switch (ch) { 304 case 'A': 305 anon_only = 1; 306 break; 307 308 case 'd': 309 debug = 1; 310 break; 311 312 case 'D': 313 daemon_mode = 1; 314 break; 315 316 case 'P': 317 portcheck = 0; 318 break; 319 320 case 'h': 321 high_data_ports = 1; 322 break; 323 324 case 'l': 325 logging++; /* > 1 == extra logging */ 326 break; 327 328 case 'M': 329 multihome = 1; 330 break; 331 332 case 'S': 333 stats = 1; 334 break; 335 336 case 't': 337 timeout = atoi(optarg); 338 if (maxtimeout < timeout) 339 maxtimeout = timeout; 340 break; 341 342 case 'T': 343 maxtimeout = atoi(optarg); 344 if (timeout > maxtimeout) 345 timeout = maxtimeout; 346 break; 347 348 case 'u': 349 { 350 long val = 0; 351 char *p; 352 umaskchange = 0; 353 354 val = strtol(optarg, &p, 8); 355 if (*p != '\0' || val < 0 || (val & ~ACCESSPERMS)) { 356 syslog(LOG_ERR, 357 "ftpd: %s is a bad value for -u, aborting..", 358 optarg); 359 exit(2); 360 } else 361 defumask = val; 362 break; 363 } 364 365 case 'U': 366 doutmp = 1; 367 break; 368 369 case 'v': 370 debug = 1; 371 break; 372 373 case '4': 374 family = AF_INET; 375 break; 376 377 case '6': 378 family = AF_INET6; 379 break; 380 381 default: 382 usage(); 383 break; 384 } 385 } 386 387 (void) freopen(_PATH_DEVNULL, "w", stderr); 388 389 /* 390 * LOG_NDELAY sets up the logging connection immediately, 391 * necessary for anonymous ftp's that chroot and can't do it later. 392 */ 393 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); 394 395 if (daemon_mode) { 396 int ctl_sock, fd; 397 struct servent *sv; 398 399 /* 400 * Detach from parent. 401 */ 402 if (daemon(1, 1) < 0) { 403 syslog(LOG_ERR, "failed to become a daemon"); 404 exit(1); 405 } 406 sa.sa_handler = reapchild; 407 (void) sigaction(SIGCHLD, &sa, NULL); 408 /* 409 * Get port number for ftp/tcp. 410 */ 411 sv = getservbyname("ftp", "tcp"); 412 if (sv == NULL) { 413 syslog(LOG_ERR, "getservbyname for ftp failed"); 414 exit(1); 415 } 416 /* 417 * Open a socket, bind it to the FTP port, and start 418 * listening. 419 */ 420 ctl_sock = socket(family, SOCK_STREAM, 0); 421 if (ctl_sock < 0) { 422 syslog(LOG_ERR, "control socket: %m"); 423 exit(1); 424 } 425 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR, 426 (char *)&on, sizeof(on)) < 0) 427 syslog(LOG_ERR, "control setsockopt: %m"); 428 memset(&server_addr, 0, sizeof(server_addr)); 429 server_addr.su_sin.sin_family = family; 430 switch (family) { 431 case AF_INET: 432 server_addr.su_len = sizeof(struct sockaddr_in); 433 server_addr.su_sin.sin_port = sv->s_port; 434 break; 435 case AF_INET6: 436 server_addr.su_len = sizeof(struct sockaddr_in6); 437 server_addr.su_sin6.sin6_port = sv->s_port; 438 break; 439 } 440 if (bind(ctl_sock, (struct sockaddr *)&server_addr, 441 server_addr.su_len)) { 442 syslog(LOG_ERR, "control bind: %m"); 443 exit(1); 444 } 445 if (listen(ctl_sock, 32) < 0) { 446 syslog(LOG_ERR, "control listen: %m"); 447 exit(1); 448 } 449 /* Stash pid in pidfile */ 450 if (pidfile(NULL)) 451 syslog(LOG_ERR, "can't open pidfile: %m"); 452 /* 453 * Loop forever accepting connection requests and forking off 454 * children to handle them. 455 */ 456 while (1) { 457 addrlen = sizeof(his_addr); 458 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, 459 &addrlen); 460 if (fork() == 0) { 461 /* child */ 462 (void) dup2(fd, 0); 463 (void) dup2(fd, 1); 464 close(ctl_sock); 465 break; 466 } 467 close(fd); 468 } 469 470 #if defined(TCPWRAPPERS) 471 /* ..in the child. */ 472 if (!check_host((struct sockaddr *)&his_addr)) 473 exit(1); 474 #endif /* TCPWRAPPERS */ 475 } else { 476 addrlen = sizeof(his_addr); 477 if (getpeername(0, (struct sockaddr *)&his_addr, 478 &addrlen) < 0) { 479 /* syslog(LOG_ERR, "getpeername (%s): %m", argv[0]); */ 480 exit(1); 481 } 482 } 483 484 /* set this here so klogin can use it... */ 485 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid()); 486 487 sa.sa_handler = SIG_IGN; 488 (void) sigaction(SIGCHLD, &sa, NULL); 489 490 sa.sa_handler = sigurg; 491 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */ 492 (void) sigaction(SIGURG, &sa, NULL); 493 494 sigfillset(&sa.sa_mask); /* block all signals in handler */ 495 sa.sa_flags = SA_RESTART; 496 sa.sa_handler = sigquit; 497 (void) sigaction(SIGHUP, &sa, NULL); 498 (void) sigaction(SIGINT, &sa, NULL); 499 (void) sigaction(SIGQUIT, &sa, NULL); 500 (void) sigaction(SIGTERM, &sa, NULL); 501 502 sa.sa_handler = lostconn; 503 (void) sigaction(SIGPIPE, &sa, NULL); 504 505 addrlen = sizeof(ctrl_addr); 506 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { 507 syslog(LOG_ERR, "getsockname: %m"); 508 exit(1); 509 } 510 if (his_addr.su_family == AF_INET6 511 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) { 512 #if 1 513 /* 514 * IPv4 control connection arrived to AF_INET6 socket. 515 * I hate to do this, but this is the easiest solution. 516 */ 517 union sockunion tmp_addr; 518 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr); 519 520 tmp_addr = his_addr; 521 memset(&his_addr, 0, sizeof(his_addr)); 522 his_addr.su_sin.sin_family = AF_INET; 523 his_addr.su_sin.sin_len = sizeof(his_addr.su_sin); 524 memcpy(&his_addr.su_sin.sin_addr, 525 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 526 sizeof(his_addr.su_sin.sin_addr)); 527 his_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 528 529 tmp_addr = ctrl_addr; 530 memset(&ctrl_addr, 0, sizeof(ctrl_addr)); 531 ctrl_addr.su_sin.sin_family = AF_INET; 532 ctrl_addr.su_sin.sin_len = sizeof(ctrl_addr.su_sin); 533 memcpy(&ctrl_addr.su_sin.sin_addr, 534 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 535 sizeof(ctrl_addr.su_sin.sin_addr)); 536 ctrl_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 537 #else 538 while (fgets(line, sizeof(line), fd) != NULL) { 539 if ((cp = strchr(line, '\n')) != NULL) 540 *cp = '\0'; 541 lreply(530, "%s", line); 542 } 543 (void) fflush(stdout); 544 (void) fclose(fd); 545 reply(530, 546 "Connection from IPv4 mapped address is not supported."); 547 exit(0); 548 #endif 549 } 550 #ifdef IP_TOS 551 if (his_addr.su_family == AF_INET) { 552 tos = IPTOS_LOWDELAY; 553 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, 554 sizeof(int)) < 0) 555 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 556 } 557 #endif 558 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1); 559 560 /* Try to handle urgent data inline */ 561 #ifdef SO_OOBINLINE 562 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0) 563 syslog(LOG_ERR, "setsockopt: %m"); 564 #endif 565 566 #ifdef F_SETOWN 567 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) 568 syslog(LOG_ERR, "fcntl F_SETOWN: %m"); 569 #endif 570 dolog((struct sockaddr *)&his_addr); 571 /* 572 * Set up default state 573 */ 574 data = -1; 575 type = TYPE_A; 576 form = FORM_N; 577 stru = STRU_F; 578 mode = MODE_S; 579 tmpline[0] = '\0'; 580 581 /* If logins are disabled, print out the message. */ 582 if ((fp = fopen(_PATH_NOLOGIN, "r")) != NULL) { 583 while (fgets(line, sizeof(line), fp) != NULL) { 584 if ((cp = strchr(line, '\n')) != NULL) 585 *cp = '\0'; 586 lreply(530, "%s", line); 587 } 588 (void) fflush(stdout); 589 (void) fclose(fp); 590 reply(530, "System not available."); 591 exit(0); 592 } 593 if ((fp = fopen(_PATH_FTPWELCOME, "r")) != NULL) { 594 while (fgets(line, sizeof(line), fp) != NULL) { 595 if ((cp = strchr(line, '\n')) != NULL) 596 *cp = '\0'; 597 lreply(220, "%s", line); 598 } 599 (void) fflush(stdout); 600 (void) fclose(fp); 601 /* reply(220,) must follow */ 602 } 603 (void) gethostname(hostname, sizeof(hostname)); 604 605 /* Make sure hostname is fully qualified. */ 606 hp = gethostbyname(hostname); 607 if (hp != NULL) 608 strcpy(hostname, hp->h_name); 609 610 if (multihome) { 611 getnameinfo((struct sockaddr *)&ctrl_addr, ctrl_addr.su_len, 612 dhostname, sizeof(dhostname), NULL, 0, 0); 613 } 614 615 reply(220, "%s FTP server (%s) ready.", 616 (multihome ? dhostname : hostname), version); 617 for (;;) 618 (void) yyparse(); 619 /* NOTREACHED */ 620 } 621 622 /* 623 * Signal handlers. 624 */ 625 626 static void 627 lostconn(signo) 628 int signo; 629 { 630 struct syslog_data sdata = SYSLOG_DATA_INIT; 631 632 if (debug) 633 syslog_r(LOG_DEBUG, &sdata, "lost connection"); 634 dologout(1); 635 } 636 637 static void 638 sigquit(signo) 639 int signo; 640 { 641 struct syslog_data sdata = SYSLOG_DATA_INIT; 642 643 syslog_r(LOG_ERR, &sdata, "got signal %s", sys_signame[signo]); 644 dologout(1); 645 } 646 647 /* 648 * Save the result of a getpwnam. Used for USER command, since 649 * the data returned must not be clobbered by any other command 650 * (e.g., globbing). 651 */ 652 static struct passwd * 653 sgetpwnam(name) 654 char *name; 655 { 656 static struct passwd *save; 657 struct passwd *pw; 658 659 if ((pw = getpwnam(name)) == NULL) 660 return (pw); 661 if (save) { 662 memset(save->pw_passwd, 0, strlen(save->pw_passwd)); 663 free(save); 664 } 665 save = pw_dup(pw); 666 if (save == NULL) { 667 perror_reply(421, "Local resource failure: malloc"); 668 dologout(1); 669 /* NOTREACHED */ 670 } 671 return (save); 672 } 673 674 static int login_attempts; /* number of failed login attempts */ 675 static int askpasswd; /* had user command, ask for passwd */ 676 static char curname[MAXLOGNAME]; /* current USER name */ 677 678 /* 679 * USER command. 680 * Sets global passwd pointer pw if named account exists and is acceptable; 681 * sets askpasswd if a PASS command is expected. If logged in previously, 682 * need to reset state. If name is "ftp" or "anonymous", the name is not in 683 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return. 684 * If account doesn't exist, ask for passwd anyway. Otherwise, check user 685 * requesting login privileges. Disallow anyone who does not have a standard 686 * shell as returned by getusershell(). Disallow anyone mentioned in the file 687 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided. 688 */ 689 void 690 user(name) 691 char *name; 692 { 693 char *cp, *shell, *style; 694 char *class = NULL; 695 696 if (logged_in) { 697 if (guest) { 698 reply(530, "Can't change user from guest login."); 699 return; 700 } else if (dochroot) { 701 reply(530, "Can't change user from chroot user."); 702 return; 703 } 704 login_close(lc); 705 lc = NULL; 706 if (as) { 707 auth_close(as); 708 as = NULL; 709 } 710 end_login(); 711 } 712 713 if ((style = strchr(name, ':')) != NULL) 714 *style++ = 0; 715 716 guest = 0; 717 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) { 718 if (checkuser(_PATH_FTPUSERS, "ftp") || 719 checkuser(_PATH_FTPUSERS, "anonymous")) 720 reply(530, "User %s access denied.", name); 721 else if ((pw = sgetpwnam("ftp")) != NULL) { 722 guest = 1; 723 askpasswd = 1; 724 lc = login_getclass(pw->pw_class); 725 reply(331, 726 "Guest login ok, send your email address as password."); 727 } else 728 reply(530, "User %s unknown.", name); 729 if (!askpasswd && logging) 730 syslog(LOG_NOTICE, 731 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost); 732 return; 733 } 734 735 shell = _PATH_BSHELL; 736 if ((pw = sgetpwnam(name))) { 737 class = pw->pw_class; 738 if (pw->pw_shell != NULL && *pw->pw_shell != '\0') 739 shell = pw->pw_shell; 740 while ((cp = getusershell()) != NULL) 741 if (strcmp(cp, shell) == 0) 742 break; 743 shell = cp; 744 endusershell(); 745 } 746 747 /* Get login class; if invalid style treat like unknown user. */ 748 lc = login_getclass(class); 749 if (lc && (style = login_getstyle(lc, style, "auth-ftp")) == NULL) { 750 login_close(lc); 751 lc = NULL; 752 pw = NULL; 753 } 754 755 /* Do pre-authentication setup. */ 756 if (lc && ((as = auth_open()) == NULL || 757 auth_setitem(as, AUTHV_STYLE, style) < 0 || 758 auth_setitem(as, AUTHV_NAME, name) < 0 || 759 auth_setitem(as, AUTHV_CLASS, class) < 0 || 760 auth_setoption(as, "login", "yes") < 0 || 761 auth_setoption(as, "notickets", "yes") < 0)) { 762 if (as) { 763 auth_close(as); 764 as = NULL; 765 } 766 login_close(lc); 767 lc = NULL; 768 reply(421, "Local resource failure"); 769 return; 770 } 771 if (logging) 772 strlcpy(curname, name, sizeof(curname)); 773 774 dochroot = (lc && login_getcapbool(lc, "ftp-chroot", 0)) || 775 checkuser(_PATH_FTPCHROOT, name); 776 if (anon_only && !dochroot) { 777 reply(530, "Sorry, only anonymous ftp allowed."); 778 return; 779 } 780 if (pw) { 781 if ((!shell && !dochroot) || checkuser(_PATH_FTPUSERS, name)) { 782 reply(530, "User %s access denied.", name); 783 if (logging) 784 syslog(LOG_NOTICE, 785 "FTP LOGIN REFUSED FROM %s, %s", 786 remotehost, name); 787 pw = NULL; 788 return; 789 } 790 } 791 792 if (as != NULL && (cp = auth_challenge(as)) != NULL) 793 reply(331, cp); 794 else 795 reply(331, "Password required for %s.", name); 796 797 askpasswd = 1; 798 /* 799 * Delay before reading passwd after first failed 800 * attempt to slow down passwd-guessing programs. 801 */ 802 if (login_attempts) 803 sleep((unsigned) login_attempts); 804 } 805 806 /* 807 * Check if a user is in the file "fname" 808 */ 809 static int 810 checkuser(fname, name) 811 char *fname; 812 char *name; 813 { 814 FILE *fp; 815 int found = 0; 816 char *p, line[BUFSIZ]; 817 818 if ((fp = fopen(fname, "r")) != NULL) { 819 while (fgets(line, sizeof(line), fp) != NULL) 820 if ((p = strchr(line, '\n')) != NULL) { 821 *p = '\0'; 822 if (line[0] == '#') 823 continue; 824 if (strcmp(line, name) == 0) { 825 found = 1; 826 break; 827 } 828 } 829 (void) fclose(fp); 830 } 831 return (found); 832 } 833 834 /* 835 * Terminate login as previous user, if any, resetting state; 836 * used when USER command is given or login fails. 837 */ 838 static void 839 end_login() 840 { 841 842 sigprocmask (SIG_BLOCK, &allsigs, NULL); 843 (void) seteuid((uid_t)0); 844 if (logged_in) { 845 ftpdlogwtmp(ttyline, "", ""); 846 if (doutmp) 847 logout(utmp.ut_line); 848 } 849 pw = NULL; 850 /* umask is restored in ftpcmd.y */ 851 setusercontext(NULL, getpwuid(0), (uid_t)0, 852 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES); 853 logged_in = 0; 854 guest = 0; 855 dochroot = 0; 856 } 857 858 void 859 pass(passwd) 860 char *passwd; 861 { 862 int authok, flags; 863 FILE *fp; 864 static char homedir[MAXPATHLEN]; 865 char *motd, *dir, rootdir[MAXPATHLEN]; 866 867 if (logged_in || askpasswd == 0) { 868 reply(503, "Login with USER first."); 869 return; 870 } 871 askpasswd = 0; 872 if (!guest) { /* "ftp" is only account allowed no password */ 873 authok = 0; 874 if (pw == NULL) { 875 useconds_t us; 876 877 /* Sleep between 1 and 3 seconds to emulate a crypt. */ 878 us = arc4random() % 3000000; 879 usleep(us); 880 } else { 881 authok = auth_userresponse(as, passwd, 0); 882 as = NULL; 883 } 884 if (authok == 0) { 885 reply(530, "Login incorrect."); 886 if (logging) 887 syslog(LOG_NOTICE, 888 "FTP LOGIN FAILED FROM %s, %s", 889 remotehost, curname); 890 pw = NULL; 891 if (login_attempts++ >= 5) { 892 syslog(LOG_NOTICE, 893 "repeated login failures from %s", 894 remotehost); 895 exit(0); 896 } 897 return; 898 } 899 } else if (lc != NULL) { 900 /* Save anonymous' password. */ 901 guestpw = strdup(passwd); 902 if (guestpw == (char *)NULL) 903 fatal("Out of memory"); 904 905 if ((as = auth_open()) == NULL) 906 fatal("Out of memory"); 907 auth_setoption(as, "FTPD_HOST", 908 multihome ? dhostname : hostname); 909 authok = auth_approval(as, lc, pw->pw_name, "ftp"); 910 auth_close(as); 911 as = NULL; 912 if (authok == 0) { 913 syslog(LOG_INFO|LOG_AUTH, 914 "FTP LOGIN FAILED (HOST) as %s: approval failure.", 915 pw->pw_name); 916 reply(530, "Approval failure.\n"); 917 exit(0); 918 } 919 } else { 920 syslog(LOG_INFO|LOG_AUTH, 921 "FTP LOGIN CLASS %s MISSING for %s: approval failure.", 922 pw->pw_class, pw->pw_name); 923 reply(530, "Permission denied.\n"); 924 exit(0); 925 } 926 login_attempts = 0; /* this time successful */ 927 if (setegid((gid_t)pw->pw_gid) < 0) { 928 reply(550, "Can't set gid."); 929 return; 930 } 931 /* set umask via setusercontext() unless -u flag was given. */ 932 flags = LOGIN_SETGROUP|LOGIN_SETPRIORITY|LOGIN_SETRESOURCES; 933 if (umaskchange) 934 flags |= LOGIN_SETUMASK; 935 else 936 (void) umask(defumask); 937 setusercontext(lc, pw, (uid_t)0, flags); 938 939 /* open wtmp before chroot */ 940 ftpdlogwtmp(ttyline, pw->pw_name, remotehost); 941 942 /* open utmp before chroot */ 943 if (doutmp) { 944 memset((void *)&utmp, 0, sizeof(utmp)); 945 (void)time(&utmp.ut_time); 946 (void)strncpy(utmp.ut_name, pw->pw_name, sizeof(utmp.ut_name)); 947 (void)strncpy(utmp.ut_host, remotehost, sizeof(utmp.ut_host)); 948 (void)strncpy(utmp.ut_line, ttyline, sizeof(utmp.ut_line)); 949 login(&utmp); 950 } 951 952 /* open stats file before chroot */ 953 if (guest && (stats == 1) && (statfd < 0)) 954 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0) 955 stats = 0; 956 957 logged_in = 1; 958 959 if ((dir = login_getcapstr(lc, "ftp-dir", NULL, NULL))) { 960 char *newdir; 961 962 newdir = copy_dir(dir, pw); 963 if (newdir == NULL) { 964 perror_reply(421, "Local resource failure: malloc"); 965 dologout(1); 966 /* NOTREACHED */ 967 } 968 free(dir); 969 free(pw->pw_dir); 970 pw->pw_dir = newdir; 971 } 972 973 if (guest || dochroot) { 974 if (multihome && guest) { 975 struct stat ts; 976 977 /* Compute root directory. */ 978 snprintf(rootdir, sizeof(rootdir), "%s/%s", 979 pw->pw_dir, dhostname); 980 if (stat(rootdir, &ts) < 0) { 981 snprintf(rootdir, sizeof(rootdir), "%s/%s", 982 pw->pw_dir, hostname); 983 } 984 } else 985 strcpy(rootdir, pw->pw_dir); 986 } 987 if (guest) { 988 /* 989 * We MUST do a chdir() after the chroot. Otherwise 990 * the old current directory will be accessible as "." 991 * outside the new root! 992 */ 993 if (chroot(rootdir) < 0 || chdir("/") < 0) { 994 reply(550, "Can't set guest privileges."); 995 goto bad; 996 } 997 strcpy(pw->pw_dir, "/"); 998 if (setenv("HOME", "/", 1) == -1) { 999 reply(550, "Can't setup environment."); 1000 goto bad; 1001 } 1002 } else if (dochroot) { 1003 if (chroot(rootdir) < 0 || chdir("/") < 0) { 1004 reply(550, "Can't change root."); 1005 goto bad; 1006 } 1007 strcpy(pw->pw_dir, "/"); 1008 if (setenv("HOME", "/", 1) == -1) { 1009 reply(550, "Can't setup environment."); 1010 goto bad; 1011 } 1012 } else if (chdir(pw->pw_dir) < 0) { 1013 if (chdir("/") < 0) { 1014 reply(530, "User %s: can't change directory to %s.", 1015 pw->pw_name, pw->pw_dir); 1016 goto bad; 1017 } else 1018 lreply(230, "No directory! Logging in with home=/"); 1019 } 1020 if (seteuid((uid_t)pw->pw_uid) < 0) { 1021 reply(550, "Can't set uid."); 1022 goto bad; 1023 } 1024 sigprocmask(SIG_UNBLOCK, &allsigs, NULL); 1025 1026 /* 1027 * Set home directory so that use of ~ (tilde) works correctly. 1028 */ 1029 if (getcwd(homedir, MAXPATHLEN) != NULL) { 1030 if (setenv("HOME", homedir, 1) == -1) { 1031 reply(550, "Can't setup environment."); 1032 goto bad; 1033 } 1034 } 1035 1036 /* 1037 * Display a login message, if it exists. 1038 * N.B. reply(230,) must follow the message. 1039 */ 1040 motd = login_getcapstr(lc, "welcome", NULL, NULL); 1041 if ((fp = fopen(motd ? motd : _PATH_FTPLOGINMESG, "r")) != NULL) { 1042 char *cp, line[LINE_MAX]; 1043 1044 while (fgets(line, sizeof(line), fp) != NULL) { 1045 if ((cp = strchr(line, '\n')) != NULL) 1046 *cp = '\0'; 1047 lreply(230, "%s", line); 1048 } 1049 (void) fflush(stdout); 1050 (void) fclose(fp); 1051 } 1052 if (motd != NULL) 1053 free(motd); 1054 if (guest) { 1055 if (ident != NULL) 1056 free(ident); 1057 ident = strdup(passwd); 1058 if (ident == NULL) 1059 fatal("Ran out of memory."); 1060 reply(230, "Guest login ok, access restrictions apply."); 1061 #ifdef HASSETPROCTITLE 1062 snprintf(proctitle, sizeof(proctitle), 1063 "%s: anonymous/%.*s", remotehost, 1064 (int)(sizeof(proctitle) - sizeof(remotehost) - 1065 sizeof(": anonymous/")), passwd); 1066 setproctitle("%s", proctitle); 1067 #endif /* HASSETPROCTITLE */ 1068 if (logging) 1069 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s", 1070 remotehost, passwd); 1071 } else { 1072 reply(230, "User %s logged in.", pw->pw_name); 1073 #ifdef HASSETPROCTITLE 1074 snprintf(proctitle, sizeof(proctitle), 1075 "%s: %s", remotehost, pw->pw_name); 1076 setproctitle("%s", proctitle); 1077 #endif /* HASSETPROCTITLE */ 1078 if (logging) 1079 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s", 1080 remotehost, pw->pw_name); 1081 } 1082 login_close(lc); 1083 lc = NULL; 1084 return; 1085 bad: 1086 /* Forget all about it... */ 1087 login_close(lc); 1088 lc = NULL; 1089 end_login(); 1090 } 1091 1092 void 1093 retrieve(cmd, name) 1094 char *cmd, *name; 1095 { 1096 FILE *fin, *dout; 1097 struct stat st; 1098 int (*closefunc) __P((FILE *)); 1099 time_t start; 1100 1101 if (cmd == 0) { 1102 fin = fopen(name, "r"), closefunc = fclose; 1103 st.st_size = 0; 1104 } else { 1105 char line[BUFSIZ]; 1106 1107 (void) snprintf(line, sizeof(line), cmd, name); 1108 name = line; 1109 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose; 1110 st.st_size = -1; 1111 st.st_blksize = BUFSIZ; 1112 } 1113 if (fin == NULL) { 1114 if (errno != 0) { 1115 perror_reply(550, name); 1116 if (cmd == 0) { 1117 LOGCMD("get", name); 1118 } 1119 } 1120 return; 1121 } 1122 byte_count = -1; 1123 if (cmd == 0 && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) { 1124 reply(550, "%s: not a plain file.", name); 1125 goto done; 1126 } 1127 if (restart_point) { 1128 if (type == TYPE_A) { 1129 off_t i, n; 1130 int c; 1131 1132 n = restart_point; 1133 i = 0; 1134 while (i++ < n) { 1135 if ((c=getc(fin)) == EOF) { 1136 perror_reply(550, name); 1137 goto done; 1138 } 1139 if (c == '\n') 1140 i++; 1141 } 1142 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) { 1143 perror_reply(550, name); 1144 goto done; 1145 } 1146 } 1147 dout = dataconn(name, st.st_size, "w"); 1148 if (dout == NULL) 1149 goto done; 1150 time(&start); 1151 send_data(fin, dout, st.st_blksize, st.st_size, 1152 (restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode))); 1153 if ((cmd == 0) && stats) 1154 logxfer(name, byte_count, start); 1155 (void) fclose(dout); 1156 data = -1; 1157 done: 1158 if (pdata >= 0) 1159 (void) close(pdata); 1160 pdata = -1; 1161 if (cmd == 0) 1162 LOGBYTES("get", name, byte_count); 1163 (*closefunc)(fin); 1164 } 1165 1166 void 1167 store(name, mode, unique) 1168 char *name, *mode; 1169 int unique; 1170 { 1171 FILE *fout, *din; 1172 int (*closefunc) __P((FILE *)); 1173 struct stat st; 1174 int fd; 1175 1176 if (restart_point && *mode != 'a') 1177 mode = "r+"; 1178 1179 if (unique && stat(name, &st) == 0) { 1180 char *nam; 1181 1182 fd = guniquefd(name, &nam); 1183 if (fd == -1) { 1184 LOGCMD(*mode == 'w' ? "put" : "append", name); 1185 return; 1186 } 1187 name = nam; 1188 fout = fdopen(fd, mode); 1189 } else 1190 fout = fopen(name, mode); 1191 1192 closefunc = fclose; 1193 if (fout == NULL) { 1194 perror_reply(553, name); 1195 LOGCMD(*mode == 'w' ? "put" : "append", name); 1196 return; 1197 } 1198 byte_count = -1; 1199 if (restart_point) { 1200 if (type == TYPE_A) { 1201 off_t i, n; 1202 int c; 1203 1204 n = restart_point; 1205 i = 0; 1206 while (i++ < n) { 1207 if ((c=getc(fout)) == EOF) { 1208 perror_reply(550, name); 1209 goto done; 1210 } 1211 if (c == '\n') 1212 i++; 1213 } 1214 /* 1215 * We must do this seek to "current" position 1216 * because we are changing from reading to 1217 * writing. 1218 */ 1219 if (fseek(fout, 0L, SEEK_CUR) < 0) { 1220 perror_reply(550, name); 1221 goto done; 1222 } 1223 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) { 1224 perror_reply(550, name); 1225 goto done; 1226 } 1227 } 1228 din = dataconn(name, (off_t)-1, "r"); 1229 if (din == NULL) 1230 goto done; 1231 if (receive_data(din, fout) == 0) { 1232 if (unique) 1233 reply(226, "Transfer complete (unique file name:%s).", 1234 name); 1235 else 1236 reply(226, "Transfer complete."); 1237 } 1238 (void) fclose(din); 1239 data = -1; 1240 pdata = -1; 1241 done: 1242 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count); 1243 (*closefunc)(fout); 1244 } 1245 1246 static FILE * 1247 getdatasock(mode) 1248 char *mode; 1249 { 1250 int on = 1, s, t, tries; 1251 1252 if (data >= 0) 1253 return (fdopen(data, mode)); 1254 sigprocmask (SIG_BLOCK, &allsigs, NULL); 1255 (void) seteuid((uid_t)0); 1256 s = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 1257 if (s < 0) 1258 goto bad; 1259 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, 1260 (char *) &on, sizeof(on)) < 0) 1261 goto bad; 1262 /* anchor socket to avoid multi-homing problems */ 1263 data_source = ctrl_addr; 1264 data_source.su_port = htons(20); /* ftp-data port */ 1265 for (tries = 1; ; tries++) { 1266 if (bind(s, (struct sockaddr *)&data_source, 1267 data_source.su_len) >= 0) 1268 break; 1269 if (errno != EADDRINUSE || tries > 10) 1270 goto bad; 1271 sleep(tries); 1272 } 1273 (void) seteuid((uid_t)pw->pw_uid); 1274 sigprocmask (SIG_UNBLOCK, &allsigs, NULL); 1275 1276 #ifdef IP_TOS 1277 if (ctrl_addr.su_family == AF_INET) { 1278 on = IPTOS_THROUGHPUT; 1279 if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on, 1280 sizeof(int)) < 0) 1281 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 1282 } 1283 #endif 1284 #ifdef TCP_NOPUSH 1285 /* 1286 * Turn off push flag to keep sender TCP from sending short packets 1287 * at the boundaries of each write(). Should probably do a SO_SNDBUF 1288 * to set the send buffer size as well, but that may not be desirable 1289 * in heavy-load situations. 1290 */ 1291 on = 1; 1292 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, (char *)&on, sizeof(on)) < 0) 1293 syslog(LOG_WARNING, "setsockopt (TCP_NOPUSH): %m"); 1294 #endif 1295 #ifdef SO_SNDBUF 1296 on = 65536; 1297 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&on, sizeof(on)) < 0) 1298 syslog(LOG_WARNING, "setsockopt (SO_SNDBUF): %m"); 1299 #endif 1300 1301 return (fdopen(s, mode)); 1302 bad: 1303 /* Return the real value of errno (close may change it) */ 1304 t = errno; 1305 (void) seteuid((uid_t)pw->pw_uid); 1306 sigprocmask (SIG_UNBLOCK, &allsigs, NULL); 1307 (void) close(s); 1308 errno = t; 1309 return (NULL); 1310 } 1311 1312 static FILE * 1313 dataconn(name, size, mode) 1314 char *name; 1315 off_t size; 1316 char *mode; 1317 { 1318 char sizebuf[32]; 1319 FILE *file; 1320 int retry = 0; 1321 in_port_t *p; 1322 char *fa, *ha; 1323 int alen; 1324 1325 file_size = size; 1326 byte_count = 0; 1327 if (size != (off_t) -1) { 1328 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", 1329 size); 1330 } else 1331 sizebuf[0] = '\0'; 1332 if (pdata >= 0) { 1333 union sockunion from; 1334 int s, fromlen = sizeof(from); 1335 1336 signal (SIGALRM, toolong); 1337 (void) alarm ((unsigned) timeout); 1338 s = accept(pdata, (struct sockaddr *)&from, &fromlen); 1339 (void) alarm (0); 1340 if (s < 0) { 1341 reply(425, "Can't open data connection."); 1342 (void) close(pdata); 1343 pdata = -1; 1344 return (NULL); 1345 } 1346 switch (from.su_family) { 1347 case AF_INET: 1348 p = (in_port_t *)&from.su_sin.sin_port; 1349 fa = (u_char *)&from.su_sin.sin_addr; 1350 ha = (u_char *)&his_addr.su_sin.sin_addr; 1351 alen = sizeof(struct in_addr); 1352 break; 1353 case AF_INET6: 1354 p = (in_port_t *)&from.su_sin6.sin6_port; 1355 fa = (u_char *)&from.su_sin6.sin6_addr; 1356 ha = (u_char *)&his_addr.su_sin6.sin6_addr; 1357 alen = sizeof(struct in6_addr); 1358 break; 1359 default: 1360 perror_reply(425, "Can't build data connection"); 1361 (void) close(pdata); 1362 (void) close(s); 1363 pdata = -1; 1364 return (NULL); 1365 } 1366 if (from.su_family != his_addr.su_family || 1367 ntohs(*p) < IPPORT_RESERVED) { 1368 perror_reply(425, "Can't build data connection"); 1369 (void) close(pdata); 1370 (void) close(s); 1371 pdata = -1; 1372 return (NULL); 1373 } 1374 if (portcheck && memcmp(fa, ha, alen) != 0) { 1375 perror_reply(435, "Can't build data connection"); 1376 (void) close(pdata); 1377 (void) close(s); 1378 pdata = -1; 1379 return (NULL); 1380 } 1381 (void) close(pdata); 1382 pdata = s; 1383 reply(150, "Opening %s mode data connection for '%s'%s.", 1384 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1385 return (fdopen(pdata, mode)); 1386 } 1387 if (data >= 0) { 1388 reply(125, "Using existing data connection for '%s'%s.", 1389 name, sizebuf); 1390 usedefault = 1; 1391 return (fdopen(data, mode)); 1392 } 1393 if (usedefault) 1394 data_dest = his_addr; 1395 usedefault = 1; 1396 file = getdatasock(mode); 1397 if (file == NULL) { 1398 char hbuf[MAXHOSTNAMELEN], pbuf[10]; 1399 1400 getnameinfo((struct sockaddr *)&data_source, data_source.su_len, 1401 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), 1402 NI_NUMERICHOST | NI_NUMERICSERV); 1403 reply(425, "Can't create data socket (%s,%s): %s.", 1404 hbuf, pbuf, strerror(errno)); 1405 return (NULL); 1406 } 1407 data = fileno(file); 1408 1409 /* 1410 * attempt to connect to reserved port on client machine; 1411 * this looks like an attack 1412 */ 1413 switch (data_dest.su_family) { 1414 case AF_INET: 1415 p = (in_port_t *)&data_dest.su_sin.sin_port; 1416 fa = (u_char *)&data_dest.su_sin.sin_addr; 1417 ha = (u_char *)&his_addr.su_sin.sin_addr; 1418 alen = sizeof(struct in_addr); 1419 break; 1420 case AF_INET6: 1421 p = (in_port_t *)&data_dest.su_sin6.sin6_port; 1422 fa = (u_char *)&data_dest.su_sin6.sin6_addr; 1423 ha = (u_char *)&his_addr.su_sin6.sin6_addr; 1424 alen = sizeof(struct in6_addr); 1425 break; 1426 default: 1427 perror_reply(425, "Can't build data connection"); 1428 (void) fclose(file); 1429 pdata = -1; 1430 return (NULL); 1431 } 1432 if (data_dest.su_family != his_addr.su_family || 1433 ntohs(*p) < IPPORT_RESERVED || ntohs(*p) == 2049) { /* XXX */ 1434 perror_reply(425, "Can't build data connection"); 1435 (void) fclose(file); 1436 data = -1; 1437 return NULL; 1438 } 1439 if (portcheck && memcmp(fa, ha, alen) != 0) { 1440 perror_reply(435, "Can't build data connection"); 1441 (void) fclose(file); 1442 data = -1; 1443 return NULL; 1444 } 1445 while (connect(data, (struct sockaddr *)&data_dest, 1446 data_dest.su_len) < 0) { 1447 if (errno == EADDRINUSE && retry < swaitmax) { 1448 sleep((unsigned) swaitint); 1449 retry += swaitint; 1450 continue; 1451 } 1452 perror_reply(425, "Can't build data connection"); 1453 (void) fclose(file); 1454 data = -1; 1455 return (NULL); 1456 } 1457 reply(150, "Opening %s mode data connection for '%s'%s.", 1458 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); 1459 return (file); 1460 } 1461 1462 /* 1463 * Tranfer the contents of "instr" to "outstr" peer using the appropriate 1464 * encapsulation of the data subject to Mode, Structure, and Type. 1465 * 1466 * NB: Form isn't handled. 1467 */ 1468 static int 1469 send_data(instr, outstr, blksize, filesize, isreg) 1470 FILE *instr, *outstr; 1471 off_t blksize; 1472 off_t filesize; 1473 int isreg; 1474 { 1475 int c, cnt, filefd, netfd; 1476 char *buf, *bp; 1477 size_t len; 1478 1479 transflag++; 1480 switch (type) { 1481 1482 case TYPE_A: 1483 while ((c = getc(instr)) != EOF) { 1484 if (recvurg) 1485 goto got_oob; 1486 byte_count++; 1487 if (c == '\n') { 1488 if (ferror(outstr)) 1489 goto data_err; 1490 (void) putc('\r', outstr); 1491 } 1492 (void) putc(c, outstr); 1493 } 1494 fflush(outstr); 1495 transflag = 0; 1496 if (ferror(instr)) 1497 goto file_err; 1498 if (ferror(outstr)) 1499 goto data_err; 1500 reply(226, "Transfer complete."); 1501 return(0); 1502 1503 case TYPE_I: 1504 case TYPE_L: 1505 /* 1506 * isreg is only set if we are not doing restart and we 1507 * are sending a regular file 1508 */ 1509 netfd = fileno(outstr); 1510 filefd = fileno(instr); 1511 1512 if (isreg && filesize < (off_t)16 * 1024 * 1024) { 1513 buf = mmap(0, filesize, PROT_READ, MAP_SHARED, filefd, 1514 (off_t)0); 1515 if (buf == MAP_FAILED) { 1516 syslog(LOG_WARNING, "mmap(%lu): %m", 1517 (unsigned long)filesize); 1518 goto oldway; 1519 } 1520 bp = buf; 1521 len = filesize; 1522 do { 1523 cnt = write(netfd, bp, len); 1524 if (recvurg) { 1525 munmap(buf, (size_t)filesize); 1526 goto got_oob; 1527 } 1528 len -= cnt; 1529 bp += cnt; 1530 if (cnt > 0) byte_count += cnt; 1531 } while(cnt > 0 && len > 0); 1532 1533 transflag = 0; 1534 munmap(buf, (size_t)filesize); 1535 if (cnt < 0) 1536 goto data_err; 1537 reply(226, "Transfer complete."); 1538 return(0); 1539 } 1540 1541 oldway: 1542 if ((buf = malloc((u_int)blksize)) == NULL) { 1543 transflag = 0; 1544 perror_reply(451, "Local resource failure: malloc"); 1545 return(-1); 1546 } 1547 1548 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 && 1549 write(netfd, buf, cnt) == cnt) 1550 byte_count += cnt; 1551 transflag = 0; 1552 (void)free(buf); 1553 if (cnt != 0) { 1554 if (cnt < 0) 1555 goto file_err; 1556 goto data_err; 1557 } 1558 reply(226, "Transfer complete."); 1559 return(0); 1560 default: 1561 transflag = 0; 1562 reply(550, "Unimplemented TYPE %d in send_data", type); 1563 return(-1); 1564 } 1565 1566 data_err: 1567 transflag = 0; 1568 perror_reply(426, "Data connection"); 1569 return(-1); 1570 1571 file_err: 1572 transflag = 0; 1573 perror_reply(551, "Error on input file"); 1574 return(-1); 1575 1576 got_oob: 1577 myoob(); 1578 recvurg = 0; 1579 transflag = 0; 1580 return(-1); 1581 } 1582 1583 /* 1584 * Transfer data from peer to "outstr" using the appropriate encapulation of 1585 * the data subject to Mode, Structure, and Type. 1586 * 1587 * N.B.: Form isn't handled. 1588 */ 1589 static int 1590 receive_data(instr, outstr) 1591 FILE *instr, *outstr; 1592 { 1593 int c; 1594 int cnt; 1595 char buf[BUFSIZ]; 1596 struct sigaction sa; 1597 volatile int bare_lfs = 0; 1598 1599 transflag++; 1600 switch (type) { 1601 1602 case TYPE_I: 1603 case TYPE_L: 1604 sigfillset(&sa.sa_mask); 1605 sa.sa_flags = SA_RESTART; 1606 sigaction(SIGALRM, &sa, NULL); 1607 1608 do { 1609 (void) alarm ((unsigned) timeout); 1610 cnt = read(fileno(instr), buf, sizeof(buf)); 1611 (void) alarm (0); 1612 if (recvurg) 1613 goto got_oob; 1614 1615 if (cnt > 0) { 1616 if (write(fileno(outstr), buf, cnt) != cnt) 1617 goto file_err; 1618 byte_count += cnt; 1619 } 1620 } while (cnt > 0); 1621 if (cnt < 0) 1622 goto data_err; 1623 transflag = 0; 1624 return (0); 1625 1626 case TYPE_E: 1627 reply(553, "TYPE E not implemented."); 1628 transflag = 0; 1629 return (-1); 1630 1631 case TYPE_A: 1632 while ((c = getc(instr)) != EOF) { 1633 if (recvurg) 1634 goto got_oob; 1635 byte_count++; 1636 if (c == '\n') 1637 bare_lfs++; 1638 while (c == '\r') { 1639 if (ferror(outstr)) 1640 goto data_err; 1641 if ((c = getc(instr)) != '\n') { 1642 (void) putc ('\r', outstr); 1643 if (c == '\0' || c == EOF) 1644 goto contin2; 1645 } 1646 } 1647 (void) putc(c, outstr); 1648 contin2: ; 1649 } 1650 fflush(outstr); 1651 if (ferror(instr)) 1652 goto data_err; 1653 if (ferror(outstr)) 1654 goto file_err; 1655 transflag = 0; 1656 if (bare_lfs) { 1657 lreply(226, 1658 "WARNING! %d bare linefeeds received in ASCII mode", 1659 bare_lfs); 1660 printf(" File may not have transferred correctly.\r\n"); 1661 } 1662 return (0); 1663 default: 1664 reply(550, "Unimplemented TYPE %d in receive_data", type); 1665 transflag = 0; 1666 return (-1); 1667 } 1668 1669 data_err: 1670 transflag = 0; 1671 perror_reply(426, "Data Connection"); 1672 return (-1); 1673 1674 file_err: 1675 transflag = 0; 1676 perror_reply(452, "Error writing file"); 1677 return (-1); 1678 1679 got_oob: 1680 myoob(); 1681 recvurg = 0; 1682 transflag = 0; 1683 return (-1); 1684 } 1685 1686 void 1687 statfilecmd(filename) 1688 char *filename; 1689 { 1690 FILE *fin; 1691 int c; 1692 int atstart; 1693 char line[LINE_MAX]; 1694 1695 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename); 1696 fin = ftpd_popen(line, "r"); 1697 lreply(211, "status of %s:", filename); 1698 atstart = 1; 1699 while ((c = getc(fin)) != EOF) { 1700 if (c == '\n') { 1701 if (ferror(stdout)){ 1702 perror_reply(421, "control connection"); 1703 (void) ftpd_pclose(fin); 1704 dologout(1); 1705 /* NOTREACHED */ 1706 } 1707 if (ferror(fin)) { 1708 perror_reply(551, filename); 1709 (void) ftpd_pclose(fin); 1710 return; 1711 } 1712 (void) putc('\r', stdout); 1713 } 1714 if (atstart && isdigit(c)) 1715 (void) putc(' ', stdout); 1716 (void) putc(c, stdout); 1717 atstart = (c == '\n'); 1718 } 1719 (void) ftpd_pclose(fin); 1720 reply(211, "End of Status"); 1721 } 1722 1723 void 1724 statcmd() 1725 { 1726 union sockunion *su; 1727 u_char *a, *p; 1728 char hbuf[MAXHOSTNAMELEN]; 1729 int ispassive; 1730 1731 lreply(211, "%s FTP server status:", hostname, version); 1732 printf(" %s\r\n", version); 1733 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1734 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST); 1735 printf(" Connected to %s", remotehost); 1736 if (strcmp(remotehost, hbuf) != 0) 1737 printf(" (%s)", hbuf); 1738 printf("\r\n"); 1739 if (logged_in) { 1740 if (guest) 1741 printf(" Logged in anonymously\r\n"); 1742 else 1743 printf(" Logged in as %s\r\n", pw->pw_name); 1744 } else if (askpasswd) 1745 printf(" Waiting for password\r\n"); 1746 else 1747 printf(" Waiting for user name\r\n"); 1748 printf(" TYPE: %s", typenames[type]); 1749 if (type == TYPE_A || type == TYPE_E) 1750 printf(", FORM: %s", formnames[form]); 1751 if (type == TYPE_L) 1752 #if NBBY == 8 1753 printf(" %d", NBBY); 1754 #else 1755 printf(" %d", bytesize); /* need definition! */ 1756 #endif 1757 printf("; STRUcture: %s; transfer MODE: %s\r\n", 1758 strunames[stru], modenames[mode]); 1759 ispassive = 0; 1760 if (data != -1) 1761 printf(" Data connection open\r\n"); 1762 else if (pdata != -1) { 1763 printf(" in Passive mode\r\n"); 1764 su = (union sockunion *)&pasv_addr; 1765 ispassive++; 1766 goto printaddr; 1767 } else if (usedefault == 0) { 1768 su = (union sockunion *)&data_dest; 1769 printaddr: 1770 /* PASV/PORT */ 1771 if (su->su_family == AF_INET) { 1772 if (ispassive) 1773 printf("211- PASV "); 1774 else 1775 printf("211- PORT "); 1776 a = (u_char *) &su->su_sin.sin_addr; 1777 p = (u_char *) &su->su_sin.sin_port; 1778 printf("(%u,%u,%u,%u,%u,%u)\r\n", 1779 a[0], a[1], a[2], a[3], 1780 p[0], p[1]); 1781 } 1782 1783 /* LPSV/LPRT */ 1784 { 1785 int alen, af, i; 1786 1787 alen = 0; 1788 switch (su->su_family) { 1789 case AF_INET: 1790 a = (u_char *) &su->su_sin.sin_addr; 1791 p = (u_char *) &su->su_sin.sin_port; 1792 alen = sizeof(su->su_sin.sin_addr); 1793 af = 4; 1794 break; 1795 case AF_INET6: 1796 a = (u_char *) &su->su_sin6.sin6_addr; 1797 p = (u_char *) &su->su_sin6.sin6_port; 1798 alen = sizeof(su->su_sin6.sin6_addr); 1799 af = 6; 1800 break; 1801 default: 1802 af = 0; 1803 break; 1804 } 1805 if (af) { 1806 if (ispassive) 1807 printf("211- LPSV "); 1808 else 1809 printf("211- LPRT "); 1810 printf("(%u,%u", af, alen); 1811 for (i = 0; i < alen; i++) 1812 printf(",%u", a[i]); 1813 printf(",%u,%u,%u)\r\n", 2, p[0], p[1]); 1814 } 1815 } 1816 1817 /* EPRT/EPSV */ 1818 { 1819 u_char af; 1820 1821 switch (su->su_family) { 1822 case AF_INET: 1823 af = 1; 1824 break; 1825 case AF_INET6: 1826 af = 2; 1827 break; 1828 default: 1829 af = 0; 1830 break; 1831 } 1832 if (af) { 1833 char hbuf[MAXHOSTNAMELEN], pbuf[10]; 1834 if (getnameinfo((struct sockaddr *)su, su->su_len, 1835 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), 1836 NI_NUMERICHOST) == 0) { 1837 if (ispassive) 1838 printf("211- EPSV "); 1839 else 1840 printf("211- EPRT "); 1841 printf("(|%u|%s|%s|)\r\n", 1842 af, hbuf, pbuf); 1843 } 1844 } 1845 } 1846 } else 1847 printf(" No data connection\r\n"); 1848 reply(211, "End of status"); 1849 } 1850 1851 void 1852 fatal(s) 1853 char *s; 1854 { 1855 1856 reply(451, "Error in server: %s\n", s); 1857 reply(221, "Closing connection due to server error."); 1858 dologout(0); 1859 /* NOTREACHED */ 1860 } 1861 1862 void 1863 #ifdef __STDC__ 1864 reply(int n, const char *fmt, ...) 1865 #else 1866 reply(n, fmt, va_alist) 1867 int n; 1868 char *fmt; 1869 va_dcl 1870 #endif 1871 { 1872 char *buf, *p, *next; 1873 va_list ap; 1874 #ifdef __STDC__ 1875 va_start(ap, fmt); 1876 #else 1877 va_start(ap); 1878 #endif 1879 if (vasprintf(&buf, fmt, ap) == -1 || buf == NULL) { 1880 printf("412 Local resource failure: malloc\r\n"); 1881 fflush(stdout); 1882 dologout(1); 1883 } 1884 next = buf; 1885 while ((p = strsep(&next, "\n\r"))) { 1886 printf("%d%s %s\r\n", n, (next != '\0') ? "-" : "", p); 1887 if (debug) 1888 syslog(LOG_DEBUG, "<--- %d%s %s", n, 1889 (next != '\0') ? "-" : "", p); 1890 } 1891 (void)fflush(stdout); 1892 free(buf); 1893 va_end(ap); 1894 } 1895 1896 void 1897 #ifdef __STDC__ 1898 lreply(int n, const char *fmt, ...) 1899 #else 1900 lreply(n, fmt, va_alist) 1901 int n; 1902 char *fmt; 1903 va_dcl 1904 #endif 1905 { 1906 va_list ap; 1907 #ifdef __STDC__ 1908 va_start(ap, fmt); 1909 #else 1910 va_start(ap); 1911 #endif 1912 (void)printf("%d- ", n); 1913 (void)vprintf(fmt, ap); 1914 va_end(ap); 1915 (void)printf("\r\n"); 1916 (void)fflush(stdout); 1917 if (debug) { 1918 #ifdef __STDC__ 1919 va_start(ap, fmt); 1920 #else 1921 va_start(ap); 1922 #endif 1923 syslog(LOG_DEBUG, "<--- %d- ", n); 1924 vsyslog(LOG_DEBUG, fmt, ap); 1925 va_end(ap); 1926 } 1927 } 1928 1929 static void 1930 ack(s) 1931 char *s; 1932 { 1933 1934 reply(250, "%s command successful.", s); 1935 } 1936 1937 void 1938 nack(s) 1939 char *s; 1940 { 1941 1942 reply(502, "%s command not implemented.", s); 1943 } 1944 1945 /* ARGSUSED */ 1946 void 1947 yyerror(s) 1948 char *s; 1949 { 1950 char *cp; 1951 1952 if ((cp = strchr(cbuf,'\n'))) 1953 *cp = '\0'; 1954 reply(500, "'%s': command not understood.", cbuf); 1955 } 1956 1957 void 1958 delete(name) 1959 char *name; 1960 { 1961 struct stat st; 1962 1963 LOGCMD("delete", name); 1964 if (stat(name, &st) < 0) { 1965 perror_reply(550, name); 1966 return; 1967 } 1968 if ((st.st_mode&S_IFMT) == S_IFDIR) { 1969 if (rmdir(name) < 0) { 1970 perror_reply(550, name); 1971 return; 1972 } 1973 goto done; 1974 } 1975 if (unlink(name) < 0) { 1976 perror_reply(550, name); 1977 return; 1978 } 1979 done: 1980 ack("DELE"); 1981 } 1982 1983 void 1984 cwd(path) 1985 char *path; 1986 { 1987 FILE *message; 1988 1989 if (chdir(path) < 0) 1990 perror_reply(550, path); 1991 else { 1992 if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) { 1993 char *cp, line[LINE_MAX]; 1994 1995 while (fgets(line, sizeof(line), message) != NULL) { 1996 if ((cp = strchr(line, '\n')) != NULL) 1997 *cp = '\0'; 1998 lreply(250, "%s", line); 1999 } 2000 (void) fflush(stdout); 2001 (void) fclose(message); 2002 } 2003 ack("CWD"); 2004 } 2005 } 2006 2007 void 2008 replydirname(name, message) 2009 const char *name, *message; 2010 { 2011 char *p, *ep; 2012 char npath[MAXPATHLEN * 2]; 2013 2014 p = npath; 2015 ep = &npath[sizeof(npath) - 1]; 2016 while (*name) { 2017 if (*name == '"') { 2018 if (ep - p < 2) 2019 break; 2020 *p++ = *name++; 2021 *p++ = '"'; 2022 } else { 2023 if (ep - p < 1) 2024 break; 2025 *p++ = *name++; 2026 } 2027 } 2028 *p = '\0'; 2029 reply(257, "\"%s\" %s", npath, message); 2030 } 2031 2032 void 2033 makedir(name) 2034 char *name; 2035 { 2036 2037 LOGCMD("mkdir", name); 2038 if (mkdir(name, 0777) < 0) 2039 perror_reply(550, name); 2040 else 2041 replydirname(name, "directory created."); 2042 } 2043 2044 void 2045 removedir(name) 2046 char *name; 2047 { 2048 2049 LOGCMD("rmdir", name); 2050 if (rmdir(name) < 0) 2051 perror_reply(550, name); 2052 else 2053 ack("RMD"); 2054 } 2055 2056 void 2057 pwd() 2058 { 2059 char path[MAXPATHLEN]; 2060 2061 if (getcwd(path, sizeof(path)) == NULL) 2062 reply(550, "Can't get current directory: %s.", strerror(errno)); 2063 else 2064 replydirname(path, "is current directory."); 2065 } 2066 2067 char * 2068 renamefrom(name) 2069 char *name; 2070 { 2071 struct stat st; 2072 2073 if (stat(name, &st) < 0) { 2074 perror_reply(550, name); 2075 return ((char *)0); 2076 } 2077 reply(350, "File exists, ready for destination name"); 2078 return (name); 2079 } 2080 2081 void 2082 renamecmd(from, to) 2083 char *from, *to; 2084 { 2085 2086 LOGCMD2("rename", from, to); 2087 if (rename(from, to) < 0) 2088 perror_reply(550, "rename"); 2089 else 2090 ack("RNTO"); 2091 } 2092 2093 static void 2094 dolog(sa) 2095 struct sockaddr *sa; 2096 { 2097 char hbuf[sizeof(remotehost)]; 2098 2099 getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0); 2100 (void) strlcpy(remotehost, hbuf, sizeof(remotehost)); 2101 2102 #ifdef HASSETPROCTITLE 2103 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); 2104 setproctitle("%s", proctitle); 2105 #endif /* HASSETPROCTITLE */ 2106 2107 if (logging) 2108 syslog(LOG_INFO, "connection from %s", remotehost); 2109 } 2110 2111 /* 2112 * Record logout in wtmp file and exit with supplied status. 2113 * NOTE: because this is called from signal handlers it cannot 2114 * use stdio (or call other functions that use stdio). 2115 */ 2116 void 2117 dologout(status) 2118 int status; 2119 { 2120 2121 transflag = 0; 2122 2123 if (logged_in) { 2124 sigprocmask(SIG_BLOCK, &allsigs, NULL); 2125 (void) seteuid((uid_t)0); 2126 ftpdlogwtmp(ttyline, "", ""); 2127 if (doutmp) 2128 logout(utmp.ut_line); 2129 } 2130 /* beware of flushing buffers after a SIGPIPE */ 2131 _exit(status); 2132 } 2133 2134 static void 2135 sigurg(signo) 2136 int signo; 2137 { 2138 2139 recvurg = 1; 2140 } 2141 2142 static void 2143 myoob() 2144 { 2145 char *cp; 2146 2147 /* only process if transfer occurring */ 2148 if (!transflag) 2149 return; 2150 cp = tmpline; 2151 if (getline(cp, 7, stdin) == NULL) { 2152 reply(221, "You could at least say goodbye."); 2153 dologout(0); 2154 } 2155 upper(cp); 2156 if (strcmp(cp, "ABOR\r\n") == 0) { 2157 tmpline[0] = '\0'; 2158 reply(426, "Transfer aborted. Data connection closed."); 2159 reply(226, "Abort successful"); 2160 } 2161 if (strcmp(cp, "STAT\r\n") == 0) { 2162 tmpline[0] = '\0'; 2163 if (file_size != (off_t) -1) 2164 reply(213, "Status: %qd of %qd bytes transferred", 2165 byte_count, file_size); 2166 else 2167 reply(213, "Status: %qd bytes transferred", byte_count); 2168 } 2169 } 2170 2171 /* 2172 * Note: a response of 425 is not mentioned as a possible response to 2173 * the PASV command in RFC959. However, it has been blessed as 2174 * a legitimate response by Jon Postel in a telephone conversation 2175 * with Rick Adams on 25 Jan 89. 2176 */ 2177 void 2178 passive() 2179 { 2180 int len, on; 2181 u_char *p, *a; 2182 2183 if (pw == NULL) { 2184 reply(530, "Please login with USER and PASS"); 2185 return; 2186 } 2187 if (pdata >= 0) 2188 close(pdata); 2189 /* 2190 * XXX 2191 * At this point, it would be nice to have an algorithm that 2192 * inserted a growing delay in an attack scenario. Such a thing 2193 * would look like continual passive sockets being opened, but 2194 * nothing serious being done with them. They're not used to 2195 * move data; the entire attempt is just to use tcp FIN_WAIT 2196 * resources. 2197 */ 2198 pdata = socket(AF_INET, SOCK_STREAM, 0); 2199 if (pdata < 0) { 2200 perror_reply(425, "Can't open passive connection"); 2201 return; 2202 } 2203 2204 #ifdef IP_PORTRANGE 2205 on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; 2206 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2207 (char *)&on, sizeof(on)) < 0) 2208 goto pasv_error; 2209 #endif 2210 2211 pasv_addr = ctrl_addr; 2212 pasv_addr.su_sin.sin_port = 0; 2213 if (bind(pdata, (struct sockaddr *)&pasv_addr, 2214 pasv_addr.su_len) < 0) 2215 goto pasv_error; 2216 2217 len = sizeof(pasv_addr); 2218 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2219 goto pasv_error; 2220 if (listen(pdata, 1) < 0) 2221 goto pasv_error; 2222 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2223 p = (u_char *) &pasv_addr.su_sin.sin_port; 2224 2225 reply(227, "Entering Passive Mode (%u,%u,%u,%u,%u,%u)", a[0], 2226 a[1], a[2], a[3], p[0], p[1]); 2227 return; 2228 2229 pasv_error: 2230 (void) seteuid((uid_t)pw->pw_uid); 2231 (void) close(pdata); 2232 pdata = -1; 2233 perror_reply(425, "Can't open passive connection"); 2234 return; 2235 } 2236 2237 /* 2238 * convert protocol identifier to/from AF 2239 */ 2240 int 2241 lpsvproto2af(int proto) 2242 { 2243 2244 switch (proto) { 2245 case 4: return AF_INET; 2246 #ifdef INET6 2247 case 6: return AF_INET6; 2248 #endif 2249 default: return -1; 2250 } 2251 } 2252 2253 int 2254 af2lpsvproto(int af) 2255 { 2256 2257 switch (af) { 2258 case AF_INET: return 4; 2259 #ifdef INET6 2260 case AF_INET6: return 6; 2261 #endif 2262 default: return -1; 2263 } 2264 } 2265 2266 int 2267 epsvproto2af(int proto) 2268 { 2269 2270 switch (proto) { 2271 case 1: return AF_INET; 2272 #ifdef INET6 2273 case 2: return AF_INET6; 2274 #endif 2275 default: return -1; 2276 } 2277 } 2278 2279 int 2280 af2epsvproto(int af) 2281 { 2282 2283 switch (af) { 2284 case AF_INET: return 1; 2285 #ifdef INET6 2286 case AF_INET6: return 2; 2287 #endif 2288 default: return -1; 2289 } 2290 } 2291 2292 /* 2293 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...) 2294 * 229 Entering Extended Passive Mode (|||port|) 2295 */ 2296 void 2297 long_passive(char *cmd, int pf) 2298 { 2299 int len, on; 2300 u_char *p, *a; 2301 2302 if (!logged_in) { 2303 syslog(LOG_NOTICE, "long passive but not logged in"); 2304 reply(503, "Login with USER first."); 2305 return; 2306 } 2307 2308 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) { 2309 /* 2310 * XXX 2311 * only EPRT/EPSV ready clients will understand this 2312 */ 2313 if (strcmp(cmd, "EPSV") != 0) 2314 reply(501, "Network protocol mismatch"); /*XXX*/ 2315 else 2316 epsv_protounsupp("Network protocol mismatch"); 2317 2318 return; 2319 } 2320 2321 if (pdata >= 0) 2322 close(pdata); 2323 /* 2324 * XXX 2325 * At this point, it would be nice to have an algorithm that 2326 * inserted a growing delay in an attack scenario. Such a thing 2327 * would look like continual passive sockets being opened, but 2328 * nothing serious being done with them. They not used to move 2329 * data; the entire attempt is just to use tcp FIN_WAIT 2330 * resources. 2331 */ 2332 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2333 if (pdata < 0) { 2334 perror_reply(425, "Can't open passive connection"); 2335 return; 2336 } 2337 2338 switch (ctrl_addr.su_family) { 2339 case AF_INET: 2340 #ifdef IP_PORTRANGE 2341 on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; 2342 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2343 (char *)&on, sizeof(on)) < 0) 2344 goto pasv_error; 2345 #endif 2346 break; 2347 case AF_INET6: 2348 #ifdef IPV6_PORTRANGE 2349 on = high_data_ports ? IPV6_PORTRANGE_HIGH 2350 : IPV6_PORTRANGE_DEFAULT; 2351 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2352 (char *)&on, sizeof(on)) < 0) 2353 goto pasv_error; 2354 #endif 2355 break; 2356 } 2357 2358 pasv_addr = ctrl_addr; 2359 pasv_addr.su_port = 0; 2360 (void) seteuid((uid_t) 0); 2361 if (bind(pdata, (struct sockaddr *) &pasv_addr, pasv_addr.su_len) < 0) { 2362 (void) seteuid((uid_t) pw->pw_uid); 2363 goto pasv_error; 2364 } 2365 (void) seteuid((uid_t) pw->pw_uid); 2366 len = pasv_addr.su_len; 2367 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2368 goto pasv_error; 2369 if (listen(pdata, 1) < 0) 2370 goto pasv_error; 2371 p = (u_char *) &pasv_addr.su_port; 2372 2373 if (strcmp(cmd, "LPSV") == 0) { 2374 switch (pasv_addr.su_family) { 2375 case AF_INET: 2376 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2377 reply(228, 2378 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2379 4, 4, a[0], a[1], a[2], a[3], 2, p[0], p[1]); 2380 return; 2381 case AF_INET6: 2382 a = (char *) &pasv_addr.su_sin6.sin6_addr; 2383 reply(228, 2384 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u," 2385 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2386 6, 16, a[0], a[1], a[2], a[3], a[4], 2387 a[5], a[6], a[7], a[8], a[9], a[10], 2388 a[11], a[12], a[13], a[14], a[15], 2389 2, p[0], p[1]); 2390 return; 2391 } 2392 } else if (strcmp(cmd, "EPSV") == 0) { 2393 switch (pasv_addr.su_family) { 2394 case AF_INET: 2395 case AF_INET6: 2396 reply(229, "Entering Extended Passive Mode (|||%u|)", 2397 ntohs(pasv_addr.su_port)); 2398 return; 2399 } 2400 } else { 2401 /* more proper error code? */ 2402 } 2403 2404 pasv_error: 2405 (void) close(pdata); 2406 pdata = -1; 2407 perror_reply(425, "Can't open passive connection"); 2408 return; 2409 } 2410 2411 /* 2412 * EPRT |proto|addr|port| 2413 */ 2414 int 2415 extended_port(const char *arg) 2416 { 2417 char *tmp = NULL; 2418 char *result[3]; 2419 char *p, *q; 2420 char delim; 2421 struct addrinfo hints; 2422 struct addrinfo *res = NULL; 2423 int i; 2424 unsigned long proto; 2425 2426 if (epsvall) { 2427 reply(501, "EPRT disallowed after EPSV ALL"); 2428 return -1; 2429 } 2430 2431 usedefault = 0; 2432 if (pdata >= 0) { 2433 (void) close(pdata); 2434 pdata = -1; 2435 } 2436 2437 tmp = strdup(arg); 2438 if (!tmp) { 2439 fatal("not enough core."); 2440 /*NOTREACHED*/ 2441 } 2442 p = tmp; 2443 delim = p[0]; 2444 p++; 2445 memset(result, 0, sizeof(result)); 2446 for (i = 0; i < 3; i++) { 2447 q = strchr(p, delim); 2448 if (!q || *q != delim) 2449 goto parsefail; 2450 *q++ = '\0'; 2451 result[i] = p; 2452 p = q; 2453 } 2454 2455 /* some more sanity check */ 2456 p = NULL; 2457 (void)strtoul(result[2], &p, 10); 2458 if (!*result[2] || *p) 2459 goto protounsupp; 2460 p = NULL; 2461 proto = strtoul(result[0], &p, 10); 2462 if (!*result[0] || *p) 2463 goto protounsupp; 2464 2465 memset(&hints, 0, sizeof(hints)); 2466 hints.ai_family = epsvproto2af((int)proto); 2467 if (hints.ai_family < 0) 2468 goto protounsupp; 2469 hints.ai_socktype = SOCK_STREAM; 2470 hints.ai_flags = AI_NUMERICHOST; /*no DNS*/ 2471 if (getaddrinfo(result[1], result[2], &hints, &res)) 2472 goto parsefail; 2473 if (res->ai_next) 2474 goto parsefail; 2475 if (sizeof(data_dest) < res->ai_addrlen) 2476 goto parsefail; 2477 memcpy(&data_dest, res->ai_addr, res->ai_addrlen); 2478 if (his_addr.su_family == AF_INET6 && 2479 data_dest.su_family == AF_INET6) { 2480 /* XXX more sanity checks! */ 2481 data_dest.su_sin6.sin6_scope_id = 2482 his_addr.su_sin6.sin6_scope_id; 2483 } 2484 if (pdata >= 0) { 2485 (void) close(pdata); 2486 pdata = -1; 2487 } 2488 reply(200, "EPRT command successful."); 2489 2490 if (tmp) 2491 free(tmp); 2492 if (res) 2493 freeaddrinfo(res); 2494 return 0; 2495 2496 parsefail: 2497 reply(500, "Invalid argument, rejected."); 2498 usedefault = 1; 2499 if (tmp) 2500 free(tmp); 2501 if (res) 2502 freeaddrinfo(res); 2503 return -1; 2504 2505 protounsupp: 2506 epsv_protounsupp("Protocol not supported"); 2507 usedefault = 1; 2508 if (tmp) 2509 free(tmp); 2510 if (res) 2511 freeaddrinfo(res); 2512 return -1; 2513 } 2514 2515 /* 2516 * 522 Protocol not supported (proto,...) 2517 * as we assume address family for control and data connections are the same, 2518 * we do not return the list of address families we support - instead, we 2519 * return the address family of the control connection. 2520 */ 2521 void 2522 epsv_protounsupp(const char *message) 2523 { 2524 int proto; 2525 2526 proto = af2epsvproto(ctrl_addr.su_family); 2527 if (proto < 0) 2528 reply(501, "%s", message); /*XXX*/ 2529 else 2530 reply(522, "%s, use (%d)", message, proto); 2531 } 2532 2533 /* 2534 * Generate unique name for file with basename "local". 2535 * The file named "local" is already known to exist. 2536 * Generates failure reply on error. 2537 */ 2538 static int 2539 guniquefd(local, nam) 2540 char *local; 2541 char **nam; 2542 { 2543 static char new[MAXPATHLEN]; 2544 struct stat st; 2545 int count, len, fd; 2546 char *cp; 2547 2548 cp = strrchr(local, '/'); 2549 if (cp) 2550 *cp = '\0'; 2551 if (stat(cp ? local : ".", &st) < 0) { 2552 perror_reply(553, cp ? local : "."); 2553 return (-1); 2554 } 2555 if (cp) 2556 *cp = '/'; 2557 len = strlcpy(new, local, sizeof(new)); 2558 if (len+2+1 >= sizeof(new)-1) 2559 return (-1); 2560 cp = new + len; 2561 *cp++ = '.'; 2562 for (count = 1; count < 100; count++) { 2563 (void)snprintf(cp, sizeof(new) - (cp - new), "%d", count); 2564 fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666); 2565 if (fd == -1) 2566 continue; 2567 if (nam) 2568 *nam = new; 2569 return (fd); 2570 } 2571 reply(452, "Unique file name cannot be created."); 2572 return (-1); 2573 } 2574 2575 /* 2576 * Format and send reply containing system error number. 2577 */ 2578 void 2579 perror_reply(code, string) 2580 int code; 2581 char *string; 2582 { 2583 2584 reply(code, "%s: %s.", string, strerror(errno)); 2585 } 2586 2587 static char *onefile[] = { 2588 "", 2589 0 2590 }; 2591 2592 void 2593 send_file_list(whichf) 2594 char *whichf; 2595 { 2596 struct stat st; 2597 DIR *dirp = NULL; 2598 struct dirent *dir; 2599 FILE *dout = NULL; 2600 char **dirlist; 2601 char *dirname; 2602 int simple = 0; 2603 volatile int freeglob = 0; 2604 glob_t gl; 2605 2606 if (strpbrk(whichf, "~{[*?") != NULL) { 2607 memset(&gl, 0, sizeof(gl)); 2608 freeglob = 1; 2609 if (glob(whichf, 2610 GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|GLOB_LIMIT, 2611 0, &gl)) { 2612 reply(550, "not found"); 2613 goto out; 2614 } else if (gl.gl_pathc == 0) { 2615 errno = ENOENT; 2616 perror_reply(550, whichf); 2617 goto out; 2618 } 2619 dirlist = gl.gl_pathv; 2620 } else { 2621 onefile[0] = whichf; 2622 dirlist = onefile; 2623 simple = 1; 2624 } 2625 2626 while ((dirname = *dirlist++)) { 2627 if (stat(dirname, &st) < 0) { 2628 /* 2629 * If user typed "ls -l", etc, and the client 2630 * used NLST, do what the user meant. 2631 */ 2632 if (dirname[0] == '-' && *dirlist == NULL && 2633 transflag == 0) { 2634 retrieve("/bin/ls %s", dirname); 2635 goto out; 2636 } 2637 perror_reply(550, whichf); 2638 if (dout != NULL) { 2639 (void) fclose(dout); 2640 transflag = 0; 2641 data = -1; 2642 pdata = -1; 2643 } 2644 goto out; 2645 } 2646 2647 if (S_ISREG(st.st_mode)) { 2648 if (dout == NULL) { 2649 dout = dataconn("file list", (off_t)-1, "w"); 2650 if (dout == NULL) 2651 goto out; 2652 transflag++; 2653 } 2654 fprintf(dout, "%s%s\n", dirname, 2655 type == TYPE_A ? "\r" : ""); 2656 byte_count += strlen(dirname) + 1; 2657 continue; 2658 } else if (!S_ISDIR(st.st_mode)) 2659 continue; 2660 2661 if ((dirp = opendir(dirname)) == NULL) 2662 continue; 2663 2664 while ((dir = readdir(dirp)) != NULL) { 2665 char nbuf[MAXPATHLEN]; 2666 2667 if (recvurg) { 2668 myoob(); 2669 recvurg = 0; 2670 transflag = 0; 2671 goto out; 2672 } 2673 2674 if (dir->d_name[0] == '.' && dir->d_namlen == 1) 2675 continue; 2676 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 2677 dir->d_namlen == 2) 2678 continue; 2679 2680 snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, 2681 dir->d_name); 2682 2683 /* 2684 * We have to do a stat to insure it's 2685 * not a directory or special file. 2686 */ 2687 if (simple || (stat(nbuf, &st) == 0 && 2688 S_ISREG(st.st_mode))) { 2689 if (dout == NULL) { 2690 dout = dataconn("file list", (off_t)-1, 2691 "w"); 2692 if (dout == NULL) 2693 goto out; 2694 transflag++; 2695 } 2696 if (nbuf[0] == '.' && nbuf[1] == '/') 2697 fprintf(dout, "%s%s\n", &nbuf[2], 2698 type == TYPE_A ? "\r" : ""); 2699 else 2700 fprintf(dout, "%s%s\n", nbuf, 2701 type == TYPE_A ? "\r" : ""); 2702 byte_count += strlen(nbuf) + 1; 2703 } 2704 } 2705 (void) closedir(dirp); 2706 } 2707 2708 if (dout == NULL) 2709 reply(550, "No files found."); 2710 else if (ferror(dout) != 0) 2711 perror_reply(550, "Data connection"); 2712 else 2713 reply(226, "Transfer complete."); 2714 2715 transflag = 0; 2716 if (dout != NULL) 2717 (void) fclose(dout); 2718 else { 2719 if (pdata >= 0) 2720 close(pdata); 2721 } 2722 data = -1; 2723 pdata = -1; 2724 out: 2725 if (freeglob) { 2726 freeglob = 0; 2727 globfree(&gl); 2728 } 2729 } 2730 2731 static void 2732 reapchild(signo) 2733 int signo; 2734 { 2735 int save_errno = errno; 2736 int rval; 2737 2738 do { 2739 rval = waitpid(-1, NULL, WNOHANG); 2740 } while (rval > 0 || (rval == -1 && errno == EINTR)); 2741 errno = save_errno; 2742 } 2743 2744 void 2745 logxfer(name, size, start) 2746 char *name; 2747 off_t size; 2748 time_t start; 2749 { 2750 char buf[400 + MAXHOSTNAMELEN*4 + MAXPATHLEN*4]; 2751 char dir[MAXPATHLEN], path[MAXPATHLEN], rpath[MAXPATHLEN]; 2752 char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4]; 2753 char *vpw; 2754 time_t now; 2755 int len; 2756 2757 if ((statfd >= 0) && (getcwd(dir, sizeof(dir)) != NULL)) { 2758 time(&now); 2759 2760 vpw = malloc(strlen(guest ? guestpw : pw->pw_name) * 4 + 1); 2761 if (vpw == NULL) 2762 return; 2763 2764 snprintf(path, sizeof(path), "%s/%s", dir, name); 2765 if (realpath(path, rpath) == NULL) 2766 strlcpy(rpath, path, sizeof(rpath)); 2767 strvis(vpath, rpath, VIS_SAFE|VIS_NOSLASH); 2768 2769 strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH); 2770 strvis(vpw, guest? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH); 2771 2772 len = snprintf(buf, sizeof(buf), 2773 "%.24s %d %s %qd %s %c %s %c %c %s ftp %d %s %s\n", 2774 ctime(&now), now - start + (now == start), 2775 vremotehost, (long long) size, vpath, 2776 ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */, 2777 'o', ((guest) ? 'a' : 'r'), 2778 vpw, 0 /* none yet */, 2779 ((guest) ? "*" : pw->pw_name), dhostname); 2780 if (len >= sizeof(buf)) { 2781 len = sizeof(buf); 2782 buf[sizeof(buf) - 1] = '\n'; 2783 } 2784 write(statfd, buf, len); 2785 free(vpw); 2786 } 2787 } 2788 2789 #if defined(TCPWRAPPERS) 2790 static int 2791 check_host(sa) 2792 struct sockaddr *sa; 2793 { 2794 struct sockaddr_in *sin; 2795 struct hostent *hp; 2796 char *addr; 2797 2798 if (sa->sa_family != AF_INET) 2799 return 1; /*XXX*/ 2800 2801 sin = (struct sockaddr_in *)sa; 2802 hp = gethostbyaddr((char *)&sin->sin_addr, 2803 sizeof(struct in_addr), AF_INET); 2804 addr = inet_ntoa(sin->sin_addr); 2805 if (hp) { 2806 if (!hosts_ctl("ftpd", hp->h_name, addr, STRING_UNKNOWN)) { 2807 syslog(LOG_NOTICE, "tcpwrappers rejected: %s [%s]", 2808 hp->h_name, addr); 2809 return (0); 2810 } 2811 } else { 2812 if (!hosts_ctl("ftpd", STRING_UNKNOWN, addr, STRING_UNKNOWN)) { 2813 syslog(LOG_NOTICE, "tcpwrappers rejected: [%s]", addr); 2814 return (0); 2815 } 2816 } 2817 return (1); 2818 } 2819 #endif /* TCPWRAPPERS */ 2820 2821 /* 2822 * Allocate space and return a copy of the specified dir. 2823 * If 'dir' begins with a tilde (~), expand it. 2824 */ 2825 char * 2826 copy_dir(dir, pw) 2827 char *dir; 2828 struct passwd *pw; 2829 { 2830 char *cp; 2831 char *newdir; 2832 char *user = NULL; 2833 size_t dirsiz; 2834 2835 /* Nothing to expand */ 2836 if (dir[0] != '~') 2837 return (strdup(dir)); 2838 2839 /* "dir" is of form ~user/some/dir, lookup user. */ 2840 if (dir[1] != '/' && dir[1] != '\0') { 2841 if ((cp = strchr(dir + 1, '/')) == NULL) 2842 cp = dir + strlen(dir); 2843 if ((user = malloc(cp - dir)) == NULL) 2844 return (NULL); 2845 strlcpy(user, dir + 1, cp - dir); 2846 2847 /* Only do lookup if it is a different user. */ 2848 if (strcmp(user, pw->pw_name) != 0) { 2849 if ((pw = getpwnam(user)) == NULL) { 2850 /* No such user, interpret literally */ 2851 free(user); 2852 return(strdup(dir)); 2853 } 2854 } 2855 } 2856 2857 /* 2858 * If there is no directory separator (/) then it is just pw_dir. 2859 * Otherwise, replace ~foo with pw_dir. 2860 */ 2861 if ((cp = strchr(dir + 1, '/')) == NULL) { 2862 newdir = strdup(pw->pw_dir); 2863 } else { 2864 dirsiz = strlen(cp) + strlen(pw->pw_dir) + 1; 2865 if ((newdir = malloc(dirsiz)) == NULL) 2866 return (NULL); 2867 strcpy(newdir, pw->pw_dir); 2868 strcat(newdir, cp); 2869 } 2870 2871 if (user) 2872 free(user); 2873 return(newdir); 2874 } 2875