ftpd.c revision 1.111
1/* $OpenBSD: ftpd.c,v 1.111 2001/12/17 23:02:53 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 67static 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 74static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94"; 75#else 76static char rcsid[] = "$OpenBSD: ftpd.c,v 1.111 2001/12/17 23:02:53 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 135static char version[] = "Version 6.5/OpenBSD"; 136 137extern off_t restart_point; 138extern char cbuf[]; 139 140union sockunion server_addr; 141union sockunion ctrl_addr; 142union sockunion data_source; 143union sockunion data_dest; 144union sockunion his_addr; 145union sockunion pasv_addr; 146 147sigset_t allsigs; 148 149int daemon_mode = 0; 150int data; 151int logged_in; 152struct passwd *pw; 153int debug = 0; 154int timeout = 900; /* timeout after 15 minutes of inactivity */ 155int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ 156int logging; 157int high_data_ports = 0; 158int anon_only = 0; 159int multihome = 0; 160int guest; 161int stats; 162int statfd = -1; 163int portcheck = 1; 164int dochroot; 165int type; 166int form; 167int stru; /* avoid C keyword */ 168int mode; 169int doutmp = 0; /* update utmp file */ 170int usedefault = 1; /* for data transfers */ 171int pdata = -1; /* for passive mode */ 172int family = AF_INET; 173volatile sig_atomic_t transflag; 174off_t file_size; 175off_t byte_count; 176#if !defined(CMASK) || CMASK == 0 177#undef CMASK 178#define CMASK 022 179#endif 180int defumask = CMASK; /* default umask value */ 181int umaskchange = 1; /* allow user to change umask value. */ 182char tmpline[7]; 183char hostname[MAXHOSTNAMELEN]; 184char remotehost[MAXHOSTNAMELEN]; 185char dhostname[MAXHOSTNAMELEN]; 186char *guestpw; 187static char ttyline[20]; 188char *tty = ttyline; /* for klogin */ 189static struct utmp utmp; /* for utmp */ 190static login_cap_t *lc; 191static auth_session_t *as; 192static volatile sig_atomic_t recvurg; 193 194#if defined(TCPWRAPPERS) 195int allow_severity = LOG_INFO; 196int deny_severity = LOG_NOTICE; 197#endif /* TCPWRAPPERS */ 198 199char *ident = NULL; 200 201 202int 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 212int swaitmax = SWAITMAX; 213int swaitint = SWAITINT; 214 215#ifdef HASSETPROCTITLE 216char 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 238static void ack __P((char *)); 239static void sigurg __P((int)); 240static void myoob __P((void)); 241static int checkuser __P((char *, char *)); 242static FILE *dataconn __P((char *, off_t, char *)); 243static void dolog __P((struct sockaddr *)); 244static char *copy_dir __P((char *, struct passwd *)); 245static char *curdir __P((void)); 246static void end_login __P((void)); 247static FILE *getdatasock __P((char *)); 248static int guniquefd __P((char *, char **)); 249static void lostconn __P((int)); 250static void sigquit __P((int)); 251static int receive_data __P((FILE *, FILE *)); 252static void replydirname __P((const char *, const char *)); 253static int send_data __P((FILE *, FILE *, off_t, off_t, int)); 254static struct passwd * 255 sgetpwnam __P((char *)); 256static void reapchild __P((int)); 257static int check_host __P((struct sockaddr *)); 258static void usage __P((void)); 259 260void logxfer __P((char *, off_t, time_t)); 261 262static char * 263curdir() 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 275char *argstr = "AdDhlMSt:T:u:UvP46"; 276 277static void 278usage() 279{ 280 syslog(LOG_ERR, 281 "usage: ftpd [-AdDhlMSUv] [-t timeout] [-T maxtimeout] [-u mask]"); 282 exit(2); 283} 284 285int 286main(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 = sigquit; 488 (void) sigaction(SIGHUP, &sa, NULL); 489 (void) sigaction(SIGINT, &sa, NULL); 490 (void) sigaction(SIGQUIT, &sa, NULL); 491 (void) sigaction(SIGTERM, &sa, NULL); 492 493 sa.sa_handler = lostconn; 494 (void) sigaction(SIGPIPE, &sa, NULL); 495 496 sa.sa_handler = SIG_IGN; 497 (void) sigaction(SIGCHLD, &sa, NULL); 498 499 sa.sa_handler = sigurg; 500 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */ 501 (void) sigaction(SIGURG, &sa, NULL); 502 503 addrlen = sizeof(ctrl_addr); 504 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { 505 syslog(LOG_ERR, "getsockname: %m"); 506 exit(1); 507 } 508 if (his_addr.su_family == AF_INET6 509 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) { 510#if 1 511 /* 512 * IPv4 control connection arrived to AF_INET6 socket. 513 * I hate to do this, but this is the easiest solution. 514 */ 515 union sockunion tmp_addr; 516 const int off = sizeof(struct in6_addr) - sizeof(struct in_addr); 517 518 tmp_addr = his_addr; 519 memset(&his_addr, 0, sizeof(his_addr)); 520 his_addr.su_sin.sin_family = AF_INET; 521 his_addr.su_sin.sin_len = sizeof(his_addr.su_sin); 522 memcpy(&his_addr.su_sin.sin_addr, 523 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 524 sizeof(his_addr.su_sin.sin_addr)); 525 his_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 526 527 tmp_addr = ctrl_addr; 528 memset(&ctrl_addr, 0, sizeof(ctrl_addr)); 529 ctrl_addr.su_sin.sin_family = AF_INET; 530 ctrl_addr.su_sin.sin_len = sizeof(ctrl_addr.su_sin); 531 memcpy(&ctrl_addr.su_sin.sin_addr, 532 &tmp_addr.su_sin6.sin6_addr.s6_addr[off], 533 sizeof(ctrl_addr.su_sin.sin_addr)); 534 ctrl_addr.su_sin.sin_port = tmp_addr.su_sin6.sin6_port; 535#else 536 while (fgets(line, sizeof(line), fd) != NULL) { 537 if ((cp = strchr(line, '\n')) != NULL) 538 *cp = '\0'; 539 lreply(530, "%s", line); 540 } 541 (void) fflush(stdout); 542 (void) fclose(fd); 543 reply(530, 544 "Connection from IPv4 mapped address is not supported."); 545 exit(0); 546#endif 547 } 548#ifdef IP_TOS 549 if (his_addr.su_family == AF_INET) { 550 tos = IPTOS_LOWDELAY; 551 if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos, 552 sizeof(int)) < 0) 553 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); 554 } 555#endif 556 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1); 557 558 /* Try to handle urgent data inline */ 559#ifdef SO_OOBINLINE 560 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0) 561 syslog(LOG_ERR, "setsockopt: %m"); 562#endif 563 564#ifdef F_SETOWN 565 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) 566 syslog(LOG_ERR, "fcntl F_SETOWN: %m"); 567#endif 568 dolog((struct sockaddr *)&his_addr); 569 /* 570 * Set up default state 571 */ 572 data = -1; 573 type = TYPE_A; 574 form = FORM_N; 575 stru = STRU_F; 576 mode = MODE_S; 577 tmpline[0] = '\0'; 578 579 /* If logins are disabled, print out the message. */ 580 if ((fp = fopen(_PATH_NOLOGIN, "r")) != NULL) { 581 while (fgets(line, sizeof(line), fp) != NULL) { 582 if ((cp = strchr(line, '\n')) != NULL) 583 *cp = '\0'; 584 lreply(530, "%s", line); 585 } 586 (void) fflush(stdout); 587 (void) fclose(fp); 588 reply(530, "System not available."); 589 exit(0); 590 } 591 if ((fp = fopen(_PATH_FTPWELCOME, "r")) != NULL) { 592 while (fgets(line, sizeof(line), fp) != NULL) { 593 if ((cp = strchr(line, '\n')) != NULL) 594 *cp = '\0'; 595 lreply(220, "%s", line); 596 } 597 (void) fflush(stdout); 598 (void) fclose(fp); 599 /* reply(220,) must follow */ 600 } 601 (void) gethostname(hostname, sizeof(hostname)); 602 603 /* Make sure hostname is fully qualified. */ 604 hp = gethostbyname(hostname); 605 if (hp != NULL) 606 strcpy(hostname, hp->h_name); 607 608 if (multihome) { 609 getnameinfo((struct sockaddr *)&ctrl_addr, ctrl_addr.su_len, 610 dhostname, sizeof(dhostname), NULL, 0, 0); 611 } 612 613 reply(220, "%s FTP server (%s) ready.", 614 (multihome ? dhostname : hostname), version); 615 for (;;) 616 (void) yyparse(); 617 /* NOTREACHED */ 618} 619 620/* 621 * Signal handlers. 622 */ 623 624static void 625lostconn(signo) 626 int signo; 627{ 628 struct syslog_data sdata = SYSLOG_DATA_INIT; 629 630 sigprocmask(SIG_BLOCK, &allsigs, NULL); 631 if (debug) 632 syslog_r(LOG_DEBUG, &sdata, "lost connection"); 633 dologout(1); 634} 635 636static void 637sigquit(signo) 638 int signo; 639{ 640 struct syslog_data sdata = SYSLOG_DATA_INIT; 641 642 sigprocmask(SIG_BLOCK, &allsigs, NULL); 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 */ 652static struct passwd * 653sgetpwnam(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 674static int login_attempts; /* number of failed login attempts */ 675static int askpasswd; /* had user command, ask for passwd */ 676static 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 */ 689void 690user(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 */ 809static int 810checkuser(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 */ 838static void 839end_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 858void 859pass(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; 1085bad: 1086 /* Forget all about it... */ 1087 login_close(lc); 1088 lc = NULL; 1089 end_login(); 1090} 1091 1092void 1093retrieve(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; 1157done: 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 1166void 1167store(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; 1241done: 1242 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count); 1243 (*closefunc)(fout); 1244} 1245 1246static FILE * 1247getdatasock(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)); 1302bad: 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 1312static FILE * 1313dataconn(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 */ 1468static int 1469send_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 1541oldway: 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 1566data_err: 1567 transflag = 0; 1568 perror_reply(426, "Data connection"); 1569 return(-1); 1570 1571file_err: 1572 transflag = 0; 1573 perror_reply(551, "Error on input file"); 1574 return(-1); 1575 1576got_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 */ 1589static int 1590receive_data(instr, outstr) 1591 FILE *instr, *outstr; 1592{ 1593 int c; 1594 int cnt; 1595 volatile int bare_lfs = 0; 1596 char buf[BUFSIZ]; 1597 1598 transflag++; 1599 switch (type) { 1600 1601 case TYPE_I: 1602 case TYPE_L: 1603 signal (SIGALRM, lostconn); 1604 1605 do { 1606 (void) alarm ((unsigned) timeout); 1607 cnt = read(fileno(instr), buf, sizeof(buf)); 1608 (void) alarm (0); 1609 if (recvurg) 1610 goto got_oob; 1611 1612 if (cnt > 0) { 1613 if (write(fileno(outstr), buf, cnt) != cnt) 1614 goto file_err; 1615 byte_count += cnt; 1616 } 1617 } while (cnt > 0); 1618 if (cnt < 0) 1619 goto data_err; 1620 transflag = 0; 1621 return (0); 1622 1623 case TYPE_E: 1624 reply(553, "TYPE E not implemented."); 1625 transflag = 0; 1626 return (-1); 1627 1628 case TYPE_A: 1629 while ((c = getc(instr)) != EOF) { 1630 if (recvurg) 1631 goto got_oob; 1632 byte_count++; 1633 if (c == '\n') 1634 bare_lfs++; 1635 while (c == '\r') { 1636 if (ferror(outstr)) 1637 goto data_err; 1638 if ((c = getc(instr)) != '\n') { 1639 (void) putc ('\r', outstr); 1640 if (c == '\0' || c == EOF) 1641 goto contin2; 1642 } 1643 } 1644 (void) putc(c, outstr); 1645 contin2: ; 1646 } 1647 fflush(outstr); 1648 if (ferror(instr)) 1649 goto data_err; 1650 if (ferror(outstr)) 1651 goto file_err; 1652 transflag = 0; 1653 if (bare_lfs) { 1654 lreply(226, 1655 "WARNING! %d bare linefeeds received in ASCII mode", 1656 bare_lfs); 1657 printf(" File may not have transferred correctly.\r\n"); 1658 } 1659 return (0); 1660 default: 1661 reply(550, "Unimplemented TYPE %d in receive_data", type); 1662 transflag = 0; 1663 return (-1); 1664 } 1665 1666data_err: 1667 transflag = 0; 1668 perror_reply(426, "Data Connection"); 1669 return (-1); 1670 1671file_err: 1672 transflag = 0; 1673 perror_reply(452, "Error writing file"); 1674 return (-1); 1675 1676got_oob: 1677 myoob(); 1678 recvurg = 0; 1679 transflag = 0; 1680 return (-1); 1681} 1682 1683void 1684statfilecmd(filename) 1685 char *filename; 1686{ 1687 FILE *fin; 1688 int c; 1689 int atstart; 1690 char line[LINE_MAX]; 1691 1692 (void)snprintf(line, sizeof(line), "/bin/ls -lgA %s", filename); 1693 fin = ftpd_popen(line, "r"); 1694 lreply(211, "status of %s:", filename); 1695 atstart = 1; 1696 while ((c = getc(fin)) != EOF) { 1697 if (c == '\n') { 1698 if (ferror(stdout)){ 1699 perror_reply(421, "control connection"); 1700 (void) ftpd_pclose(fin); 1701 dologout(1); 1702 /* NOTREACHED */ 1703 } 1704 if (ferror(fin)) { 1705 perror_reply(551, filename); 1706 (void) ftpd_pclose(fin); 1707 return; 1708 } 1709 (void) putc('\r', stdout); 1710 } 1711 if (atstart && isdigit(c)) 1712 (void) putc(' ', stdout); 1713 (void) putc(c, stdout); 1714 atstart = (c == '\n'); 1715 } 1716 (void) ftpd_pclose(fin); 1717 reply(211, "End of Status"); 1718} 1719 1720void 1721statcmd() 1722{ 1723 union sockunion *su; 1724 u_char *a, *p; 1725 char hbuf[MAXHOSTNAMELEN]; 1726 int ispassive; 1727 1728 lreply(211, "%s FTP server status:", hostname, version); 1729 printf(" %s\r\n", version); 1730 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, 1731 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST); 1732 printf(" Connected to %s", remotehost); 1733 if (strcmp(remotehost, hbuf) != 0) 1734 printf(" (%s)", hbuf); 1735 printf("\r\n"); 1736 if (logged_in) { 1737 if (guest) 1738 printf(" Logged in anonymously\r\n"); 1739 else 1740 printf(" Logged in as %s\r\n", pw->pw_name); 1741 } else if (askpasswd) 1742 printf(" Waiting for password\r\n"); 1743 else 1744 printf(" Waiting for user name\r\n"); 1745 printf(" TYPE: %s", typenames[type]); 1746 if (type == TYPE_A || type == TYPE_E) 1747 printf(", FORM: %s", formnames[form]); 1748 if (type == TYPE_L) 1749#if NBBY == 8 1750 printf(" %d", NBBY); 1751#else 1752 printf(" %d", bytesize); /* need definition! */ 1753#endif 1754 printf("; STRUcture: %s; transfer MODE: %s\r\n", 1755 strunames[stru], modenames[mode]); 1756 ispassive = 0; 1757 if (data != -1) 1758 printf(" Data connection open\r\n"); 1759 else if (pdata != -1) { 1760 printf(" in Passive mode\r\n"); 1761 su = (union sockunion *)&pasv_addr; 1762 ispassive++; 1763 goto printaddr; 1764 } else if (usedefault == 0) { 1765 su = (union sockunion *)&data_dest; 1766printaddr: 1767 /* PASV/PORT */ 1768 if (su->su_family == AF_INET) { 1769 if (ispassive) 1770 printf("211- PASV "); 1771 else 1772 printf("211- PORT "); 1773 a = (u_char *) &su->su_sin.sin_addr; 1774 p = (u_char *) &su->su_sin.sin_port; 1775 printf("(%u,%u,%u,%u,%u,%u)\r\n", 1776 a[0], a[1], a[2], a[3], 1777 p[0], p[1]); 1778 } 1779 1780 /* LPSV/LPRT */ 1781 { 1782 int alen, af, i; 1783 1784 alen = 0; 1785 switch (su->su_family) { 1786 case AF_INET: 1787 a = (u_char *) &su->su_sin.sin_addr; 1788 p = (u_char *) &su->su_sin.sin_port; 1789 alen = sizeof(su->su_sin.sin_addr); 1790 af = 4; 1791 break; 1792 case AF_INET6: 1793 a = (u_char *) &su->su_sin6.sin6_addr; 1794 p = (u_char *) &su->su_sin6.sin6_port; 1795 alen = sizeof(su->su_sin6.sin6_addr); 1796 af = 6; 1797 break; 1798 default: 1799 af = 0; 1800 break; 1801 } 1802 if (af) { 1803 if (ispassive) 1804 printf("211- LPSV "); 1805 else 1806 printf("211- LPRT "); 1807 printf("(%u,%u", af, alen); 1808 for (i = 0; i < alen; i++) 1809 printf(",%u", a[i]); 1810 printf(",%u,%u,%u)\r\n", 2, p[0], p[1]); 1811 } 1812 } 1813 1814 /* EPRT/EPSV */ 1815 { 1816 u_char af; 1817 1818 switch (su->su_family) { 1819 case AF_INET: 1820 af = 1; 1821 break; 1822 case AF_INET6: 1823 af = 2; 1824 break; 1825 default: 1826 af = 0; 1827 break; 1828 } 1829 if (af) { 1830 char hbuf[MAXHOSTNAMELEN], pbuf[10]; 1831 if (getnameinfo((struct sockaddr *)su, su->su_len, 1832 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), 1833 NI_NUMERICHOST) == 0) { 1834 if (ispassive) 1835 printf("211- EPSV "); 1836 else 1837 printf("211- EPRT "); 1838 printf("(|%u|%s|%s|)\r\n", 1839 af, hbuf, pbuf); 1840 } 1841 } 1842 } 1843 } else 1844 printf(" No data connection\r\n"); 1845 reply(211, "End of status"); 1846} 1847 1848void 1849fatal(s) 1850 char *s; 1851{ 1852 1853 reply(451, "Error in server: %s\n", s); 1854 reply(221, "Closing connection due to server error."); 1855 dologout(0); 1856 /* NOTREACHED */ 1857} 1858 1859void 1860#ifdef __STDC__ 1861reply(int n, const char *fmt, ...) 1862#else 1863reply(n, fmt, va_alist) 1864 int n; 1865 char *fmt; 1866 va_dcl 1867#endif 1868{ 1869 char *buf, *p, *next; 1870 va_list ap; 1871#ifdef __STDC__ 1872 va_start(ap, fmt); 1873#else 1874 va_start(ap); 1875#endif 1876 if (vasprintf(&buf, fmt, ap) == -1 || buf == NULL) { 1877 printf("412 Local resource failure: malloc\r\n"); 1878 fflush(stdout); 1879 dologout(1); 1880 } 1881 next = buf; 1882 while ((p = strsep(&next, "\n\r"))) { 1883 printf("%d%s %s\r\n", n, (next != '\0') ? "-" : "", p); 1884 if (debug) 1885 syslog(LOG_DEBUG, "<--- %d%s %s", n, 1886 (next != '\0') ? "-" : "", p); 1887 } 1888 (void)fflush(stdout); 1889 free(buf); 1890 va_end(ap); 1891} 1892 1893void 1894#ifdef __STDC__ 1895lreply(int n, const char *fmt, ...) 1896#else 1897lreply(n, fmt, va_alist) 1898 int n; 1899 char *fmt; 1900 va_dcl 1901#endif 1902{ 1903 va_list ap; 1904#ifdef __STDC__ 1905 va_start(ap, fmt); 1906#else 1907 va_start(ap); 1908#endif 1909 (void)printf("%d- ", n); 1910 (void)vprintf(fmt, ap); 1911 va_end(ap); 1912 (void)printf("\r\n"); 1913 (void)fflush(stdout); 1914 if (debug) { 1915#ifdef __STDC__ 1916 va_start(ap, fmt); 1917#else 1918 va_start(ap); 1919#endif 1920 syslog(LOG_DEBUG, "<--- %d- ", n); 1921 vsyslog(LOG_DEBUG, fmt, ap); 1922 va_end(ap); 1923 } 1924} 1925 1926static void 1927ack(s) 1928 char *s; 1929{ 1930 1931 reply(250, "%s command successful.", s); 1932} 1933 1934void 1935nack(s) 1936 char *s; 1937{ 1938 1939 reply(502, "%s command not implemented.", s); 1940} 1941 1942/* ARGSUSED */ 1943void 1944yyerror(s) 1945 char *s; 1946{ 1947 char *cp; 1948 1949 if ((cp = strchr(cbuf,'\n'))) 1950 *cp = '\0'; 1951 reply(500, "'%s': command not understood.", cbuf); 1952} 1953 1954void 1955delete(name) 1956 char *name; 1957{ 1958 struct stat st; 1959 1960 LOGCMD("delete", name); 1961 if (stat(name, &st) < 0) { 1962 perror_reply(550, name); 1963 return; 1964 } 1965 if ((st.st_mode&S_IFMT) == S_IFDIR) { 1966 if (rmdir(name) < 0) { 1967 perror_reply(550, name); 1968 return; 1969 } 1970 goto done; 1971 } 1972 if (unlink(name) < 0) { 1973 perror_reply(550, name); 1974 return; 1975 } 1976done: 1977 ack("DELE"); 1978} 1979 1980void 1981cwd(path) 1982 char *path; 1983{ 1984 FILE *message; 1985 1986 if (chdir(path) < 0) 1987 perror_reply(550, path); 1988 else { 1989 if ((message = fopen(_PATH_CWDMESG, "r")) != NULL) { 1990 char *cp, line[LINE_MAX]; 1991 1992 while (fgets(line, sizeof(line), message) != NULL) { 1993 if ((cp = strchr(line, '\n')) != NULL) 1994 *cp = '\0'; 1995 lreply(250, "%s", line); 1996 } 1997 (void) fflush(stdout); 1998 (void) fclose(message); 1999 } 2000 ack("CWD"); 2001 } 2002} 2003 2004void 2005replydirname(name, message) 2006 const char *name, *message; 2007{ 2008 char *p, *ep; 2009 char npath[MAXPATHLEN * 2]; 2010 2011 p = npath; 2012 ep = &npath[sizeof(npath) - 1]; 2013 while (*name) { 2014 if (*name == '"') { 2015 if (ep - p < 2) 2016 break; 2017 *p++ = *name++; 2018 *p++ = '"'; 2019 } else { 2020 if (ep - p < 1) 2021 break; 2022 *p++ = *name++; 2023 } 2024 } 2025 *p = '\0'; 2026 reply(257, "\"%s\" %s", npath, message); 2027} 2028 2029void 2030makedir(name) 2031 char *name; 2032{ 2033 2034 LOGCMD("mkdir", name); 2035 if (mkdir(name, 0777) < 0) 2036 perror_reply(550, name); 2037 else 2038 replydirname(name, "directory created."); 2039} 2040 2041void 2042removedir(name) 2043 char *name; 2044{ 2045 2046 LOGCMD("rmdir", name); 2047 if (rmdir(name) < 0) 2048 perror_reply(550, name); 2049 else 2050 ack("RMD"); 2051} 2052 2053void 2054pwd() 2055{ 2056 char path[MAXPATHLEN]; 2057 2058 if (getcwd(path, sizeof(path)) == NULL) 2059 reply(550, "Can't get current directory: %s.", strerror(errno)); 2060 else 2061 replydirname(path, "is current directory."); 2062} 2063 2064char * 2065renamefrom(name) 2066 char *name; 2067{ 2068 struct stat st; 2069 2070 if (stat(name, &st) < 0) { 2071 perror_reply(550, name); 2072 return ((char *)0); 2073 } 2074 reply(350, "File exists, ready for destination name"); 2075 return (name); 2076} 2077 2078void 2079renamecmd(from, to) 2080 char *from, *to; 2081{ 2082 2083 LOGCMD2("rename", from, to); 2084 if (rename(from, to) < 0) 2085 perror_reply(550, "rename"); 2086 else 2087 ack("RNTO"); 2088} 2089 2090static void 2091dolog(sa) 2092 struct sockaddr *sa; 2093{ 2094 char hbuf[sizeof(remotehost)]; 2095 2096 getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0, 0); 2097 (void) strlcpy(remotehost, hbuf, sizeof(remotehost)); 2098 2099#ifdef HASSETPROCTITLE 2100 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); 2101 setproctitle("%s", proctitle); 2102#endif /* HASSETPROCTITLE */ 2103 2104 if (logging) 2105 syslog(LOG_INFO, "connection from %s", remotehost); 2106} 2107 2108/* 2109 * Record logout in wtmp file and exit with supplied status. 2110 * NOTE: because this is called from signal handlers it cannot 2111 * use stdio (or call other functions that use stdio). 2112 */ 2113void 2114dologout(status) 2115 int status; 2116{ 2117 2118 transflag = 0; 2119 2120 if (logged_in) { 2121 sigprocmask(SIG_BLOCK, &allsigs, NULL); 2122 (void) seteuid((uid_t)0); 2123 ftpdlogwtmp(ttyline, "", ""); 2124 if (doutmp) 2125 logout(utmp.ut_line); 2126 } 2127 /* beware of flushing buffers after a SIGPIPE */ 2128 _exit(status); 2129} 2130 2131static void 2132sigurg(signo) 2133 int signo; 2134{ 2135 2136 recvurg = 1; 2137} 2138 2139static void 2140myoob() 2141{ 2142 char *cp; 2143 2144 /* only process if transfer occurring */ 2145 if (!transflag) 2146 return; 2147 cp = tmpline; 2148 if (getline(cp, 7, stdin) == NULL) { 2149 reply(221, "You could at least say goodbye."); 2150 dologout(0); 2151 } 2152 upper(cp); 2153 if (strcmp(cp, "ABOR\r\n") == 0) { 2154 tmpline[0] = '\0'; 2155 reply(426, "Transfer aborted. Data connection closed."); 2156 reply(226, "Abort successful"); 2157 } 2158 if (strcmp(cp, "STAT\r\n") == 0) { 2159 tmpline[0] = '\0'; 2160 if (file_size != (off_t) -1) 2161 reply(213, "Status: %qd of %qd bytes transferred", 2162 byte_count, file_size); 2163 else 2164 reply(213, "Status: %qd bytes transferred", byte_count); 2165 } 2166} 2167 2168/* 2169 * Note: a response of 425 is not mentioned as a possible response to 2170 * the PASV command in RFC959. However, it has been blessed as 2171 * a legitimate response by Jon Postel in a telephone conversation 2172 * with Rick Adams on 25 Jan 89. 2173 */ 2174void 2175passive() 2176{ 2177 int len, on; 2178 u_char *p, *a; 2179 2180 if (pw == NULL) { 2181 reply(530, "Please login with USER and PASS"); 2182 return; 2183 } 2184 if (pdata >= 0) 2185 close(pdata); 2186 /* 2187 * XXX 2188 * At this point, it would be nice to have an algorithm that 2189 * inserted a growing delay in an attack scenario. Such a thing 2190 * would look like continual passive sockets being opened, but 2191 * nothing serious being done with them. They're not used to 2192 * move data; the entire attempt is just to use tcp FIN_WAIT 2193 * resources. 2194 */ 2195 pdata = socket(AF_INET, SOCK_STREAM, 0); 2196 if (pdata < 0) { 2197 perror_reply(425, "Can't open passive connection"); 2198 return; 2199 } 2200 2201#ifdef IP_PORTRANGE 2202 on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; 2203 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2204 (char *)&on, sizeof(on)) < 0) 2205 goto pasv_error; 2206#endif 2207 2208 pasv_addr = ctrl_addr; 2209 pasv_addr.su_sin.sin_port = 0; 2210 if (bind(pdata, (struct sockaddr *)&pasv_addr, 2211 pasv_addr.su_len) < 0) 2212 goto pasv_error; 2213 2214 len = sizeof(pasv_addr); 2215 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2216 goto pasv_error; 2217 if (listen(pdata, 1) < 0) 2218 goto pasv_error; 2219 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2220 p = (u_char *) &pasv_addr.su_sin.sin_port; 2221 2222 reply(227, "Entering Passive Mode (%u,%u,%u,%u,%u,%u)", a[0], 2223 a[1], a[2], a[3], p[0], p[1]); 2224 return; 2225 2226pasv_error: 2227 (void) seteuid((uid_t)pw->pw_uid); 2228 (void) close(pdata); 2229 pdata = -1; 2230 perror_reply(425, "Can't open passive connection"); 2231 return; 2232} 2233 2234/* 2235 * convert protocol identifier to/from AF 2236 */ 2237int 2238lpsvproto2af(int proto) 2239{ 2240 2241 switch (proto) { 2242 case 4: return AF_INET; 2243#ifdef INET6 2244 case 6: return AF_INET6; 2245#endif 2246 default: return -1; 2247 } 2248} 2249 2250int 2251af2lpsvproto(int af) 2252{ 2253 2254 switch (af) { 2255 case AF_INET: return 4; 2256#ifdef INET6 2257 case AF_INET6: return 6; 2258#endif 2259 default: return -1; 2260 } 2261} 2262 2263int 2264epsvproto2af(int proto) 2265{ 2266 2267 switch (proto) { 2268 case 1: return AF_INET; 2269#ifdef INET6 2270 case 2: return AF_INET6; 2271#endif 2272 default: return -1; 2273 } 2274} 2275 2276int 2277af2epsvproto(int af) 2278{ 2279 2280 switch (af) { 2281 case AF_INET: return 1; 2282#ifdef INET6 2283 case AF_INET6: return 2; 2284#endif 2285 default: return -1; 2286 } 2287} 2288 2289/* 2290 * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...) 2291 * 229 Entering Extended Passive Mode (|||port|) 2292 */ 2293void 2294long_passive(char *cmd, int pf) 2295{ 2296 int len, on; 2297 u_char *p, *a; 2298 2299 if (!logged_in) { 2300 syslog(LOG_NOTICE, "long passive but not logged in"); 2301 reply(503, "Login with USER first."); 2302 return; 2303 } 2304 2305 if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) { 2306 /* 2307 * XXX 2308 * only EPRT/EPSV ready clients will understand this 2309 */ 2310 if (strcmp(cmd, "EPSV") != 0) 2311 reply(501, "Network protocol mismatch"); /*XXX*/ 2312 else 2313 epsv_protounsupp("Network protocol mismatch"); 2314 2315 return; 2316 } 2317 2318 if (pdata >= 0) 2319 close(pdata); 2320 /* 2321 * XXX 2322 * At this point, it would be nice to have an algorithm that 2323 * inserted a growing delay in an attack scenario. Such a thing 2324 * would look like continual passive sockets being opened, but 2325 * nothing serious being done with them. They not used to move 2326 * data; the entire attempt is just to use tcp FIN_WAIT 2327 * resources. 2328 */ 2329 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); 2330 if (pdata < 0) { 2331 perror_reply(425, "Can't open passive connection"); 2332 return; 2333 } 2334 2335 switch (ctrl_addr.su_family) { 2336 case AF_INET: 2337#ifdef IP_PORTRANGE 2338 on = high_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; 2339 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, 2340 (char *)&on, sizeof(on)) < 0) 2341 goto pasv_error; 2342#endif 2343 break; 2344 case AF_INET6: 2345#ifdef IPV6_PORTRANGE 2346 on = high_data_ports ? IPV6_PORTRANGE_HIGH 2347 : IPV6_PORTRANGE_DEFAULT; 2348 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, 2349 (char *)&on, sizeof(on)) < 0) 2350 goto pasv_error; 2351#endif 2352 break; 2353 } 2354 2355 pasv_addr = ctrl_addr; 2356 pasv_addr.su_port = 0; 2357 (void) seteuid((uid_t) 0); 2358 if (bind(pdata, (struct sockaddr *) &pasv_addr, pasv_addr.su_len) < 0) { 2359 (void) seteuid((uid_t) pw->pw_uid); 2360 goto pasv_error; 2361 } 2362 (void) seteuid((uid_t) pw->pw_uid); 2363 len = pasv_addr.su_len; 2364 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) 2365 goto pasv_error; 2366 if (listen(pdata, 1) < 0) 2367 goto pasv_error; 2368 p = (u_char *) &pasv_addr.su_port; 2369 2370 if (strcmp(cmd, "LPSV") == 0) { 2371 switch (pasv_addr.su_family) { 2372 case AF_INET: 2373 a = (u_char *) &pasv_addr.su_sin.sin_addr; 2374 reply(228, 2375 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2376 4, 4, a[0], a[1], a[2], a[3], 2, p[0], p[1]); 2377 return; 2378 case AF_INET6: 2379 a = (char *) &pasv_addr.su_sin6.sin6_addr; 2380 reply(228, 2381 "Entering Long Passive Mode (%u,%u,%u,%u,%u,%u," 2382 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u)", 2383 6, 16, a[0], a[1], a[2], a[3], a[4], 2384 a[5], a[6], a[7], a[8], a[9], a[10], 2385 a[11], a[12], a[13], a[14], a[15], 2386 2, p[0], p[1]); 2387 return; 2388 } 2389 } else if (strcmp(cmd, "EPSV") == 0) { 2390 switch (pasv_addr.su_family) { 2391 case AF_INET: 2392 case AF_INET6: 2393 reply(229, "Entering Extended Passive Mode (|||%u|)", 2394 ntohs(pasv_addr.su_port)); 2395 return; 2396 } 2397 } else { 2398 /* more proper error code? */ 2399 } 2400 2401 pasv_error: 2402 (void) close(pdata); 2403 pdata = -1; 2404 perror_reply(425, "Can't open passive connection"); 2405 return; 2406} 2407 2408/* 2409 * EPRT |proto|addr|port| 2410 */ 2411int 2412extended_port(const char *arg) 2413{ 2414 char *tmp = NULL; 2415 char *result[3]; 2416 char *p, *q; 2417 char delim; 2418 struct addrinfo hints; 2419 struct addrinfo *res = NULL; 2420 int i; 2421 unsigned long proto; 2422 2423 if (epsvall) { 2424 reply(501, "EPRT disallowed after EPSV ALL"); 2425 return -1; 2426 } 2427 2428 usedefault = 0; 2429 if (pdata >= 0) { 2430 (void) close(pdata); 2431 pdata = -1; 2432 } 2433 2434 tmp = strdup(arg); 2435 if (!tmp) { 2436 fatal("not enough core."); 2437 /*NOTREACHED*/ 2438 } 2439 p = tmp; 2440 delim = p[0]; 2441 p++; 2442 memset(result, 0, sizeof(result)); 2443 for (i = 0; i < 3; i++) { 2444 q = strchr(p, delim); 2445 if (!q || *q != delim) 2446 goto parsefail; 2447 *q++ = '\0'; 2448 result[i] = p; 2449 p = q; 2450 } 2451 2452 /* some more sanity check */ 2453 p = NULL; 2454 (void)strtoul(result[2], &p, 10); 2455 if (!*result[2] || *p) 2456 goto protounsupp; 2457 p = NULL; 2458 proto = strtoul(result[0], &p, 10); 2459 if (!*result[0] || *p) 2460 goto protounsupp; 2461 2462 memset(&hints, 0, sizeof(hints)); 2463 hints.ai_family = epsvproto2af((int)proto); 2464 if (hints.ai_family < 0) 2465 goto protounsupp; 2466 hints.ai_socktype = SOCK_STREAM; 2467 hints.ai_flags = AI_NUMERICHOST; /*no DNS*/ 2468 if (getaddrinfo(result[1], result[2], &hints, &res)) 2469 goto parsefail; 2470 if (res->ai_next) 2471 goto parsefail; 2472 if (sizeof(data_dest) < res->ai_addrlen) 2473 goto parsefail; 2474 memcpy(&data_dest, res->ai_addr, res->ai_addrlen); 2475 if (his_addr.su_family == AF_INET6 && 2476 data_dest.su_family == AF_INET6) { 2477 /* XXX more sanity checks! */ 2478 data_dest.su_sin6.sin6_scope_id = 2479 his_addr.su_sin6.sin6_scope_id; 2480 } 2481 if (pdata >= 0) { 2482 (void) close(pdata); 2483 pdata = -1; 2484 } 2485 reply(200, "EPRT command successful."); 2486 2487 if (tmp) 2488 free(tmp); 2489 if (res) 2490 freeaddrinfo(res); 2491 return 0; 2492 2493parsefail: 2494 reply(500, "Invalid argument, rejected."); 2495 usedefault = 1; 2496 if (tmp) 2497 free(tmp); 2498 if (res) 2499 freeaddrinfo(res); 2500 return -1; 2501 2502protounsupp: 2503 epsv_protounsupp("Protocol not supported"); 2504 usedefault = 1; 2505 if (tmp) 2506 free(tmp); 2507 if (res) 2508 freeaddrinfo(res); 2509 return -1; 2510} 2511 2512/* 2513 * 522 Protocol not supported (proto,...) 2514 * as we assume address family for control and data connections are the same, 2515 * we do not return the list of address families we support - instead, we 2516 * return the address family of the control connection. 2517 */ 2518void 2519epsv_protounsupp(const char *message) 2520{ 2521 int proto; 2522 2523 proto = af2epsvproto(ctrl_addr.su_family); 2524 if (proto < 0) 2525 reply(501, "%s", message); /*XXX*/ 2526 else 2527 reply(522, "%s, use (%d)", message, proto); 2528} 2529 2530/* 2531 * Generate unique name for file with basename "local". 2532 * The file named "local" is already known to exist. 2533 * Generates failure reply on error. 2534 */ 2535static int 2536guniquefd(local, nam) 2537 char *local; 2538 char **nam; 2539{ 2540 static char new[MAXPATHLEN]; 2541 struct stat st; 2542 int count, len, fd; 2543 char *cp; 2544 2545 cp = strrchr(local, '/'); 2546 if (cp) 2547 *cp = '\0'; 2548 if (stat(cp ? local : ".", &st) < 0) { 2549 perror_reply(553, cp ? local : "."); 2550 return (-1); 2551 } 2552 if (cp) 2553 *cp = '/'; 2554 len = strlcpy(new, local, sizeof(new)); 2555 if (len+2+1 >= sizeof(new)-1) 2556 return (-1); 2557 cp = new + len; 2558 *cp++ = '.'; 2559 for (count = 1; count < 100; count++) { 2560 (void)snprintf(cp, sizeof(new) - (cp - new), "%d", count); 2561 fd = open(new, O_RDWR|O_CREAT|O_EXCL, 0666); 2562 if (fd == -1) 2563 continue; 2564 if (nam) 2565 *nam = new; 2566 return (fd); 2567 } 2568 reply(452, "Unique file name cannot be created."); 2569 return (-1); 2570} 2571 2572/* 2573 * Format and send reply containing system error number. 2574 */ 2575void 2576perror_reply(code, string) 2577 int code; 2578 char *string; 2579{ 2580 2581 reply(code, "%s: %s.", string, strerror(errno)); 2582} 2583 2584static char *onefile[] = { 2585 "", 2586 0 2587}; 2588 2589void 2590send_file_list(whichf) 2591 char *whichf; 2592{ 2593 struct stat st; 2594 DIR *dirp = NULL; 2595 struct dirent *dir; 2596 FILE *dout = NULL; 2597 char **dirlist; 2598 char *dirname; 2599 int simple = 0; 2600 volatile int freeglob = 0; 2601 glob_t gl; 2602 2603 if (strpbrk(whichf, "~{[*?") != NULL) { 2604 memset(&gl, 0, sizeof(gl)); 2605 freeglob = 1; 2606 if (glob(whichf, 2607 GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|GLOB_LIMIT, 2608 0, &gl)) { 2609 reply(550, "not found"); 2610 goto out; 2611 } else if (gl.gl_pathc == 0) { 2612 errno = ENOENT; 2613 perror_reply(550, whichf); 2614 goto out; 2615 } 2616 dirlist = gl.gl_pathv; 2617 } else { 2618 onefile[0] = whichf; 2619 dirlist = onefile; 2620 simple = 1; 2621 } 2622 2623 while ((dirname = *dirlist++)) { 2624 if (stat(dirname, &st) < 0) { 2625 /* 2626 * If user typed "ls -l", etc, and the client 2627 * used NLST, do what the user meant. 2628 */ 2629 if (dirname[0] == '-' && *dirlist == NULL && 2630 transflag == 0) { 2631 retrieve("/bin/ls %s", dirname); 2632 goto out; 2633 } 2634 perror_reply(550, whichf); 2635 if (dout != NULL) { 2636 (void) fclose(dout); 2637 transflag = 0; 2638 data = -1; 2639 pdata = -1; 2640 } 2641 goto out; 2642 } 2643 2644 if (S_ISREG(st.st_mode)) { 2645 if (dout == NULL) { 2646 dout = dataconn("file list", (off_t)-1, "w"); 2647 if (dout == NULL) 2648 goto out; 2649 transflag++; 2650 } 2651 fprintf(dout, "%s%s\n", dirname, 2652 type == TYPE_A ? "\r" : ""); 2653 byte_count += strlen(dirname) + 1; 2654 continue; 2655 } else if (!S_ISDIR(st.st_mode)) 2656 continue; 2657 2658 if ((dirp = opendir(dirname)) == NULL) 2659 continue; 2660 2661 while ((dir = readdir(dirp)) != NULL) { 2662 char nbuf[MAXPATHLEN]; 2663 2664 if (recvurg) { 2665 myoob(); 2666 recvurg = 0; 2667 transflag = 0; 2668 goto out; 2669 } 2670 2671 if (dir->d_name[0] == '.' && dir->d_namlen == 1) 2672 continue; 2673 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && 2674 dir->d_namlen == 2) 2675 continue; 2676 2677 snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, 2678 dir->d_name); 2679 2680 /* 2681 * We have to do a stat to insure it's 2682 * not a directory or special file. 2683 */ 2684 if (simple || (stat(nbuf, &st) == 0 && 2685 S_ISREG(st.st_mode))) { 2686 if (dout == NULL) { 2687 dout = dataconn("file list", (off_t)-1, 2688 "w"); 2689 if (dout == NULL) 2690 goto out; 2691 transflag++; 2692 } 2693 if (nbuf[0] == '.' && nbuf[1] == '/') 2694 fprintf(dout, "%s%s\n", &nbuf[2], 2695 type == TYPE_A ? "\r" : ""); 2696 else 2697 fprintf(dout, "%s%s\n", nbuf, 2698 type == TYPE_A ? "\r" : ""); 2699 byte_count += strlen(nbuf) + 1; 2700 } 2701 } 2702 (void) closedir(dirp); 2703 } 2704 2705 if (dout == NULL) 2706 reply(550, "No files found."); 2707 else if (ferror(dout) != 0) 2708 perror_reply(550, "Data connection"); 2709 else 2710 reply(226, "Transfer complete."); 2711 2712 transflag = 0; 2713 if (dout != NULL) 2714 (void) fclose(dout); 2715 else { 2716 if (pdata >= 0) 2717 close(pdata); 2718 } 2719 data = -1; 2720 pdata = -1; 2721out: 2722 if (freeglob) { 2723 freeglob = 0; 2724 globfree(&gl); 2725 } 2726} 2727 2728static void 2729reapchild(signo) 2730 int signo; 2731{ 2732 int save_errno = errno; 2733 int rval; 2734 2735 do { 2736 rval = waitpid(-1, NULL, WNOHANG); 2737 } while (rval > 0 || (rval == -1 && errno == EINTR)); 2738 errno = save_errno; 2739} 2740 2741void 2742logxfer(name, size, start) 2743 char *name; 2744 off_t size; 2745 time_t start; 2746{ 2747 char buf[400 + MAXHOSTNAMELEN*4 + MAXPATHLEN*4]; 2748 char dir[MAXPATHLEN], path[MAXPATHLEN], rpath[MAXPATHLEN]; 2749 char vremotehost[MAXHOSTNAMELEN*4], vpath[MAXPATHLEN*4]; 2750 char *vpw; 2751 time_t now; 2752 int len; 2753 2754 if ((statfd >= 0) && (getcwd(dir, sizeof(dir)) != NULL)) { 2755 time(&now); 2756 2757 vpw = malloc(strlen(guest ? guestpw : pw->pw_name) * 4 + 1); 2758 if (vpw == NULL) 2759 return; 2760 2761 snprintf(path, sizeof(path), "%s/%s", dir, name); 2762 if (realpath(path, rpath) == NULL) 2763 strlcpy(rpath, path, sizeof(rpath)); 2764 strvis(vpath, rpath, VIS_SAFE|VIS_NOSLASH); 2765 2766 strvis(vremotehost, remotehost, VIS_SAFE|VIS_NOSLASH); 2767 strvis(vpw, guest? guestpw : pw->pw_name, VIS_SAFE|VIS_NOSLASH); 2768 2769 len = snprintf(buf, sizeof(buf), 2770 "%.24s %d %s %qd %s %c %s %c %c %s ftp %d %s %s\n", 2771 ctime(&now), now - start + (now == start), 2772 vremotehost, (long long) size, vpath, 2773 ((type == TYPE_A) ? 'a' : 'b'), "*" /* none yet */, 2774 'o', ((guest) ? 'a' : 'r'), 2775 vpw, 0 /* none yet */, 2776 ((guest) ? "*" : pw->pw_name), dhostname); 2777 if (len >= sizeof(buf)) { 2778 len = sizeof(buf); 2779 buf[sizeof(buf) - 1] = '\n'; 2780 } 2781 write(statfd, buf, len); 2782 free(vpw); 2783 } 2784} 2785 2786#if defined(TCPWRAPPERS) 2787static int 2788check_host(sa) 2789 struct sockaddr *sa; 2790{ 2791 struct sockaddr_in *sin; 2792 struct hostent *hp; 2793 char *addr; 2794 2795 if (sa->sa_family != AF_INET) 2796 return 1; /*XXX*/ 2797 2798 sin = (struct sockaddr_in *)sa; 2799 hp = gethostbyaddr((char *)&sin->sin_addr, 2800 sizeof(struct in_addr), AF_INET); 2801 addr = inet_ntoa(sin->sin_addr); 2802 if (hp) { 2803 if (!hosts_ctl("ftpd", hp->h_name, addr, STRING_UNKNOWN)) { 2804 syslog(LOG_NOTICE, "tcpwrappers rejected: %s [%s]", 2805 hp->h_name, addr); 2806 return (0); 2807 } 2808 } else { 2809 if (!hosts_ctl("ftpd", STRING_UNKNOWN, addr, STRING_UNKNOWN)) { 2810 syslog(LOG_NOTICE, "tcpwrappers rejected: [%s]", addr); 2811 return (0); 2812 } 2813 } 2814 return (1); 2815} 2816#endif /* TCPWRAPPERS */ 2817 2818/* 2819 * Allocate space and return a copy of the specified dir. 2820 * If 'dir' begins with a tilde (~), expand it. 2821 */ 2822char * 2823copy_dir(dir, pw) 2824 char *dir; 2825 struct passwd *pw; 2826{ 2827 char *cp; 2828 char *newdir; 2829 char *user = NULL; 2830 size_t dirsiz; 2831 2832 /* Nothing to expand */ 2833 if (dir[0] != '~') 2834 return (strdup(dir)); 2835 2836 /* "dir" is of form ~user/some/dir, lookup user. */ 2837 if (dir[1] != '/' && dir[1] != '\0') { 2838 if ((cp = strchr(dir + 1, '/')) == NULL) 2839 cp = dir + strlen(dir); 2840 if ((user = malloc(cp - dir)) == NULL) 2841 return (NULL); 2842 strlcpy(user, dir + 1, cp - dir); 2843 2844 /* Only do lookup if it is a different user. */ 2845 if (strcmp(user, pw->pw_name) != 0) { 2846 if ((pw = getpwnam(user)) == NULL) { 2847 /* No such user, interpret literally */ 2848 free(user); 2849 return(strdup(dir)); 2850 } 2851 } 2852 } 2853 2854 /* 2855 * If there is no directory separator (/) then it is just pw_dir. 2856 * Otherwise, replace ~foo with pw_dir. 2857 */ 2858 if ((cp = strchr(dir + 1, '/')) == NULL) { 2859 newdir = strdup(pw->pw_dir); 2860 } else { 2861 dirsiz = strlen(cp) + strlen(pw->pw_dir) + 1; 2862 if ((newdir = malloc(dirsiz)) == NULL) 2863 return (NULL); 2864 strcpy(newdir, pw->pw_dir); 2865 strcat(newdir, cp); 2866 } 2867 2868 if (user) 2869 free(user); 2870 return(newdir); 2871} 2872