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