xref: /netbsd/libexec/ftpd/ftpd.c (revision 1920faf9)
1 /*	$NetBSD: ftpd.c,v 1.206 2021/07/03 14:59:49 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 /*
62  * Copyright (C) 1997 and 1998 WIDE Project.
63  * All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. Neither the name of the project nor the names of its contributors
74  *    may be used to endorse or promote products derived from this software
75  *    without specific prior written permission.
76  *
77  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
78  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
81  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87  * SUCH DAMAGE.
88  */
89 
90 #include <sys/cdefs.h>
91 #ifndef lint
92 __COPYRIGHT("@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\
93  The Regents of the University of California.  All rights reserved.");
94 #endif /* not lint */
95 
96 #ifndef lint
97 #if 0
98 static char sccsid[] = "@(#)ftpd.c	8.5 (Berkeley) 4/28/95";
99 #else
100 __RCSID("$NetBSD: ftpd.c,v 1.206 2021/07/03 14:59:49 christos Exp $");
101 #endif
102 #endif /* not lint */
103 
104 /*
105  * FTP server.
106  */
107 #include <sys/param.h>
108 #include <sys/stat.h>
109 #include <sys/ioctl.h>
110 #include <sys/socket.h>
111 #include <sys/wait.h>
112 #include <sys/mman.h>
113 #include <sys/resource.h>
114 
115 #include <netinet/in.h>
116 #include <netinet/in_systm.h>
117 #include <netinet/ip.h>
118 
119 #define	FTP_NAMES
120 #include <arpa/ftp.h>
121 #include <arpa/inet.h>
122 #include <arpa/telnet.h>
123 
124 #include <ctype.h>
125 #include <dirent.h>
126 #include <err.h>
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <fnmatch.h>
130 #include <glob.h>
131 #include <grp.h>
132 #include <limits.h>
133 #include <netdb.h>
134 #include <pwd.h>
135 #include <poll.h>
136 #include <signal.h>
137 #include <stdarg.h>
138 #include <stdio.h>
139 #include <stdlib.h>
140 #include <string.h>
141 #include <syslog.h>
142 #include <time.h>
143 #include <tzfile.h>
144 #include <unistd.h>
145 #include <util.h>
146 #ifdef SUPPORT_UTMP
147 #include <utmp.h>
148 #endif
149 #ifdef SUPPORT_UTMPX
150 #include <utmpx.h>
151 #endif
152 #ifdef SKEY
153 #include <skey.h>
154 #endif
155 #ifdef KERBEROS5
156 #include <com_err.h>
157 #include <krb5/krb5.h>
158 #endif
159 
160 #ifdef	LOGIN_CAP
161 #include <login_cap.h>
162 #endif
163 
164 #ifdef USE_PAM
165 #include <security/pam_appl.h>
166 #endif
167 
168 #include "pfilter.h"
169 
170 #define	GLOBAL
171 #include "extern.h"
172 #include "pathnames.h"
173 #include "version.h"
174 
175 static sig_atomic_t	transflag;
176 static sig_atomic_t	urgflag;
177 
178 int	data;
179 int	Dflag;
180 int	fflag;
181 int	sflag;
182 int	stru;			/* avoid C keyword */
183 int	mode;
184 int	dataport;		/* use specific data port */
185 int	dopidfile;		/* maintain pid file */
186 int	doutmp;			/* update utmp file */
187 int	dowtmp;			/* update wtmp file */
188 int	doxferlog;		/* syslog/write wu-ftpd style xferlog entries */
189 int	xferlogfd;		/* fd to write wu-ftpd xferlog entries to */
190 int	getnameopts;		/* flags for use with getname() */
191 int	dropprivs;		/* if privileges should or have been dropped */
192 int	mapped;			/* IPv4 connection on AF_INET6 socket */
193 off_t	file_size;
194 off_t	byte_count;
195 static char ttyline[20];
196 
197 #ifdef USE_PAM
198 static int	auth_pam(void);
199 pam_handle_t	*pamh = NULL;
200 #endif
201 
202 #ifdef SUPPORT_UTMP
203 static struct utmp utmp;	/* for utmp */
204 #endif
205 #ifdef SUPPORT_UTMPX
206 static struct utmpx utmpx;	/* for utmpx */
207 #endif
208 
209 static const char *anondir = NULL;
210 static const char *confdir = _DEFAULT_CONFDIR;
211 
212 static char	*curname;		/* current USER name */
213 static size_t	curname_len;		/* length of curname (include NUL) */
214 
215 #if defined(KERBEROS) || defined(KERBEROS5)
216 int	has_ccache = 0;
217 int	notickets = 1;
218 char	*krbtkfile_env = NULL;
219 char	*tty = ttyline;
220 int	login_krb5_forwardable_tgt = 0;
221 #endif
222 
223 int epsvall = 0;
224 
225 /*
226  * Timeout intervals for retrying connections
227  * to hosts that don't accept PORT cmds.  This
228  * is a kludge, but given the problems with TCP...
229  */
230 #define	SWAITMAX	90	/* wait at most 90 seconds */
231 #define	SWAITINT	5	/* interval between retries */
232 
233 int	swaitmax = SWAITMAX;
234 int	swaitint = SWAITINT;
235 
236 enum send_status {
237 	SS_SUCCESS,
238 	SS_ABORTED,			/* transfer aborted */
239 	SS_NO_TRANSFER,			/* no transfer made yet */
240 	SS_FILE_ERROR,			/* file read error */
241 	SS_DATA_ERROR			/* data send error */
242 };
243 
244 static int	 bind_pasv_addr(void);
245 static int	 checkuser(const char *, const char *, int, int, char **);
246 static int	 checkaccess(const char *);
247 static int	 checkpassword(const struct passwd *, const char *);
248 static void	 do_pass(int, int, const char *);
249 static void	 end_login(void);
250 static FILE	*getdatasock(const char *);
251 static char	*gunique(const char *);
252 static void	 login_utmp(const char *, const char *, const char *,
253 		     struct sockinet *);
254 static void	 logremotehost(struct sockinet *);
255 __dead static void	 lostconn(int);
256 __dead static void	 toolong(int);
257 __dead static void	 sigquit(int);
258 static void	 sigurg(int);
259 static int	 handleoobcmd(void);
260 static int	 receive_data(FILE *, FILE *);
261 static int	 send_data(FILE *, FILE *, const struct stat *, int);
262 static struct passwd *sgetpwnam(const char *);
263 static int	 write_data(int, char *, size_t, off_t *, struct timeval *,
264 		     int);
265 static enum send_status
266 		 send_data_with_read(int, int, const struct stat *, int);
267 static enum send_status
268 		 send_data_with_mmap(int, int, const struct stat *, int);
269 static void	 logrusage(const struct rusage *, const struct rusage *);
270 static void	 logout_utmp(void);
271 
272 int	main(int, char *[]);
273 
274 #if defined(KERBEROS)
275 int	klogin(struct passwd *, char *, char *, char *);
276 void	kdestroy(void);
277 #endif
278 #if defined(KERBEROS5)
279 int	k5login(struct passwd *, char *, char *, char *);
280 void	k5destroy(void);
281 #endif
282 
283 int
main(int argc,char * argv[])284 main(int argc, char *argv[])
285 {
286 	int		ch, on = 1, tos, keepalive;
287 	socklen_t	addrlen;
288 #ifdef KERBEROS5
289 	krb5_error_code	kerror;
290 #endif
291 	char		*p;
292 	const char	*xferlogname = NULL;
293 	long		l;
294 	struct sigaction sa;
295 	sa_family_t	af = AF_UNSPEC;
296 
297 	connections = 1;
298 	ftpd_debug = 0;
299 	logging = 0;
300 	pdata = -1;
301 	Dflag = 0;
302 	fflag = 0;
303 	sflag = 0;
304 	dataport = 0;
305 	dopidfile = 1;		/* default: DO use a pid file to count users */
306 	doutmp = 0;		/* default: Do NOT log to utmp */
307 	dowtmp = 1;		/* default: DO log to wtmp */
308 	doxferlog = 0;		/* default: Do NOT syslog xferlog */
309 	xferlogfd = -1;		/* default: Do NOT write xferlog file */
310 	getnameopts = 0;	/* default: xlate addrs to name */
311 	dropprivs = 0;
312 	mapped = 0;
313 	usedefault = 1;
314 	emailaddr = NULL;
315 	hostname[0] = '\0';
316 	homedir[0] = '\0';
317 	gidcount = 0;
318 	is_oob = 0;
319 	version = FTPD_VERSION;
320 
321 	/*
322 	 * LOG_NDELAY sets up the logging connection immediately,
323 	 * necessary for anonymous ftp's that chroot and can't do it later.
324 	 */
325 	openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
326 
327 	while ((ch = getopt(argc, argv,
328 	    "46a:c:C:Dde:fh:HlL:nP:qQrst:T:uUvV:wWX")) != -1) {
329 		switch (ch) {
330 		case '4':
331 			af = AF_INET;
332 			break;
333 
334 		case '6':
335 			af = AF_INET6;
336 			break;
337 
338 		case 'a':
339 			anondir = optarg;
340 			break;
341 
342 		case 'c':
343 			confdir = optarg;
344 			break;
345 
346 		case 'C':
347 			if ((p = strchr(optarg, '@')) != NULL) {
348 				*p++ = '\0';
349 				strlcpy(remotehost, p, MAXHOSTNAMELEN + 1);
350 				if (inet_pton(AF_INET, p,
351 				    &his_addr.su_addr) == 1) {
352 					his_addr.su_family = AF_INET;
353 					his_addr.su_len =
354 					    sizeof(his_addr.si_su.su_sin);
355 #ifdef INET6
356 				} else if (inet_pton(AF_INET6, p,
357 				    &his_addr.su_6addr) == 1) {
358 					his_addr.su_family = AF_INET6;
359 					his_addr.su_len =
360 					    sizeof(his_addr.si_su.su_sin6);
361 #endif
362 				} else
363 					his_addr.su_family = AF_UNSPEC;
364 			}
365 			pw = sgetpwnam(optarg);
366 			exit(checkaccess(optarg) ? 0 : 1);
367 			/* NOTREACHED */
368 
369 		case 'D':
370 			Dflag = 1;
371 			break;
372 
373 		case 'd':
374 		case 'v':		/* deprecated */
375 			ftpd_debug = 1;
376 			break;
377 
378 		case 'e':
379 			emailaddr = optarg;
380 			break;
381 
382 		case 'f':
383 			fflag = 1;
384 			break;
385 
386 		case 'h':
387 			strlcpy(hostname, optarg, sizeof(hostname));
388 			break;
389 
390 		case 'H':
391 			if (gethostname(hostname, sizeof(hostname)) == -1)
392 				hostname[0] = '\0';
393 			hostname[sizeof(hostname) - 1] = '\0';
394 			break;
395 
396 		case 'l':
397 			logging++;	/* > 1 == extra logging */
398 			break;
399 
400 		case 'L':
401 			xferlogname = optarg;
402 			break;
403 
404 		case 'n':
405 			getnameopts = NI_NUMERICHOST;
406 			break;
407 
408 		case 'P':
409 			errno = 0;
410 			p = NULL;
411 			l = strtol(optarg, &p, 10);
412 			if (errno || *optarg == '\0' || *p != '\0' ||
413 			    l < IPPORT_RESERVED ||
414 			    l > IPPORT_ANONMAX) {
415 				syslog(LOG_WARNING, "Invalid dataport %s",
416 				    optarg);
417 				dataport = 0;
418 			}
419 			dataport = (int)l;
420 			break;
421 
422 		case 'q':
423 			dopidfile = 1;
424 			break;
425 
426 		case 'Q':
427 			dopidfile = 0;
428 			break;
429 
430 		case 'r':
431 			dropprivs = 1;
432 			break;
433 
434 		case 's':
435 			sflag = 1;
436 			break;
437 
438 		case 't':
439 		case 'T':
440 			syslog(LOG_WARNING,
441 			    "-%c has been deprecated in favour of ftpd.conf",
442 			    ch);
443 			break;
444 
445 		case 'u':
446 			doutmp = 1;
447 			break;
448 
449 		case 'U':
450 			doutmp = 0;
451 			break;
452 
453 		case 'V':
454 			if (EMPTYSTR(optarg) || strcmp(optarg, "-") == 0)
455 				version = NULL;
456 			else
457 				version = ftpd_strdup(optarg);
458 			break;
459 
460 		case 'w':
461 			dowtmp = 1;
462 			break;
463 
464 		case 'W':
465 			dowtmp = 0;
466 			break;
467 
468 		case 'X':
469 			doxferlog |= 1;
470 			break;
471 
472 		default:
473 			if (optopt == 'a' || optopt == 'C')
474 				exit(1);
475 			syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
476 			break;
477 		}
478 	}
479 	if (EMPTYSTR(confdir))
480 		confdir = _DEFAULT_CONFDIR;
481 
482 	pfilter_open();
483 
484 	if (dowtmp) {
485 #ifdef SUPPORT_UTMPX
486 		ftpd_initwtmpx();
487 #endif
488 #ifdef SUPPORT_UTMP
489 		ftpd_initwtmp();
490 #endif
491 	}
492 	errno = 0;
493 	l = sysconf(_SC_LOGIN_NAME_MAX);
494 	if (l == -1 && errno != 0) {
495 		syslog(LOG_ERR, "sysconf _SC_LOGIN_NAME_MAX: %m");
496 		exit(1);
497 	} else if (l <= 0) {
498 		syslog(LOG_WARNING, "using conservative LOGIN_NAME_MAX value");
499 		curname_len = _POSIX_LOGIN_NAME_MAX;
500 	} else
501 		curname_len = (size_t)l;
502 	curname = malloc(curname_len);
503 	if (curname == NULL) {
504 		syslog(LOG_ERR, "malloc: %m");
505 		exit(1);
506 	}
507 	curname[0] = '\0';
508 
509 	if (Dflag) {
510 		int error, fd, i, n, *socks;
511 		struct pollfd *fds;
512 		struct addrinfo hints, *res, *res0;
513 
514 		if (!fflag && daemon(1, 0) == -1) {
515 			syslog(LOG_ERR, "failed to daemonize: %m");
516 			exit(1);
517 		}
518 		(void)memset(&sa, 0, sizeof(sa));
519 		sa.sa_handler = SIG_IGN;
520 		sa.sa_flags = SA_NOCLDWAIT;
521 		sigemptyset(&sa.sa_mask);
522 		(void)sigaction(SIGCHLD, &sa, NULL);
523 
524 		(void)memset(&hints, 0, sizeof(hints));
525 		hints.ai_flags = AI_PASSIVE;
526 		hints.ai_family = af;
527 		hints.ai_socktype = SOCK_STREAM;
528 		error = getaddrinfo(NULL, "ftp", &hints, &res0);
529 		if (error) {
530 			syslog(LOG_ERR, "getaddrinfo: %s", gai_strerror(error));
531 			exit(1);
532 		}
533 
534 		for (n = 0, res = res0; res != NULL; res = res->ai_next)
535 			n++;
536 		if (n == 0) {
537 			syslog(LOG_ERR, "no addresses available");
538 			exit(1);
539 		}
540 		socks = malloc(n * sizeof(int));
541 		fds = malloc(n * sizeof(struct pollfd));
542 		if (socks == NULL || fds == NULL) {
543 			syslog(LOG_ERR, "malloc: %m");
544 			exit(1);
545 		}
546 
547 		for (n = 0, res = res0; res != NULL; res = res->ai_next) {
548 			socks[n] = socket(res->ai_family, res->ai_socktype,
549 			    res->ai_protocol);
550 			if (socks[n] == -1)
551 				continue;
552 			(void)setsockopt(socks[n], SOL_SOCKET, SO_REUSEADDR,
553 			    &on, sizeof(on));
554 			if (bind(socks[n], res->ai_addr, res->ai_addrlen)
555 			    == -1) {
556 				(void)close(socks[n]);
557 				continue;
558 			}
559 			if (listen(socks[n], 12) == -1) {
560 				(void)close(socks[n]);
561 				continue;
562 			}
563 
564 			fds[n].fd = socks[n];
565 			fds[n].events = POLLIN;
566 			n++;
567 		}
568 		if (n == 0) {
569 			syslog(LOG_ERR, "%m");
570 			exit(1);
571 		}
572 		freeaddrinfo(res0);
573 
574 		if (pidfile(NULL) == -1)
575 			syslog(LOG_ERR, "failed to write a pid file: %m");
576 
577 		for (;;) {
578 			if (poll(fds, n, INFTIM) == -1) {
579 				if (errno == EINTR)
580 					continue;
581 				syslog(LOG_ERR, "poll: %m");
582 				exit(1);
583 			}
584 			for (i = 0; i < n; i++) {
585 				if (fds[i].revents & POLLIN) {
586 					fd = accept(fds[i].fd, NULL, NULL);
587 					if (fd == -1) {
588 						syslog(LOG_ERR, "accept: %m");
589 						continue;
590 					}
591 					switch (fork()) {
592 					case -1:
593 						syslog(LOG_ERR, "fork: %m");
594 						break;
595 					case 0:
596 						goto child;
597 						/* NOTREACHED */
598 					}
599 					(void)close(fd);
600 				}
601 			}
602 		}
603  child:
604 		(void)dup2(fd, STDIN_FILENO);
605 		(void)dup2(fd, STDOUT_FILENO);
606 		(void)dup2(fd, STDERR_FILENO);
607 		for (i = 0; i < n; i++)
608 			(void)close(socks[i]);
609 	}
610 
611 	memset((char *)&his_addr, 0, sizeof(his_addr));
612 	addrlen = sizeof(his_addr.si_su);
613 	if (getpeername(0, (struct sockaddr *)&his_addr.si_su, &addrlen) < 0) {
614 		syslog((errno == ENOTCONN) ? LOG_NOTICE : LOG_ERR,
615 		    "getpeername (%s): %m",argv[0]);
616 		exit(1);
617 	}
618 	his_addr.su_len = addrlen;
619 	memset((char *)&ctrl_addr, 0, sizeof(ctrl_addr));
620 	addrlen = sizeof(ctrl_addr.si_su);
621 	if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
622 		syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
623 		exit(1);
624 	}
625 	ctrl_addr.su_len = addrlen;
626 #ifdef INET6
627 	if (his_addr.su_family == AF_INET6
628 	 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_6addr)) {
629 #if 1
630 		/*
631 		 * IPv4 control connection arrived to AF_INET6 socket.
632 		 * I hate to do this, but this is the easiest solution.
633 		 *
634 		 * The assumption is untrue on SIIT environment.
635 		 */
636 		struct sockinet tmp_addr;
637 		const int off = sizeof(struct in6_addr) - sizeof(struct in_addr);
638 
639 		tmp_addr = his_addr;
640 		memset(&his_addr, 0, sizeof(his_addr));
641 		his_addr.su_family = AF_INET;
642 		his_addr.su_len = sizeof(his_addr.si_su.su_sin);
643 		memcpy(&his_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
644 		    sizeof(his_addr.su_addr));
645 		his_addr.su_port = tmp_addr.su_port;
646 
647 		tmp_addr = ctrl_addr;
648 		memset(&ctrl_addr, 0, sizeof(ctrl_addr));
649 		ctrl_addr.su_family = AF_INET;
650 		ctrl_addr.su_len = sizeof(ctrl_addr.si_su.su_sin);
651 		memcpy(&ctrl_addr.su_addr, &tmp_addr.su_6addr.s6_addr[off],
652 		    sizeof(ctrl_addr.su_addr));
653 		ctrl_addr.su_port = tmp_addr.su_port;
654 #else
655 		while (fgets(line, sizeof(line), fd) != NULL) {
656 			if ((cp = strchr(line, '\n')) != NULL)
657 				*cp = '\0';
658 			reply(-530, "%s", line);
659 		}
660 		(void) fflush(stdout);
661 		(void) fclose(fd);
662 		reply(530,
663 		    "Connection from IPv4 mapped address is not supported.");
664 		exit(0);
665 #endif
666 
667 		mapped = 1;
668 	} else
669 #endif /* INET6 */
670 		mapped = 0;
671 #ifdef IP_TOS
672 	if (!mapped && his_addr.su_family == AF_INET) {
673 		tos = IPTOS_LOWDELAY;
674 		if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&tos,
675 			       sizeof(int)) < 0)
676 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
677 	}
678 #endif
679 	/* if the hostname hasn't been given, attempt to determine it */
680 	if (hostname[0] == '\0') {
681 		if (getnameinfo((struct sockaddr *)&ctrl_addr.si_su,
682 		    ctrl_addr.su_len, hostname, sizeof(hostname), NULL, 0,
683 			getnameopts) != 0)
684 			(void)gethostname(hostname, sizeof(hostname));
685 		hostname[sizeof(hostname) - 1] = '\0';
686 	}
687 
688 	/* set this here so klogin can use it... */
689 	(void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
690 
691 	(void) freopen(_PATH_DEVNULL, "w", stderr);
692 
693 	memset(&sa, 0, sizeof(sa));
694 	sa.sa_handler = SIG_DFL;
695 	sa.sa_flags = SA_RESTART;
696 	sigemptyset(&sa.sa_mask);
697 	(void) sigaction(SIGCHLD, &sa, NULL);
698 
699 	sa.sa_handler = sigquit;
700 	sa.sa_flags = SA_RESTART;
701 	sigfillset(&sa.sa_mask);	/* block all sigs in these handlers */
702 	(void) sigaction(SIGHUP, &sa, NULL);
703 	(void) sigaction(SIGINT, &sa, NULL);
704 	(void) sigaction(SIGQUIT, &sa, NULL);
705 	(void) sigaction(SIGTERM, &sa, NULL);
706 	sa.sa_handler = lostconn;
707 	(void) sigaction(SIGPIPE, &sa, NULL);
708 	sa.sa_handler = toolong;
709 	(void) sigaction(SIGALRM, &sa, NULL);
710 	sa.sa_handler = sigurg;
711 	(void) sigaction(SIGURG, &sa, NULL);
712 
713 	/* Try to handle urgent data inline */
714 #ifdef SO_OOBINLINE
715 	if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)) < 0)
716 		syslog(LOG_WARNING, "setsockopt: %m");
717 #endif
718 	/* Set keepalives on the socket to detect dropped connections.  */
719 #ifdef SO_KEEPALIVE
720 	keepalive = 1;
721 	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepalive,
722 	    sizeof(int)) < 0)
723 		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
724 #endif
725 
726 #ifdef	F_SETOWN
727 	if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
728 		syslog(LOG_WARNING, "fcntl F_SETOWN: %m");
729 #endif
730 	logremotehost(&his_addr);
731 	/*
732 	 * Set up default state
733 	 */
734 	data = -1;
735 	type = TYPE_A;
736 	form = FORM_N;
737 	stru = STRU_F;
738 	mode = MODE_S;
739 	tmpline[0] = '\0';
740 	hasyyerrored = 0;
741 
742 #ifdef KERBEROS5
743 	kerror = krb5_init_context(&kcontext);
744 	if (kerror) {
745 		syslog(LOG_ERR, "%s when initializing Kerberos context",
746 		    error_message(kerror));
747 		exit(0);
748 	}
749 #endif /* KERBEROS5 */
750 
751 	init_curclass();
752 	curclass.timeout = 300;		/* 5 minutes, as per login(1) */
753 	curclass.type = CLASS_REAL;
754 
755 	/* If logins are disabled, print out the message. */
756 	if (display_file(_PATH_NOLOGIN, 530)) {
757 		reply(530, "System not available.");
758 		exit(0);
759 	}
760 	(void)display_file(conffilename(_NAME_FTPWELCOME), 220);
761 		/* reply(220,) must follow */
762 	if (EMPTYSTR(version))
763 		reply(220, "%s FTP server ready.", hostname);
764 	else
765 		reply(220, "%s FTP server (%s) ready.", hostname, version);
766 
767 	if (xferlogname != NULL) {
768 		xferlogfd = open(xferlogname, O_WRONLY | O_APPEND | O_CREAT,
769 		    0660);
770 		if (xferlogfd == -1)
771 			syslog(LOG_WARNING, "open xferlog `%s': %m",
772 			    xferlogname);
773 		else
774 			doxferlog |= 2;
775 	}
776 
777 	ftp_loop();
778 	/* NOTREACHED */
779 }
780 
781 static void
lostconn(int signo __unused)782 lostconn(int signo __unused)
783 {
784 
785 	if (ftpd_debug)
786 		syslog(LOG_DEBUG, "lost connection");
787 	dologout(1);
788 }
789 
790 static void
toolong(int signo __unused)791 toolong(int signo __unused)
792 {
793 
794 		/* XXXSIGRACE */
795 	reply(421,
796 	    "Timeout (" LLF " seconds): closing control connection.",
797 	    (LLT)curclass.timeout);
798 	if (logging)
799 		syslog(LOG_INFO, "User %s timed out after " LLF " seconds",
800 		    (pw ? pw->pw_name : "unknown"), (LLT)curclass.timeout);
801 	dologout(1);
802 }
803 
804 static void
sigquit(int signo)805 sigquit(int signo)
806 {
807 
808 	if (ftpd_debug)
809 		syslog(LOG_DEBUG, "got signal %d", signo);
810 	dologout(1);
811 }
812 
813 static void
sigurg(int signo __unused)814 sigurg(int signo __unused)
815 {
816 
817 	urgflag = 1;
818 }
819 
820 
821 /*
822  * Save the result of a getpwnam.  Used for USER command, since
823  * the data returned must not be clobbered by any other command
824  * (e.g., globbing).
825  */
826 static struct passwd *
sgetpwnam(const char * name)827 sgetpwnam(const char *name)
828 {
829 	static struct passwd save;
830 	struct passwd *p;
831 
832 	if ((p = getpwnam(name)) == NULL)
833 		return (p);
834 	if (save.pw_name) {
835 		free((char *)save.pw_name);
836 		memset(save.pw_passwd, 0, strlen(save.pw_passwd));
837 		free((char *)save.pw_passwd);
838 		free((char *)save.pw_gecos);
839 		free((char *)save.pw_dir);
840 		free((char *)save.pw_shell);
841 	}
842 	save = *p;
843 	save.pw_name = ftpd_strdup(p->pw_name);
844 	save.pw_passwd = ftpd_strdup(p->pw_passwd);
845 	save.pw_gecos = ftpd_strdup(p->pw_gecos);
846 	save.pw_dir = ftpd_strdup(p->pw_dir);
847 	save.pw_shell = ftpd_strdup(p->pw_shell);
848 	return (&save);
849 }
850 
851 static int	login_attempts;	/* number of failed login attempts */
852 static int	askpasswd;	/* had USER command, ask for PASSwd */
853 static int	permitted;	/* USER permitted */
854 
855 /*
856  * USER command.
857  * Sets global passwd pointer pw if named account exists and is acceptable;
858  * sets askpasswd if a PASS command is expected.  If logged in previously,
859  * need to reset state.  If name is "ftp" or "anonymous", the name is not in
860  * _NAME_FTPUSERS, and ftp account exists, set guest and pw, then just return.
861  * If account doesn't exist, ask for passwd anyway.  Otherwise, check user
862  * requesting login privileges.  Disallow anyone who does not have a standard
863  * shell as returned by getusershell().  Disallow anyone mentioned in the file
864  * _NAME_FTPUSERS to allow people such as root and uucp to be avoided.
865  */
866 void
user(const char * name)867 user(const char *name)
868 {
869 	char	*class;
870 #ifdef	LOGIN_CAP
871 	login_cap_t *lc = NULL;
872 #endif
873 #ifdef USE_PAM
874 	int e;
875 #endif
876 
877 	class = NULL;
878 	if (logged_in) {
879 		switch (curclass.type) {
880 		case CLASS_GUEST:
881 			reply(530, "Can't change user from guest login.");
882 			return;
883 		case CLASS_CHROOT:
884 			reply(530, "Can't change user from chroot user.");
885 			return;
886 		case CLASS_REAL:
887 			if (dropprivs) {
888 				reply(530, "Can't change user.");
889 				return;
890 			}
891 			end_login();
892 			break;
893 		default:
894 			abort();
895 		}
896 	}
897 
898 #if defined(KERBEROS)
899 	kdestroy();
900 #endif
901 #if defined(KERBEROS5)
902 	k5destroy();
903 #endif
904 
905 	curclass.type = CLASS_REAL;
906 	askpasswd = 0;
907 	permitted = 0;
908 
909 	if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
910 			/* need `pw' setup for checkaccess() and checkuser () */
911 		if ((pw = sgetpwnam("ftp")) == NULL)
912 			reply(530, "User %s unknown.", name);
913 		else if (! checkaccess("ftp") || ! checkaccess("anonymous"))
914 			reply(530, "User %s access denied.", name);
915 		else {
916 			curclass.type = CLASS_GUEST;
917 			askpasswd = 1;
918 			reply(331,
919 			    "Guest login ok, type your name as password.");
920 		}
921 		if (!askpasswd) {
922 			if (logging)
923 				syslog(LOG_NOTICE,
924 				    "ANONYMOUS FTP LOGIN REFUSED FROM %s",
925 				    remoteloghost);
926 			end_login();
927 			goto cleanup_user;
928 		}
929 		name = "ftp";
930 	} else
931 		pw = sgetpwnam(name);
932 
933 	strlcpy(curname, name, curname_len);
934 
935 			/* check user in /etc/ftpusers, and setup class */
936 	permitted = checkuser(_NAME_FTPUSERS, curname, 1, 0, &class);
937 
938 			/* check user in /etc/ftpchroot */
939 #ifdef	LOGIN_CAP
940 	lc = login_getpwclass(pw);
941 #endif
942 	if (checkuser(_NAME_FTPCHROOT, curname, 0, 0, NULL)
943 #ifdef	LOGIN_CAP	/* Allow login.conf configuration as well */
944 	    || login_getcapbool(lc, "ftp-chroot", 0)
945 #endif
946 	) {
947 		if (curclass.type == CLASS_GUEST) {
948 			syslog(LOG_NOTICE,
949 	    "Can't change guest user to chroot class; remove entry in %s",
950 			    _NAME_FTPCHROOT);
951 			exit(1);
952 		}
953 		curclass.type = CLASS_CHROOT;
954 	}
955 
956 			/* determine default class */
957 	if (class == NULL) {
958 		switch (curclass.type) {
959 		case CLASS_GUEST:
960 			class = ftpd_strdup("guest");
961 			break;
962 		case CLASS_CHROOT:
963 			class = ftpd_strdup("chroot");
964 			break;
965 		case CLASS_REAL:
966 			class = ftpd_strdup("real");
967 			break;
968 		default:
969 			syslog(LOG_ERR, "unknown curclass.type %d; aborting",
970 			    curclass.type);
971 			abort();
972 		}
973 	}
974 			/* parse ftpd.conf, setting up various parameters */
975 	parse_conf(class);
976 			/* if not guest user, check for valid shell */
977 	if (pw == NULL)
978 		permitted = 0;
979 	else {
980 		const char	*cp, *shell;
981 
982 		if ((shell = pw->pw_shell) == NULL || *shell == 0)
983 			shell = _PATH_BSHELL;
984 		while ((cp = getusershell()) != NULL)
985 			if (strcmp(cp, shell) == 0)
986 				break;
987 		endusershell();
988 		if (cp == NULL && curclass.type != CLASS_GUEST)
989 			permitted = 0;
990 	}
991 
992 			/* deny quickly (after USER not PASS) if requested */
993 	if (CURCLASS_FLAGS_ISSET(denyquick) && !permitted) {
994 		reply(530, "User %s may not use FTP.", curname);
995 		if (logging)
996 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
997 			    remoteloghost, curname);
998 		end_login();
999 		goto cleanup_user;
1000 	}
1001 
1002 			/* if haven't asked yet (i.e, not anon), ask now */
1003 	if (!askpasswd) {
1004 		askpasswd = 1;
1005 #ifdef USE_PAM
1006 		e = auth_pam();		/* this does reply(331, ...) */
1007 		do_pass(1, e, "");
1008 		goto cleanup_user;
1009 #else /* !USE_PAM */
1010 #ifdef SKEY
1011 		if (skey_haskey(curname) == 0) {
1012 			const char *myskey;
1013 
1014 			myskey = skey_keyinfo(curname);
1015 			reply(331, "Password [ %s ] required for %s.",
1016 			    myskey ? myskey : "error getting challenge",
1017 			    curname);
1018 		} else
1019 #endif
1020 			reply(331, "Password required for %s.", curname);
1021 #endif /* !USE_PAM */
1022 	}
1023 
1024  cleanup_user:
1025 #ifdef LOGIN_CAP
1026 	login_close(lc);
1027 #endif
1028 	/*
1029 	 * Delay before reading passwd after first failed
1030 	 * attempt to slow down passwd-guessing programs.
1031 	 */
1032 	if (login_attempts)
1033 		sleep((unsigned) login_attempts);
1034 
1035 	if (class)
1036 		free(class);
1037 }
1038 
1039 /*
1040  * Determine whether something is to happen (allow access, chroot)
1041  * for a user. Each line is a shell-style glob followed by
1042  * `yes' or `no'.
1043  *
1044  * For backward compatibility, `allow' and `deny' are synonymns
1045  * for `yes' and `no', respectively.
1046  *
1047  * Each glob is matched against the username in turn, and the first
1048  * match found is used. If no match is found, the result is the
1049  * argument `def'. If a match is found but without and explicit
1050  * `yes'/`no', the result is the opposite of def.
1051  *
1052  * If the file doesn't exist at all, the result is the argument
1053  * `nofile'
1054  *
1055  * Any line starting with `#' is considered a comment and ignored.
1056  *
1057  * Returns 0 if the user is denied, or 1 if they are allowed.
1058  *
1059  * NOTE: needs struct passwd *pw setup before use.
1060  */
1061 static int
checkuser(const char * fname,const char * name,int def,int nofile,char ** retclass)1062 checkuser(const char *fname, const char *name, int def, int nofile,
1063 	    char **retclass)
1064 {
1065 	FILE	*fd;
1066 	int	 retval;
1067 	char	*word, *perm, *class, *buf, *p;
1068 	size_t	 len, line;
1069 
1070 	retval = def;
1071 	if (retclass != NULL)
1072 		*retclass = NULL;
1073 	if ((fd = fopen(conffilename(fname), "r")) == NULL)
1074 		return nofile;
1075 
1076 	line = 0;
1077 	for (;
1078 	    (buf = fparseln(fd, &len, &line, NULL, FPARSELN_UNESCCOMM |
1079 			    FPARSELN_UNESCCONT | FPARSELN_UNESCESC)) != NULL;
1080 	    free(buf), buf = NULL) {
1081 		word = perm = class = NULL;
1082 		p = buf;
1083 		if (len < 1)
1084 			continue;
1085 		if (p[len - 1] == '\n')
1086 			p[--len] = '\0';
1087 		if (EMPTYSTR(p))
1088 			continue;
1089 
1090 		NEXTWORD(p, word);
1091 		NEXTWORD(p, perm);
1092 		NEXTWORD(p, class);
1093 		if (EMPTYSTR(word))
1094 			continue;
1095 		if (!EMPTYSTR(class)) {
1096 			if (strcasecmp(class, "all") == 0 ||
1097 			    strcasecmp(class, "none") == 0) {
1098 				syslog(LOG_WARNING,
1099 		"%s line %d: illegal user-defined class `%s' - skipping entry",
1100 					    fname, (int)line, class);
1101 				continue;
1102 			}
1103 		}
1104 
1105 					/* have a host specifier */
1106 		if ((p = strchr(word, '@')) != NULL) {
1107 			unsigned char	net[16], mask[16], *addr;
1108 			int		addrlen, bits, bytes, a;
1109 
1110 			*p++ = '\0';
1111 					/* check against network or CIDR */
1112 			memset(net, 0x00, sizeof(net));
1113 			if ((bits = inet_net_pton(his_addr.su_family, p, net,
1114 			    sizeof(net))) != -1) {
1115 #ifdef INET6
1116 				if (his_addr.su_family == AF_INET) {
1117 #endif
1118 					addrlen = 4;
1119 					addr = (unsigned char *)&his_addr.su_addr;
1120 #ifdef INET6
1121 				} else {
1122 					addrlen = 16;
1123 					addr = (unsigned char *)&his_addr.su_6addr;
1124 				}
1125 #endif
1126 				bytes = bits / 8;
1127 				bits = bits % 8;
1128 				if (bytes > 0)
1129 					memset(mask, 0xFF, bytes);
1130 				if (bytes < addrlen)
1131 					mask[bytes] = 0xFF << (8 - bits);
1132 				if (bytes + 1 < addrlen)
1133 					memset(mask + bytes + 1, 0x00,
1134 					    addrlen - bytes - 1);
1135 				for (a = 0; a < addrlen; a++)
1136 					if ((addr[a] & mask[a]) != net[a])
1137 						break;
1138 				if (a < addrlen)
1139 					continue;
1140 
1141 					/* check against hostname glob */
1142 			} else if (fnmatch(p, remotehost, FNM_CASEFOLD) != 0)
1143 				continue;
1144 		}
1145 
1146 					/* have a group specifier */
1147 		if ((p = strchr(word, ':')) != NULL) {
1148 			gid_t	*groups, *ng;
1149 			int	 gsize, i, found;
1150 
1151 			if (pw == NULL)
1152 				continue;	/* no match for unknown user */
1153 			*p++ = '\0';
1154 			groups = NULL;
1155 			gsize = 16;
1156 			do {
1157 				ng = realloc(groups, gsize * sizeof(gid_t));
1158 				if (ng == NULL)
1159 					fatal(
1160 					    "Local resource failure: realloc");
1161 				groups = ng;
1162 			} while (getgrouplist(pw->pw_name, pw->pw_gid,
1163 						groups, &gsize) == -1);
1164 			found = 0;
1165 			for (i = 0; i < gsize; i++) {
1166 				struct group *g;
1167 
1168 				if ((g = getgrgid(groups[i])) == NULL)
1169 					continue;
1170 				if (fnmatch(p, g->gr_name, 0) == 0) {
1171 					found = 1;
1172 					break;
1173 				}
1174 			}
1175 			free(groups);
1176 			if (!found)
1177 				continue;
1178 		}
1179 
1180 					/* check against username glob */
1181 		if (fnmatch(word, name, 0) != 0)
1182 			continue;
1183 
1184 		if (perm != NULL &&
1185 		    ((strcasecmp(perm, "allow") == 0) ||
1186 		     (strcasecmp(perm, "yes") == 0)))
1187 			retval = 1;
1188 		else if (perm != NULL &&
1189 		    ((strcasecmp(perm, "deny") == 0) ||
1190 		     (strcasecmp(perm, "no") == 0)))
1191 			retval = 0;
1192 		else
1193 			retval = !def;
1194 		if (!EMPTYSTR(class) && retclass != NULL)
1195 			*retclass = ftpd_strdup(class);
1196 		free(buf);
1197 		break;
1198 	}
1199 	(void) fclose(fd);
1200 	return (retval);
1201 }
1202 
1203 /*
1204  * Check if user is allowed by /etc/ftpusers
1205  * returns 1 for yes, 0 for no
1206  *
1207  * NOTE: needs struct passwd *pw setup (for checkuser())
1208  */
1209 static int
checkaccess(const char * name)1210 checkaccess(const char *name)
1211 {
1212 
1213 	return (checkuser(_NAME_FTPUSERS, name, 1, 0, NULL));
1214 }
1215 
1216 static void
login_utmp(const char * line,const char * name,const char * host,struct sockinet * haddr)1217 login_utmp(const char *line, const char *name, const char *host,
1218     struct sockinet *haddr)
1219 {
1220 #if defined(SUPPORT_UTMPX) || defined(SUPPORT_UTMP)
1221 	struct timeval tv;
1222 	(void)gettimeofday(&tv, NULL);
1223 #endif
1224 #ifdef SUPPORT_UTMPX
1225 	if (doutmp) {
1226 		(void)memset(&utmpx, 0, sizeof(utmpx));
1227 		utmpx.ut_tv = tv;
1228 		utmpx.ut_pid = getpid();
1229 		utmpx.ut_id[0] = 'f';
1230 		utmpx.ut_id[1] = 't';
1231 		utmpx.ut_id[2] = 'p';
1232 		utmpx.ut_id[3] = '*';
1233 		utmpx.ut_type = USER_PROCESS;
1234 		(void)strncpy(utmpx.ut_name, name, sizeof(utmpx.ut_name));
1235 		(void)strncpy(utmpx.ut_line, line, sizeof(utmpx.ut_line));
1236 		(void)strncpy(utmpx.ut_host, host, sizeof(utmpx.ut_host));
1237 		(void)memcpy(&utmpx.ut_ss, &haddr->si_su, haddr->su_len);
1238 		ftpd_loginx(&utmpx);
1239 	}
1240 	if (dowtmp)
1241 		ftpd_logwtmpx(line, name, host, haddr, 0, USER_PROCESS);
1242 #endif
1243 #ifdef SUPPORT_UTMP
1244 	if (doutmp) {
1245 		(void)memset(&utmp, 0, sizeof(utmp));
1246 		(void)time(&utmp.ut_time);
1247 		(void)strncpy(utmp.ut_name, name, sizeof(utmp.ut_name));
1248 		(void)strncpy(utmp.ut_line, line, sizeof(utmp.ut_line));
1249 		(void)strncpy(utmp.ut_host, host, sizeof(utmp.ut_host));
1250 		ftpd_login(&utmp);
1251 	}
1252 	if (dowtmp)
1253 		ftpd_logwtmp(line, name, host);
1254 #endif
1255 }
1256 
1257 static void
logout_utmp(void)1258 logout_utmp(void)
1259 {
1260 #ifdef SUPPORT_UTMPX
1261 	int okwtmpx = dowtmp;
1262 #endif
1263 #ifdef SUPPORT_UTMP
1264 	int okwtmp = dowtmp;
1265 #endif
1266 	if (logged_in) {
1267 #ifdef SUPPORT_UTMPX
1268 		if (doutmp)
1269 			okwtmpx &= ftpd_logoutx(ttyline, 0, DEAD_PROCESS);
1270 		if (okwtmpx)
1271 			ftpd_logwtmpx(ttyline, "", "", NULL, 0, DEAD_PROCESS);
1272 #endif
1273 #ifdef SUPPORT_UTMP
1274 		if (doutmp)
1275 			okwtmp &= ftpd_logout(ttyline);
1276 		if (okwtmp)
1277 			ftpd_logwtmp(ttyline, "", "");
1278 #endif
1279 	}
1280 }
1281 
1282 /*
1283  * Terminate login as previous user (if any), resetting state;
1284  * used when USER command is given or login fails.
1285  */
1286 static void
end_login(void)1287 end_login(void)
1288 {
1289 #ifdef USE_PAM
1290 	int e;
1291 #endif
1292 	logout_utmp();
1293 	show_chdir_messages(-1);		/* flush chdir cache */
1294 	if (pw != NULL && pw->pw_passwd != NULL)
1295 		memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
1296 	pw = NULL;
1297 	logged_in = 0;
1298 	askpasswd = 0;
1299 	permitted = 0;
1300 	quietmessages = 0;
1301 	gidcount = 0;
1302 	curclass.type = CLASS_REAL;
1303 	(void) seteuid((uid_t)0);
1304 #ifdef	LOGIN_CAP
1305 	setusercontext(NULL, getpwuid(0), 0,
1306 		       LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1307 #endif
1308 #ifdef USE_PAM
1309 	if (pamh) {
1310 		if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1311 			syslog(LOG_ERR, "pam_setcred: %s",
1312 			    pam_strerror(pamh, e));
1313 		if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1314 			syslog(LOG_ERR, "pam_close_session: %s",
1315 			    pam_strerror(pamh, e));
1316 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1317 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1318 		pamh = NULL;
1319 	}
1320 #endif
1321 }
1322 
1323 void
pass(const char * passwd)1324 pass(const char *passwd)
1325 {
1326 	do_pass(0, 0, passwd);
1327 }
1328 
1329 /*
1330  * Perform the passwd confirmation and login.
1331  *
1332  * If pass_checked is zero, confirm passwd is correct, & ignore pass_rval.
1333  * This is the traditional PASS implementation.
1334  *
1335  * If pass_checked is non-zero, use pass_rval and ignore passwd.
1336  * This is used by auth_pam() which has already parsed PASS.
1337  * This only applies to curclass.type != CLASS_GUEST.
1338  */
1339 static void
do_pass(int pass_checked,int pass_rval,const char * passwd)1340 do_pass(int pass_checked, int pass_rval, const char *passwd)
1341 {
1342 	int		 rval;
1343 	char		 root[MAXPATHLEN];
1344 #ifdef	LOGIN_CAP
1345 	login_cap_t *lc = NULL;
1346 #endif
1347 #ifdef USE_PAM
1348 	int e;
1349 #endif
1350 
1351 	rval = 1;
1352 
1353 	if (logged_in || askpasswd == 0) {
1354 		reply(503, "Login with USER first.");
1355 		return;
1356 	}
1357 	askpasswd = 0;
1358 	if (curclass.type != CLASS_GUEST) {
1359 			/* "ftp" is the only account allowed with no password */
1360 		if (pw == NULL) {
1361 			rval = 1;	/* failure below */
1362 			goto skip;
1363 		}
1364 		if (pass_checked) {	/* password validated in user() */
1365 			rval = pass_rval;
1366 			goto skip;
1367 		}
1368 #ifdef USE_PAM
1369 		syslog(LOG_ERR, "do_pass: USE_PAM shouldn't get here");
1370 		rval = 1;
1371 		goto skip;
1372 #endif
1373 #if defined(KERBEROS)
1374 		if (klogin(pw, "", hostname, (char *)passwd) == 0) {
1375 			rval = 0;
1376 			goto skip;
1377 		}
1378 #endif
1379 #if defined(KERBEROS5)
1380 		if (k5login(pw, "", hostname, (char *)passwd) == 0) {
1381 			rval = 0;
1382 			goto skip;
1383 		}
1384 #endif
1385 #ifdef SKEY
1386 		if (skey_haskey(pw->pw_name) == 0) {
1387 			char *p;
1388 			int r;
1389 
1390 			p = ftpd_strdup(passwd);
1391 			r = skey_passcheck(pw->pw_name, p);
1392 			free(p);
1393 			if (r != -1) {
1394 				rval = 0;
1395 				goto skip;
1396 			}
1397 		}
1398 #endif
1399 		if (!sflag)
1400 			rval = checkpassword(pw, passwd);
1401 		else
1402 			rval = 1;
1403 
1404  skip:
1405 
1406 			/*
1407 			 * If rval > 0, the user failed the authentication check
1408 			 * above.  If rval == 0, either Kerberos or local
1409 			 * authentication succeeded.
1410 			 */
1411 		if (rval) {
1412 			reply(530, "%s", rval == 2 ? "Password expired." :
1413 			    "Login incorrect.");
1414 			pfilter_notify(1, rval == 2 ? "exppass" : "badpass");
1415 			if (logging) {
1416 				syslog(LOG_NOTICE,
1417 				    "FTP LOGIN FAILED FROM %s", remoteloghost);
1418 				syslog(LOG_AUTHPRIV | LOG_NOTICE,
1419 				    "FTP LOGIN FAILED FROM %s, %s",
1420 				    remoteloghost, curname);
1421 			}
1422 			pw = NULL;
1423 			if (login_attempts++ >= 5) {
1424 				syslog(LOG_NOTICE,
1425 				    "repeated login failures from %s",
1426 				    remoteloghost);
1427 				exit(0);
1428 			}
1429 			return;
1430 		}
1431 	}
1432 
1433 			/* password ok; check if anything else prevents login */
1434 	if (! permitted) {
1435 		reply(530, "User %s may not use FTP.", pw->pw_name);
1436 		if (logging)
1437 			syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s",
1438 			    remoteloghost, pw->pw_name);
1439 		goto bad;
1440 	}
1441 
1442 	login_attempts = 0;		/* this time successful */
1443 	if (setegid((gid_t)pw->pw_gid) < 0) {
1444 		reply(550, "Can't set gid.");
1445 		goto bad;
1446 	}
1447 #ifdef	LOGIN_CAP
1448 	if ((lc = login_getpwclass(pw)) != NULL) {
1449 #ifdef notyet
1450 		char	remote_ip[NI_MAXHOST];
1451 
1452 		if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1453 			remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1454 			NI_NUMERICHOST))
1455 				*remote_ip = 0;
1456 		remote_ip[sizeof(remote_ip) - 1] = 0;
1457 		if (!auth_hostok(lc, remotehost, remote_ip)) {
1458 			pfilter_notify(1, "bannedhost");
1459 			syslog(LOG_INFO|LOG_AUTH,
1460 			    "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1461 			    pw->pw_name);
1462 			reply(530, "Permission denied.");
1463 			pw = NULL;
1464 			return;
1465 		}
1466 		if (!auth_timeok(lc, time(NULL))) {
1467 			reply(530, "Login not available right now.");
1468 			pw = NULL;
1469 			return;
1470 		}
1471 #endif
1472 	}
1473 	setsid();
1474 	setusercontext(lc, pw, 0,
1475 		LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1476 		LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1477 #else
1478 	(void) initgroups(pw->pw_name, pw->pw_gid);
1479 			/* cache groups for cmds.c::matchgroup() */
1480 #endif
1481 #ifdef USE_PAM
1482 	if (pamh) {
1483 		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1484 			syslog(LOG_ERR, "pam_open_session: %s",
1485 			    pam_strerror(pamh, e));
1486 		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
1487 		    != PAM_SUCCESS) {
1488 			syslog(LOG_ERR, "pam_setcred: %s",
1489 			    pam_strerror(pamh, e));
1490 		}
1491 	}
1492 #endif
1493 	gidcount = getgroups(0, NULL);
1494 	if (gidlist)
1495 		free(gidlist);
1496 	gidlist = malloc(gidcount * sizeof *gidlist);
1497 	gidcount = getgroups(gidcount, gidlist);
1498 
1499 	/* open utmp/wtmp before chroot */
1500 	login_utmp(ttyline, pw->pw_name, remotehost, &his_addr);
1501 
1502 	logged_in = 1;
1503 
1504 	connections = 1;
1505 	if (dopidfile)
1506 		count_users();
1507 	if (curclass.limit != -1 && connections > curclass.limit) {
1508 		if (! EMPTYSTR(curclass.limitfile))
1509 			(void)display_file(conffilename(curclass.limitfile),
1510 			    530);
1511 		reply(530,
1512 		    "User %s access denied, connection limit of " LLF
1513 		    " reached.",
1514 		    pw->pw_name, (LLT)curclass.limit);
1515 		syslog(LOG_NOTICE,
1516 		    "Maximum connection limit of " LLF
1517 		    " for class %s reached, login refused for %s",
1518 		    (LLT)curclass.limit, curclass.classname, pw->pw_name);
1519 		goto bad;
1520 	}
1521 
1522 	homedir[0] = '/';
1523 	switch (curclass.type) {
1524 	case CLASS_GUEST:
1525 			/*
1526 			 * We MUST do a chdir() after the chroot. Otherwise
1527 			 * the old current directory will be accessible as "."
1528 			 * outside the new root!
1529 			 */
1530 		format_path(root,
1531 		    curclass.chroot ? curclass.chroot :
1532 		    anondir ? anondir :
1533 		    pw->pw_dir);
1534 		format_path(homedir,
1535 		    curclass.homedir ? curclass.homedir :
1536 		    "/");
1537 		if (EMPTYSTR(homedir))
1538 			homedir[0] = '/';
1539 		if (EMPTYSTR(root) || chroot(root) < 0) {
1540 			syslog(LOG_NOTICE,
1541 			    "GUEST user %s: can't chroot to %s: %m",
1542 			    pw->pw_name, root);
1543 			goto bad_guest;
1544 		}
1545 		if (chdir(homedir) < 0) {
1546 			syslog(LOG_NOTICE,
1547 			    "GUEST user %s: can't chdir to %s: %m",
1548 			    pw->pw_name, homedir);
1549  bad_guest:
1550 			fatal("Can't set guest privileges.");
1551 		}
1552 		break;
1553 	case CLASS_CHROOT:
1554 		format_path(root,
1555 		    curclass.chroot ? curclass.chroot :
1556 		    pw->pw_dir);
1557 		format_path(homedir,
1558 		    curclass.homedir ? curclass.homedir :
1559 		    "/");
1560 		if (EMPTYSTR(homedir))
1561 			homedir[0] = '/';
1562 		if (EMPTYSTR(root) || chroot(root) < 0) {
1563 			syslog(LOG_NOTICE,
1564 			    "CHROOT user %s: can't chroot to %s: %m",
1565 			    pw->pw_name, root);
1566 			goto bad_chroot;
1567 		}
1568 		if (chdir(homedir) < 0) {
1569 			syslog(LOG_NOTICE,
1570 			    "CHROOT user %s: can't chdir to %s: %m",
1571 			    pw->pw_name, homedir);
1572  bad_chroot:
1573 			fatal("Can't change root.");
1574 		}
1575 		break;
1576 	case CLASS_REAL:
1577 			/* only chroot REAL if explicitly requested */
1578 		if (! EMPTYSTR(curclass.chroot)) {
1579 			format_path(root, curclass.chroot);
1580 			if (EMPTYSTR(root) || chroot(root) < 0) {
1581 				syslog(LOG_NOTICE,
1582 				    "REAL user %s: can't chroot to %s: %m",
1583 				    pw->pw_name, root);
1584 				goto bad_chroot;
1585 			}
1586 		}
1587 		format_path(homedir,
1588 		    curclass.homedir ? curclass.homedir :
1589 		    pw->pw_dir);
1590 		if (EMPTYSTR(homedir) || chdir(homedir) < 0) {
1591 			if (chdir("/") < 0) {
1592 				syslog(LOG_NOTICE,
1593 				    "REAL user %s: can't chdir to %s: %m",
1594 				    pw->pw_name,
1595 				    !EMPTYSTR(homedir) ?  homedir : "/");
1596 				reply(530,
1597 				    "User %s: can't change directory to %s.",
1598 				    pw->pw_name,
1599 				    !EMPTYSTR(homedir) ? homedir : "/");
1600 				goto bad;
1601 			} else {
1602 				reply(-230,
1603 				    "No directory! Logging in with home=/");
1604 				homedir[0] = '/';
1605 			}
1606 		}
1607 		break;
1608 	}
1609 #ifndef LOGIN_CAP
1610 	setsid();
1611 	setlogin(pw->pw_name);
1612 #endif
1613 	if (dropprivs ||
1614 	    (curclass.type != CLASS_REAL &&
1615 	    ntohs(ctrl_addr.su_port) > IPPORT_RESERVED + 1)) {
1616 		dropprivs++;
1617 		if (setgid((gid_t)pw->pw_gid) < 0) {
1618 			reply(550, "Can't set gid.");
1619 			goto bad_perms;
1620 		}
1621 		if (setuid((uid_t)pw->pw_uid) < 0) {
1622 			reply(550, "Can't set uid.");
1623 			goto bad_perms;
1624 		}
1625 	} else {
1626 		if (seteuid((uid_t)pw->pw_uid) < 0) {
1627 			reply(550, "Can't set uid.");
1628 			goto bad_perms;
1629 		}
1630 	}
1631 	setenv("HOME", homedir, 1);
1632 
1633 	if (curclass.type == CLASS_GUEST && passwd[0] == '-')
1634 		quietmessages = 1;
1635 
1636 			/*
1637 			 * Display a login message, if it exists.
1638 			 * N.B. reply(230,) must follow the message.
1639 			 */
1640 	if (! EMPTYSTR(curclass.motd))
1641 		(void)display_file(conffilename(curclass.motd), 230);
1642 	show_chdir_messages(230);
1643 	if (curclass.type == CLASS_GUEST) {
1644 		char *p;
1645 
1646 		reply(230, "Guest login ok, access restrictions apply.");
1647 #if defined(HAVE_SETPROCTITLE)
1648 		snprintf(proctitle, sizeof(proctitle),
1649 		    "%s: anonymous/%s", remotehost, passwd);
1650 		setproctitle("%s", proctitle);
1651 #endif /* defined(HAVE_SETPROCTITLE) */
1652 		if (logging)
1653 			syslog(LOG_INFO,
1654 			"ANONYMOUS FTP LOGIN FROM %s, %s (class: %s, type: %s)",
1655 			    remoteloghost, passwd,
1656 			    curclass.classname, CURCLASSTYPE);
1657 			/* store guest password reply into pw_passwd */
1658 		REASSIGN(pw->pw_passwd, ftpd_strdup(passwd));
1659 		for (p = pw->pw_passwd; *p; p++)
1660 			if (!isgraph((unsigned char)*p))
1661 				*p = '_';
1662 	} else {
1663 		reply(230, "User %s logged in.", pw->pw_name);
1664 #if defined(HAVE_SETPROCTITLE)
1665 		snprintf(proctitle, sizeof(proctitle),
1666 		    "%s: %s", remotehost, pw->pw_name);
1667 		setproctitle("%s", proctitle);
1668 #endif /* defined(HAVE_SETPROCTITLE) */
1669 		if (logging)
1670 			syslog(LOG_INFO,
1671 			    "FTP LOGIN FROM %s as %s (class: %s, type: %s)",
1672 			    remoteloghost, pw->pw_name,
1673 			    curclass.classname, CURCLASSTYPE);
1674 	}
1675 	(void) umask(curclass.umask);
1676 #ifdef	LOGIN_CAP
1677 	login_close(lc);
1678 #endif
1679 	return;
1680 
1681  bad:
1682 #ifdef	LOGIN_CAP
1683 	login_close(lc);
1684 #endif
1685 			/* Forget all about it... */
1686 	end_login();
1687 	return;
1688 
1689 bad_perms:
1690 	syslog(LOG_NOTICE, "user %s: can't setuid/gid: %m", pw->pw_name);
1691 	fatal("Can't drop privileges.");
1692 }
1693 
1694 void
retrieve(const char * argv[],const char * name)1695 retrieve(const char *argv[], const char *name)
1696 {
1697 	FILE *fin, *dout;
1698 	struct stat st;
1699 	int (*closefunc)(FILE *) = NULL;
1700 	int dolog, sendrv, closerv, stderrfd, isconversion, isdata, isls;
1701 	struct timeval start, finish, td, *tdp;
1702 	struct rusage rusage_before, rusage_after;
1703 	const char *dispname;
1704 	const char *error;
1705 
1706 	sendrv = closerv = stderrfd = -1;
1707 	isconversion = isdata = isls = dolog = 0;
1708 	tdp = NULL;
1709 	dispname = name;
1710 	fin = dout = NULL;
1711 	error = NULL;
1712 	if (argv == NULL) {		/* if not running a command ... */
1713 		dolog = 1;
1714 		isdata = 1;
1715 		fin = fopen(name, "r");
1716 		closefunc = fclose;
1717 		if (fin == NULL)	/* doesn't exist?; try a conversion */
1718 			argv = do_conversion(name);
1719 		if (argv != NULL) {
1720 			isconversion++;
1721 			syslog(LOG_DEBUG, "get command: '%s' on '%s'",
1722 			    argv[0], name);
1723 		}
1724 	}
1725 	if (argv != NULL) {
1726 		char temp[MAXPATHLEN];
1727 
1728 		if (strcmp(argv[0], INTERNAL_LS) == 0) {
1729 			isls = 1;
1730 			stderrfd = -1;
1731 		} else {
1732 			(void)snprintf(temp, sizeof(temp), "%s", TMPFILE);
1733 			stderrfd = mkstemp(temp);
1734 			if (stderrfd != -1)
1735 				(void)unlink(temp);
1736 		}
1737 		dispname = argv[0];
1738 		fin = ftpd_popen(argv, "r", stderrfd);
1739 		closefunc = ftpd_pclose;
1740 		st.st_size = -1;
1741 		st.st_blksize = BUFSIZ;
1742 	}
1743 	if (fin == NULL) {
1744 		if (errno != 0) {
1745 			perror_reply(550, dispname);
1746 			if (dolog)
1747 				logxfer("get", -1, name, NULL, NULL,
1748 				    strerror(errno));
1749 		}
1750 		goto cleanupretrieve;
1751 	}
1752 	byte_count = -1;
1753 	if (argv == NULL
1754 	    && (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode))) {
1755 		error = "Not a plain file";
1756 		reply(550, "%s: %s.", dispname, error);
1757 		goto done;
1758 	}
1759 	if (restart_point) {
1760 		if (type == TYPE_A) {
1761 			off_t i;
1762 			int c;
1763 
1764 			for (i = 0; i < restart_point; i++) {
1765 				if ((c=getc(fin)) == EOF) {
1766 					error = strerror(errno);
1767 					perror_reply(550, dispname);
1768 					goto done;
1769 				}
1770 				if (c == '\n')
1771 					i++;
1772 			}
1773 		} else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1774 			error = strerror(errno);
1775 			perror_reply(550, dispname);
1776 			goto done;
1777 		}
1778 	}
1779 	dout = dataconn(dispname, st.st_size, "w");
1780 	if (dout == NULL)
1781 		goto done;
1782 
1783 	(void)getrusage(RUSAGE_SELF, &rusage_before);
1784 	(void)gettimeofday(&start, NULL);
1785 	sendrv = send_data(fin, dout, &st, isdata);
1786 	(void)gettimeofday(&finish, NULL);
1787 	(void)getrusage(RUSAGE_SELF, &rusage_after);
1788 	closedataconn(dout);		/* close now to affect timing stats */
1789 	timersub(&finish, &start, &td);
1790 	tdp = &td;
1791  done:
1792 	if (dolog) {
1793 		logxfer("get", byte_count, name, NULL, tdp, error);
1794 		if (tdp != NULL)
1795 			logrusage(&rusage_before, &rusage_after);
1796 	}
1797 	closerv = (*closefunc)(fin);
1798 	if (sendrv == 0) {
1799 		FILE *errf;
1800 		struct stat sb;
1801 
1802 		if (!isls && argv != NULL && closerv != 0) {
1803 			reply(-226,
1804 			    "Command returned an exit status of %d",
1805 			    closerv);
1806 			if (isconversion)
1807 				syslog(LOG_WARNING,
1808 				    "retrieve command: '%s' returned %d",
1809 				    argv[0], closerv);
1810 		}
1811 		if (!isls && argv != NULL && stderrfd != -1 &&
1812 		    (fstat(stderrfd, &sb) == 0) && sb.st_size > 0 &&
1813 		    ((errf = fdopen(stderrfd, "r")) != NULL)) {
1814 			char *cp, line[LINE_MAX];
1815 
1816 			reply(-226, "Command error messages:");
1817 			rewind(errf);
1818 			while (fgets(line, sizeof(line), errf) != NULL) {
1819 				if ((cp = strchr(line, '\n')) != NULL)
1820 					*cp = '\0';
1821 				reply(0, "  %s", line);
1822 			}
1823 			(void) fflush(stdout);
1824 			(void) fclose(errf);
1825 				/* a reply(226,) must follow */
1826 		}
1827 		reply(226, "Transfer complete.");
1828 	}
1829  cleanupretrieve:
1830 	if (stderrfd != -1)
1831 		(void)close(stderrfd);
1832 	if (isconversion)
1833 		free(argv);
1834 }
1835 
1836 void
store(const char * name,const char * fmode,int unique)1837 store(const char *name, const char *fmode, int unique)
1838 {
1839 	FILE *fout, *din;
1840 	struct stat st;
1841 	int (*closefunc)(FILE *);
1842 	struct timeval start, finish, td, *tdp;
1843 	const char *desc, *error;
1844 
1845 	din = NULL;
1846 	desc = (*fmode == 'w') ? "put" : "append";
1847 	error = NULL;
1848 	if (unique && stat(name, &st) == 0 &&
1849 	    (name = gunique(name)) == NULL) {
1850 		logxfer(desc, -1, name, NULL, NULL,
1851 		    "cannot create unique file");
1852 		goto cleanupstore;
1853 	}
1854 
1855 	if (restart_point)
1856 		fmode = "r+";
1857 	fout = fopen(name, fmode);
1858 	closefunc = fclose;
1859 	tdp = NULL;
1860 	if (fout == NULL) {
1861 		perror_reply(553, name);
1862 		logxfer(desc, -1, name, NULL, NULL, strerror(errno));
1863 		goto cleanupstore;
1864 	}
1865 	byte_count = -1;
1866 	if (restart_point) {
1867 		if (type == TYPE_A) {
1868 			off_t i;
1869 			int c;
1870 
1871 			for (i = 0; i < restart_point; i++) {
1872 				if ((c=getc(fout)) == EOF) {
1873 					error = strerror(errno);
1874 					perror_reply(550, name);
1875 					goto done;
1876 				}
1877 				if (c == '\n')
1878 					i++;
1879 			}
1880 			/*
1881 			 * We must do this seek to "current" position
1882 			 * because we are changing from reading to
1883 			 * writing.
1884 			 */
1885 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
1886 				error = strerror(errno);
1887 				perror_reply(550, name);
1888 				goto done;
1889 			}
1890 		} else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1891 			error = strerror(errno);
1892 			perror_reply(550, name);
1893 			goto done;
1894 		}
1895 	}
1896 	din = dataconn(name, (off_t)-1, "r");
1897 	if (din == NULL)
1898 		goto done;
1899 	(void)gettimeofday(&start, NULL);
1900 	if (receive_data(din, fout) == 0) {
1901 		if (unique)
1902 			reply(226, "Transfer complete (unique file name:%s).",
1903 			    name);
1904 		else
1905 			reply(226, "Transfer complete.");
1906 	}
1907 	(void)gettimeofday(&finish, NULL);
1908 	closedataconn(din);		/* close now to affect timing stats */
1909 	timersub(&finish, &start, &td);
1910 	tdp = &td;
1911  done:
1912 	logxfer(desc, byte_count, name, NULL, tdp, error);
1913 	(*closefunc)(fout);
1914  cleanupstore:
1915 	;
1916 }
1917 
1918 static FILE *
getdatasock(const char * fmode)1919 getdatasock(const char *fmode)
1920 {
1921 	int		on, s, t, tries;
1922 	in_port_t	port;
1923 
1924 	on = 1;
1925 	if (data >= 0)
1926 		return (fdopen(data, fmode));
1927 	if (! dropprivs)
1928 		(void) seteuid((uid_t)0);
1929 	s = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
1930 	if (s < 0)
1931 		goto bad;
1932 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
1933 	    (char *) &on, sizeof(on)) < 0)
1934 		goto bad;
1935 	if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
1936 	    (char *) &on, sizeof(on)) < 0)
1937 		goto bad;
1938 			/* anchor socket to avoid multi-homing problems */
1939 	data_source = ctrl_addr;
1940 			/*
1941 			 * By default source port for PORT connctions is
1942 			 * ctrlport-1 (see RFC959 section 5.2).
1943 			 * However, if privs have been dropped and that
1944 			 * would be < IPPORT_RESERVED, use a random port
1945 			 * instead.
1946 			 */
1947 	if (dataport)
1948 		port = dataport;
1949 	else
1950 		port = ntohs(ctrl_addr.su_port) - 1;
1951 	if (dropprivs && port < IPPORT_RESERVED)
1952 		port = 0;		/* use random port */
1953 	data_source.su_port = htons(port);
1954 
1955 	for (tries = 1; ; tries++) {
1956 		if (bind(s, (struct sockaddr *)&data_source.si_su,
1957 		    data_source.su_len) >= 0)
1958 			break;
1959 		if (errno != EADDRINUSE || tries > 10)
1960 			goto bad;
1961 		sleep(tries);
1962 	}
1963 	if (! dropprivs)
1964 		(void) seteuid((uid_t)pw->pw_uid);
1965 #ifdef IP_TOS
1966 	if (!mapped && ctrl_addr.su_family == AF_INET) {
1967 		on = IPTOS_THROUGHPUT;
1968 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&on,
1969 			       sizeof(int)) < 0)
1970 			syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
1971 	}
1972 #endif
1973 	return (fdopen(s, fmode));
1974  bad:
1975 		/* Return the real value of errno (close may change it) */
1976 	t = errno;
1977 	if (! dropprivs)
1978 		(void) seteuid((uid_t)pw->pw_uid);
1979 	if (s >= 0)
1980 		(void) close(s);
1981 	errno = t;
1982 	return (NULL);
1983 }
1984 
1985 FILE *
dataconn(const char * name,off_t size,const char * fmode)1986 dataconn(const char *name, off_t size, const char *fmode)
1987 {
1988 	char sizebuf[32];
1989 	FILE *file;
1990 	int retry, tos, keepalive, conerrno;
1991 
1992 	file_size = size;
1993 	byte_count = 0;
1994 	if (size != (off_t) -1)
1995 		(void)snprintf(sizebuf, sizeof(sizebuf), " (" LLF " byte%s)",
1996 		    (LLT)size, PLURAL(size));
1997 	else
1998 		sizebuf[0] = '\0';
1999 	if (pdata >= 0) {
2000 		struct sockinet from;
2001 		int s;
2002 		socklen_t fromlen = sizeof(from.su_len);
2003 
2004 		(void) alarm(curclass.timeout);
2005 		s = accept(pdata, (struct sockaddr *)&from.si_su, &fromlen);
2006 		(void) alarm(0);
2007 		if (s < 0) {
2008 			reply(425, "Can't open data connection.");
2009 			(void) close(pdata);
2010 			pdata = -1;
2011 			return (NULL);
2012 		}
2013 		(void) close(pdata);
2014 		pdata = s;
2015 		switch (from.su_family) {
2016 		case AF_INET:
2017 #ifdef IP_TOS
2018 			if (!mapped) {
2019 				tos = IPTOS_THROUGHPUT;
2020 				(void) setsockopt(s, IPPROTO_IP, IP_TOS,
2021 				    (char *)&tos, sizeof(int));
2022 			}
2023 			break;
2024 #endif
2025 		}
2026 		/* Set keepalives on the socket to detect dropped conns. */
2027 #ifdef SO_KEEPALIVE
2028 		keepalive = 1;
2029 		(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
2030 		    (char *)&keepalive, sizeof(int));
2031 #endif
2032 		reply(150, "Opening %s mode data connection for '%s'%s.",
2033 		     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2034 		return (fdopen(pdata, fmode));
2035 	}
2036 	if (data >= 0) {
2037 		reply(125, "Using existing data connection for '%s'%s.",
2038 		    name, sizebuf);
2039 		usedefault = 1;
2040 		return (fdopen(data, fmode));
2041 	}
2042 	if (usedefault)
2043 		data_dest = his_addr;
2044 	usedefault = 1;
2045 	retry = conerrno = 0;
2046 	do {
2047 		file = getdatasock(fmode);
2048 		if (file == NULL) {
2049 			char hbuf[NI_MAXHOST];
2050 			char pbuf[NI_MAXSERV];
2051 
2052 			if (getnameinfo((struct sockaddr *)&data_source.si_su,
2053 			    data_source.su_len, hbuf, sizeof(hbuf), pbuf,
2054 			    sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV))
2055 				strlcpy(hbuf, "?", sizeof(hbuf));
2056 			reply(425, "Can't create data socket (%s,%s): %s.",
2057 			      hbuf, pbuf, strerror(errno));
2058 			return (NULL);
2059 		}
2060 		data = fileno(file);
2061 		conerrno = 0;
2062 		if (connect(data, (struct sockaddr *)&data_dest.si_su,
2063 		    data_dest.su_len) == 0)
2064 			break;
2065 		conerrno = errno;
2066 		(void) fclose(file);
2067 		file = NULL;
2068 		data = -1;
2069 		if (conerrno == EADDRINUSE) {
2070 			sleep((unsigned) swaitint);
2071 			retry += swaitint;
2072 		} else {
2073 			break;
2074 		}
2075 	} while (retry <= swaitmax);
2076 	if (conerrno != 0) {
2077 		perror_reply(425, "Can't build data connection");
2078 		return (NULL);
2079 	}
2080 	reply(150, "Opening %s mode data connection for '%s'%s.",
2081 	     type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2082 	return (file);
2083 }
2084 
2085 void
closedataconn(FILE * fd)2086 closedataconn(FILE *fd)
2087 {
2088 
2089 	if (fd == NULL)
2090 		return;
2091 	(void)fclose(fd);
2092 	data = -1;
2093 	if (pdata >= 0)
2094 		(void)close(pdata);
2095 	pdata = -1;
2096 }
2097 
2098 int
write_data(int fd,char * buf,size_t size,off_t * bufrem,struct timeval * then,int isdata)2099 write_data(int fd, char *buf, size_t size, off_t *bufrem,
2100     struct timeval *then, int isdata)
2101 {
2102 	struct timeval now, td;
2103 	ssize_t c;
2104 
2105 	while (size > 0) {
2106 		c = size;
2107 		if (curclass.writesize) {
2108 			if (curclass.writesize < c)
2109 				c = curclass.writesize;
2110 		}
2111 		if (curclass.rateget) {
2112 			if (*bufrem < c)
2113 				c = *bufrem;
2114 		}
2115 		(void) alarm(curclass.timeout);
2116 		c = write(fd, buf, c);
2117 		if (c <= 0)
2118 			return (1);
2119 		buf += c;
2120 		size -= c;
2121 		byte_count += c;
2122 		if (isdata) {
2123 			total_data_out += c;
2124 			total_data += c;
2125 		}
2126 		total_bytes_out += c;
2127 		total_bytes += c;
2128 		if (curclass.rateget) {
2129 			*bufrem -= c;
2130 			if (*bufrem == 0) {
2131 				(void)gettimeofday(&now, NULL);
2132 				timersub(&now, then, &td);
2133 				if (td.tv_sec == 0) {
2134 					usleep(1000000 - td.tv_usec);
2135 					(void)gettimeofday(then, NULL);
2136 				} else
2137 					*then = now;
2138 				*bufrem = curclass.rateget;
2139 			}
2140 		}
2141 	}
2142 	return (0);
2143 }
2144 
2145 static enum send_status
send_data_with_read(int filefd,int netfd,const struct stat * st,int isdata)2146 send_data_with_read(int filefd, int netfd, const struct stat *st, int isdata)
2147 {
2148 	struct timeval then;
2149 	off_t bufrem;
2150 	ssize_t readsize;
2151 	char *buf;
2152 	int c, error;
2153 
2154 	if (curclass.readsize > 0)
2155 		readsize = curclass.readsize;
2156 	else
2157 		readsize = st->st_blksize;
2158 	if ((buf = malloc(readsize)) == NULL) {
2159 		perror_reply(451, "Local resource failure: malloc");
2160 		return (SS_NO_TRANSFER);
2161 	}
2162 
2163 	if (curclass.rateget) {
2164 		bufrem = curclass.rateget;
2165 		(void)gettimeofday(&then, NULL);
2166 	} else
2167 		bufrem = readsize;
2168 	for (;;) {
2169 		(void) alarm(curclass.timeout);
2170 		c = read(filefd, buf, readsize);
2171 		if (c == 0)
2172 			error = SS_SUCCESS;
2173 		else if (c < 0)
2174 			error = SS_FILE_ERROR;
2175 		else if (write_data(netfd, buf, c, &bufrem, &then, isdata))
2176 			error = SS_DATA_ERROR;
2177 		else if (urgflag && handleoobcmd())
2178 			error = SS_ABORTED;
2179 		else
2180 			continue;
2181 
2182 		free(buf);
2183 		return (error);
2184 	}
2185 }
2186 
2187 static enum send_status
send_data_with_mmap(int filefd,int netfd,const struct stat * st,int isdata)2188 send_data_with_mmap(int filefd, int netfd, const struct stat *st, int isdata)
2189 {
2190 	struct timeval then;
2191 	off_t bufrem, filesize, off, origoff;
2192 	ssize_t mapsize, winsize;
2193 	int error, sendbufsize, sendlowat;
2194 	void *win;
2195 
2196 	bufrem = 0;
2197 	if (curclass.sendbufsize) {
2198 		sendbufsize = curclass.sendbufsize;
2199 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF,
2200 		    &sendbufsize, sizeof(int)) == -1)
2201 			syslog(LOG_WARNING, "setsockopt(SO_SNDBUF, %d): %m",
2202 			    sendbufsize);
2203 	}
2204 
2205 	if (curclass.sendlowat) {
2206 		sendlowat = curclass.sendlowat;
2207 		if (setsockopt(netfd, SOL_SOCKET, SO_SNDLOWAT,
2208 		    &sendlowat, sizeof(int)) == -1)
2209 			syslog(LOG_WARNING, "setsockopt(SO_SNDLOWAT, %d): %m",
2210 			    sendlowat);
2211 	}
2212 
2213 	winsize = curclass.mmapsize;
2214 	filesize = st->st_size;
2215 	if (ftpd_debug)
2216 		syslog(LOG_INFO, "mmapsize = " LLF ", writesize = " LLF,
2217 		    (LLT)winsize, (LLT)curclass.writesize);
2218 	if (winsize <= 0)
2219 		goto try_read;
2220 
2221 	off = lseek(filefd, (off_t)0, SEEK_CUR);
2222 	if (off == -1)
2223 		goto try_read;
2224 
2225 	origoff = off;
2226 	if (curclass.rateget) {
2227 		bufrem = curclass.rateget;
2228 		(void)gettimeofday(&then, NULL);
2229 	} else
2230 		bufrem = winsize;
2231 	while (1) {
2232 		mapsize = MIN(filesize - off, winsize);
2233 		if (mapsize == 0)
2234 			break;
2235 		win = mmap(NULL, mapsize, PROT_READ,
2236 		    MAP_FILE|MAP_SHARED, filefd, off);
2237 		if (win == MAP_FAILED) {
2238 			if (off == origoff)
2239 				goto try_read;
2240 			return (SS_FILE_ERROR);
2241 		}
2242 		(void) madvise(win, mapsize, MADV_SEQUENTIAL);
2243 		error = write_data(netfd, win, mapsize, &bufrem, &then,
2244 		    isdata);
2245 		(void) madvise(win, mapsize, MADV_DONTNEED);
2246 		munmap(win, mapsize);
2247 		if (urgflag && handleoobcmd())
2248 			return (SS_ABORTED);
2249 		if (error)
2250 			return (SS_DATA_ERROR);
2251 		off += mapsize;
2252 	}
2253 	return (SS_SUCCESS);
2254 
2255  try_read:
2256 	return (send_data_with_read(filefd, netfd, st, isdata));
2257 }
2258 
2259 /*
2260  * Transfer the contents of "instr" to "outstr" peer using the appropriate
2261  * encapsulation of the data subject to Mode, Structure, and Type.
2262  *
2263  * NB: Form isn't handled.
2264  */
2265 static int
send_data(FILE * instr,FILE * outstr,const struct stat * st,int isdata)2266 send_data(FILE *instr, FILE *outstr, const struct stat *st, int isdata)
2267 {
2268 	int	 c, filefd, netfd, rval;
2269 
2270 	urgflag = 0;
2271 	transflag = 1;
2272 	rval = -1;
2273 
2274 	switch (type) {
2275 
2276 	case TYPE_A:
2277  /* XXXLUKEM: rate limit ascii send (get) */
2278 		(void) alarm(curclass.timeout);
2279 		while ((c = getc(instr)) != EOF) {
2280 			if (urgflag && handleoobcmd())
2281 				goto cleanup_send_data;
2282 			byte_count++;
2283 			if (c == '\n') {
2284 				if (ferror(outstr))
2285 					goto data_err;
2286 				(void) putc('\r', outstr);
2287 				if (isdata) {
2288 					total_data_out++;
2289 					total_data++;
2290 				}
2291 				total_bytes_out++;
2292 				total_bytes++;
2293 			}
2294 			(void) putc(c, outstr);
2295 			if (isdata) {
2296 				total_data_out++;
2297 				total_data++;
2298 			}
2299 			total_bytes_out++;
2300 			total_bytes++;
2301 			if ((byte_count % 4096) == 0)
2302 				(void) alarm(curclass.timeout);
2303 		}
2304 		(void) alarm(0);
2305 		fflush(outstr);
2306 		if (ferror(instr))
2307 			goto file_err;
2308 		if (ferror(outstr))
2309 			goto data_err;
2310 		rval = 0;
2311 		goto cleanup_send_data;
2312 
2313 	case TYPE_I:
2314 	case TYPE_L:
2315 		filefd = fileno(instr);
2316 		netfd = fileno(outstr);
2317 		switch (send_data_with_mmap(filefd, netfd, st, isdata)) {
2318 
2319 		case SS_SUCCESS:
2320 			break;
2321 
2322 		case SS_ABORTED:
2323 		case SS_NO_TRANSFER:
2324 			goto cleanup_send_data;
2325 
2326 		case SS_FILE_ERROR:
2327 			goto file_err;
2328 
2329 		case SS_DATA_ERROR:
2330 			goto data_err;
2331 		}
2332 		rval = 0;
2333 		goto cleanup_send_data;
2334 
2335 	default:
2336 		reply(550, "Unimplemented TYPE %d in send_data", type);
2337 		goto cleanup_send_data;
2338 	}
2339 
2340  data_err:
2341 	(void) alarm(0);
2342 	perror_reply(426, "Data connection");
2343 	goto cleanup_send_data;
2344 
2345  file_err:
2346 	(void) alarm(0);
2347 	perror_reply(551, "Error on input file");
2348 	goto cleanup_send_data;
2349 
2350  cleanup_send_data:
2351 	(void) alarm(0);
2352 	transflag = 0;
2353 	urgflag = 0;
2354 	if (isdata) {
2355 		total_files_out++;
2356 		total_files++;
2357 	}
2358 	total_xfers_out++;
2359 	total_xfers++;
2360 	return (rval);
2361 }
2362 
2363 /*
2364  * Transfer data from peer to "outstr" using the appropriate encapulation of
2365  * the data subject to Mode, Structure, and Type.
2366  *
2367  * N.B.: Form isn't handled.
2368  */
2369 static int
receive_data(FILE * instr,FILE * outstr)2370 receive_data(FILE *instr, FILE *outstr)
2371 {
2372 	int	c, netfd, filefd, rval;
2373 	int	volatile bare_lfs;
2374 	off_t	byteswritten;
2375 	char	*buf;
2376 	ssize_t	readsize;
2377 	struct sigaction sa, sa_saved;
2378 	struct stat st;
2379 
2380 	memset(&sa, 0, sizeof(sa));
2381 	sigfillset(&sa.sa_mask);
2382 	sa.sa_flags = SA_RESTART;
2383 	sa.sa_handler = lostconn;
2384 	(void) sigaction(SIGALRM, &sa, &sa_saved);
2385 
2386 	bare_lfs = 0;
2387 	urgflag = 0;
2388 	transflag = 1;
2389 	rval = -1;
2390 	byteswritten = 0;
2391 	buf = NULL;
2392 
2393 #define FILESIZECHECK(x) \
2394 			do { \
2395 				if (curclass.maxfilesize != -1 && \
2396 				    (x) > curclass.maxfilesize) { \
2397 					errno = EFBIG; \
2398 					goto file_err; \
2399 				} \
2400 			} while (0)
2401 
2402 	switch (type) {
2403 
2404 	case TYPE_I:
2405 	case TYPE_L:
2406 		netfd = fileno(instr);
2407 		filefd = fileno(outstr);
2408 		(void) alarm(curclass.timeout);
2409 		if (curclass.readsize)
2410 			readsize = curclass.readsize;
2411 		else if (fstat(filefd, &st) != -1)
2412 			readsize = (ssize_t)st.st_blksize;
2413 		else
2414 			readsize = BUFSIZ;
2415 		if ((buf = malloc(readsize)) == NULL) {
2416 			perror_reply(451, "Local resource failure: malloc");
2417 			goto cleanup_recv_data;
2418 		}
2419 		if (curclass.rateput) {
2420 			while (1) {
2421 				int d;
2422 				struct timeval then, now, td;
2423 				off_t bufrem;
2424 
2425 				(void)gettimeofday(&then, NULL);
2426 				errno = c = d = 0;
2427 				for (bufrem = curclass.rateput; bufrem > 0; ) {
2428 					if ((c = read(netfd, buf,
2429 					    MIN(readsize, bufrem))) <= 0)
2430 						goto recvdone;
2431 					if (urgflag && handleoobcmd())
2432 						goto cleanup_recv_data;
2433 					FILESIZECHECK(byte_count + c);
2434 					if ((d = write(filefd, buf, c)) != c)
2435 						goto file_err;
2436 					(void) alarm(curclass.timeout);
2437 					bufrem -= c;
2438 					byte_count += c;
2439 					total_data_in += c;
2440 					total_data += c;
2441 					total_bytes_in += c;
2442 					total_bytes += c;
2443 				}
2444 				(void)gettimeofday(&now, NULL);
2445 				timersub(&now, &then, &td);
2446 				if (td.tv_sec == 0)
2447 					usleep(1000000 - td.tv_usec);
2448 			}
2449 		} else {
2450 			while ((c = read(netfd, buf, readsize)) > 0) {
2451 				if (urgflag && handleoobcmd())
2452 					goto cleanup_recv_data;
2453 				FILESIZECHECK(byte_count + c);
2454 				if (write(filefd, buf, c) != c)
2455 					goto file_err;
2456 				(void) alarm(curclass.timeout);
2457 				byte_count += c;
2458 				total_data_in += c;
2459 				total_data += c;
2460 				total_bytes_in += c;
2461 				total_bytes += c;
2462 			}
2463 		}
2464  recvdone:
2465 		if (c < 0)
2466 			goto data_err;
2467 		rval = 0;
2468 		goto cleanup_recv_data;
2469 
2470 	case TYPE_E:
2471 		reply(553, "TYPE E not implemented.");
2472 		goto cleanup_recv_data;
2473 
2474 	case TYPE_A:
2475 		(void) alarm(curclass.timeout);
2476  /* XXXLUKEM: rate limit ascii receive (put) */
2477 		while ((c = getc(instr)) != EOF) {
2478 			if (urgflag && handleoobcmd())
2479 				goto cleanup_recv_data;
2480 			byte_count++;
2481 			total_data_in++;
2482 			total_data++;
2483 			total_bytes_in++;
2484 			total_bytes++;
2485 			if ((byte_count % 4096) == 0)
2486 				(void) alarm(curclass.timeout);
2487 			if (c == '\n')
2488 				bare_lfs++;
2489 			while (c == '\r') {
2490 				if (ferror(outstr))
2491 					goto data_err;
2492 				if ((c = getc(instr)) != '\n') {
2493 					byte_count++;
2494 					total_data_in++;
2495 					total_data++;
2496 					total_bytes_in++;
2497 					total_bytes++;
2498 					if ((byte_count % 4096) == 0)
2499 						(void) alarm(curclass.timeout);
2500 					byteswritten++;
2501 					FILESIZECHECK(byteswritten);
2502 					(void) putc ('\r', outstr);
2503 					if (c == '\0' || c == EOF)
2504 						goto contin2;
2505 				}
2506 			}
2507 			byteswritten++;
2508 			FILESIZECHECK(byteswritten);
2509 			(void) putc(c, outstr);
2510  contin2:	;
2511 		}
2512 		(void) alarm(0);
2513 		fflush(outstr);
2514 		if (ferror(instr))
2515 			goto data_err;
2516 		if (ferror(outstr))
2517 			goto file_err;
2518 		if (bare_lfs) {
2519 			reply(-226,
2520 			    "WARNING! %d bare linefeeds received in ASCII mode",
2521 			    bare_lfs);
2522 			reply(0, "File may not have transferred correctly.");
2523 		}
2524 		rval = 0;
2525 		goto cleanup_recv_data;
2526 
2527 	default:
2528 		reply(550, "Unimplemented TYPE %d in receive_data", type);
2529 		goto cleanup_recv_data;
2530 	}
2531 #undef FILESIZECHECK
2532 
2533  data_err:
2534 	(void) alarm(0);
2535 	perror_reply(426, "Data Connection");
2536 	goto cleanup_recv_data;
2537 
2538  file_err:
2539 	(void) alarm(0);
2540 	perror_reply(452, "Error writing file");
2541 	goto cleanup_recv_data;
2542 
2543  cleanup_recv_data:
2544 	(void) alarm(0);
2545 	(void) sigaction(SIGALRM, &sa_saved, NULL);
2546 	if (buf)
2547 		free(buf);
2548 	transflag = 0;
2549 	urgflag = 0;
2550 	total_files_in++;
2551 	total_files++;
2552 	total_xfers_in++;
2553 	total_xfers++;
2554 	return (rval);
2555 }
2556 
2557 void
statcmd(void)2558 statcmd(void)
2559 {
2560 	struct sockinet *su = NULL;
2561 	static char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
2562 	unsigned char *a, *p;
2563 	int ispassive, af;
2564 	off_t otbi, otbo, otb;
2565 
2566 	a = p = NULL;
2567 
2568 	reply(-211, "%s FTP server status:", hostname);
2569 	reply(0, "Version: %s", EMPTYSTR(version) ? "<suppressed>" : version);
2570 	hbuf[0] = '\0';
2571 	if (!getnameinfo((struct sockaddr *)&his_addr.si_su, his_addr.su_len,
2572 			hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)
2573 	    && strcmp(remotehost, hbuf) != 0)
2574 		reply(0, "Connected to %s (%s)", remotehost, hbuf);
2575 	else
2576 		reply(0, "Connected to %s", remotehost);
2577 
2578 	if (logged_in) {
2579 		if (curclass.type == CLASS_GUEST)
2580 			reply(0, "Logged in anonymously");
2581 		else
2582 			reply(0, "Logged in as %s%s", pw->pw_name,
2583 			    curclass.type == CLASS_CHROOT ? " (chroot)" : "");
2584 	} else if (askpasswd)
2585 		reply(0, "Waiting for password");
2586 	else
2587 		reply(0, "Waiting for user name");
2588 	cprintf(stdout, "    TYPE: %s", typenames[type]);
2589 	if (type == TYPE_A || type == TYPE_E)
2590 		cprintf(stdout, ", FORM: %s", formnames[form]);
2591 	if (type == TYPE_L) {
2592 #if NBBY == 8
2593 		cprintf(stdout, " %d", NBBY);
2594 #else
2595 			/* XXX: `bytesize' needs to be defined in this case */
2596 		cprintf(stdout, " %d", bytesize);
2597 #endif
2598 	}
2599 	cprintf(stdout, "; STRUcture: %s; transfer MODE: %s\r\n",
2600 	    strunames[stru], modenames[mode]);
2601 	ispassive = 0;
2602 	if (data != -1) {
2603 		reply(0, "Data connection open");
2604 		su = NULL;
2605 	} else if (pdata != -1) {
2606 		reply(0, "in Passive mode");
2607 		if (curclass.advertise.su_len != 0)
2608 			su = &curclass.advertise;
2609 		else
2610 			su = &pasv_addr;
2611 		ispassive = 1;
2612 		goto printaddr;
2613 	} else if (usedefault == 0) {
2614 		su = (struct sockinet *)&data_dest;
2615 
2616 		if (epsvall) {
2617 			reply(0, "EPSV only mode (EPSV ALL)");
2618 			goto epsvonly;
2619 		}
2620  printaddr:
2621 							/* PASV/PORT */
2622 		if (su->su_family == AF_INET) {
2623 			a = (unsigned char *) &su->su_addr;
2624 			p = (unsigned char *) &su->su_port;
2625 #define UC(b) (((int) b) & 0xff)
2626 			reply(0, "%s (%d,%d,%d,%d,%d,%d)",
2627 				ispassive ? "PASV" : "PORT" ,
2628 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2629 				UC(p[0]), UC(p[1]));
2630 		}
2631 
2632 							/* LPSV/LPRT */
2633 	    {
2634 		int alen, i;
2635 
2636 		alen = 0;
2637 		switch (su->su_family) {
2638 		case AF_INET:
2639 			a = (unsigned char *) &su->su_addr;
2640 			p = (unsigned char *) &su->su_port;
2641 			alen = sizeof(su->su_addr);
2642 			af = 4;
2643 			break;
2644 #ifdef INET6
2645 		case AF_INET6:
2646 			a = (unsigned char *) &su->su_6addr;
2647 			p = (unsigned char *) &su->su_port;
2648 			alen = sizeof(su->su_6addr);
2649 			af = 6;
2650 			break;
2651 #endif
2652 		default:
2653 			af = 0;
2654 			break;
2655 		}
2656 		if (af) {
2657 			cprintf(stdout, "    %s (%d,%d",
2658 			    ispassive ? "LPSV" : "LPRT", af, alen);
2659 			for (i = 0; i < alen; i++)
2660 				cprintf(stdout, ",%d", UC(a[i]));
2661 			cprintf(stdout, ",%d,%d,%d)\r\n",
2662 			    2, UC(p[0]), UC(p[1]));
2663 #undef UC
2664 		}
2665 	    }
2666 
2667 		/* EPRT/EPSV */
2668  epsvonly:
2669 		af = af2epsvproto(su->su_family);
2670 		hbuf[0] = '\0';
2671 		if (af > 0) {
2672 			struct sockinet tmp;
2673 
2674 			tmp = *su;
2675 #ifdef INET6
2676 			if (tmp.su_family == AF_INET6)
2677 				tmp.su_scope_id = 0;
2678 #endif
2679 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
2680 			    tmp.su_len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
2681 			    NI_NUMERICHOST | NI_NUMERICSERV) == 0)
2682 				reply(0, "%s (|%d|%s|%s|)",
2683 				    ispassive ? "EPSV" : "EPRT",
2684 				    af, hbuf, sbuf);
2685 		}
2686 	} else
2687 		reply(0, "No data connection");
2688 
2689 	if (logged_in) {
2690 		reply(0,
2691 		    "Data sent:        " LLF " byte%s in " LLF " file%s",
2692 		    (LLT)total_data_out, PLURAL(total_data_out),
2693 		    (LLT)total_files_out, PLURAL(total_files_out));
2694 		reply(0,
2695 		    "Data received:    " LLF " byte%s in " LLF " file%s",
2696 		    (LLT)total_data_in, PLURAL(total_data_in),
2697 		    (LLT)total_files_in, PLURAL(total_files_in));
2698 		reply(0,
2699 		    "Total data:       " LLF " byte%s in " LLF " file%s",
2700 		    (LLT)total_data, PLURAL(total_data),
2701 		    (LLT)total_files, PLURAL(total_files));
2702 	}
2703 	otbi = total_bytes_in;
2704 	otbo = total_bytes_out;
2705 	otb = total_bytes;
2706 	reply(0, "Traffic sent:     " LLF " byte%s in " LLF " transfer%s",
2707 	    (LLT)otbo, PLURAL(otbo),
2708 	    (LLT)total_xfers_out, PLURAL(total_xfers_out));
2709 	reply(0, "Traffic received: " LLF " byte%s in " LLF " transfer%s",
2710 	    (LLT)otbi, PLURAL(otbi),
2711 	    (LLT)total_xfers_in, PLURAL(total_xfers_in));
2712 	reply(0, "Total traffic:    " LLF " byte%s in " LLF " transfer%s",
2713 	    (LLT)otb, PLURAL(otb),
2714 	    (LLT)total_xfers, PLURAL(total_xfers));
2715 
2716 	if (logged_in && !CURCLASS_FLAGS_ISSET(private)) {
2717 		struct ftpconv *cp;
2718 
2719 		reply(0, "%s", "");
2720 		reply(0, "Class: %s, type: %s",
2721 		    curclass.classname, CURCLASSTYPE);
2722 		reply(0, "Check PORT/LPRT commands: %sabled",
2723 		    CURCLASS_FLAGS_ISSET(checkportcmd) ? "en" : "dis");
2724 		if (! EMPTYSTR(curclass.display))
2725 			reply(0, "Display file: %s", curclass.display);
2726 		if (! EMPTYSTR(curclass.notify))
2727 			reply(0, "Notify fileglob: %s", curclass.notify);
2728 		reply(0, "Idle timeout: " LLF ", maximum timeout: " LLF,
2729 		    (LLT)curclass.timeout, (LLT)curclass.maxtimeout);
2730 		reply(0, "Current connections: %d", connections);
2731 		if (curclass.limit == -1)
2732 			reply(0, "Maximum connections: unlimited");
2733 		else
2734 			reply(0, "Maximum connections: " LLF,
2735 			    (LLT)curclass.limit);
2736 		if (curclass.limitfile)
2737 			reply(0, "Connection limit exceeded message file: %s",
2738 			    conffilename(curclass.limitfile));
2739 		if (! EMPTYSTR(curclass.chroot))
2740 			reply(0, "Chroot format: %s", curclass.chroot);
2741 		reply(0, "Deny bad ftpusers(5) quickly: %sabled",
2742 		    CURCLASS_FLAGS_ISSET(denyquick) ? "en" : "dis");
2743 		if (! EMPTYSTR(curclass.homedir))
2744 			reply(0, "Homedir format: %s", curclass.homedir);
2745 		if (curclass.maxfilesize == -1)
2746 			reply(0, "Maximum file size: unlimited");
2747 		else
2748 			reply(0, "Maximum file size: " LLF,
2749 			    (LLT)curclass.maxfilesize);
2750 		if (! EMPTYSTR(curclass.motd))
2751 			reply(0, "MotD file: %s", conffilename(curclass.motd));
2752 		reply(0,
2753 	    "Modify commands (CHMOD, DELE, MKD, RMD, RNFR, UMASK): %sabled",
2754 		    CURCLASS_FLAGS_ISSET(modify) ? "en" : "dis");
2755 		reply(0, "Upload commands (APPE, STOR, STOU): %sabled",
2756 		    CURCLASS_FLAGS_ISSET(upload) ? "en" : "dis");
2757 		reply(0, "Sanitize file names: %sabled",
2758 		    CURCLASS_FLAGS_ISSET(sanenames) ? "en" : "dis");
2759 		reply(0, "PASV/LPSV/EPSV connections: %sabled",
2760 		    CURCLASS_FLAGS_ISSET(passive) ? "en" : "dis");
2761 		if (curclass.advertise.su_len != 0) {
2762 			char buf[50];	/* big enough for IPv6 address */
2763 			const char *bp;
2764 
2765 			bp = inet_ntop(curclass.advertise.su_family,
2766 			    (void *)&curclass.advertise.su_addr,
2767 			    buf, sizeof(buf));
2768 			if (bp != NULL)
2769 				reply(0, "PASV advertise address: %s", bp);
2770 		}
2771 		if (curclass.portmin && curclass.portmax)
2772 			reply(0, "PASV port range: " LLF " - " LLF,
2773 			    (LLT)curclass.portmin, (LLT)curclass.portmax);
2774 		if (curclass.rateget)
2775 			reply(0, "Rate get limit: " LLF " bytes/sec",
2776 			    (LLT)curclass.rateget);
2777 		else
2778 			reply(0, "Rate get limit: disabled");
2779 		if (curclass.rateput)
2780 			reply(0, "Rate put limit: " LLF " bytes/sec",
2781 			    (LLT)curclass.rateput);
2782 		else
2783 			reply(0, "Rate put limit: disabled");
2784 		if (curclass.mmapsize)
2785 			reply(0, "Mmap size: " LLF, (LLT)curclass.mmapsize);
2786 		else
2787 			reply(0, "Mmap size: disabled");
2788 		if (curclass.readsize)
2789 			reply(0, "Read size: " LLF, (LLT)curclass.readsize);
2790 		else
2791 			reply(0, "Read size: default");
2792 		if (curclass.writesize)
2793 			reply(0, "Write size: " LLF, (LLT)curclass.writesize);
2794 		else
2795 			reply(0, "Write size: default");
2796 		if (curclass.recvbufsize)
2797 			reply(0, "Receive buffer size: " LLF,
2798 			    (LLT)curclass.recvbufsize);
2799 		else
2800 			reply(0, "Receive buffer size: default");
2801 		if (curclass.sendbufsize)
2802 			reply(0, "Send buffer size: " LLF,
2803 			    (LLT)curclass.sendbufsize);
2804 		else
2805 			reply(0, "Send buffer size: default");
2806 		if (curclass.sendlowat)
2807 			reply(0, "Send low water mark: " LLF,
2808 			    (LLT)curclass.sendlowat);
2809 		else
2810 			reply(0, "Send low water mark: default");
2811 		reply(0, "Umask: %.04o", curclass.umask);
2812 		for (cp = curclass.conversions; cp != NULL; cp=cp->next) {
2813 			if (cp->suffix == NULL || cp->types == NULL ||
2814 			    cp->command == NULL)
2815 				continue;
2816 			reply(0, "Conversion: %s [%s] disable: %s, command: %s",
2817 			    cp->suffix, cp->types, cp->disable, cp->command);
2818 		}
2819 	}
2820 
2821 	reply(211, "End of status");
2822 }
2823 
2824 void
fatal(const char * s)2825 fatal(const char *s)
2826 {
2827 
2828 	reply(451, "Error in server: %s\n", s);
2829 	reply(221, "Closing connection due to server error.");
2830 	dologout(0);
2831 	/* NOTREACHED */
2832 }
2833 
2834 /*
2835  * reply() --
2836  *	depending on the value of n, display fmt with a trailing CRLF and
2837  *	prefix of:
2838  *	n < -1		prefix the message with abs(n) + "-"	(initial line)
2839  *	n == 0		prefix the message with 4 spaces	(middle lines)
2840  *	n >  0		prefix the message with n + " "		(final line)
2841  */
2842 void
reply(int n,const char * fmt,...)2843 reply(int n, const char *fmt, ...)
2844 {
2845 	char	msg[MAXPATHLEN * 2 + 100];
2846 	size_t	b;
2847 	va_list	ap;
2848 
2849 	if (n == 0)
2850 		b = snprintf(msg, sizeof(msg), "    ");
2851 	else if (n < 0)
2852 		b = snprintf(msg, sizeof(msg), "%d-", -n);
2853 	else
2854 		b = snprintf(msg, sizeof(msg), "%d ", n);
2855 	va_start(ap, fmt);
2856 	vsnprintf(msg + b, sizeof(msg) - b, fmt, ap);
2857 	va_end(ap);
2858 	cprintf(stdout, "%s\r\n", msg);
2859 	(void)fflush(stdout);
2860 	if (ftpd_debug)
2861 		syslog(LOG_DEBUG, "<--- %s", msg);
2862 }
2863 
2864 static void
logremotehost(struct sockinet * who)2865 logremotehost(struct sockinet *who)
2866 {
2867 
2868 #if defined(HAVE_SOCKADDR_SNPRINTF)
2869 	char abuf[MAXHOSTNAMELEN];
2870 #endif
2871 
2872 	struct sockaddr *sa = (struct sockaddr *)&who->si_su;
2873 	if (getnameinfo(sa, who->su_len, remotehost, sizeof(remotehost), NULL,
2874 	    0, getnameopts))
2875 		strlcpy(remotehost, "?", sizeof(remotehost));
2876 #if defined(HAVE_SOCKADDR_SNPRINTF)
2877 	sockaddr_snprintf(abuf, sizeof(abuf), "%a", sa);
2878 	snprintf(remoteloghost, sizeof(remoteloghost), "%s(%s)", remotehost,
2879 	    abuf);
2880 #else
2881 	strlcpy(remoteloghost, remotehost, sizeof(remoteloghost));
2882 #endif
2883 
2884 #if defined(HAVE_SETPROCTITLE)
2885 	snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
2886 	setproctitle("%s", proctitle);
2887 #endif /* defined(HAVE_SETPROCTITLE) */
2888 	if (logging)
2889 		syslog(LOG_INFO, "connection from %s to %s",
2890 		    remoteloghost, hostname);
2891 }
2892 
2893 /*
2894  * Record logout in wtmp file and exit with supplied status.
2895  * NOTE: because this is called from signal handlers it cannot
2896  *       use stdio (or call other functions that use stdio).
2897  */
2898 void
dologout(int status)2899 dologout(int status)
2900 {
2901 	/*
2902 	* Prevent reception of SIGURG from resulting in a resumption
2903 	* back to the main program loop.
2904 	*/
2905 	transflag = 0;
2906 	logout_utmp();
2907 	if (logged_in) {
2908 #ifdef KERBEROS
2909 		if (!notickets && krbtkfile_env)
2910 			unlink(krbtkfile_env);
2911 #endif
2912 	}
2913 	/* beware of flushing buffers after a SIGPIPE */
2914 	if (xferlogfd != -1)
2915 		close(xferlogfd);
2916 	_exit(status);
2917 }
2918 
2919 void
abor(void)2920 abor(void)
2921 {
2922 
2923 	if (!transflag)
2924 		return;
2925 	tmpline[0] = '\0';
2926 	is_oob = 0;
2927 	reply(426, "Transfer aborted. Data connection closed.");
2928 	reply(226, "Abort successful");
2929 	transflag = 0;		/* flag that the transfer has aborted */
2930 }
2931 
2932 void
statxfer(void)2933 statxfer(void)
2934 {
2935 
2936 	if (!transflag)
2937 		return;
2938 	tmpline[0] = '\0';
2939 	is_oob = 0;
2940 	if (file_size != (off_t) -1)
2941 		reply(213,
2942 		    "Status: " LLF " of " LLF " byte%s transferred",
2943 		    (LLT)byte_count, (LLT)file_size,
2944 		    PLURAL(byte_count));
2945 	else
2946 		reply(213, "Status: " LLF " byte%s transferred",
2947 		    (LLT)byte_count, PLURAL(byte_count));
2948 }
2949 
2950 /*
2951  * Call when urgflag != 0 to handle Out Of Band commands.
2952  * Returns non zero if the OOB command aborted the transfer
2953  * by setting transflag to 0. (c.f., "ABOR").
2954  */
2955 static int
handleoobcmd(void)2956 handleoobcmd(void)
2957 {
2958 	char *cp;
2959 	int ret;
2960 
2961 	if (!urgflag)
2962 		return (0);
2963 	urgflag = 0;
2964 	/* only process if transfer occurring */
2965 	if (!transflag)
2966 		return (0);
2967 	cp = tmpline;
2968 	ret = get_line(cp, sizeof(tmpline)-1, stdin);
2969 	if (ret == -1) {
2970 		reply(221, "You could at least say goodbye.");
2971 		dologout(0);
2972 	} else if (ret == -2) {
2973 		/* Ignore truncated command */
2974 		/* XXX: abort xfer with "500 command too long", & return 1 ? */
2975 		return 0;
2976 	}
2977 		/*
2978 		 * Manually parse OOB commands, because we can't
2979 		 * recursively call the yacc parser...
2980 		 */
2981 	if (strcasecmp(cp, "ABOR\r\n") == 0) {
2982 		abor();
2983 	} else if (strcasecmp(cp, "STAT\r\n") == 0) {
2984 		statxfer();
2985 	} else {
2986 		/* XXX: error with "500 unknown command" ? */
2987 	}
2988 	return (transflag == 0);
2989 }
2990 
2991 static int
bind_pasv_addr(void)2992 bind_pasv_addr(void)
2993 {
2994 	static int passiveport;
2995 	int port, len;
2996 
2997 	len = pasv_addr.su_len;
2998 	if (curclass.portmin == 0 && curclass.portmax == 0) {
2999 		pasv_addr.su_port = 0;
3000 		return (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len));
3001 	}
3002 
3003 	if (passiveport == 0) {
3004 		srand(getpid());
3005 		passiveport = rand() % (curclass.portmax - curclass.portmin)
3006 		    + curclass.portmin;
3007 	}
3008 
3009 	port = passiveport;
3010 	while (1) {
3011 		port++;
3012 		if (port > curclass.portmax)
3013 			port = curclass.portmin;
3014 		else if (port == passiveport) {
3015 			errno = EAGAIN;
3016 			return (-1);
3017 		}
3018 		pasv_addr.su_port = htons(port);
3019 		if (bind(pdata, (struct sockaddr *)&pasv_addr.si_su, len) == 0)
3020 			break;
3021 		if (errno != EADDRINUSE)
3022 			return (-1);
3023 	}
3024 	passiveport = port;
3025 	return (0);
3026 }
3027 
3028 /*
3029  * Note: a response of 425 is not mentioned as a possible response to
3030  *	the PASV command in RFC959. However, it has been blessed as
3031  *	a legitimate response by Jon Postel in a telephone conversation
3032  *	with Rick Adams on 25 Jan 89.
3033  */
3034 void
passive(void)3035 passive(void)
3036 {
3037 	socklen_t len;
3038 	int recvbufsize;
3039 	char *p, *a;
3040 
3041 	if (pdata >= 0)
3042 		close(pdata);
3043 	pdata = socket(AF_INET, SOCK_STREAM, 0);
3044 	if (pdata < 0 || !logged_in) {
3045 		perror_reply(425, "Can't open passive connection");
3046 		return;
3047 	}
3048 	pasv_addr = ctrl_addr;
3049 
3050 	if (bind_pasv_addr() < 0)
3051 		goto pasv_error;
3052 	len = pasv_addr.su_len;
3053 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
3054 		goto pasv_error;
3055 	pasv_addr.su_len = len;
3056 	if (curclass.recvbufsize) {
3057 		recvbufsize = curclass.recvbufsize;
3058 		if (setsockopt(pdata, SOL_SOCKET, SO_RCVBUF, &recvbufsize,
3059 			       sizeof(int)) == -1)
3060 			syslog(LOG_WARNING, "setsockopt(SO_RCVBUF, %d): %m",
3061 			       recvbufsize);
3062 	}
3063 	if (listen(pdata, 1) < 0)
3064 		goto pasv_error;
3065 	if (curclass.advertise.su_len != 0)
3066 		a = (char *) &curclass.advertise.su_addr;
3067 	else
3068 		a = (char *) &pasv_addr.su_addr;
3069 	p = (char *) &pasv_addr.su_port;
3070 
3071 #define UC(b) (((int) b) & 0xff)
3072 
3073 	reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
3074 		UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
3075 	return;
3076 
3077  pasv_error:
3078 	(void) close(pdata);
3079 	pdata = -1;
3080 	perror_reply(425, "Can't open passive connection");
3081 	return;
3082 }
3083 
3084 /*
3085  * convert protocol identifier to/from AF
3086  */
3087 int
lpsvproto2af(int proto)3088 lpsvproto2af(int proto)
3089 {
3090 
3091 	switch (proto) {
3092 	case 4:
3093 		return AF_INET;
3094 #ifdef INET6
3095 	case 6:
3096 		return AF_INET6;
3097 #endif
3098 	default:
3099 		return -1;
3100 	}
3101 }
3102 
3103 int
af2lpsvproto(int af)3104 af2lpsvproto(int af)
3105 {
3106 
3107 	switch (af) {
3108 	case AF_INET:
3109 		return 4;
3110 #ifdef INET6
3111 	case AF_INET6:
3112 		return 6;
3113 #endif
3114 	default:
3115 		return -1;
3116 	}
3117 }
3118 
3119 int
epsvproto2af(int proto)3120 epsvproto2af(int proto)
3121 {
3122 
3123 	switch (proto) {
3124 	case 1:
3125 		return AF_INET;
3126 #ifdef INET6
3127 	case 2:
3128 		return AF_INET6;
3129 #endif
3130 	default:
3131 		return -1;
3132 	}
3133 }
3134 
3135 int
af2epsvproto(int af)3136 af2epsvproto(int af)
3137 {
3138 
3139 	switch (af) {
3140 	case AF_INET:
3141 		return 1;
3142 #ifdef INET6
3143 	case AF_INET6:
3144 		return 2;
3145 #endif
3146 	default:
3147 		return -1;
3148 	}
3149 }
3150 
3151 /*
3152  * 228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)
3153  * 229 Entering Extended Passive Mode (|||port|)
3154  */
3155 void
long_passive(const char * cmd,int pf)3156 long_passive(const char *cmd, int pf)
3157 {
3158 	socklen_t len;
3159 	char *p, *a;
3160 
3161 	if (!logged_in) {
3162 		syslog(LOG_NOTICE, "long passive but not logged in");
3163 		reply(503, "Login with USER first.");
3164 		return;
3165 	}
3166 
3167 	if (pf != PF_UNSPEC && ctrl_addr.su_family != pf) {
3168 		/*
3169 		 * XXX: only EPRT/EPSV ready clients will understand this
3170 		 */
3171 		if (strcmp(cmd, "EPSV") != 0)
3172 			reply(501, "Network protocol mismatch"); /*XXX*/
3173 		else
3174 			epsv_protounsupp("Network protocol mismatch");
3175 
3176 		return;
3177 	}
3178 
3179 	if (pdata >= 0)
3180 		close(pdata);
3181 	pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
3182 	if (pdata < 0) {
3183 		perror_reply(425, "Can't open passive connection");
3184 		return;
3185 	}
3186 	pasv_addr = ctrl_addr;
3187 	if (bind_pasv_addr() < 0)
3188 		goto pasv_error;
3189 	len = pasv_addr.su_len;
3190 	if (getsockname(pdata, (struct sockaddr *) &pasv_addr.si_su, &len) < 0)
3191 		goto pasv_error;
3192 	pasv_addr.su_len = len;
3193 	if (listen(pdata, 1) < 0)
3194 		goto pasv_error;
3195 	p = (char *) &pasv_addr.su_port;
3196 
3197 #define UC(b) (((int) b) & 0xff)
3198 
3199 	if (strcmp(cmd, "LPSV") == 0) {
3200 		struct sockinet *advert;
3201 
3202 		if (curclass.advertise.su_len != 0)
3203 			advert = &curclass.advertise;
3204 		else
3205 			advert = &pasv_addr;
3206 		switch (advert->su_family) {
3207 		case AF_INET:
3208 			a = (char *) &advert->su_addr;
3209 			reply(228,
3210     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3211 				4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3212 				2, UC(p[0]), UC(p[1]));
3213 			return;
3214 #ifdef INET6
3215 		case AF_INET6:
3216 			a = (char *) &advert->su_6addr;
3217 			reply(228,
3218     "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3219 				6, 16,
3220 				UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3221 				UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3222 				UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3223 				UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3224 				2, UC(p[0]), UC(p[1]));
3225 			return;
3226 #endif
3227 		}
3228 #undef UC
3229 	} else if (strcmp(cmd, "EPSV") == 0) {
3230 		switch (pasv_addr.su_family) {
3231 		case AF_INET:
3232 #ifdef INET6
3233 		case AF_INET6:
3234 #endif
3235 			reply(229, "Entering Extended Passive Mode (|||%d|)",
3236 			    ntohs(pasv_addr.su_port));
3237 			return;
3238 		}
3239 	} else {
3240 		/* more proper error code? */
3241 	}
3242 
3243  pasv_error:
3244 	(void) close(pdata);
3245 	pdata = -1;
3246 	perror_reply(425, "Can't open passive connection");
3247 	return;
3248 }
3249 
3250 int
extended_port(const char * arg)3251 extended_port(const char *arg)
3252 {
3253 	char *tmp = NULL;
3254 	char *result[3];
3255 	char *p, *q;
3256 	char delim;
3257 	struct addrinfo hints;
3258 	struct addrinfo *res = NULL;
3259 	int i;
3260 	unsigned long proto;
3261 
3262 	tmp = ftpd_strdup(arg);
3263 	p = tmp;
3264 	delim = p[0];
3265 	p++;
3266 	memset(result, 0, sizeof(result));
3267 	for (i = 0; i < 3; i++) {
3268 		q = strchr(p, delim);
3269 		if (!q || *q != delim)
3270 			goto parsefail;
3271 		*q++ = '\0';
3272 		result[i] = p;
3273 		p = q;
3274 	}
3275 
3276 			/* some more sanity checks */
3277 	errno = 0;
3278 	p = NULL;
3279 	(void)strtoul(result[2], &p, 10);
3280 	if (errno || !*result[2] || *p)
3281 		goto parsefail;
3282 	errno = 0;
3283 	p = NULL;
3284 	proto = strtoul(result[0], &p, 10);
3285 	if (errno || !*result[0] || *p)
3286 		goto protounsupp;
3287 
3288 	memset(&hints, 0, sizeof(hints));
3289 	hints.ai_family = epsvproto2af((int)proto);
3290 	if (hints.ai_family < 0)
3291 		goto protounsupp;
3292 	hints.ai_socktype = SOCK_STREAM;
3293 	hints.ai_flags = AI_NUMERICHOST;
3294 	if (getaddrinfo(result[1], result[2], &hints, &res))
3295 		goto parsefail;
3296 	if (res->ai_next)
3297 		goto parsefail;
3298 	if (sizeof(data_dest) < res->ai_addrlen)
3299 		goto parsefail;
3300 	memcpy(&data_dest.si_su, res->ai_addr, res->ai_addrlen);
3301 	data_dest.su_len = res->ai_addrlen;
3302 #ifdef INET6
3303 	if (his_addr.su_family == AF_INET6 &&
3304 	    data_dest.su_family == AF_INET6) {
3305 			/* XXX: more sanity checks! */
3306 		data_dest.su_scope_id = his_addr.su_scope_id;
3307 	}
3308 #endif
3309 
3310 	if (tmp != NULL)
3311 		free(tmp);
3312 	if (res)
3313 		freeaddrinfo(res);
3314 	return 0;
3315 
3316  parsefail:
3317 	reply(500, "Invalid argument, rejected.");
3318 	usedefault = 1;
3319 	if (tmp != NULL)
3320 		free(tmp);
3321 	if (res)
3322 		freeaddrinfo(res);
3323 	return -1;
3324 
3325  protounsupp:
3326 	epsv_protounsupp("Protocol not supported");
3327 	usedefault = 1;
3328 	if (tmp != NULL)
3329 		free(tmp);
3330 	return -1;
3331 }
3332 
3333 /*
3334  * 522 Protocol not supported (proto,...)
3335  * as we assume address family for control and data connections are the same,
3336  * we do not return the list of address families we support - instead, we
3337  * return the address family of the control connection.
3338  */
3339 void
epsv_protounsupp(const char * message)3340 epsv_protounsupp(const char *message)
3341 {
3342 	int proto;
3343 
3344 	proto = af2epsvproto(ctrl_addr.su_family);
3345 	if (proto < 0)
3346 		reply(501, "%s", message);	/* XXX */
3347 	else
3348 		reply(522, "%s, use (%d)", message, proto);
3349 }
3350 
3351 /*
3352  * Generate unique name for file with basename "local".
3353  * The file named "local" is already known to exist.
3354  * Generates failure reply on error.
3355  *
3356  * XXX:	this function should under go changes similar to
3357  *	the mktemp(3)/mkstemp(3) changes.
3358  */
3359 static char *
gunique(const char * local)3360 gunique(const char *local)
3361 {
3362 	static char new[MAXPATHLEN];
3363 	struct stat st;
3364 	char *cp;
3365 	int count;
3366 
3367 	cp = strrchr(local, '/');
3368 	if (cp)
3369 		*cp = '\0';
3370 	if (stat(cp ? local : ".", &st) < 0) {
3371 		perror_reply(553, cp ? local : ".");
3372 		return (NULL);
3373 	}
3374 	if (cp)
3375 		*cp = '/';
3376 	for (count = 1; count < 100; count++) {
3377 		(void)snprintf(new, sizeof(new) - 1, "%s.%d", local, count);
3378 		if (stat(new, &st) < 0)
3379 			return (new);
3380 	}
3381 	reply(452, "Unique file name cannot be created.");
3382 	return (NULL);
3383 }
3384 
3385 /*
3386  * Format and send reply containing system error number.
3387  */
3388 void
perror_reply(int code,const char * string)3389 perror_reply(int code, const char *string)
3390 {
3391 	int save_errno;
3392 
3393 	save_errno = errno;
3394 	reply(code, "%s: %s.", string, strerror(errno));
3395 	errno = save_errno;
3396 }
3397 
3398 static char *onefile[] = {
3399 	NULL,
3400 	0
3401 };
3402 
3403 void
send_file_list(const char * whichf)3404 send_file_list(const char *whichf)
3405 {
3406 	struct stat st;
3407 	DIR *dirp;
3408 	struct dirent *dir;
3409 	FILE *volatile dout;
3410 	char **volatile dirlist;
3411 	char *dirname, *p;
3412 	char *notglob;
3413 	int volatile simple;
3414 	int volatile freeglob;
3415 	glob_t gl;
3416 
3417 	dirp = NULL;
3418 	dout = NULL;
3419 	notglob = NULL;
3420 	simple = 0;
3421 	freeglob = 0;
3422 	urgflag = 0;
3423 
3424 	p = NULL;
3425 	if (strpbrk(whichf, "~{[*?") != NULL) {
3426 		int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE|GLOB_LIMIT;
3427 
3428 		memset(&gl, 0, sizeof(gl));
3429 		freeglob = 1;
3430 		if (glob(whichf, flags, 0, &gl)) {
3431 			reply(450, "Not found");
3432 			goto cleanup_send_file_list;
3433 		} else if (gl.gl_pathc == 0) {
3434 			errno = ENOENT;
3435 			perror_reply(450, whichf);
3436 			goto cleanup_send_file_list;
3437 		}
3438 		dirlist = gl.gl_pathv;
3439 	} else {
3440 		notglob = ftpd_strdup(whichf);
3441 		onefile[0] = notglob;
3442 		dirlist = onefile;
3443 		simple = 1;
3444 	}
3445 					/* XXX: } for vi sm */
3446 
3447 	while ((dirname = *dirlist++) != NULL) {
3448 		int trailingslash = 0;
3449 
3450 		if (stat(dirname, &st) < 0) {
3451 			/*
3452 			 * If user typed "ls -l", etc, and the client
3453 			 * used NLST, do what the user meant.
3454 			 */
3455 			/* XXX: nuke this support? */
3456 			if (dirname[0] == '-' && *dirlist == NULL &&
3457 			    transflag == 0) {
3458 				const char *argv[] = { INTERNAL_LS, "", NULL };
3459 
3460 				argv[1] = dirname;
3461 				retrieve(argv, dirname);
3462 				goto cleanup_send_file_list;
3463 			}
3464 			perror_reply(450, whichf);
3465 			goto cleanup_send_file_list;
3466 		}
3467 
3468 		if (S_ISREG(st.st_mode)) {
3469 			/*
3470 			 * XXXRFC:
3471 			 *	should we follow RFC959 and not work
3472 			 *	for non directories?
3473 			 */
3474 			if (dout == NULL) {
3475 				dout = dataconn("file list", (off_t)-1, "w");
3476 				if (dout == NULL)
3477 					goto cleanup_send_file_list;
3478 				transflag = 1;
3479 			}
3480 			cprintf(dout, "%s%s\n", dirname,
3481 			    type == TYPE_A ? "\r" : "");
3482 			continue;
3483 		} else if (!S_ISDIR(st.st_mode))
3484 			continue;
3485 
3486 		if (dirname[strlen(dirname) - 1] == '/')
3487 			trailingslash++;
3488 
3489 		if ((dirp = opendir(dirname)) == NULL)
3490 			continue;
3491 
3492 		while ((dir = readdir(dirp)) != NULL) {
3493 			char nbuf[MAXPATHLEN];
3494 
3495 			if (urgflag && handleoobcmd()) {
3496 				(void) closedir(dirp);
3497 				goto cleanup_send_file_list;
3498 			}
3499 
3500 			if (ISDOTDIR(dir->d_name) || ISDOTDOTDIR(dir->d_name))
3501 				continue;
3502 
3503 			(void)snprintf(nbuf, sizeof(nbuf), "%s%s%s", dirname,
3504 			    trailingslash ? "" : "/", dir->d_name);
3505 
3506 			/*
3507 			 * We have to do a stat to ensure it's
3508 			 * not a directory or special file.
3509 			 */
3510 			/*
3511 			 * XXXRFC:
3512 			 *	should we follow RFC959 and filter out
3513 			 *	non files ?   lukem - NO!, or not until
3514 			 *	our ftp client uses MLS{T,D} for completion.
3515 			 */
3516 			if (simple || (stat(nbuf, &st) == 0 &&
3517 			    S_ISREG(st.st_mode))) {
3518 				if (dout == NULL) {
3519 					dout = dataconn("file list", (off_t)-1,
3520 						"w");
3521 					if (dout == NULL) {
3522 						(void) closedir(dirp);
3523 						goto cleanup_send_file_list;
3524 					}
3525 					transflag = 1;
3526 				}
3527 				p = nbuf;
3528 				if (nbuf[0] == '.' && nbuf[1] == '/')
3529 					p = &nbuf[2];
3530 				cprintf(dout, "%s%s\n", p,
3531 				    type == TYPE_A ? "\r" : "");
3532 			}
3533 		}
3534 		(void) closedir(dirp);
3535 	}
3536 
3537 	if (dout == NULL)
3538 		reply(450, "No files found.");
3539 	else if (ferror(dout) != 0)
3540 		perror_reply(451, "Data connection");
3541 	else
3542 		reply(226, "Transfer complete.");
3543 
3544  cleanup_send_file_list:
3545 	closedataconn(dout);
3546 	transflag = 0;
3547 	urgflag = 0;
3548 	total_xfers++;
3549 	total_xfers_out++;
3550 	if (notglob)
3551 		free(notglob);
3552 	if (freeglob)
3553 		globfree(&gl);
3554 }
3555 
3556 char *
conffilename(const char * s)3557 conffilename(const char *s)
3558 {
3559 	static char filename[MAXPATHLEN];
3560 
3561 	if (*s == '/')
3562 		strlcpy(filename, s, sizeof(filename));
3563 	else
3564 		(void)snprintf(filename, sizeof(filename), "%s/%s", confdir ,s);
3565 	return (filename);
3566 }
3567 
3568 /*
3569  * logxfer --
3570  *	if logging > 1, then based on the arguments, syslog a message:
3571  *	 if bytes != -1		"<command> <file1> = <bytes> bytes"
3572  *	 else if file2 != NULL	"<command> <file1> <file2>"
3573  *	 else			"<command> <file1>"
3574  *	if elapsed != NULL, append "in xxx.yyy seconds"
3575  *	if error != NULL, append ": " + error
3576  *
3577  *	if doxferlog != 0, bytes != -1, and command is "get", "put",
3578  *	or "append", syslog and/or write a wu-ftpd style xferlog entry
3579  */
3580 void
logxfer(const char * command,off_t bytes,const char * file1,const char * file2,const struct timeval * elapsed,const char * error)3581 logxfer(const char *command, off_t bytes, const char *file1, const char *file2,
3582     const struct timeval *elapsed, const char *error)
3583 {
3584 	char		 buf[MAXPATHLEN * 2 + 100];
3585 	char		 realfile1[MAXPATHLEN], realfile2[MAXPATHLEN];
3586 	const char	*r1, *r2;
3587 	char		 direction;
3588 	size_t		 len;
3589 	time_t		 now;
3590 
3591 	if (logging <=1 && !doxferlog)
3592 		return;
3593 
3594 	r1 = r2 = NULL;
3595 	if ((r1 = realpath(file1, realfile1)) == NULL)
3596 		r1 = file1;
3597 	if (file2 != NULL)
3598 		if ((r2 = realpath(file2, realfile2)) == NULL)
3599 			r2 = file2;
3600 
3601 		/*
3602 		 * syslog command
3603 		 */
3604 	if (logging > 1) {
3605 		len = snprintf(buf, sizeof(buf), "%s %s", command, r1);
3606 		if (bytes != (off_t)-1)
3607 			len += snprintf(buf + len, sizeof(buf) - len,
3608 			    " = " LLF " byte%s", (LLT) bytes, PLURAL(bytes));
3609 		else if (r2 != NULL)
3610 			len += snprintf(buf + len, sizeof(buf) - len,
3611 			    " %s", r2);
3612 		if (elapsed != NULL)
3613 			len += snprintf(buf + len, sizeof(buf) - len,
3614 			    " in " LLF ".%.03ld seconds",
3615 			    (LLT)elapsed->tv_sec,
3616 			    (long)(elapsed->tv_usec / 1000));
3617 		if (error != NULL)
3618 			len += snprintf(buf + len, sizeof(buf) - len,
3619 			    ": %s", error);
3620 		syslog(LOG_INFO, "%s", buf);
3621 	}
3622 
3623 		/*
3624 		 * syslog wu-ftpd style log entry, prefixed with "xferlog: "
3625 		 */
3626 	if (!doxferlog || bytes == -1)
3627 		return;
3628 
3629 	if (strcmp(command, "get") == 0)
3630 		direction = 'o';
3631 	else if (strcmp(command, "put") == 0 || strcmp(command, "append") == 0)
3632 		direction = 'i';
3633 	else
3634 		return;
3635 
3636 	time(&now);
3637 	len = snprintf(buf, sizeof(buf),
3638 	    "%.24s " LLF " %s " LLF " %s %c %s %c %c %s FTP 0 * %c\n",
3639 
3640 /*
3641  * XXX: wu-ftpd puts ' (send)' or ' (recv)' in the syslog message, and removes
3642  *	the full date.  This may be problematic for accurate log parsing,
3643  *	given that syslog messages don't contain the full date.
3644  */
3645 	    ctime(&now),
3646 	    (LLT)
3647 	    (elapsed == NULL ? 0 : elapsed->tv_sec + (elapsed->tv_usec > 0)),
3648 	    remotehost,
3649 	    (LLT) bytes,
3650 	    r1,
3651 	    type == TYPE_A ? 'a' : 'b',
3652 	    "_",		/* XXX: take conversions into account? */
3653 	    direction,
3654 
3655 	    curclass.type == CLASS_GUEST ?  'a' :
3656 	    curclass.type == CLASS_CHROOT ? 'g' :
3657 	    curclass.type == CLASS_REAL ?   'r' : '?',
3658 
3659 	    curclass.type == CLASS_GUEST ? pw->pw_passwd : pw->pw_name,
3660 	    error != NULL ? 'i' : 'c'
3661 	    );
3662 
3663 	if ((doxferlog & 2) && xferlogfd != -1)
3664 		write(xferlogfd, buf, len);
3665 	if ((doxferlog & 1)) {
3666 		buf[len-1] = '\n';	/* strip \n from syslog message */
3667 		syslog(LOG_INFO, "xferlog: %s", buf);
3668 	}
3669 }
3670 
3671 /*
3672  * Log the resource usage.
3673  *
3674  * XXX: more resource usage to logging?
3675  */
3676 void
logrusage(const struct rusage * rusage_before,const struct rusage * rusage_after)3677 logrusage(const struct rusage *rusage_before,
3678     const struct rusage *rusage_after)
3679 {
3680 	struct timeval usrtime, systime;
3681 
3682 	if (logging <= 1)
3683 		return;
3684 
3685 	timersub(&rusage_after->ru_utime, &rusage_before->ru_utime, &usrtime);
3686 	timersub(&rusage_after->ru_stime, &rusage_before->ru_stime, &systime);
3687 	syslog(LOG_INFO, LLF ".%.03ldu " LLF ".%.03lds %ld+%ldio %ldpf+%ldw",
3688 	    (LLT)usrtime.tv_sec, (long)(usrtime.tv_usec / 1000),
3689 	    (LLT)systime.tv_sec, (long)(systime.tv_usec / 1000),
3690 	    rusage_after->ru_inblock - rusage_before->ru_inblock,
3691 	    rusage_after->ru_oublock - rusage_before->ru_oublock,
3692 	    rusage_after->ru_majflt - rusage_before->ru_majflt,
3693 	    rusage_after->ru_nswap - rusage_before->ru_nswap);
3694 }
3695 
3696 /*
3697  * Determine if `password' is valid for user given in `pw'.
3698  * Returns 2 if password expired, 1 if otherwise failed, 0 if ok
3699  */
3700 int
checkpassword(const struct passwd * pwent,const char * password)3701 checkpassword(const struct passwd *pwent, const char *password)
3702 {
3703 	const char *orig;
3704 	char	*new;
3705 	time_t	 change, expire, now;
3706 
3707 	change = expire = 0;
3708 	if (pwent == NULL)
3709 		return 1;
3710 
3711 	time(&now);
3712 	orig = pwent->pw_passwd;	/* save existing password */
3713 	expire = pwent->pw_expire;
3714 	change = pwent->pw_change;
3715 	if (change == _PASSWORD_CHGNOW)
3716 		change = now;
3717 
3718 	if (orig[0] == '\0')		/* don't allow empty passwords */
3719 		return 1;
3720 
3721 	new = crypt(password, orig);	/* encrypt given password */
3722 	if (strcmp(new, orig) != 0)	/* compare */
3723 		return 1;
3724 
3725 	if ((expire && now >= expire) || (change && now >= change))
3726 		return 2;		/* check if expired */
3727 
3728 	return 0;			/* OK! */
3729 }
3730 
3731 char *
ftpd_strdup(const char * s)3732 ftpd_strdup(const char *s)
3733 {
3734 	char *new = strdup(s);
3735 
3736 	if (new == NULL)
3737 		fatal("Local resource failure: malloc");
3738 		/* NOTREACHED */
3739 	return (new);
3740 }
3741 
3742 /*
3743  * As per fprintf(), but increment total_bytes and total_bytes_out,
3744  * by the appropriate amount.
3745  */
3746 void
cprintf(FILE * fd,const char * fmt,...)3747 cprintf(FILE *fd, const char *fmt, ...)
3748 {
3749 	off_t b;
3750 	va_list ap;
3751 
3752 	va_start(ap, fmt);
3753 	b = vfprintf(fd, fmt, ap);
3754 	va_end(ap);
3755 	total_bytes += b;
3756 	total_bytes_out += b;
3757 }
3758 
3759 #ifdef USE_PAM
3760 /*
3761  * the following code is stolen from imap-uw PAM authentication module and
3762  * login.c
3763  */
3764 typedef struct {
3765 	const char *uname;	/* user name */
3766 	int	    triedonce;	/* if non-zero, tried before */
3767 } ftpd_cred_t;
3768 
3769 static int
auth_conv(int num_msg,const struct pam_message ** msg,struct pam_response ** resp,void * appdata)3770 auth_conv(int num_msg, const struct pam_message **msg,
3771     struct pam_response **resp, void *appdata)
3772 {
3773 	int i, ret;
3774 	size_t n;
3775 	ftpd_cred_t *cred = (ftpd_cred_t *) appdata;
3776 	struct pam_response *myreply;
3777 	char pbuf[FTP_BUFLEN];
3778 
3779 	if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
3780 		return (PAM_CONV_ERR);
3781 	myreply = calloc(num_msg, sizeof *myreply);
3782 	if (myreply == NULL)
3783 		return PAM_BUF_ERR;
3784 
3785 	for (i = 0; i < num_msg; i++) {
3786 		myreply[i].resp_retcode = 0;
3787 		myreply[i].resp = NULL;
3788 		switch (msg[i]->msg_style) {
3789 		case PAM_PROMPT_ECHO_ON:	/* user */
3790 			myreply[i].resp = ftpd_strdup(cred->uname);
3791 			/* PAM frees resp. */
3792 			break;
3793 		case PAM_PROMPT_ECHO_OFF:	/* authtok (password) */
3794 				/*
3795 				 * Only send a single 331 reply and
3796 				 * then expect a PASS.
3797 				 */
3798 			if (cred->triedonce) {
3799 				syslog(LOG_ERR,
3800 			"auth_conv: already performed PAM_PROMPT_ECHO_OFF");
3801 				goto fail;
3802 			}
3803 			cred->triedonce++;
3804 			if (msg[i]->msg[0] == '\0') {
3805 				(void)strlcpy(pbuf, "password", sizeof(pbuf));
3806 			} else {
3807 					/* Uncapitalize msg */
3808 				(void)strlcpy(pbuf, msg[i]->msg, sizeof(pbuf));
3809 				if (isupper((unsigned char)pbuf[0]))
3810 					pbuf[0] = tolower(
3811 					    (unsigned char)pbuf[0]);
3812 					/* Remove trailing ':' and whitespace */
3813 				n = strlen(pbuf);
3814 				while (n-- > 0) {
3815 					if (isspace((unsigned char)pbuf[n]) ||
3816 					    pbuf[n] == ':')
3817 						pbuf[n] = '\0';
3818 					else
3819 						break;
3820 				}
3821 			}
3822 				/* Send reply, wait for a response. */
3823 			reply(331, "User %s accepted, provide %s.",
3824 			    cred->uname, pbuf);
3825 			(void) alarm(curclass.timeout);
3826 			ret = get_line(pbuf, sizeof(pbuf)-1, stdin);
3827 			(void) alarm(0);
3828 			if (ret == -1) {
3829 				reply(221, "You could at least say goodbye.");
3830 				dologout(0);
3831 			} else if (ret == -2) {
3832 			    /* XXX: should we do this reply(-530, ..) ? */
3833 				reply(-530, "Command too long.");
3834 				goto fail;
3835 			}
3836 				/* Ensure it is PASS */
3837 			if (strncasecmp(pbuf, "PASS ", 5) != 0) {
3838 				syslog(LOG_ERR,
3839 				    "auth_conv: unexpected reply '%.4s'", pbuf);
3840 				/* XXX: should we do this reply(-530, ..) ? */
3841 				reply(-530, "Unexpected reply '%.4s'.", pbuf);
3842 				goto fail;
3843 			}
3844 				/* Strip CRLF from "PASS" reply */
3845 			n = strlen(pbuf);
3846 			while (--n >= 5 &&
3847 			    (pbuf[n] == '\r' || pbuf[n] == '\n'))
3848 			    pbuf[n] = '\0';
3849 				/* Copy password into reply */
3850 			myreply[i].resp = ftpd_strdup(pbuf+5);
3851 				/* PAM frees resp. */
3852 			break;
3853 		case PAM_TEXT_INFO:
3854 		case PAM_ERROR_MSG:
3855 			break;
3856 		default:			/* unknown message style */
3857 			goto fail;
3858 		}
3859 	}
3860 
3861 	*resp = myreply;
3862 	return PAM_SUCCESS;
3863 
3864  fail:
3865 	free(myreply);
3866 	*resp = NULL;
3867 	return PAM_CONV_ERR;
3868 }
3869 
3870 /*
3871  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
3872  * authenticated, or 1 if not authenticated.  If some sort of PAM system
3873  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
3874  * function returns -1.  This can be used as an indication that we should
3875  * fall back to a different authentication mechanism.
3876  * pw maybe be updated to a new user if PAM_USER changes from curname.
3877  */
3878 static int
auth_pam(void)3879 auth_pam(void)
3880 {
3881 	const char *tmpl_user;
3882 	const void *item;
3883 	int rval;
3884 	int e;
3885 	ftpd_cred_t auth_cred = { curname, 0 };
3886 	struct pam_conv conv = { &auth_conv, &auth_cred };
3887 
3888 	e = pam_start("ftpd", curname, &conv, &pamh);
3889 	if (e != PAM_SUCCESS) {
3890 		/*
3891 		 * In OpenPAM, it's OK to pass NULL to pam_strerror()
3892 		 * if context creation has failed in the first place.
3893 		 */
3894 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
3895 		return -1;
3896 	}
3897 
3898 	e = pam_set_item(pamh, PAM_RHOST, remotehost);
3899 	if (e != PAM_SUCCESS) {
3900 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
3901 			pam_strerror(pamh, e));
3902 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3903 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3904 		}
3905 		pamh = NULL;
3906 		return -1;
3907 	}
3908 
3909 	e = pam_set_item(pamh, PAM_SOCKADDR, &his_addr);
3910 	if (e != PAM_SUCCESS) {
3911 		syslog(LOG_ERR, "pam_set_item(PAM_SOCKADDR): %s",
3912 			pam_strerror(pamh, e));
3913 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3914 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3915 		}
3916 		pamh = NULL;
3917 		return -1;
3918 	}
3919 
3920 	e = pam_authenticate(pamh, 0);
3921 	if (ftpd_debug)
3922 		syslog(LOG_DEBUG, "pam_authenticate: user '%s' returned %d",
3923 		    curname, e);
3924 	switch (e) {
3925 	case PAM_SUCCESS:
3926 		/*
3927 		 * With PAM we support the concept of a "template"
3928 		 * user.  The user enters a login name which is
3929 		 * authenticated by PAM, usually via a remote service
3930 		 * such as RADIUS or TACACS+.  If authentication
3931 		 * succeeds, a different but related "template" name
3932 		 * is used for setting the credentials, shell, and
3933 		 * home directory.  The name the user enters need only
3934 		 * exist on the remote authentication server, but the
3935 		 * template name must be present in the local password
3936 		 * database.
3937 		 *
3938 		 * This is supported by two various mechanisms in the
3939 		 * individual modules.  However, from the application's
3940 		 * point of view, the template user is always passed
3941 		 * back as a changed value of the PAM_USER item.
3942 		 */
3943 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
3944 		    PAM_SUCCESS) {
3945 			tmpl_user = (const char *) item;
3946 			if (pw == NULL
3947 			    || strcmp(pw->pw_name, tmpl_user) != 0) {
3948 				pw = sgetpwnam(tmpl_user);
3949 				if (ftpd_debug)
3950 					syslog(LOG_DEBUG,
3951 					    "auth_pam: PAM changed "
3952 					    "user from '%s' to '%s'",
3953 					    curname, pw->pw_name);
3954 				(void)strlcpy(curname, pw->pw_name,
3955 				    curname_len);
3956 			}
3957 		} else
3958 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
3959 			    pam_strerror(pamh, e));
3960 		rval = 0;
3961 		break;
3962 
3963 	case PAM_AUTH_ERR:
3964 	case PAM_USER_UNKNOWN:
3965 	case PAM_MAXTRIES:
3966 		rval = 1;
3967 		break;
3968 
3969 	default:
3970 		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
3971 		rval = -1;
3972 		break;
3973 	}
3974 
3975 	if (rval == 0) {
3976 		e = pam_acct_mgmt(pamh, 0);
3977 		if (e != PAM_SUCCESS) {
3978 			syslog(LOG_ERR, "pam_acct_mgmt: %s",
3979 						pam_strerror(pamh, e));
3980 			rval = 1;
3981 		}
3982 	}
3983 
3984 	if (rval != 0) {
3985 		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
3986 			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
3987 		}
3988 		pamh = NULL;
3989 	}
3990 	return rval;
3991 }
3992 
3993 #endif /* USE_PAM */
3994