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