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