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