sshd.c revision 57470
1/*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 *                    All rights reserved
5 * Created: Fri Mar 17 17:09:28 1995 ylo
6 * This program is the ssh daemon.  It listens for connections from clients, and
7 * performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection.  This can also handle forwarding of X11, TCP/IP, and authentication
10 * agent connections.
11 *
12 * $FreeBSD: head/crypto/openssh/sshd.c 57470 2000-02-25 05:22:14Z green $
13 */
14
15#include "includes.h"
16RCSID("$OpenBSD: sshd.c,v 1.88 2000/02/15 16:52:57 markus Exp $");
17
18#include "xmalloc.h"
19#include "rsa.h"
20#include "ssh.h"
21#include "pty.h"
22#include "packet.h"
23#include "buffer.h"
24#include "cipher.h"
25#include "mpaux.h"
26#include "servconf.h"
27#include "uidswap.h"
28#include "compat.h"
29#include <poll.h>
30#include <time.h>
31
32#ifdef LIBWRAP
33#include <tcpd.h>
34#include <syslog.h>
35int allow_severity = LOG_INFO;
36int deny_severity = LOG_WARNING;
37#endif /* LIBWRAP */
38
39#ifdef __FreeBSD__
40#include <libutil.h>
41#include <syslog.h>
42#define	LOGIN_CAP
43#endif /* __FreeBSD__ */
44
45#ifdef LOGIN_CAP
46#include <login_cap.h>
47#endif /* LOGIN_CAP */
48
49#ifndef O_NOCTTY
50#define O_NOCTTY	0
51#endif
52
53/* Local Xauthority file. */
54static char *xauthfile = NULL;
55
56/* Server configuration options. */
57ServerOptions options;
58
59/* Name of the server configuration file. */
60char *config_file_name = SERVER_CONFIG_FILE;
61
62/*
63 * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
64 * Default value is AF_UNSPEC means both IPv4 and IPv6.
65 */
66int IPv4or6 = AF_UNSPEC;
67
68/*
69 * Debug mode flag.  This can be set on the command line.  If debug
70 * mode is enabled, extra debugging output will be sent to the system
71 * log, the daemon will not go to background, and will exit after processing
72 * the first connection.
73 */
74int debug_flag = 0;
75
76/* Flag indicating that the daemon is being started from inetd. */
77int inetd_flag = 0;
78
79/* debug goes to stderr unless inetd_flag is set */
80int log_stderr = 0;
81
82/* argv[0] without path. */
83char *av0;
84
85/* Saved arguments to main(). */
86char **saved_argv;
87
88/*
89 * The sockets that the server is listening; this is used in the SIGHUP
90 * signal handler.
91 */
92#define	MAX_LISTEN_SOCKS	16
93int listen_socks[MAX_LISTEN_SOCKS];
94int num_listen_socks = 0;
95
96/*
97 * the client's version string, passed by sshd2 in compat mode. if != NULL,
98 * sshd will skip the version-number exchange
99 */
100char *client_version_string = NULL;
101
102/* Flags set in auth-rsa from authorized_keys flags.  These are set in auth-rsa.c. */
103int no_port_forwarding_flag = 0;
104int no_agent_forwarding_flag = 0;
105int no_x11_forwarding_flag = 0;
106int no_pty_flag = 0;
107
108/* RSA authentication "command=" option. */
109char *forced_command = NULL;
110
111/* RSA authentication "environment=" options. */
112struct envstring *custom_environment = NULL;
113
114/* Session id for the current session. */
115unsigned char session_id[16];
116
117/*
118 * Any really sensitive data in the application is contained in this
119 * structure. The idea is that this structure could be locked into memory so
120 * that the pages do not get written into swap.  However, there are some
121 * problems. The private key contains BIGNUMs, and we do not (in principle)
122 * have access to the internals of them, and locking just the structure is
123 * not very useful.  Currently, memory locking is not implemented.
124 */
125struct {
126	RSA *private_key;	 /* Private part of server key. */
127	RSA *host_key;		 /* Private part of host key. */
128} sensitive_data;
129
130/*
131 * Flag indicating whether the current session key has been used.  This flag
132 * is set whenever the key is used, and cleared when the key is regenerated.
133 */
134int key_used = 0;
135
136/* This is set to true when SIGHUP is received. */
137int received_sighup = 0;
138
139/* Public side of the server key.  This value is regenerated regularly with
140   the private key. */
141RSA *public_key;
142
143/* These are used to implement connections_per_period. */
144struct magic_connection {
145		struct timeval connections_begin;
146		unsigned int connections_this_period;
147} *magic_connections;
148/* Magic number, too!  TODO: this doesn't have to be static. */
149const size_t MAGIC_CONNECTIONS_SIZE = 1;
150
151static __inline int
152magic_hash(struct sockaddr_storage *sa) {
153
154	return 0;
155}
156
157static __inline struct timeval
158timevaldiff(struct timeval *tv1, struct timeval *tv2) {
159	struct timeval diff;
160	int carry;
161
162	carry = tv1->tv_usec > tv2->tv_usec;
163	diff.tv_sec = tv2->tv_sec - tv1->tv_sec - (carry ? 0 : 1);
164	diff.tv_usec = tv2->tv_usec - tv1->tv_usec + (carry ? 1000000 : 0);
165
166	return diff;
167}
168
169/* Prototypes for various functions defined later in this file. */
170void do_ssh_kex();
171void do_authentication();
172void do_authloop(struct passwd * pw);
173void do_fake_authloop(char *user);
174void do_authenticated(struct passwd * pw);
175void do_exec_pty(const char *command, int ptyfd, int ttyfd,
176	         const char *ttyname, struct passwd * pw, const char *term,
177	         const char *display, const char *auth_proto,
178	         const char *auth_data);
179void do_exec_no_pty(const char *command, struct passwd * pw,
180	            const char *display, const char *auth_proto,
181	            const char *auth_data);
182void do_child(const char *command, struct passwd * pw, const char *term,
183	      const char *display, const char *auth_proto,
184	      const char *auth_data, const char *ttyname);
185
186/*
187 * Remove local Xauthority file.
188 */
189void
190xauthfile_cleanup_proc(void *ignore)
191{
192	debug("xauthfile_cleanup_proc called");
193
194	if (xauthfile != NULL) {
195		char *p;
196		unlink(xauthfile);
197		p = strrchr(xauthfile, '/');
198		if (p != NULL) {
199			*p = '\0';
200			rmdir(xauthfile);
201		}
202		xfree(xauthfile);
203		xauthfile = NULL;
204	}
205}
206
207/*
208 * Close all listening sockets
209 */
210void
211close_listen_socks(void)
212{
213	int i;
214	for (i = 0; i < num_listen_socks; i++)
215		close(listen_socks[i]);
216	num_listen_socks = -1;
217}
218
219/*
220 * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
221 * the effect is to reread the configuration file (and to regenerate
222 * the server key).
223 */
224void
225sighup_handler(int sig)
226{
227	received_sighup = 1;
228	signal(SIGHUP, sighup_handler);
229}
230
231/*
232 * Called from the main program after receiving SIGHUP.
233 * Restarts the server.
234 */
235void
236sighup_restart()
237{
238	log("Received SIGHUP; restarting.");
239	close_listen_socks();
240	execv(saved_argv[0], saved_argv);
241	log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
242	exit(1);
243}
244
245/*
246 * Generic signal handler for terminating signals in the master daemon.
247 * These close the listen socket; not closing it seems to cause "Address
248 * already in use" problems on some machines, which is inconvenient.
249 */
250void
251sigterm_handler(int sig)
252{
253	log("Received signal %d; terminating.", sig);
254	close_listen_socks();
255	exit(255);
256}
257
258/*
259 * SIGCHLD handler.  This is called whenever a child dies.  This will then
260 * reap any zombies left by exited c.
261 */
262void
263main_sigchld_handler(int sig)
264{
265	int save_errno = errno;
266	int status;
267
268	while (waitpid(-1, &status, WNOHANG) > 0)
269		;
270
271	signal(SIGCHLD, main_sigchld_handler);
272	errno = save_errno;
273}
274
275/*
276 * Signal handler for the alarm after the login grace period has expired.
277 */
278void
279grace_alarm_handler(int sig)
280{
281	/* Close the connection. */
282	packet_close();
283
284	/* Log error and exit. */
285	fatal("Timeout before authentication for %s.", get_remote_ipaddr());
286}
287
288/*
289 * convert ssh auth msg type into description
290 */
291char *
292get_authname(int type)
293{
294	static char buf[1024];
295	switch (type) {
296	case SSH_CMSG_AUTH_PASSWORD:
297		return "password";
298	case SSH_CMSG_AUTH_RSA:
299		return "rsa";
300	case SSH_CMSG_AUTH_RHOSTS_RSA:
301		return "rhosts-rsa";
302	case SSH_CMSG_AUTH_RHOSTS:
303		return "rhosts";
304#ifdef KRB4
305	case SSH_CMSG_AUTH_KERBEROS:
306		return "kerberos";
307#endif
308#ifdef SKEY
309	case SSH_CMSG_AUTH_TIS_RESPONSE:
310		return "s/key";
311#endif
312	}
313	snprintf(buf, sizeof buf, "bad-auth-msg-%d", type);
314	return buf;
315}
316
317/*
318 * Signal handler for the key regeneration alarm.  Note that this
319 * alarm only occurs in the daemon waiting for connections, and it does not
320 * do anything with the private key or random state before forking.
321 * Thus there should be no concurrency control/asynchronous execution
322 * problems.
323 */
324void
325key_regeneration_alarm(int sig)
326{
327	int save_errno = errno;
328
329	/* Check if we should generate a new key. */
330	if (key_used) {
331		/* This should really be done in the background. */
332		log("Generating new %d bit RSA key.", options.server_key_bits);
333
334		if (sensitive_data.private_key != NULL)
335			RSA_free(sensitive_data.private_key);
336		sensitive_data.private_key = RSA_new();
337
338		if (public_key != NULL)
339			RSA_free(public_key);
340		public_key = RSA_new();
341
342		rsa_generate_key(sensitive_data.private_key, public_key,
343				 options.server_key_bits);
344		arc4random_stir();
345		key_used = 0;
346		log("RSA key generation complete.");
347	}
348	/* Reschedule the alarm. */
349	signal(SIGALRM, key_regeneration_alarm);
350	alarm(options.key_regeneration_time);
351	errno = save_errno;
352}
353
354/*
355 * Main program for the daemon.
356 */
357int
358main(int ac, char **av)
359{
360	extern char *optarg;
361	extern int optind;
362	int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
363	socklen_t fromlen;
364 	int connections_per_period_exceeded = 0;
365	int remote_major, remote_minor;
366	int silentrsa = 0;
367	fd_set *fdset;
368	struct sockaddr_storage from;
369	char buf[100];			/* Must not be larger than remote_version. */
370	char remote_version[100];	/* Must be at least as big as buf. */
371	const char *remote_ip;
372	int remote_port;
373	char *comment;
374	FILE *f;
375	struct linger linger;
376	struct addrinfo *ai;
377	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
378	int listen_sock, maxfd;
379
380	/* Save argv[0]. */
381	saved_argv = av;
382	if (strchr(av[0], '/'))
383		av0 = strrchr(av[0], '/') + 1;
384	else
385		av0 = av[0];
386
387	/* Initialize configuration options to their default values. */
388	initialize_server_options(&options);
389
390	/* Parse command-line arguments. */
391	while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
392		switch (opt) {
393		case '4':
394			IPv4or6 = AF_INET;
395			break;
396		case '6':
397			IPv4or6 = AF_INET6;
398			break;
399		case 'f':
400			config_file_name = optarg;
401			break;
402		case 'd':
403			debug_flag = 1;
404			options.log_level = SYSLOG_LEVEL_DEBUG;
405			break;
406		case 'i':
407			inetd_flag = 1;
408			break;
409		case 'Q':
410			silentrsa = 1;
411			break;
412		case 'q':
413			options.log_level = SYSLOG_LEVEL_QUIET;
414			break;
415		case 'b':
416			options.server_key_bits = atoi(optarg);
417			break;
418		case 'p':
419			options.ports_from_cmdline = 1;
420			if (options.num_ports >= MAX_PORTS)
421				fatal("too many ports.\n");
422			options.ports[options.num_ports++] = atoi(optarg);
423			break;
424		case 'g':
425			options.login_grace_time = atoi(optarg);
426			break;
427		case 'k':
428			options.key_regeneration_time = atoi(optarg);
429			break;
430		case 'h':
431			options.host_key_file = optarg;
432			break;
433		case 'V':
434			client_version_string = optarg;
435			/* only makes sense with inetd_flag, i.e. no listen() */
436			inetd_flag = 1;
437			break;
438		case '?':
439		default:
440			fprintf(stderr, "sshd version %s\n", SSH_VERSION);
441			fprintf(stderr, "Usage: %s [options]\n", av0);
442			fprintf(stderr, "Options:\n");
443			fprintf(stderr, "  -f file    Configuration file (default %s)\n", SERVER_CONFIG_FILE);
444			fprintf(stderr, "  -d         Debugging mode\n");
445			fprintf(stderr, "  -i         Started from inetd\n");
446			fprintf(stderr, "  -q         Quiet (no logging)\n");
447			fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
448			fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
449			fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
450			fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
451			fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
452			    HOST_KEY_FILE);
453			fprintf(stderr, "  -4         Use IPv4 only\n");
454			fprintf(stderr, "  -6         Use IPv6 only\n");
455			exit(1);
456		}
457	}
458
459	/*
460	 * Force logging to stderr until we have loaded the private host
461	 * key (unless started from inetd)
462	 */
463	log_init(av0,
464	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
465	    options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
466	    !inetd_flag);
467
468	/* check if RSA support exists */
469	if (rsa_alive() == 0) {
470		if (silentrsa == 0)
471			printf("sshd: no RSA support in libssl and libcrypto -- exiting.  See ssl(8)\n");
472		log("no RSA support in libssl and libcrypto -- exiting.  See ssl(8)");
473		exit(1);
474	}
475	/* Read server configuration options from the configuration file. */
476	read_server_config(&options, config_file_name);
477
478	/* Fill in default values for those options not explicitly set. */
479	fill_default_server_options(&options);
480
481	/* Check certain values for sanity. */
482	if (options.server_key_bits < 512 ||
483	    options.server_key_bits > 32768) {
484		fprintf(stderr, "Bad server key size.\n");
485		exit(1);
486	}
487	/* Check that there are no remaining arguments. */
488	if (optind < ac) {
489		fprintf(stderr, "Extra argument %s.\n", av[optind]);
490		exit(1);
491	}
492
493	debug("sshd version %.100s", SSH_VERSION);
494
495	sensitive_data.host_key = RSA_new();
496	errno = 0;
497	/* Load the host key.  It must have empty passphrase. */
498	if (!load_private_key(options.host_key_file, "",
499			      sensitive_data.host_key, &comment)) {
500		error("Could not load host key: %.200s: %.100s",
501		      options.host_key_file, strerror(errno));
502		exit(1);
503	}
504	xfree(comment);
505
506	/* Initialize the log (it is reinitialized below in case we
507	   forked). */
508	if (debug_flag && !inetd_flag)
509		log_stderr = 1;
510	log_init(av0, options.log_level, options.log_facility, log_stderr);
511
512	/* If not in debugging mode, and not started from inetd,
513	   disconnect from the controlling terminal, and fork.  The
514	   original process exits. */
515	if (!debug_flag && !inetd_flag) {
516#ifdef TIOCNOTTY
517		int fd;
518#endif /* TIOCNOTTY */
519		if (daemon(0, 0) < 0)
520			fatal("daemon() failed: %.200s", strerror(errno));
521
522		/* Disconnect from the controlling tty. */
523#ifdef TIOCNOTTY
524		fd = open("/dev/tty", O_RDWR | O_NOCTTY);
525		if (fd >= 0) {
526			(void) ioctl(fd, TIOCNOTTY, NULL);
527			close(fd);
528		}
529#endif /* TIOCNOTTY */
530	}
531	/* Reinitialize the log (because of the fork above). */
532	log_init(av0, options.log_level, options.log_facility, log_stderr);
533
534	/* Check that server and host key lengths differ sufficiently.
535	   This is necessary to make double encryption work with rsaref.
536	   Oh, I hate software patents. I dont know if this can go? Niels */
537	if (options.server_key_bits >
538	BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
539	    options.server_key_bits <
540	BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
541		options.server_key_bits =
542			BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
543		debug("Forcing server key to %d bits to make it differ from host key.",
544		      options.server_key_bits);
545	}
546	/* Do not display messages to stdout in RSA code. */
547	rsa_set_verbose(0);
548
549	/* Initialize the random number generator. */
550	arc4random_stir();
551
552	/* Chdir to the root directory so that the current disk can be
553	   unmounted if desired. */
554	chdir("/");
555
556	/* Close connection cleanly after attack. */
557	cipher_attack_detected = packet_disconnect;
558
559	/* Start listening for a socket, unless started from inetd. */
560	if (inetd_flag) {
561		int s1, s2;
562		s1 = dup(0);	/* Make sure descriptors 0, 1, and 2 are in use. */
563		s2 = dup(s1);
564		sock_in = dup(0);
565		sock_out = dup(1);
566		/* We intentionally do not close the descriptors 0, 1, and 2
567		   as our code for setting the descriptors won\'t work
568		   if ttyfd happens to be one of those. */
569		debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
570
571		public_key = RSA_new();
572		sensitive_data.private_key = RSA_new();
573
574		log("Generating %d bit RSA key.", options.server_key_bits);
575		rsa_generate_key(sensitive_data.private_key, public_key,
576				 options.server_key_bits);
577		arc4random_stir();
578		log("RSA key generation complete.");
579	} else {
580		for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
581			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
582				continue;
583			if (num_listen_socks >= MAX_LISTEN_SOCKS)
584				fatal("Too many listen sockets. "
585				    "Enlarge MAX_LISTEN_SOCKS");
586			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
587			    ntop, sizeof(ntop), strport, sizeof(strport),
588			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
589				error("getnameinfo failed");
590				continue;
591			}
592			/* Create socket for listening. */
593			listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
594			if (listen_sock < 0) {
595				/* kernel may not support ipv6 */
596				verbose("socket: %.100s", strerror(errno));
597				continue;
598			}
599			if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
600				error("listen_sock O_NONBLOCK: %s", strerror(errno));
601				close(listen_sock);
602				continue;
603			}
604			/*
605			 * Set socket options.  We try to make the port
606			 * reusable and have it close as fast as possible
607			 * without waiting in unnecessary wait states on
608			 * close.
609			 */
610			setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
611			    (void *) &on, sizeof(on));
612			linger.l_onoff = 1;
613			linger.l_linger = 5;
614			setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
615			    (void *) &linger, sizeof(linger));
616
617			debug("Bind to port %s on %s.", strport, ntop);
618
619			/* Bind the socket to the desired port. */
620			if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
621				error("Bind to port %s on %s failed: %.200s.",
622				    strport, ntop, strerror(errno));
623				close(listen_sock);
624				continue;
625			}
626			listen_socks[num_listen_socks] = listen_sock;
627			num_listen_socks++;
628
629			/* Start listening on the port. */
630			log("Server listening on %s port %s.", ntop, strport);
631			if (listen(listen_sock, 5) < 0)
632				fatal("listen: %.100s", strerror(errno));
633
634		}
635		freeaddrinfo(options.listen_addrs);
636
637		if (!num_listen_socks)
638			fatal("Cannot bind any address.");
639
640		if (!debug_flag) {
641			/*
642			 * Record our pid in /etc/sshd_pid to make it easier
643			 * to kill the correct sshd.  We don\'t want to do
644			 * this before the bind above because the bind will
645			 * fail if there already is a daemon, and this will
646			 * overwrite any old pid in the file.
647			 */
648			f = fopen(SSH_DAEMON_PID_FILE, "w");
649			if (f) {
650				fprintf(f, "%u\n", (unsigned int) getpid());
651				fclose(f);
652			}
653		}
654
655		public_key = RSA_new();
656		sensitive_data.private_key = RSA_new();
657
658		log("Generating %d bit RSA key.", options.server_key_bits);
659		rsa_generate_key(sensitive_data.private_key, public_key,
660				 options.server_key_bits);
661		arc4random_stir();
662		log("RSA key generation complete.");
663
664		/* Schedule server key regeneration alarm. */
665		signal(SIGALRM, key_regeneration_alarm);
666		alarm(options.key_regeneration_time);
667
668		/* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
669		signal(SIGHUP, sighup_handler);
670		signal(SIGTERM, sigterm_handler);
671		signal(SIGQUIT, sigterm_handler);
672
673		/* Arrange SIGCHLD to be caught. */
674		signal(SIGCHLD, main_sigchld_handler);
675
676		/* setup fd set for listen */
677		maxfd = 0;
678		for (i = 0; i < num_listen_socks; i++)
679			if (listen_socks[i] > maxfd)
680				maxfd = listen_socks[i];
681		fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
682		fdset = (fd_set *)xmalloc(fdsetsz);
683
684		/* Initialize the magic_connections table.  It's magical! */
685		magic_connections = calloc(MAGIC_CONNECTIONS_SIZE,
686		    sizeof(struct magic_connection));
687		if (magic_connections == NULL)
688			fatal("calloc: %s", strerror(errno));
689
690		/*
691		 * Stay listening for connections until the system crashes or
692		 * the daemon is killed with a signal.
693		 */
694		for (;;) {
695			if (received_sighup)
696				sighup_restart();
697			/* Wait in select until there is a connection. */
698			memset(fdset, 0, fdsetsz);
699			for (i = 0; i < num_listen_socks; i++)
700				FD_SET(listen_socks[i], fdset);
701			if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
702				if (errno != EINTR)
703					error("select: %.100s", strerror(errno));
704				continue;
705			}
706			for (i = 0; i < num_listen_socks; i++) {
707				if (!FD_ISSET(listen_socks[i], fdset))
708					continue;
709			fromlen = sizeof(from);
710			newsock = accept(listen_socks[i], (struct sockaddr *)&from,
711			    &fromlen);
712			if (newsock < 0) {
713				if (errno != EINTR && errno != EWOULDBLOCK)
714					error("accept: %.100s", strerror(errno));
715				continue;
716			}
717			if (fcntl(newsock, F_SETFL, 0) < 0) {
718				error("newsock del O_NONBLOCK: %s", strerror(errno));
719				continue;
720			}
721			if (options.connections_per_period != 0) {
722				struct timeval diff, connections_end;
723				struct magic_connection *mc;
724
725				(void)gettimeofday(&connections_end, NULL);
726				mc = &magic_connections[magic_hash(&from)];
727				diff = timevaldiff(&mc->connections_begin, &connections_end);
728				if (diff.tv_sec >= options.connections_period) {
729					/*
730					 * Slide the window forward only after completely
731					 * leaving it.
732					 */
733					mc->connections_begin = connections_end;
734					mc->connections_this_period = 1;
735				} else {
736					if (++mc->connections_this_period >
737					    options.connections_per_period)
738						connections_per_period_exceeded = 1;
739				}
740			}
741
742			/*
743			 * Got connection.  Fork a child to handle it unless
744			 * we are in debugging mode or the maximum number of
745			 * connections per period has been exceeded.
746			 */
747			if (debug_flag) {
748				/*
749				 * In debugging mode.  Close the listening
750				 * socket, and start processing the
751				 * connection without forking.
752				 */
753				debug("Server will not fork when running in debugging mode.");
754				close_listen_socks();
755				sock_in = newsock;
756				sock_out = newsock;
757				pid = getpid();
758				break;
759			} else if (connections_per_period_exceeded) {
760				log("Connection rate limit of %u/%us has been exceeded; "
761				    "dropping connection from %s.",
762				    options.connections_per_period, options.connections_period,
763				    ntop);
764				connections_per_period_exceeded = 0;
765			} else {
766				/*
767				 * Normal production daemon.  Fork, and have
768				 * the child process the connection. The
769				 * parent continues listening.
770				 */
771				if ((pid = fork()) == 0) {
772					/*
773					 * Child.  Close the listening socket, and start using the
774					 * accepted socket.  Reinitialize logging (since our pid has
775					 * changed).  We break out of the loop to handle the connection.
776					 */
777					close_listen_socks();
778					sock_in = newsock;
779					sock_out = newsock;
780					log_init(av0, options.log_level, options.log_facility, log_stderr);
781					break;
782				}
783			}
784
785			/* Parent.  Stay in the loop. */
786			if (pid < 0)
787				error("fork: %.100s", strerror(errno));
788			else
789				debug("Forked child %d.", pid);
790
791			/* Mark that the key has been used (it was "given" to the child). */
792			key_used = 1;
793
794			arc4random_stir();
795
796			/* Close the new socket (the child is now taking care of it). */
797			close(newsock);
798			} /* for (i = 0; i < num_listen_socks; i++) */
799			/* child process check (or debug mode) */
800			if (num_listen_socks < 0)
801				break;
802		}
803	}
804
805	/* This is the child processing a new connection. */
806
807	/*
808	 * Disable the key regeneration alarm.  We will not regenerate the
809	 * key since we are no longer in a position to give it to anyone. We
810	 * will not restart on SIGHUP since it no longer makes sense.
811	 */
812	alarm(0);
813	signal(SIGALRM, SIG_DFL);
814	signal(SIGHUP, SIG_DFL);
815	signal(SIGTERM, SIG_DFL);
816	signal(SIGQUIT, SIG_DFL);
817	signal(SIGCHLD, SIG_DFL);
818
819	/*
820	 * Set socket options for the connection.  We want the socket to
821	 * close as fast as possible without waiting for anything.  If the
822	 * connection is not a socket, these will do nothing.
823	 */
824	/* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
825	linger.l_onoff = 1;
826	linger.l_linger = 5;
827	setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
828
829	/*
830	 * Register our connection.  This turns encryption off because we do
831	 * not have a key.
832	 */
833	packet_set_connection(sock_in, sock_out);
834
835	remote_port = get_remote_port();
836	remote_ip = get_remote_ipaddr();
837
838	/* Check whether logins are denied from this host. */
839#ifdef LIBWRAP
840	/* XXX LIBWRAP noes not know about IPv6 */
841	{
842		struct request_info req;
843
844		request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
845		fromhost(&req);
846
847		if (!hosts_access(&req)) {
848			close(sock_in);
849			close(sock_out);
850			refuse(&req);
851		}
852/*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
853	}
854#endif /* LIBWRAP */
855	/* Log the connection. */
856	verbose("Connection from %.500s port %d", remote_ip, remote_port);
857
858	/*
859	 * We don\'t want to listen forever unless the other side
860	 * successfully authenticates itself.  So we set up an alarm which is
861	 * cleared after successful authentication.  A limit of zero
862	 * indicates no limit. Note that we don\'t set the alarm in debugging
863	 * mode; it is just annoying to have the server exit just when you
864	 * are about to discover the bug.
865	 */
866	signal(SIGALRM, grace_alarm_handler);
867	if (!debug_flag)
868		alarm(options.login_grace_time);
869
870	if (client_version_string != NULL) {
871		/* we are exec'ed by sshd2, so skip exchange of protocol version */
872		strlcpy(buf, client_version_string, sizeof(buf));
873	} else {
874		/* Send our protocol version identification. */
875		snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
876			 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
877		if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf)) {
878			log("Could not write ident string to %s.", remote_ip);
879			fatal_cleanup();
880		}
881
882		/* Read other side\'s version identification. */
883		for (i = 0; i < sizeof(buf) - 1; i++) {
884			if (read(sock_in, &buf[i], 1) != 1) {
885				log("Did not receive ident string from %s.", remote_ip);
886				fatal_cleanup();
887			}
888			if (buf[i] == '\r') {
889				buf[i] = '\n';
890				buf[i + 1] = 0;
891				break;
892			}
893			if (buf[i] == '\n') {
894				/* buf[i] == '\n' */
895				buf[i + 1] = 0;
896				break;
897			}
898		}
899		buf[sizeof(buf) - 1] = 0;
900	}
901
902	/*
903	 * Check that the versions match.  In future this might accept
904	 * several versions and set appropriate flags to handle them.
905	 */
906	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
907	    remote_version) != 3) {
908		char *s = "Protocol mismatch.\n";
909
910		(void) atomicio(write, sock_out, s, strlen(s));
911		close(sock_in);
912		close(sock_out);
913		log("Bad protocol version identification '%.100s' from %s",
914		    buf, remote_ip);
915		fatal_cleanup();
916	}
917	debug("Client protocol version %d.%d; client software version %.100s",
918	      remote_major, remote_minor, remote_version);
919	if (remote_major != PROTOCOL_MAJOR) {
920		char *s = "Protocol major versions differ.\n";
921
922		(void) atomicio(write, sock_out, s, strlen(s));
923		close(sock_in);
924		close(sock_out);
925		log("Protocol major versions differ for %s: %d vs. %d",
926		    remote_ip, PROTOCOL_MAJOR, remote_major);
927		fatal_cleanup();
928	}
929	/* Check that the client has sufficiently high software version. */
930	if (remote_major == 1 && remote_minor < 3)
931		packet_disconnect("Your ssh version is too old and is no longer supported.  Please install a newer version.");
932
933	if (remote_major == 1 && remote_minor == 3) {
934		/* note that this disables agent-forwarding */
935		enable_compat13();
936	}
937	/*
938	 * Check that the connection comes from a privileged port.  Rhosts-
939	 * and Rhosts-RSA-Authentication only make sense from priviledged
940	 * programs.  Of course, if the intruder has root access on his local
941	 * machine, he can connect from any port.  So do not use these
942	 * authentication methods from machines that you do not trust.
943	 */
944	if (remote_port >= IPPORT_RESERVED ||
945	    remote_port < IPPORT_RESERVED / 2) {
946		options.rhosts_authentication = 0;
947		options.rhosts_rsa_authentication = 0;
948	}
949#ifdef KRB4
950	if (!packet_connection_is_ipv4() &&
951	    options.kerberos_authentication) {
952		debug("Kerberos Authentication disabled, only available for IPv4.");
953		options.kerberos_authentication = 0;
954	}
955#endif /* KRB4 */
956
957	packet_set_nonblocking();
958
959	/* perform the key exchange */
960	do_ssh_kex();
961
962	/* authenticate user and start session */
963	do_authentication();
964
965#ifdef KRB4
966	/* Cleanup user's ticket cache file. */
967	if (options.kerberos_ticket_cleanup)
968		(void) dest_tkt();
969#endif /* KRB4 */
970
971	/* Cleanup user's local Xauthority file. */
972	if (xauthfile)
973		xauthfile_cleanup_proc(NULL);
974
975	/* The connection has been terminated. */
976	verbose("Closing connection to %.100s", remote_ip);
977	packet_close();
978	exit(0);
979}
980
981/*
982 * SSH1 key exchange
983 */
984void
985do_ssh_kex()
986{
987	int i, len;
988	int plen, slen;
989	BIGNUM *session_key_int;
990	unsigned char session_key[SSH_SESSION_KEY_LENGTH];
991	unsigned char cookie[8];
992	unsigned int cipher_type, auth_mask, protocol_flags;
993	u_int32_t rand = 0;
994
995	/*
996	 * Generate check bytes that the client must send back in the user
997	 * packet in order for it to be accepted; this is used to defy ip
998	 * spoofing attacks.  Note that this only works against somebody
999	 * doing IP spoofing from a remote machine; any machine on the local
1000	 * network can still see outgoing packets and catch the random
1001	 * cookie.  This only affects rhosts authentication, and this is one
1002	 * of the reasons why it is inherently insecure.
1003	 */
1004	for (i = 0; i < 8; i++) {
1005		if (i % 4 == 0)
1006			rand = arc4random();
1007		cookie[i] = rand & 0xff;
1008		rand >>= 8;
1009	}
1010
1011	/*
1012	 * Send our public key.  We include in the packet 64 bits of random
1013	 * data that must be matched in the reply in order to prevent IP
1014	 * spoofing.
1015	 */
1016	packet_start(SSH_SMSG_PUBLIC_KEY);
1017	for (i = 0; i < 8; i++)
1018		packet_put_char(cookie[i]);
1019
1020	/* Store our public server RSA key. */
1021	packet_put_int(BN_num_bits(public_key->n));
1022	packet_put_bignum(public_key->e);
1023	packet_put_bignum(public_key->n);
1024
1025	/* Store our public host RSA key. */
1026	packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1027	packet_put_bignum(sensitive_data.host_key->e);
1028	packet_put_bignum(sensitive_data.host_key->n);
1029
1030	/* Put protocol flags. */
1031	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1032
1033	/* Declare which ciphers we support. */
1034	packet_put_int(cipher_mask());
1035
1036	/* Declare supported authentication types. */
1037	auth_mask = 0;
1038	if (options.rhosts_authentication)
1039		auth_mask |= 1 << SSH_AUTH_RHOSTS;
1040	if (options.rhosts_rsa_authentication)
1041		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1042	if (options.rsa_authentication)
1043		auth_mask |= 1 << SSH_AUTH_RSA;
1044#ifdef KRB4
1045	if (options.kerberos_authentication)
1046		auth_mask |= 1 << SSH_AUTH_KERBEROS;
1047#endif
1048#ifdef AFS
1049	if (options.kerberos_tgt_passing)
1050		auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1051	if (options.afs_token_passing)
1052		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1053#endif
1054#ifdef SKEY
1055	if (options.skey_authentication == 1)
1056		auth_mask |= 1 << SSH_AUTH_TIS;
1057#endif
1058	if (options.password_authentication)
1059		auth_mask |= 1 << SSH_AUTH_PASSWORD;
1060	packet_put_int(auth_mask);
1061
1062	/* Send the packet and wait for it to be sent. */
1063	packet_send();
1064	packet_write_wait();
1065
1066	debug("Sent %d bit public key and %d bit host key.",
1067	      BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1068
1069	/* Read clients reply (cipher type and session key). */
1070	packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1071
1072	/* Get cipher type and check whether we accept this. */
1073	cipher_type = packet_get_char();
1074
1075        if (!(cipher_mask() & (1 << cipher_type)))
1076		packet_disconnect("Warning: client selects unsupported cipher.");
1077
1078	/* Get check bytes from the packet.  These must match those we
1079	   sent earlier with the public key packet. */
1080	for (i = 0; i < 8; i++)
1081		if (cookie[i] != packet_get_char())
1082			packet_disconnect("IP Spoofing check bytes do not match.");
1083
1084	debug("Encryption type: %.200s", cipher_name(cipher_type));
1085
1086	/* Get the encrypted integer. */
1087	session_key_int = BN_new();
1088	packet_get_bignum(session_key_int, &slen);
1089
1090	protocol_flags = packet_get_int();
1091	packet_set_protocol_flags(protocol_flags);
1092
1093	packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1094
1095	/*
1096	 * Decrypt it using our private server key and private host key (key
1097	 * with larger modulus first).
1098	 */
1099	if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1100		/* Private key has bigger modulus. */
1101		if (BN_num_bits(sensitive_data.private_key->n) <
1102		    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1103			fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1104			      get_remote_ipaddr(),
1105			      BN_num_bits(sensitive_data.private_key->n),
1106			      BN_num_bits(sensitive_data.host_key->n),
1107			      SSH_KEY_BITS_RESERVED);
1108		}
1109		rsa_private_decrypt(session_key_int, session_key_int,
1110				    sensitive_data.private_key);
1111		rsa_private_decrypt(session_key_int, session_key_int,
1112				    sensitive_data.host_key);
1113	} else {
1114		/* Host key has bigger modulus (or they are equal). */
1115		if (BN_num_bits(sensitive_data.host_key->n) <
1116		    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1117			fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1118			      get_remote_ipaddr(),
1119			      BN_num_bits(sensitive_data.host_key->n),
1120			      BN_num_bits(sensitive_data.private_key->n),
1121			      SSH_KEY_BITS_RESERVED);
1122		}
1123		rsa_private_decrypt(session_key_int, session_key_int,
1124				    sensitive_data.host_key);
1125		rsa_private_decrypt(session_key_int, session_key_int,
1126				    sensitive_data.private_key);
1127	}
1128
1129	compute_session_id(session_id, cookie,
1130			   sensitive_data.host_key->n,
1131			   sensitive_data.private_key->n);
1132
1133	/* Destroy the private and public keys.  They will no longer be needed. */
1134	RSA_free(public_key);
1135	RSA_free(sensitive_data.private_key);
1136	RSA_free(sensitive_data.host_key);
1137
1138	/*
1139	 * Extract session key from the decrypted integer.  The key is in the
1140	 * least significant 256 bits of the integer; the first byte of the
1141	 * key is in the highest bits.
1142	 */
1143	BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1144	len = BN_num_bytes(session_key_int);
1145	if (len < 0 || len > sizeof(session_key))
1146		fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1147		      get_remote_ipaddr(),
1148		      len, sizeof(session_key));
1149	memset(session_key, 0, sizeof(session_key));
1150	BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1151
1152	/* Destroy the decrypted integer.  It is no longer needed. */
1153	BN_clear_free(session_key_int);
1154
1155	/* Xor the first 16 bytes of the session key with the session id. */
1156	for (i = 0; i < 16; i++)
1157		session_key[i] ^= session_id[i];
1158
1159	/* Set the session key.  From this on all communications will be encrypted. */
1160	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1161
1162	/* Destroy our copy of the session key.  It is no longer needed. */
1163	memset(session_key, 0, sizeof(session_key));
1164
1165	debug("Received session key; encryption turned on.");
1166
1167	/* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
1168	packet_start(SSH_SMSG_SUCCESS);
1169	packet_send();
1170	packet_write_wait();
1171}
1172
1173
1174/*
1175 * Check if the user is allowed to log in via ssh. If user is listed in
1176 * DenyUsers or user's primary group is listed in DenyGroups, false will
1177 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1178 * if AllowGroups isn't empty and user isn't listed there, false will be
1179 * returned.
1180 * If the user's shell is not executable, false will be returned.
1181 * Otherwise true is returned.
1182 */
1183static int
1184allowed_user(struct passwd * pw)
1185{
1186	struct stat st;
1187	struct group *grp;
1188	int i;
1189
1190	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
1191	if (!pw)
1192		return 0;
1193
1194	/* deny if shell does not exists or is not executable */
1195	if (stat(pw->pw_shell, &st) != 0)
1196		return 0;
1197	if (!((st.st_mode & S_IFREG) && (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP))))
1198		return 0;
1199
1200	/* Return false if user is listed in DenyUsers */
1201	if (options.num_deny_users > 0) {
1202		if (!pw->pw_name)
1203			return 0;
1204		for (i = 0; i < options.num_deny_users; i++)
1205			if (match_pattern(pw->pw_name, options.deny_users[i]))
1206				return 0;
1207	}
1208	/* Return false if AllowUsers isn't empty and user isn't listed there */
1209	if (options.num_allow_users > 0) {
1210		if (!pw->pw_name)
1211			return 0;
1212		for (i = 0; i < options.num_allow_users; i++)
1213			if (match_pattern(pw->pw_name, options.allow_users[i]))
1214				break;
1215		/* i < options.num_allow_users iff we break for loop */
1216		if (i >= options.num_allow_users)
1217			return 0;
1218	}
1219	/* Get the primary group name if we need it. Return false if it fails */
1220	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1221		grp = getgrgid(pw->pw_gid);
1222		if (!grp)
1223			return 0;
1224
1225		/* Return false if user's group is listed in DenyGroups */
1226		if (options.num_deny_groups > 0) {
1227			if (!grp->gr_name)
1228				return 0;
1229			for (i = 0; i < options.num_deny_groups; i++)
1230				if (match_pattern(grp->gr_name, options.deny_groups[i]))
1231					return 0;
1232		}
1233		/*
1234		 * Return false if AllowGroups isn't empty and user's group
1235		 * isn't listed there
1236		 */
1237		if (options.num_allow_groups > 0) {
1238			if (!grp->gr_name)
1239				return 0;
1240			for (i = 0; i < options.num_allow_groups; i++)
1241				if (match_pattern(grp->gr_name, options.allow_groups[i]))
1242					break;
1243			/* i < options.num_allow_groups iff we break for
1244			   loop */
1245			if (i >= options.num_allow_groups)
1246				return 0;
1247		}
1248	}
1249	/* Fail if the account's expiration time has passed. */
1250	if (pw->pw_expire != 0) {
1251		struct timeval tv;
1252
1253		(void)gettimeofday(&tv, NULL);
1254		if (tv.tv_sec >= pw->pw_expire)
1255			return 0;
1256	}
1257	/* We found no reason not to let this user try to log on... */
1258	return 1;
1259}
1260
1261/*
1262 * Performs authentication of an incoming connection.  Session key has already
1263 * been exchanged and encryption is enabled.
1264 */
1265void
1266do_authentication()
1267{
1268	struct passwd *pw, pwcopy;
1269	int plen, ulen;
1270	char *user;
1271
1272	/* Get the name of the user that we wish to log in as. */
1273	packet_read_expect(&plen, SSH_CMSG_USER);
1274
1275	/* Get the user name. */
1276	user = packet_get_string(&ulen);
1277	packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1278
1279	setproctitle("%s", user);
1280
1281#ifdef AFS
1282	/* If machine has AFS, set process authentication group. */
1283	if (k_hasafs()) {
1284		k_setpag();
1285		k_unlog();
1286	}
1287#endif /* AFS */
1288
1289	/* Verify that the user is a valid user. */
1290	pw = getpwnam(user);
1291	if (!pw || !allowed_user(pw))
1292		do_fake_authloop(user);
1293	xfree(user);
1294
1295	/* Take a copy of the returned structure. */
1296	memset(&pwcopy, 0, sizeof(pwcopy));
1297	pwcopy.pw_name = xstrdup(pw->pw_name);
1298	pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1299	pwcopy.pw_uid = pw->pw_uid;
1300	pwcopy.pw_gid = pw->pw_gid;
1301	pwcopy.pw_dir = xstrdup(pw->pw_dir);
1302	pwcopy.pw_shell = xstrdup(pw->pw_shell);
1303	pwcopy.pw_class = xstrdup(pw->pw_class);
1304	pwcopy.pw_expire = pw->pw_expire;
1305	pwcopy.pw_change = pw->pw_change;
1306	pw = &pwcopy;
1307
1308	/*
1309	 * If we are not running as root, the user must have the same uid as
1310	 * the server.
1311	 */
1312	if (getuid() != 0 && pw->pw_uid != getuid())
1313		packet_disconnect("Cannot change user when server not running as root.");
1314
1315	debug("Attempting authentication for %.100s.", pw->pw_name);
1316
1317	/* If the user has no password, accept authentication immediately. */
1318	if (options.password_authentication &&
1319#ifdef KRB4
1320	    (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1321#endif /* KRB4 */
1322	    auth_password(pw, "")) {
1323		/* Authentication with empty password succeeded. */
1324		log("Login for user %s from %.100s, accepted without authentication.",
1325		    pw->pw_name, get_remote_ipaddr());
1326	} else {
1327		/* Loop until the user has been authenticated or the
1328		   connection is closed, do_authloop() returns only if
1329		   authentication is successfull */
1330		do_authloop(pw);
1331	}
1332
1333	/* Check if the user is logging in as root and root logins are disallowed. */
1334	if (pw->pw_uid == 0 && !options.permit_root_login) {
1335		if (forced_command)
1336			log("Root login accepted for forced command.");
1337		else
1338			packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1339					  get_canonical_hostname());
1340	}
1341	/* The user has been authenticated and accepted. */
1342	packet_start(SSH_SMSG_SUCCESS);
1343	packet_send();
1344	packet_write_wait();
1345
1346	/* Perform session preparation. */
1347	do_authenticated(pw);
1348}
1349
1350#define AUTH_FAIL_MAX 6
1351#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1352#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
1353
1354/*
1355 * read packets and try to authenticate local user *pw.
1356 * return if authentication is successfull
1357 */
1358void
1359do_authloop(struct passwd * pw)
1360{
1361	int attempt = 0;
1362	unsigned int bits;
1363	BIGNUM *client_host_key_e, *client_host_key_n;
1364	BIGNUM *n;
1365	char *client_user, *password;
1366	char user[1024];
1367	int plen, dlen, nlen, ulen, elen;
1368	int type = 0;
1369	void (*authlog) (const char *fmt,...) = verbose;
1370
1371	/* Indicate that authentication is needed. */
1372	packet_start(SSH_SMSG_FAILURE);
1373	packet_send();
1374	packet_write_wait();
1375
1376	for (attempt = 1;; attempt++) {
1377		int authenticated = 0;
1378		strlcpy(user, "", sizeof user);
1379
1380		/* Get a packet from the client. */
1381		type = packet_read(&plen);
1382
1383		/* Process the packet. */
1384		switch (type) {
1385#ifdef AFS
1386		case SSH_CMSG_HAVE_KERBEROS_TGT:
1387			if (!options.kerberos_tgt_passing) {
1388				/* packet_get_all(); */
1389				verbose("Kerberos tgt passing disabled.");
1390				break;
1391			} else {
1392				/* Accept Kerberos tgt. */
1393				char *tgt = packet_get_string(&dlen);
1394				packet_integrity_check(plen, 4 + dlen, type);
1395				if (!auth_kerberos_tgt(pw, tgt))
1396					verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1397				xfree(tgt);
1398			}
1399			continue;
1400
1401		case SSH_CMSG_HAVE_AFS_TOKEN:
1402			if (!options.afs_token_passing || !k_hasafs()) {
1403				/* packet_get_all(); */
1404				verbose("AFS token passing disabled.");
1405				break;
1406			} else {
1407				/* Accept AFS token. */
1408				char *token_string = packet_get_string(&dlen);
1409				packet_integrity_check(plen, 4 + dlen, type);
1410				if (!auth_afs_token(pw, token_string))
1411					verbose("AFS token REFUSED for %s", pw->pw_name);
1412				xfree(token_string);
1413			}
1414			continue;
1415#endif /* AFS */
1416#ifdef KRB4
1417		case SSH_CMSG_AUTH_KERBEROS:
1418			if (!options.kerberos_authentication) {
1419				/* packet_get_all(); */
1420				verbose("Kerberos authentication disabled.");
1421				break;
1422			} else {
1423				/* Try Kerberos v4 authentication. */
1424				KTEXT_ST auth;
1425				char *tkt_user = NULL;
1426				char *kdata = packet_get_string((unsigned int *) &auth.length);
1427				packet_integrity_check(plen, 4 + auth.length, type);
1428
1429				if (auth.length < MAX_KTXT_LEN)
1430					memcpy(auth.dat, kdata, auth.length);
1431				xfree(kdata);
1432
1433				authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1434
1435				if (authenticated) {
1436					snprintf(user, sizeof user, " tktuser %s", tkt_user);
1437					xfree(tkt_user);
1438				}
1439			}
1440			break;
1441#endif /* KRB4 */
1442
1443		case SSH_CMSG_AUTH_RHOSTS:
1444			if (!options.rhosts_authentication) {
1445				verbose("Rhosts authentication disabled.");
1446				break;
1447			}
1448			/*
1449			 * Get client user name.  Note that we just have to
1450			 * trust the client; this is one reason why rhosts
1451			 * authentication is insecure. (Another is
1452			 * IP-spoofing on a local network.)
1453			 */
1454			client_user = packet_get_string(&ulen);
1455			packet_integrity_check(plen, 4 + ulen, type);
1456
1457			/* Try to authenticate using /etc/hosts.equiv and
1458			   .rhosts. */
1459			authenticated = auth_rhosts(pw, client_user);
1460
1461			snprintf(user, sizeof user, " ruser %s", client_user);
1462			xfree(client_user);
1463			break;
1464
1465		case SSH_CMSG_AUTH_RHOSTS_RSA:
1466			if (!options.rhosts_rsa_authentication) {
1467				verbose("Rhosts with RSA authentication disabled.");
1468				break;
1469			}
1470			/*
1471			 * Get client user name.  Note that we just have to
1472			 * trust the client; root on the client machine can
1473			 * claim to be any user.
1474			 */
1475			client_user = packet_get_string(&ulen);
1476
1477			/* Get the client host key. */
1478			client_host_key_e = BN_new();
1479			client_host_key_n = BN_new();
1480			bits = packet_get_int();
1481			packet_get_bignum(client_host_key_e, &elen);
1482			packet_get_bignum(client_host_key_n, &nlen);
1483
1484			if (bits != BN_num_bits(client_host_key_n))
1485				error("Warning: keysize mismatch for client_host_key: "
1486				      "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1487			packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1488
1489			authenticated = auth_rhosts_rsa(pw, client_user,
1490				   client_host_key_e, client_host_key_n);
1491			BN_clear_free(client_host_key_e);
1492			BN_clear_free(client_host_key_n);
1493
1494			snprintf(user, sizeof user, " ruser %s", client_user);
1495			xfree(client_user);
1496			break;
1497
1498		case SSH_CMSG_AUTH_RSA:
1499			if (!options.rsa_authentication) {
1500				verbose("RSA authentication disabled.");
1501				break;
1502			}
1503			/* RSA authentication requested. */
1504			n = BN_new();
1505			packet_get_bignum(n, &nlen);
1506			packet_integrity_check(plen, nlen, type);
1507			authenticated = auth_rsa(pw, n);
1508			BN_clear_free(n);
1509			break;
1510
1511		case SSH_CMSG_AUTH_PASSWORD:
1512			if (!options.password_authentication) {
1513				verbose("Password authentication disabled.");
1514				break;
1515			}
1516			/*
1517			 * Read user password.  It is in plain text, but was
1518			 * transmitted over the encrypted channel so it is
1519			 * not visible to an outside observer.
1520			 */
1521			password = packet_get_string(&dlen);
1522			packet_integrity_check(plen, 4 + dlen, type);
1523
1524			/* Try authentication with the password. */
1525			authenticated = auth_password(pw, password);
1526
1527			memset(password, 0, strlen(password));
1528			xfree(password);
1529			break;
1530
1531#ifdef SKEY
1532		case SSH_CMSG_AUTH_TIS:
1533			debug("rcvd SSH_CMSG_AUTH_TIS");
1534			if (options.skey_authentication == 1) {
1535				char *skeyinfo = skey_keyinfo(pw->pw_name);
1536				if (skeyinfo == NULL) {
1537					debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1538					skeyinfo = skey_fake_keyinfo(pw->pw_name);
1539				}
1540				if (skeyinfo != NULL) {
1541					/* we send our s/key- in tis-challenge messages */
1542					debug("sending challenge '%s'", skeyinfo);
1543					packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1544					packet_put_string(skeyinfo, strlen(skeyinfo));
1545					packet_send();
1546					packet_write_wait();
1547					continue;
1548				}
1549			}
1550			break;
1551		case SSH_CMSG_AUTH_TIS_RESPONSE:
1552			debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1553			if (options.skey_authentication == 1) {
1554				char *response = packet_get_string(&dlen);
1555				debug("skey response == '%s'", response);
1556				packet_integrity_check(plen, 4 + dlen, type);
1557				authenticated = (skey_haskey(pw->pw_name) == 0 &&
1558						 skey_passcheck(pw->pw_name, response) != -1);
1559				xfree(response);
1560			}
1561			break;
1562#else
1563		case SSH_CMSG_AUTH_TIS:
1564			/* TIS Authentication is unsupported */
1565			log("TIS authentication unsupported.");
1566			break;
1567#endif
1568
1569		default:
1570			/*
1571			 * Any unknown messages will be ignored (and failure
1572			 * returned) during authentication.
1573			 */
1574			log("Unknown message during authentication: type %d", type);
1575			break;
1576		}
1577
1578		/* Raise logging level */
1579		if (authenticated ||
1580		    attempt == AUTH_FAIL_LOG ||
1581		    type == SSH_CMSG_AUTH_PASSWORD)
1582			authlog = log;
1583
1584		authlog("%s %s for %.200s from %.200s port %d%s",
1585			authenticated ? "Accepted" : "Failed",
1586			get_authname(type),
1587			pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1588			get_remote_ipaddr(),
1589			get_remote_port(),
1590			user);
1591
1592		if (authenticated)
1593			return;
1594
1595		if (attempt > AUTH_FAIL_MAX)
1596			packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1597
1598		/* Send a message indicating that the authentication attempt failed. */
1599		packet_start(SSH_SMSG_FAILURE);
1600		packet_send();
1601		packet_write_wait();
1602	}
1603}
1604
1605/*
1606 * The user does not exist or access is denied,
1607 * but fake indication that authentication is needed.
1608 */
1609void
1610do_fake_authloop(char *user)
1611{
1612	int attempt = 0;
1613
1614	log("Faking authloop for illegal user %.200s from %.200s port %d",
1615	    user,
1616	    get_remote_ipaddr(),
1617	    get_remote_port());
1618
1619	/* Indicate that authentication is needed. */
1620	packet_start(SSH_SMSG_FAILURE);
1621	packet_send();
1622	packet_write_wait();
1623
1624	/*
1625	 * Keep reading packets, and always respond with a failure.  This is
1626	 * to avoid disclosing whether such a user really exists.
1627	 */
1628	for (attempt = 1;; attempt++) {
1629		/* Read a packet.  This will not return if the client disconnects. */
1630		int plen;
1631		int type = packet_read(&plen);
1632#ifdef SKEY
1633		int dlen;
1634		char *password, *skeyinfo;
1635		/* Try to send a fake s/key challenge. */
1636		if (options.skey_authentication == 1 &&
1637		    (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1638			password = NULL;
1639			if (type == SSH_CMSG_AUTH_TIS) {
1640				packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1641				packet_put_string(skeyinfo, strlen(skeyinfo));
1642				packet_send();
1643				packet_write_wait();
1644				continue;
1645			} else if (type == SSH_CMSG_AUTH_PASSWORD &&
1646			           options.password_authentication &&
1647			           (password = packet_get_string(&dlen)) != NULL &&
1648			           dlen == 5 &&
1649			           strncasecmp(password, "s/key", 5) == 0 ) {
1650				packet_send_debug(skeyinfo);
1651			}
1652			if (password != NULL)
1653				xfree(password);
1654		}
1655#endif
1656		if (attempt > AUTH_FAIL_MAX)
1657			packet_disconnect(AUTH_FAIL_MSG, user);
1658
1659		/*
1660		 * Send failure.  This should be indistinguishable from a
1661		 * failed authentication.
1662		 */
1663		packet_start(SSH_SMSG_FAILURE);
1664		packet_send();
1665		packet_write_wait();
1666	}
1667	/* NOTREACHED */
1668	abort();
1669}
1670
1671struct pty_cleanup_context {
1672	const char *ttyname;
1673	int pid;
1674};
1675
1676/*
1677 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
1678 * dropped connection).
1679 */
1680void
1681pty_cleanup_proc(void *context)
1682{
1683	struct pty_cleanup_context *cu = context;
1684
1685	debug("pty_cleanup_proc called");
1686
1687	/* Record that the user has logged out. */
1688	record_logout(cu->pid, cu->ttyname);
1689
1690	/* Release the pseudo-tty. */
1691	pty_release(cu->ttyname);
1692}
1693
1694/* simple cleanup: chown tty slave back to root */
1695static void
1696pty_release_proc(void *tty)
1697{
1698	char *ttyname = tty;
1699	pty_release(ttyname);
1700}
1701
1702/*
1703 * Prepares for an interactive session.  This is called after the user has
1704 * been successfully authenticated.  During this message exchange, pseudo
1705 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1706 * are requested, etc.
1707 */
1708void
1709do_authenticated(struct passwd * pw)
1710{
1711	int type;
1712	int compression_level = 0, enable_compression_after_reply = 0;
1713	int have_pty = 0, ptyfd = -1, ttyfd = -1;
1714	int row, col, xpixel, ypixel, screen;
1715	char ttyname[64];
1716	char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1717	int n_bytes;
1718
1719	/*
1720	 * Cancel the alarm we set to limit the time taken for
1721	 * authentication.
1722	 */
1723	alarm(0);
1724
1725	/*
1726	 * Inform the channel mechanism that we are the server side and that
1727	 * the client may request to connect to any port at all. (The user
1728	 * could do it anyway, and we wouldn\'t know what is permitted except
1729	 * by the client telling us, so we can equally well trust the client
1730	 * not to request anything bogus.)
1731	 */
1732	if (!no_port_forwarding_flag)
1733		channel_permit_all_opens();
1734
1735	/*
1736	 * We stay in this loop until the client requests to execute a shell
1737	 * or a command.
1738	 */
1739	while (1) {
1740		int plen, dlen;
1741
1742		/* Get a packet from the client. */
1743		type = packet_read(&plen);
1744
1745		/* Process the packet. */
1746		switch (type) {
1747		case SSH_CMSG_REQUEST_COMPRESSION:
1748			packet_integrity_check(plen, 4, type);
1749			compression_level = packet_get_int();
1750			if (compression_level < 1 || compression_level > 9) {
1751				packet_send_debug("Received illegal compression level %d.",
1752						  compression_level);
1753				goto fail;
1754			}
1755			/* Enable compression after we have responded with SUCCESS. */
1756			enable_compression_after_reply = 1;
1757			break;
1758
1759		case SSH_CMSG_REQUEST_PTY:
1760			if (no_pty_flag) {
1761				debug("Allocating a pty not permitted for this authentication.");
1762				goto fail;
1763			}
1764			if (have_pty)
1765				packet_disconnect("Protocol error: you already have a pty.");
1766
1767			debug("Allocating pty.");
1768
1769			/* Allocate a pty and open it. */
1770			if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1771			    sizeof(ttyname))) {
1772				error("Failed to allocate pty.");
1773				goto fail;
1774			}
1775			fatal_add_cleanup(pty_release_proc, (void *)ttyname);
1776			pty_setowner(pw, ttyname);
1777
1778			/* Get TERM from the packet.  Note that the value may be of arbitrary length. */
1779			term = packet_get_string(&dlen);
1780			packet_integrity_check(dlen, strlen(term), type);
1781
1782			/* Remaining bytes */
1783			n_bytes = plen - (4 + dlen + 4 * 4);
1784
1785			if (strcmp(term, "") == 0) {
1786				xfree(term);
1787				term = NULL;
1788			}
1789
1790			/* Get window size from the packet. */
1791			row = packet_get_int();
1792			col = packet_get_int();
1793			xpixel = packet_get_int();
1794			ypixel = packet_get_int();
1795			pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1796
1797			/* Get tty modes from the packet. */
1798			tty_parse_modes(ttyfd, &n_bytes);
1799			packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
1800
1801			/* Indicate that we now have a pty. */
1802			have_pty = 1;
1803			break;
1804
1805		case SSH_CMSG_X11_REQUEST_FORWARDING:
1806			if (!options.x11_forwarding) {
1807				packet_send_debug("X11 forwarding disabled in server configuration file.");
1808				goto fail;
1809			}
1810#ifdef XAUTH_PATH
1811			if (no_x11_forwarding_flag) {
1812				packet_send_debug("X11 forwarding not permitted for this authentication.");
1813				goto fail;
1814			}
1815			debug("Received request for X11 forwarding with auth spoofing.");
1816			if (display)
1817				packet_disconnect("Protocol error: X11 display already set.");
1818			{
1819				int proto_len, data_len;
1820				proto = packet_get_string(&proto_len);
1821				data = packet_get_string(&data_len);
1822				packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1823			}
1824			if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1825				screen = packet_get_int();
1826			else
1827				screen = 0;
1828			display = x11_create_display_inet(screen, options.x11_display_offset);
1829			if (!display)
1830				goto fail;
1831
1832			/* Setup to always have a local .Xauthority. */
1833			xauthfile = xmalloc(MAXPATHLEN);
1834			strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1835			temporarily_use_uid(pw->pw_uid);
1836			if (mkdtemp(xauthfile) == NULL) {
1837				restore_uid();
1838				error("private X11 dir: mkdtemp %s failed: %s",
1839				    xauthfile, strerror(errno));
1840				xfree(xauthfile);
1841				xauthfile = NULL;
1842				goto fail;
1843			}
1844			restore_uid();
1845			strlcat(xauthfile, "/cookies", MAXPATHLEN);
1846			fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1847			break;
1848#else /* XAUTH_PATH */
1849			packet_send_debug("No xauth program; cannot forward with spoofing.");
1850			goto fail;
1851#endif /* XAUTH_PATH */
1852
1853		case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1854			if (no_agent_forwarding_flag || compat13) {
1855				debug("Authentication agent forwarding not permitted for this authentication.");
1856				goto fail;
1857			}
1858			debug("Received authentication agent forwarding request.");
1859			auth_input_request_forwarding(pw);
1860			break;
1861
1862		case SSH_CMSG_PORT_FORWARD_REQUEST:
1863			if (no_port_forwarding_flag) {
1864				debug("Port forwarding not permitted for this authentication.");
1865				goto fail;
1866			}
1867			debug("Received TCP/IP port forwarding request.");
1868			channel_input_port_forward_request(pw->pw_uid == 0);
1869			break;
1870
1871		case SSH_CMSG_MAX_PACKET_SIZE:
1872			if (packet_set_maxsize(packet_get_int()) < 0)
1873				goto fail;
1874			break;
1875
1876		case SSH_CMSG_EXEC_SHELL:
1877			/* Set interactive/non-interactive mode. */
1878			packet_set_interactive(have_pty || display != NULL,
1879					       options.keepalives);
1880
1881			if (forced_command != NULL)
1882				goto do_forced_command;
1883			debug("Forking shell.");
1884			packet_integrity_check(plen, 0, type);
1885			if (have_pty)
1886				do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1887			else
1888				do_exec_no_pty(NULL, pw, display, proto, data);
1889			return;
1890
1891		case SSH_CMSG_EXEC_CMD:
1892			/* Set interactive/non-interactive mode. */
1893			packet_set_interactive(have_pty || display != NULL,
1894					       options.keepalives);
1895
1896			if (forced_command != NULL)
1897				goto do_forced_command;
1898			/* Get command from the packet. */
1899			{
1900				int dlen;
1901				command = packet_get_string(&dlen);
1902				debug("Executing command '%.500s'", command);
1903				packet_integrity_check(plen, 4 + dlen, type);
1904			}
1905			if (have_pty)
1906				do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1907			else
1908				do_exec_no_pty(command, pw, display, proto, data);
1909			xfree(command);
1910			return;
1911
1912		default:
1913			/*
1914			 * Any unknown messages in this phase are ignored,
1915			 * and a failure message is returned.
1916			 */
1917			log("Unknown packet type received after authentication: %d", type);
1918			goto fail;
1919		}
1920
1921		/* The request was successfully processed. */
1922		packet_start(SSH_SMSG_SUCCESS);
1923		packet_send();
1924		packet_write_wait();
1925
1926		/* Enable compression now that we have replied if appropriate. */
1927		if (enable_compression_after_reply) {
1928			enable_compression_after_reply = 0;
1929			packet_start_compression(compression_level);
1930		}
1931		continue;
1932
1933fail:
1934		/* The request failed. */
1935		packet_start(SSH_SMSG_FAILURE);
1936		packet_send();
1937		packet_write_wait();
1938		continue;
1939
1940do_forced_command:
1941		/*
1942		 * There is a forced command specified for this login.
1943		 * Execute it.
1944		 */
1945		debug("Executing forced command: %.900s", forced_command);
1946		if (have_pty)
1947			do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1948		else
1949			do_exec_no_pty(forced_command, pw, display, proto, data);
1950		return;
1951	}
1952}
1953
1954/*
1955 * This is called to fork and execute a command when we have no tty.  This
1956 * will call do_child from the child, and server_loop from the parent after
1957 * setting up file descriptors and such.
1958 */
1959void
1960do_exec_no_pty(const char *command, struct passwd * pw,
1961	       const char *display, const char *auth_proto,
1962	       const char *auth_data)
1963{
1964	int pid;
1965
1966#ifdef USE_PIPES
1967	int pin[2], pout[2], perr[2];
1968	/* Allocate pipes for communicating with the program. */
1969	if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1970		packet_disconnect("Could not create pipes: %.100s",
1971				  strerror(errno));
1972#else /* USE_PIPES */
1973	int inout[2], err[2];
1974	/* Uses socket pairs to communicate with the program. */
1975	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1976	    socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1977		packet_disconnect("Could not create socket pairs: %.100s",
1978				  strerror(errno));
1979#endif /* USE_PIPES */
1980
1981	setproctitle("%s@notty", pw->pw_name);
1982
1983	/* Fork the child. */
1984	if ((pid = fork()) == 0) {
1985		/* Child.  Reinitialize the log since the pid has changed. */
1986		log_init(av0, options.log_level, options.log_facility, log_stderr);
1987
1988		/*
1989		 * Create a new session and process group since the 4.4BSD
1990		 * setlogin() affects the entire process group.
1991		 */
1992		if (setsid() < 0)
1993			error("setsid failed: %.100s", strerror(errno));
1994
1995#ifdef USE_PIPES
1996		/*
1997		 * Redirect stdin.  We close the parent side of the socket
1998		 * pair, and make the child side the standard input.
1999		 */
2000		close(pin[1]);
2001		if (dup2(pin[0], 0) < 0)
2002			perror("dup2 stdin");
2003		close(pin[0]);
2004
2005		/* Redirect stdout. */
2006		close(pout[0]);
2007		if (dup2(pout[1], 1) < 0)
2008			perror("dup2 stdout");
2009		close(pout[1]);
2010
2011		/* Redirect stderr. */
2012		close(perr[0]);
2013		if (dup2(perr[1], 2) < 0)
2014			perror("dup2 stderr");
2015		close(perr[1]);
2016#else /* USE_PIPES */
2017		/*
2018		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
2019		 * use the same socket, as some programs (particularly rdist)
2020		 * seem to depend on it.
2021		 */
2022		close(inout[1]);
2023		close(err[1]);
2024		if (dup2(inout[0], 0) < 0)	/* stdin */
2025			perror("dup2 stdin");
2026		if (dup2(inout[0], 1) < 0)	/* stdout.  Note: same socket as stdin. */
2027			perror("dup2 stdout");
2028		if (dup2(err[0], 2) < 0)	/* stderr */
2029			perror("dup2 stderr");
2030#endif /* USE_PIPES */
2031
2032		/* Do processing for the child (exec command etc). */
2033		do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
2034		/* NOTREACHED */
2035	}
2036	if (pid < 0)
2037		packet_disconnect("fork failed: %.100s", strerror(errno));
2038#ifdef USE_PIPES
2039	/* We are the parent.  Close the child sides of the pipes. */
2040	close(pin[0]);
2041	close(pout[1]);
2042	close(perr[1]);
2043
2044	/* Enter the interactive session. */
2045	server_loop(pid, pin[1], pout[0], perr[0]);
2046	/* server_loop has closed pin[1], pout[1], and perr[1]. */
2047#else /* USE_PIPES */
2048	/* We are the parent.  Close the child sides of the socket pairs. */
2049	close(inout[0]);
2050	close(err[0]);
2051
2052	/*
2053	 * Enter the interactive session.  Note: server_loop must be able to
2054	 * handle the case that fdin and fdout are the same.
2055	 */
2056	server_loop(pid, inout[1], inout[1], err[1]);
2057	/* server_loop has closed inout[1] and err[1]. */
2058#endif /* USE_PIPES */
2059}
2060
2061/*
2062 * This is called to fork and execute a command when we have a tty.  This
2063 * will call do_child from the child, and server_loop from the parent after
2064 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2065 * lastlog, and other such operations.
2066 */
2067void
2068do_exec_pty(const char *command, int ptyfd, int ttyfd,
2069	    const char *ttyname, struct passwd * pw, const char *term,
2070	    const char *display, const char *auth_proto,
2071	    const char *auth_data)
2072{
2073	int pid, fdout;
2074	int ptymaster;
2075	const char *hostname;
2076	time_t last_login_time;
2077	char buf[100], *time_string;
2078	FILE *f;
2079	char line[256];
2080	struct stat st;
2081	int quiet_login;
2082	struct sockaddr_storage from;
2083	socklen_t fromlen;
2084	struct pty_cleanup_context cleanup_context;
2085#ifdef LOGIN_CAP
2086	login_cap_t *lc;
2087	char *fname;
2088#endif /* LOGIN_CAP */
2089
2090	/* Get remote host name. */
2091	hostname = get_canonical_hostname();
2092
2093	/*
2094	 * Get the time when the user last logged in.  Buf will be set to
2095	 * contain the hostname the last login was from.
2096	 */
2097	if (!options.use_login) {
2098		last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2099						      buf, sizeof(buf));
2100	}
2101	setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
2102
2103	/* Fork the child. */
2104	if ((pid = fork()) == 0) {
2105		pid = getpid();
2106
2107		/* Child.  Reinitialize the log because the pid has
2108		   changed. */
2109		log_init(av0, options.log_level, options.log_facility, log_stderr);
2110
2111		/* Close the master side of the pseudo tty. */
2112		close(ptyfd);
2113
2114		/* Make the pseudo tty our controlling tty. */
2115		pty_make_controlling_tty(&ttyfd, ttyname);
2116
2117		/* Redirect stdin from the pseudo tty. */
2118		if (dup2(ttyfd, fileno(stdin)) < 0)
2119			error("dup2 stdin failed: %.100s", strerror(errno));
2120
2121		/* Redirect stdout to the pseudo tty. */
2122		if (dup2(ttyfd, fileno(stdout)) < 0)
2123			error("dup2 stdin failed: %.100s", strerror(errno));
2124
2125		/* Redirect stderr to the pseudo tty. */
2126		if (dup2(ttyfd, fileno(stderr)) < 0)
2127			error("dup2 stdin failed: %.100s", strerror(errno));
2128
2129		/* Close the extra descriptor for the pseudo tty. */
2130		close(ttyfd);
2131
2132		/*
2133		 * Get IP address of client.  This is needed because we want
2134		 * to record where the user logged in from.  If the
2135		 * connection is not a socket, let the ip address be 0.0.0.0.
2136		 */
2137		memset(&from, 0, sizeof(from));
2138		if (packet_get_connection_in() == packet_get_connection_out()) {
2139			fromlen = sizeof(from);
2140			if (getpeername(packet_get_connection_in(),
2141			     (struct sockaddr *) & from, &fromlen) < 0) {
2142				debug("getpeername: %.100s", strerror(errno));
2143				fatal_cleanup();
2144			}
2145		}
2146		/* Record that there was a login on that terminal. */
2147		record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2148			     (struct sockaddr *)&from);
2149
2150		/* Check if .hushlogin exists. */
2151		snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2152		quiet_login = stat(line, &st) >= 0;
2153#ifdef LOGIN_CAP
2154		lc = login_getpwclass(pw);
2155		if (lc == NULL)
2156			lc = login_getclassbyname(NULL, pw);
2157		quiet_login = login_getcapbool(lc, "hushlogin", quiet_login);
2158#endif /* LOGIN_CAP */
2159
2160		/*
2161		 * If the user has logged in before, display the time of last
2162		 * login. However, don't display anything extra if a command
2163		 * has been specified (so that ssh can be used to execute
2164		 * commands on a remote machine without users knowing they
2165		 * are going to another machine). Login(1) will do this for
2166		 * us as well, so check if login(1) is used
2167		 */
2168		if (command == NULL && last_login_time != 0 && !quiet_login &&
2169		    !options.use_login) {
2170			/* Convert the date to a string. */
2171			time_string = ctime(&last_login_time);
2172			/* Remove the trailing newline. */
2173			if (strchr(time_string, '\n'))
2174				*strchr(time_string, '\n') = 0;
2175			/* Display the last login time.  Host if displayed
2176			   if known. */
2177			if (strcmp(buf, "") == 0)
2178				printf("Last login: %s\r\n", time_string);
2179			else
2180				printf("Last login: %s from %s\r\n", time_string, buf);
2181		}
2182#ifdef LOGIN_CAP
2183		if (command == NULL && !quiet_login && !options.use_login) {
2184			fname = login_getcapstr(lc, "copyright", NULL, NULL);
2185			if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
2186				while (fgets(line, sizeof(line), f) != NULL)
2187					fputs(line, stdout);
2188				fclose(f);
2189			} else
2190				(void)printf("%s\n\t%s %s\n",
2191		"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
2192		    "The Regents of the University of California. ",
2193		    "All rights reserved.");
2194		}
2195#endif /* LOGIN_CAP */
2196		/*
2197		 * Print /etc/motd unless a command was specified or printing
2198		 * it was disabled in server options or login(1) will be
2199		 * used.  Note that some machines appear to print it in
2200		 * /etc/profile or similar.
2201		 */
2202		if (command == NULL && options.print_motd && !quiet_login &&
2203		    !options.use_login) {
2204#ifdef LOGIN_CAP
2205			fname = login_getcapstr(lc, "welcome", NULL, NULL);
2206			login_close(lc);
2207			if (fname == NULL || (f = fopen(fname, "r")) == NULL)
2208				f = fopen("/etc/motd", "r");
2209#else /* LOGIN_CAP */
2210			f = fopen("/etc/motd", "r");
2211#endif /* LOGIN_CAP */
2212			/* Print /etc/motd if it exists. */
2213			if (f) {
2214				while (fgets(line, sizeof(line), f))
2215					fputs(line, stdout);
2216				fclose(f);
2217			}
2218		}
2219
2220		/* Do common processing for the child, such as execing the command. */
2221		do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2222		/* NOTREACHED */
2223	}
2224	if (pid < 0)
2225		packet_disconnect("fork failed: %.100s", strerror(errno));
2226	/* Parent.  Close the slave side of the pseudo tty. */
2227	close(ttyfd);
2228
2229	/*
2230	 * Add a cleanup function to clear the utmp entry and record logout
2231	 * time in case we call fatal() (e.g., the connection gets closed).
2232	 */
2233	cleanup_context.pid = pid;
2234	cleanup_context.ttyname = ttyname;
2235	fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2236	fatal_remove_cleanup(pty_release_proc, (void *) ttyname);
2237
2238	/*
2239	 * Create another descriptor of the pty master side for use as the
2240	 * standard input.  We could use the original descriptor, but this
2241	 * simplifies code in server_loop.  The descriptor is bidirectional.
2242	 */
2243	fdout = dup(ptyfd);
2244	if (fdout < 0)
2245		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
2246
2247	/* we keep a reference to the pty master */
2248	ptymaster = dup(ptyfd);
2249	if (ptymaster < 0)
2250		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
2251
2252	/* Enter interactive session. */
2253	server_loop(pid, ptyfd, fdout, -1);
2254	/* server_loop _has_ closed ptyfd and fdout. */
2255
2256	/* Cancel the cleanup function. */
2257	fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2258
2259	/* Record that the user has logged out. */
2260	record_logout(pid, ttyname);
2261
2262	/* Release the pseudo-tty. */
2263	pty_release(ttyname);
2264
2265	/*
2266	 * Close the server side of the socket pairs.  We must do this after
2267	 * the pty cleanup, so that another process doesn't get this pty
2268	 * while we're still cleaning up.
2269	 */
2270	if (close(ptymaster) < 0)
2271		error("close(ptymaster): %s", strerror(errno));
2272}
2273
2274/*
2275 * Sets the value of the given variable in the environment.  If the variable
2276 * already exists, its value is overriden.
2277 */
2278void
2279child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2280	      const char *value)
2281{
2282	unsigned int i, namelen;
2283	char **env;
2284
2285	/*
2286	 * Find the slot where the value should be stored.  If the variable
2287	 * already exists, we reuse the slot; otherwise we append a new slot
2288	 * at the end of the array, expanding if necessary.
2289	 */
2290	env = *envp;
2291	namelen = strlen(name);
2292	for (i = 0; env[i]; i++)
2293		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2294			break;
2295	if (env[i]) {
2296		/* Reuse the slot. */
2297		xfree(env[i]);
2298	} else {
2299		/* New variable.  Expand if necessary. */
2300		if (i >= (*envsizep) - 1) {
2301			(*envsizep) += 50;
2302			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2303		}
2304		/* Need to set the NULL pointer at end of array beyond the new slot. */
2305		env[i + 1] = NULL;
2306	}
2307
2308	/* Allocate space and format the variable in the appropriate slot. */
2309	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2310	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2311}
2312
2313/*
2314 * Reads environment variables from the given file and adds/overrides them
2315 * into the environment.  If the file does not exist, this does nothing.
2316 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2317 * and assignments of the form name=value.  No other forms are allowed.
2318 */
2319void
2320read_environment_file(char ***env, unsigned int *envsize,
2321		      const char *filename)
2322{
2323	FILE *f;
2324	char buf[4096];
2325	char *cp, *value;
2326
2327	f = fopen(filename, "r");
2328	if (!f)
2329		return;
2330
2331	while (fgets(buf, sizeof(buf), f)) {
2332		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2333			;
2334		if (!*cp || *cp == '#' || *cp == '\n')
2335			continue;
2336		if (strchr(cp, '\n'))
2337			*strchr(cp, '\n') = '\0';
2338		value = strchr(cp, '=');
2339		if (value == NULL) {
2340			fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2341			continue;
2342		}
2343		/* Replace the equals sign by nul, and advance value to the value string. */
2344		*value = '\0';
2345		value++;
2346		child_set_env(env, envsize, cp, value);
2347	}
2348	fclose(f);
2349}
2350
2351/*
2352 * Performs common processing for the child, such as setting up the
2353 * environment, closing extra file descriptors, setting the user and group
2354 * ids, and executing the command or shell.
2355 */
2356void
2357do_child(const char *command, struct passwd * pw, const char *term,
2358	 const char *display, const char *auth_proto,
2359	 const char *auth_data, const char *ttyname)
2360{
2361	char *shell;
2362	const char *cp = NULL;
2363	char buf[256];
2364	FILE *f;
2365	unsigned int envsize, i;
2366	char **env;
2367	extern char **environ;
2368	struct stat st;
2369	char *argv[10];
2370#ifdef LOGIN_CAP
2371	login_cap_t *lc;
2372
2373	lc = login_getpwclass(pw);
2374	if (lc == NULL)
2375		lc = login_getclassbyname(NULL, pw);
2376#endif /* LOGIN_CAP */
2377
2378	f = fopen("/etc/nologin", "r");
2379#ifdef __FreeBSD__
2380	if (f == NULL)
2381		f = fopen("/var/run/nologin", "r");
2382#endif /* __FreeBSD__ */
2383	if (f) {
2384		/* /etc/nologin exists.  Print its contents and exit. */
2385#ifdef LOGIN_CAP
2386		/* On FreeBSD, etc., allow overriding nologin via login.conf. */
2387		if (!login_getcapbool(lc, "ignorenologin", 0)) {
2388#else /* LOGIN_CAP */
2389		if (1) {
2390#endif /* LOGIN_CAP */
2391			while (fgets(buf, sizeof(buf), f))
2392				fputs(buf, stderr);
2393			fclose(f);
2394			if (pw->pw_uid != 0)
2395				exit(254);
2396		}
2397
2398	}
2399	/* Set login name in the kernel. */
2400	if (setlogin(pw->pw_name) < 0)
2401		error("setlogin failed: %s", strerror(errno));
2402
2403	/* Set uid, gid, and groups. */
2404	/* Login(1) does this as well, and it needs uid 0 for the "-h"
2405	   switch, so we let login(1) to this for us. */
2406	if (!options.use_login) {
2407#ifdef LOGIN_CAP
2408		if (setclasscontext(pw->pw_class, LOGIN_SETPRIORITY |
2409		    LOGIN_SETRESOURCES | LOGIN_SETUMASK) == -1) {
2410			perror("setclasscontext");
2411			exit(1);
2412		}
2413#endif /* LOGIN_CAP */
2414		if (getuid() == 0 || geteuid() == 0) {
2415			if (setgid(pw->pw_gid) < 0) {
2416				perror("setgid");
2417				exit(1);
2418			}
2419			/* Initialize the group list. */
2420			if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2421				perror("initgroups");
2422				exit(1);
2423			}
2424			endgrent();
2425
2426			/* Permanently switch to the desired uid. */
2427			permanently_set_uid(pw->pw_uid);
2428		}
2429		if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2430			fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2431	}
2432	/*
2433	 * Get the shell from the password data.  An empty shell field is
2434	 * legal, and means /bin/sh.
2435	 */
2436#ifdef LOGIN_CAP
2437	shell = pw->pw_shell;
2438	shell = login_getcapstr(lc, "shell", shell, shell);
2439	if (shell[0] == '\0')
2440		shell = _PATH_BSHELL;
2441#else /* LOGIN_CAP */
2442	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2443#endif /* LOGIN_CAP */
2444
2445#ifdef AFS
2446	/* Try to get AFS tokens for the local cell. */
2447	if (k_hasafs()) {
2448		char cell[64];
2449
2450		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2451			krb_afslog(cell, 0);
2452
2453		krb_afslog(0, 0);
2454	}
2455#endif /* AFS */
2456
2457	/* Initialize the environment. */
2458	envsize = 100;
2459	env = xmalloc(envsize * sizeof(char *));
2460	env[0] = NULL;
2461
2462	if (!options.use_login) {
2463		/* Set basic environment. */
2464		child_set_env(&env, &envsize, "USER", pw->pw_name);
2465		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2466		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2467#ifdef LOGIN_CAP
2468		child_set_env(&env, &envsize, "PATH",
2469		    login_getpath(lc, "path", _PATH_STDPATH));
2470#else /* LOGIN_CAP */
2471		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2472#endif /* LOGIN_CAP */
2473
2474		snprintf(buf, sizeof buf, "%.200s/%.50s",
2475			 _PATH_MAILDIR, pw->pw_name);
2476		child_set_env(&env, &envsize, "MAIL", buf);
2477
2478		/* Normal systems set SHELL by default. */
2479		child_set_env(&env, &envsize, "SHELL", shell);
2480	}
2481	if (getenv("TZ"))
2482		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2483
2484	/* Set custom environment options from RSA authentication. */
2485	while (custom_environment) {
2486		struct envstring *ce = custom_environment;
2487		char *s = ce->s;
2488		int i;
2489		for (i = 0; s[i] != '=' && s[i]; i++);
2490		if (s[i] == '=') {
2491			s[i] = 0;
2492			child_set_env(&env, &envsize, s, s + i + 1);
2493		}
2494		custom_environment = ce->next;
2495		xfree(ce->s);
2496		xfree(ce);
2497	}
2498
2499	snprintf(buf, sizeof buf, "%.50s %d %d",
2500		 get_remote_ipaddr(), get_remote_port(), get_local_port());
2501	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2502
2503	if (ttyname)
2504		child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2505	if (term)
2506		child_set_env(&env, &envsize, "TERM", term);
2507	if (display)
2508		child_set_env(&env, &envsize, "DISPLAY", display);
2509
2510#ifdef KRB4
2511	{
2512		extern char *ticket;
2513
2514		if (ticket)
2515			child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2516	}
2517#endif /* KRB4 */
2518
2519	if (xauthfile)
2520		child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2521	if (auth_get_socket_name() != NULL)
2522		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2523			      auth_get_socket_name());
2524
2525	/* read $HOME/.ssh/environment. */
2526	if (!options.use_login) {
2527		snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2528		read_environment_file(&env, &envsize, buf);
2529	}
2530	if (debug_flag) {
2531		/* dump the environment */
2532		fprintf(stderr, "Environment:\n");
2533		for (i = 0; env[i]; i++)
2534			fprintf(stderr, "  %.200s\n", env[i]);
2535	}
2536	/*
2537	 * Close the connection descriptors; note that this is the child, and
2538	 * the server will still have the socket open, and it is important
2539	 * that we do not shutdown it.  Note that the descriptors cannot be
2540	 * closed before building the environment, as we call
2541	 * get_remote_ipaddr there.
2542	 */
2543	if (packet_get_connection_in() == packet_get_connection_out())
2544		close(packet_get_connection_in());
2545	else {
2546		close(packet_get_connection_in());
2547		close(packet_get_connection_out());
2548	}
2549	/*
2550	 * Close all descriptors related to channels.  They will still remain
2551	 * open in the parent.
2552	 */
2553	/* XXX better use close-on-exec? -markus */
2554	channel_close_all();
2555
2556	/*
2557	 * Close any extra file descriptors.  Note that there may still be
2558	 * descriptors left by system functions.  They will be closed later.
2559	 */
2560	endpwent();
2561
2562#ifdef LOGIN_CAP
2563 	login_close(lc);
2564#endif /* LOGIN_CAP */
2565
2566	/*
2567	 * Close any extra open file descriptors so that we don\'t have them
2568	 * hanging around in clients.  Note that we want to do this after
2569	 * initgroups, because at least on Solaris 2.3 it leaves file
2570	 * descriptors open.
2571	 */
2572	for (i = 3; i < getdtablesize(); i++)
2573		close(i);
2574
2575	/* Change current directory to the user\'s home directory. */
2576	if (chdir(pw->pw_dir) < 0)
2577		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2578			pw->pw_dir, strerror(errno));
2579
2580	/*
2581	 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2582	 * xauth are run in the proper environment.
2583	 */
2584	environ = env;
2585
2586	/*
2587	 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2588	 * in this order).
2589	 */
2590	if (!options.use_login) {
2591#ifdef __FreeBSD__
2592		/*
2593		 * If the password change time is set and has passed, give the
2594		 * user a password expiry notice and chance to change it.
2595		 */
2596		if (pw->pw_change != 0) {
2597			struct timeval tv;
2598
2599			(void)gettimeofday(&tv, NULL);
2600			if (tv.tv_sec >= pw->pw_change) {
2601				(void)printf(
2602				    "Sorry -- your password has expired.\n");
2603				syslog(LOG_INFO,
2604				    "%s Password expired - forcing change",
2605				    pw->pw_name);
2606				if (system("/usr/bin/passwd") != 0)
2607					perror("/usr/bin/passwd");
2608			}
2609		}
2610#endif /* __FreeBSD__ */
2611		if (stat(SSH_USER_RC, &st) >= 0) {
2612			if (debug_flag)
2613				fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2614
2615			f = popen("/bin/sh " SSH_USER_RC, "w");
2616			if (f) {
2617				if (auth_proto != NULL && auth_data != NULL)
2618					fprintf(f, "%s %s\n", auth_proto, auth_data);
2619				pclose(f);
2620			} else
2621				fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2622		} else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2623			if (debug_flag)
2624				fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2625
2626			f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2627			if (f) {
2628				if (auth_proto != NULL && auth_data != NULL)
2629					fprintf(f, "%s %s\n", auth_proto, auth_data);
2630				pclose(f);
2631			} else
2632				fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2633		}
2634#ifdef XAUTH_PATH
2635		else {
2636			/* Add authority data to .Xauthority if appropriate. */
2637			if (auth_proto != NULL && auth_data != NULL) {
2638				if (debug_flag)
2639					fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2640						XAUTH_PATH, display, auth_proto, auth_data);
2641
2642				f = popen(XAUTH_PATH " -q -", "w");
2643				if (f) {
2644					fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2645					fclose(f);
2646				} else
2647					fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2648			}
2649		}
2650#endif /* XAUTH_PATH */
2651
2652		/* Get the last component of the shell name. */
2653		cp = strrchr(shell, '/');
2654		if (cp)
2655			cp++;
2656		else
2657			cp = shell;
2658	}
2659	/*
2660	 * If we have no command, execute the shell.  In this case, the shell
2661	 * name to be passed in argv[0] is preceded by '-' to indicate that
2662	 * this is a login shell.
2663	 */
2664	if (!command) {
2665		if (!options.use_login) {
2666			char buf[256];
2667
2668			/*
2669			 * Check for mail if we have a tty and it was enabled
2670			 * in server options.
2671			 */
2672			if (ttyname && options.check_mail) {
2673				char *mailbox;
2674				struct stat mailstat;
2675				mailbox = getenv("MAIL");
2676				if (mailbox != NULL) {
2677					if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2678						printf("No mail.\n");
2679					else if (mailstat.st_mtime < mailstat.st_atime)
2680						printf("You have mail.\n");
2681					else
2682						printf("You have new mail.\n");
2683				}
2684			}
2685			/* Start the shell.  Set initial character to '-'. */
2686			buf[0] = '-';
2687			strncpy(buf + 1, cp, sizeof(buf) - 1);
2688			buf[sizeof(buf) - 1] = 0;
2689
2690			/* Execute the shell. */
2691			argv[0] = buf;
2692			argv[1] = NULL;
2693			execve(shell, argv, env);
2694
2695			/* Executing the shell failed. */
2696			perror(shell);
2697			exit(1);
2698
2699		} else {
2700			/* Launch login(1). */
2701
2702			execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
2703			      "-p", "-f", "--", pw->pw_name, NULL);
2704
2705			/* Login couldn't be executed, die. */
2706
2707			perror("login");
2708			exit(1);
2709		}
2710	}
2711	/*
2712	 * Execute the command using the user's shell.  This uses the -c
2713	 * option to execute the command.
2714	 */
2715	argv[0] = (char *) cp;
2716	argv[1] = "-c";
2717	argv[2] = (char *) command;
2718	argv[3] = NULL;
2719	execve(shell, argv, env);
2720	perror(shell);
2721	exit(1);
2722}
2723