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