xref: /freebsd/crypto/openssh/session.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
1 /*
2  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3  *                    All rights reserved
4  *
5  * As far as I am concerned, the code I have written for this software
6  * can be used freely for any purpose.  Any derived versions of this
7  * software must be clearly marked as such, and if the derived work is
8  * incompatible with the protocol description in the RFC file, it must be
9  * called by a name other than "ssh" or "Secure Shell".
10  *
11  * SSH2 support by Markus Friedl.
12  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "includes.h"
36 RCSID("$OpenBSD: session.c,v 1.128 2002/02/16 00:51:44 markus Exp $");
37 RCSID("$FreeBSD$");
38 
39 #include "ssh.h"
40 #include "ssh1.h"
41 #include "ssh2.h"
42 #include "xmalloc.h"
43 #include "sshpty.h"
44 #include "packet.h"
45 #include "buffer.h"
46 #include "mpaux.h"
47 #include "uidswap.h"
48 #include "compat.h"
49 #include "channels.h"
50 #include "bufaux.h"
51 #include "auth.h"
52 #include "auth-options.h"
53 #include "pathnames.h"
54 #include "log.h"
55 #include "servconf.h"
56 #include "sshlogin.h"
57 #include "serverloop.h"
58 #include "canohost.h"
59 #include "session.h"
60 
61 #ifdef __FreeBSD__
62 #define _PATH_CHPASS "/usr/bin/passwd"
63 #endif /* __FreeBSD__ */
64 
65 #if defined(HAVE_LOGIN_CAP) || defined(USE_PAM)
66 #include <libgen.h>
67 #endif
68 #ifdef HAVE_LOGIN_CAP
69 #include <login_cap.h>
70 #endif
71 
72 /* types */
73 
74 #define TTYSZ 64
75 typedef struct Session Session;
76 struct Session {
77 	int	used;
78 	int	self;
79 	struct passwd *pw;
80 	Authctxt *authctxt;
81 	pid_t	pid;
82 	/* tty */
83 	char	*term;
84 	int	ptyfd, ttyfd, ptymaster;
85 	int	row, col, xpixel, ypixel;
86 	char	tty[TTYSZ];
87 	/* X11 */
88 	int	display_number;
89 	char	*display;
90 	int	screen;
91 	char	*auth_display;
92 	char	*auth_proto;
93 	char	*auth_data;
94 	int	single_connection;
95 	/* proto 2 */
96 	int	chanid;
97 	int	is_subsystem;
98 };
99 
100 /* func */
101 
102 Session *session_new(void);
103 void	session_set_fds(Session *, int, int, int);
104 static void	session_pty_cleanup(void *);
105 void	session_proctitle(Session *);
106 int	session_setup_x11fwd(Session *);
107 void	do_exec_pty(Session *, const char *);
108 void	do_exec_no_pty(Session *, const char *);
109 void	do_exec(Session *, const char *);
110 void	do_login(Session *, const char *);
111 void	do_child(Session *, const char *);
112 void	do_motd(void);
113 int	check_quietlogin(Session *, const char *);
114 
115 static void do_authenticated1(Authctxt *);
116 static void do_authenticated2(Authctxt *);
117 
118 static void session_close(Session *);
119 static int session_pty_req(Session *);
120 
121 /* import */
122 extern ServerOptions options;
123 extern char *__progname;
124 extern int log_stderr;
125 extern int debug_flag;
126 extern u_int utmp_len;
127 extern int startup_pipe;
128 extern void destroy_sensitive_data(void);
129 
130 /* original command from peer. */
131 const char *original_command = NULL;
132 
133 /* data */
134 #define MAX_SESSIONS 10
135 Session	sessions[MAX_SESSIONS];
136 
137 #ifdef HAVE_LOGIN_CAP
138 static login_cap_t *lc;
139 #endif
140 
141 void
142 do_authenticated(Authctxt *authctxt)
143 {
144 	/*
145 	 * Cancel the alarm we set to limit the time taken for
146 	 * authentication.
147 	 */
148 	alarm(0);
149 	if (startup_pipe != -1) {
150 		close(startup_pipe);
151 		startup_pipe = -1;
152 	}
153 #ifdef HAVE_LOGIN_CAP
154 	if ((lc = login_getpwclass(authctxt->pw)) == NULL) {
155 		error("unable to get login class");
156 		return;
157 	}
158 #ifdef BSD_AUTH
159 	if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
160 		packet_disconnect("Approval failure for %s",
161 		    authctxt->pw->pw_name);
162 	}
163 #endif
164 #endif
165 	/* setup the channel layer */
166 	if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
167 		channel_permit_all_opens();
168 
169 	if (compat20)
170 		do_authenticated2(authctxt);
171 	else
172 		do_authenticated1(authctxt);
173 
174 	/* remove agent socket */
175 	if (auth_get_socket_name())
176 		auth_sock_cleanup_proc(authctxt->pw);
177 #ifdef KRB4
178 	if (options.kerberos_ticket_cleanup)
179 		krb4_cleanup_proc(authctxt);
180 #endif
181 #ifdef KRB5
182 	if (options.kerberos_ticket_cleanup)
183 		krb5_cleanup_proc(authctxt);
184 #endif
185 }
186 
187 /*
188  * Prepares for an interactive session.  This is called after the user has
189  * been successfully authenticated.  During this message exchange, pseudo
190  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
191  * are requested, etc.
192  */
193 static void
194 do_authenticated1(Authctxt *authctxt)
195 {
196 	Session *s;
197 	char *command;
198 	int success, type, screen_flag;
199 	int compression_level = 0, enable_compression_after_reply = 0;
200 	u_int proto_len, data_len, dlen;
201 
202 	s = session_new();
203 	s->authctxt = authctxt;
204 	s->pw = authctxt->pw;
205 
206 	/*
207 	 * We stay in this loop until the client requests to execute a shell
208 	 * or a command.
209 	 */
210 	for (;;) {
211 		success = 0;
212 
213 		/* Get a packet from the client. */
214 		type = packet_read();
215 
216 		/* Process the packet. */
217 		switch (type) {
218 		case SSH_CMSG_REQUEST_COMPRESSION:
219 			compression_level = packet_get_int();
220 			packet_check_eom();
221 			if (compression_level < 1 || compression_level > 9) {
222 				packet_send_debug("Received illegal compression level %d.",
223 				    compression_level);
224 				break;
225 			}
226 			/* Enable compression after we have responded with SUCCESS. */
227 			enable_compression_after_reply = 1;
228 			success = 1;
229 			break;
230 
231 		case SSH_CMSG_REQUEST_PTY:
232 			success = session_pty_req(s);
233 			break;
234 
235 		case SSH_CMSG_X11_REQUEST_FORWARDING:
236 			s->auth_proto = packet_get_string(&proto_len);
237 			s->auth_data = packet_get_string(&data_len);
238 
239 			screen_flag = packet_get_protocol_flags() &
240 			    SSH_PROTOFLAG_SCREEN_NUMBER;
241 			debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
242 
243 			if (packet_remaining() == 4) {
244 				if (!screen_flag)
245 					debug2("Buggy client: "
246 					    "X11 screen flag missing");
247 				s->screen = packet_get_int();
248 			} else {
249 				s->screen = 0;
250 			}
251 			packet_check_eom();
252 			success = session_setup_x11fwd(s);
253 			if (!success) {
254 				xfree(s->auth_proto);
255 				xfree(s->auth_data);
256 				s->auth_proto = NULL;
257 				s->auth_data = NULL;
258 			}
259 			break;
260 
261 		case SSH_CMSG_AGENT_REQUEST_FORWARDING:
262 			if (no_agent_forwarding_flag || compat13) {
263 				debug("Authentication agent forwarding not permitted for this authentication.");
264 				break;
265 			}
266 			debug("Received authentication agent forwarding request.");
267 			success = auth_input_request_forwarding(s->pw);
268 			break;
269 
270 		case SSH_CMSG_PORT_FORWARD_REQUEST:
271 			if (no_port_forwarding_flag) {
272 				debug("Port forwarding not permitted for this authentication.");
273 				break;
274 			}
275 			if (!options.allow_tcp_forwarding) {
276 				debug("Port forwarding not permitted.");
277 				break;
278 			}
279 			debug("Received TCP/IP port forwarding request.");
280 			channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
281 			success = 1;
282 			break;
283 
284 		case SSH_CMSG_MAX_PACKET_SIZE:
285 			if (packet_set_maxsize(packet_get_int()) > 0)
286 				success = 1;
287 			break;
288 
289 #if defined(AFS) || defined(KRB5)
290 		case SSH_CMSG_HAVE_KERBEROS_TGT:
291 			if (!options.kerberos_tgt_passing) {
292 				verbose("Kerberos TGT passing disabled.");
293 			} else {
294 				char *kdata = packet_get_string(&dlen);
295 				packet_check_eom();
296 
297 				/* XXX - 0x41, see creds_to_radix version */
298 				if (kdata[0] != 0x41) {
299 #ifdef KRB5
300 					krb5_data tgt;
301 					tgt.data = kdata;
302 					tgt.length = dlen;
303 
304 					if (auth_krb5_tgt(s->authctxt, &tgt))
305 						success = 1;
306 					else
307 						verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
308 #endif /* KRB5 */
309 				} else {
310 #ifdef AFS
311 					if (auth_krb4_tgt(s->authctxt, kdata))
312 						success = 1;
313 					else
314 						verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
315 #endif /* AFS */
316 				}
317 				xfree(kdata);
318 			}
319 			break;
320 #endif /* AFS || KRB5 */
321 
322 #ifdef AFS
323 		case SSH_CMSG_HAVE_AFS_TOKEN:
324 			if (!options.afs_token_passing || !k_hasafs()) {
325 				verbose("AFS token passing disabled.");
326 			} else {
327 				/* Accept AFS token. */
328 				char *token = packet_get_string(&dlen);
329 				packet_check_eom();
330 
331 				if (auth_afs_token(s->authctxt, token))
332 					success = 1;
333 				else
334 					verbose("AFS token refused for %.100s",
335 					    s->authctxt->user);
336 				xfree(token);
337 			}
338 			break;
339 #endif /* AFS */
340 
341 		case SSH_CMSG_EXEC_SHELL:
342 		case SSH_CMSG_EXEC_CMD:
343 			if (type == SSH_CMSG_EXEC_CMD) {
344 				command = packet_get_string(&dlen);
345 				debug("Exec command '%.500s'", command);
346 				do_exec(s, command);
347 				xfree(command);
348 			} else {
349 				do_exec(s, NULL);
350 			}
351 			packet_check_eom();
352 			session_close(s);
353 			return;
354 
355 		default:
356 			/*
357 			 * Any unknown messages in this phase are ignored,
358 			 * and a failure message is returned.
359 			 */
360 			log("Unknown packet type received after authentication: %d", type);
361 		}
362 		packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
363 		packet_send();
364 		packet_write_wait();
365 
366 		/* Enable compression now that we have replied if appropriate. */
367 		if (enable_compression_after_reply) {
368 			enable_compression_after_reply = 0;
369 			packet_start_compression(compression_level);
370 		}
371 	}
372 }
373 
374 /*
375  * This is called to fork and execute a command when we have no tty.  This
376  * will call do_child from the child, and server_loop from the parent after
377  * setting up file descriptors and such.
378  */
379 void
380 do_exec_no_pty(Session *s, const char *command)
381 {
382 	int pid;
383 
384 #ifdef USE_PIPES
385 	int pin[2], pout[2], perr[2];
386 	/* Allocate pipes for communicating with the program. */
387 	if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
388 		packet_disconnect("Could not create pipes: %.100s",
389 				  strerror(errno));
390 #else /* USE_PIPES */
391 	int inout[2], err[2];
392 	/* Uses socket pairs to communicate with the program. */
393 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
394 	    socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
395 		packet_disconnect("Could not create socket pairs: %.100s",
396 				  strerror(errno));
397 #endif /* USE_PIPES */
398 	if (s == NULL)
399 		fatal("do_exec_no_pty: no session");
400 
401 	session_proctitle(s);
402 
403 #ifdef USE_PAM
404 	do_pam_setcred();
405 #endif /* USE_PAM */
406 
407 	/* Fork the child. */
408 	if ((pid = fork()) == 0) {
409 		/* Child.  Reinitialize the log since the pid has changed. */
410 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
411 
412 		/*
413 		 * Create a new session and process group since the 4.4BSD
414 		 * setlogin() affects the entire process group.
415 		 */
416 		if (setsid() < 0)
417 			error("setsid failed: %.100s", strerror(errno));
418 
419 #ifdef USE_PIPES
420 		/*
421 		 * Redirect stdin.  We close the parent side of the socket
422 		 * pair, and make the child side the standard input.
423 		 */
424 		close(pin[1]);
425 		if (dup2(pin[0], 0) < 0)
426 			perror("dup2 stdin");
427 		close(pin[0]);
428 
429 		/* Redirect stdout. */
430 		close(pout[0]);
431 		if (dup2(pout[1], 1) < 0)
432 			perror("dup2 stdout");
433 		close(pout[1]);
434 
435 		/* Redirect stderr. */
436 		close(perr[0]);
437 		if (dup2(perr[1], 2) < 0)
438 			perror("dup2 stderr");
439 		close(perr[1]);
440 #else /* USE_PIPES */
441 		/*
442 		 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
443 		 * use the same socket, as some programs (particularly rdist)
444 		 * seem to depend on it.
445 		 */
446 		close(inout[1]);
447 		close(err[1]);
448 		if (dup2(inout[0], 0) < 0)	/* stdin */
449 			perror("dup2 stdin");
450 		if (dup2(inout[0], 1) < 0)	/* stdout.  Note: same socket as stdin. */
451 			perror("dup2 stdout");
452 		if (dup2(err[0], 2) < 0)	/* stderr */
453 			perror("dup2 stderr");
454 #endif /* USE_PIPES */
455 
456 		/* Do processing for the child (exec command etc). */
457 		do_child(s, command);
458 		/* NOTREACHED */
459 	}
460 	if (pid < 0)
461 		packet_disconnect("fork failed: %.100s", strerror(errno));
462 	s->pid = pid;
463 	/* Set interactive/non-interactive mode. */
464 	packet_set_interactive(s->display != NULL);
465 #ifdef USE_PIPES
466 	/* We are the parent.  Close the child sides of the pipes. */
467 	close(pin[0]);
468 	close(pout[1]);
469 	close(perr[1]);
470 
471 	if (compat20) {
472 		session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
473 	} else {
474 		/* Enter the interactive session. */
475 		server_loop(pid, pin[1], pout[0], perr[0]);
476 		/* server_loop has closed pin[1], pout[0], and perr[0]. */
477 	}
478 #else /* USE_PIPES */
479 	/* We are the parent.  Close the child sides of the socket pairs. */
480 	close(inout[0]);
481 	close(err[0]);
482 
483 	/*
484 	 * Enter the interactive session.  Note: server_loop must be able to
485 	 * handle the case that fdin and fdout are the same.
486 	 */
487 	if (compat20) {
488 		session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
489 	} else {
490 		server_loop(pid, inout[1], inout[1], err[1]);
491 		/* server_loop has closed inout[1] and err[1]. */
492 	}
493 #endif /* USE_PIPES */
494 }
495 
496 /*
497  * This is called to fork and execute a command when we have a tty.  This
498  * will call do_child from the child, and server_loop from the parent after
499  * setting up file descriptors, controlling tty, updating wtmp, utmp,
500  * lastlog, and other such operations.
501  */
502 void
503 do_exec_pty(Session *s, const char *command)
504 {
505 	int fdout, ptyfd, ttyfd, ptymaster;
506 	pid_t pid;
507 
508 	if (s == NULL)
509 		fatal("do_exec_pty: no session");
510 	ptyfd = s->ptyfd;
511 	ttyfd = s->ttyfd;
512 
513 #ifdef USE_PAM
514 	do_pam_session(s->pw->pw_name, basename(s->tty));
515 	do_pam_setcred();
516 #endif /* USE_PAM */
517 
518 	/* Fork the child. */
519 	if ((pid = fork()) == 0) {
520 
521 		/* Child.  Reinitialize the log because the pid has changed. */
522 		log_init(__progname, options.log_level, options.log_facility, log_stderr);
523 		/* Close the master side of the pseudo tty. */
524 		close(ptyfd);
525 
526 		/* Make the pseudo tty our controlling tty. */
527 		pty_make_controlling_tty(&ttyfd, s->tty);
528 
529 		/* Redirect stdin/stdout/stderr from the pseudo tty. */
530 		if (dup2(ttyfd, 0) < 0)
531 			error("dup2 stdin: %s", strerror(errno));
532 		if (dup2(ttyfd, 1) < 0)
533 			error("dup2 stdout: %s", strerror(errno));
534 		if (dup2(ttyfd, 2) < 0)
535 			error("dup2 stderr: %s", strerror(errno));
536 
537 		/* Close the extra descriptor for the pseudo tty. */
538 		close(ttyfd);
539 
540 		/* record login, etc. similar to login(1) */
541 		if (!(options.use_login && command == NULL))
542 			do_login(s, command);
543 
544 		/* Do common processing for the child, such as execing the command. */
545 		do_child(s, command);
546 		/* NOTREACHED */
547 	}
548 	if (pid < 0)
549 		packet_disconnect("fork failed: %.100s", strerror(errno));
550 	s->pid = pid;
551 
552 	/* Parent.  Close the slave side of the pseudo tty. */
553 	close(ttyfd);
554 
555 	/*
556 	 * Create another descriptor of the pty master side for use as the
557 	 * standard input.  We could use the original descriptor, but this
558 	 * simplifies code in server_loop.  The descriptor is bidirectional.
559 	 */
560 	fdout = dup(ptyfd);
561 	if (fdout < 0)
562 		packet_disconnect("dup #1 failed: %.100s", strerror(errno));
563 
564 	/* we keep a reference to the pty master */
565 	ptymaster = dup(ptyfd);
566 	if (ptymaster < 0)
567 		packet_disconnect("dup #2 failed: %.100s", strerror(errno));
568 	s->ptymaster = ptymaster;
569 
570 	/* Enter interactive session. */
571 	packet_set_interactive(1);
572 	if (compat20) {
573 		session_set_fds(s, ptyfd, fdout, -1);
574 	} else {
575 		server_loop(pid, ptyfd, fdout, -1);
576 		/* server_loop _has_ closed ptyfd and fdout. */
577 	}
578 }
579 
580 /*
581  * This is called to fork and execute a command.  If another command is
582  * to be forced, execute that instead.
583  */
584 void
585 do_exec(Session *s, const char *command)
586 {
587 	if (forced_command) {
588 		original_command = command;
589 		command = forced_command;
590 		debug("Forced command '%.900s'", command);
591 	}
592 
593 	if (s->ttyfd != -1)
594 		do_exec_pty(s, command);
595 	else
596 		do_exec_no_pty(s, command);
597 
598 	original_command = NULL;
599 }
600 
601 
602 /* administrative, login(1)-like work */
603 void
604 do_login(Session *s, const char *command)
605 {
606 	FILE *f;
607 #ifndef USE_PAM
608 	char *time_string;
609 	char *newcommand = NULL;
610 #endif
611 	char buf[256];
612 #ifndef USE_PAM
613 	char hostname[MAXHOSTNAMELEN];
614 	socklen_t fromlen;
615 	struct sockaddr_storage from;
616 	time_t last_login_time;
617 #endif
618 	struct passwd * pw = s->pw;
619 #ifndef USE_PAM
620 	pid_t pid = getpid();
621 #endif
622 #ifdef __FreeBSD__
623 #define DEFAULT_WARN  (2L * 7L * 86400L)  /* Two weeks */
624 	struct timeval tv;
625 	time_t warntime = DEFAULT_WARN;
626 #endif /* __FreeBSD__ */
627 
628 #ifndef USE_PAM
629 	/*
630 	 * Let PAM handle utmp / wtmp.
631 	 */
632 	/*
633 	 * Get IP address of client. If the connection is not a socket, let
634 	 * the address be 0.0.0.0.
635 	 */
636 	memset(&from, 0, sizeof(from));
637 	if (packet_connection_is_on_socket()) {
638 		fromlen = sizeof(from);
639 		if (getpeername(packet_get_connection_in(),
640 		    (struct sockaddr *) & from, &fromlen) < 0) {
641 			debug("getpeername: %.100s", strerror(errno));
642 			fatal_cleanup();
643 		}
644 	}
645 #endif
646 
647 #ifndef USE_PAM
648 	/* Get the time and hostname when the user last logged in. */
649 	if (options.print_lastlog) {
650 		hostname[0] = '\0';
651 		last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
652 		    hostname, sizeof(hostname));
653 	}
654 
655 	/* Record that there was a login on that tty from the remote host. */
656 	record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
657 	    get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
658 	    (struct sockaddr *)&from);
659 #endif
660 
661 #ifdef USE_PAM
662 	/*
663 	 * If password change is needed, do it now.
664 	 * This needs to occur before the ~/.hushlogin check.
665 	 */
666 	if (pam_password_change_required()) {
667 		print_pam_messages();
668 		do_pam_chauthtok();
669 	}
670 #endif
671 #ifdef __FreeBSD__
672 	if (pw->pw_change || pw->pw_expire)
673 		(void)gettimeofday(&tv, NULL);
674 #ifdef HAVE_LOGIN_CAP
675 	warntime = login_getcaptime(lc, "warnpassword",
676 				    DEFAULT_WARN, DEFAULT_WARN);
677 #endif /* HAVE_LOGIN_CAP */
678 #ifndef USE_PAM
679 	/*
680 	 * If the password change time is set and has passed, give the
681 	 * user a password expiry notice and chance to change it.
682 	 */
683 	if (pw->pw_change != 0) {
684 		if (tv.tv_sec >= pw->pw_change) {
685 			(void)printf(
686 			    "Sorry -- your password has expired.\n");
687 			log("%s Password expired - forcing change",
688 			    pw->pw_name);
689 			if (newcommand != NULL)
690 				xfree(newcommand);
691 			newcommand = xstrdup(_PATH_CHPASS);
692 		} else if (pw->pw_change - tv.tv_sec < warntime &&
693 			   !check_quietlogin(s, command))
694 			(void)printf(
695 			    "Warning: your password expires on %s",
696 			     ctime(&pw->pw_change));
697 	}
698 #endif
699 #ifdef HAVE_LOGIN_CAP
700 	warntime = login_getcaptime(lc, "warnexpire",
701 				    DEFAULT_WARN, DEFAULT_WARN);
702 #endif /* HAVE_LOGIN_CAP */
703 #ifndef USE_PAM
704 	if (pw->pw_expire) {
705 		if (tv.tv_sec >= pw->pw_expire) {
706 			(void)printf(
707 			    "Sorry -- your account has expired.\n");
708 			log(
709 	   "LOGIN %.200s REFUSED (EXPIRED) FROM %.200s ON TTY %.200s",
710 				pw->pw_name, get_remote_name_or_ip(utmp_len,
711 				options.verify_reverse_mapping), s->tty);
712 			exit(254);
713 		} else if (pw->pw_expire - tv.tv_sec < warntime &&
714 			   !check_quietlogin(s, command))
715 			(void)printf(
716 			    "Warning: your account expires on %s",
717 			     ctime(&pw->pw_expire));
718 	}
719 #endif /* !USE_PAM */
720 #endif /* __FreeBSD__ */
721 #ifdef HAVE_LOGIN_CAP
722 	if (!auth_ttyok(lc, basename(s->tty))) {
723 		(void)printf("Permission denied.\n");
724 		log(
725 	       "LOGIN %.200s REFUSED (TTY) FROM %.200s ON TTY %.200s",
726 		    pw->pw_name, get_remote_name_or_ip(utmp_len,
727 			options.verify_reverse_mapping), s->tty);
728 		exit(254);
729 	}
730 #endif /* HAVE_LOGIN_CAP */
731 
732 #ifdef USE_PAM
733 	if (command == NULL && options.print_lastlog &&
734 	    !check_quietlogin(s, command) &&
735 	    !options.use_login && !pam_password_change_required())
736 		print_pam_messages();
737 #else /* !USE_PAM */
738 	/*
739 	 * If the user has logged in before, display the time of last
740 	 * login. However, don't display anything extra if a command
741 	 * has been specified (so that ssh can be used to execute
742 	 * commands on a remote machine without users knowing they
743 	 * are going to another machine). Login(1) will do this for
744 	 * us as well, so check if login(1) is used
745 	 */
746 
747 	if (command == NULL && options.print_lastlog &&
748 	    last_login_time != 0 && !check_quietlogin(s, command) &&
749 	    !options.use_login) {
750 		time_string = ctime(&last_login_time);
751 		if (strchr(time_string, '\n'))
752 			*strchr(time_string, '\n') = 0;
753 		if (strcmp(hostname, "") == 0)
754 			printf("Last login: %s\r\n", time_string);
755 		else
756 			printf("Last login: %s from %s\r\n", time_string, hostname);
757 	}
758 #endif /* !USE_PAM */
759 
760 	if (command == NULL && !check_quietlogin(s, command) &&
761 	    !options.use_login) {
762 #ifdef HAVE_LOGIN_CAP
763 		const char *fname = login_getcapstr(lc, "copyright", NULL, NULL);
764 		if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
765 			while (fgets(buf, sizeof(buf), f) != NULL)
766 				fputs(buf, stdout);
767 				fclose(f);
768 		} else
769 #endif /* HAVE_LOGIN_CAP */
770 			(void)printf("%s\n\t%s %s\n",
771 		"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
772 		"The Regents of the University of California. ",
773 		"All rights reserved.");
774 		(void)printf("\n");
775 	/*
776 	 * Print /etc/motd unless a command was specified or printing
777 	 * it was disabled in server options or login(1) will be
778 	 * used.  Note that some machines appear to print it in
779 	 * /etc/profile or similar.
780 	 */
781 		do_motd();
782 	}
783 }
784 
785 /*
786  * Display the message of the day.
787  */
788 void
789 do_motd(void)
790 {
791 	FILE *f;
792 	char buf[256];
793 
794 	if (options.print_motd) {
795 #ifdef HAVE_LOGIN_CAP
796 		f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
797 		    "/etc/motd"), "r");
798 #else
799 		f = fopen("/etc/motd", "r");
800 #endif
801 		if (f) {
802 			while (fgets(buf, sizeof(buf), f))
803 				fputs(buf, stdout);
804 			fclose(f);
805 		}
806 	}
807 }
808 
809 
810 /*
811  * Check for quiet login, either .hushlogin or command given.
812  */
813 int
814 check_quietlogin(Session *s, const char *command)
815 {
816 	char buf[256];
817 	struct passwd *pw = s->pw;
818 	struct stat st;
819 
820 	/* Return 1 if .hushlogin exists or a command given. */
821 	if (command != NULL)
822 		return 1;
823 	snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
824 #ifdef HAVE_LOGIN_CAP
825 	if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
826 		return 1;
827 #else
828 	if (stat(buf, &st) >= 0)
829 		return 1;
830 #endif
831 	return 0;
832 }
833 
834 /*
835  * Sets the value of the given variable in the environment.  If the variable
836  * already exists, its value is overriden.
837  */
838 static void
839 child_set_env(char ***envp, u_int *envsizep, const char *name,
840 	const char *value)
841 {
842 	u_int i, namelen;
843 	char **env;
844 
845 	/*
846 	 * Find the slot where the value should be stored.  If the variable
847 	 * already exists, we reuse the slot; otherwise we append a new slot
848 	 * at the end of the array, expanding if necessary.
849 	 */
850 	env = *envp;
851 	namelen = strlen(name);
852 	for (i = 0; env[i]; i++)
853 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
854 			break;
855 	if (env[i]) {
856 		/* Reuse the slot. */
857 		xfree(env[i]);
858 	} else {
859 		/* New variable.  Expand if necessary. */
860 		if (i >= (*envsizep) - 1) {
861 			(*envsizep) += 50;
862 			env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
863 		}
864 		/* Need to set the NULL pointer at end of array beyond the new slot. */
865 		env[i + 1] = NULL;
866 	}
867 
868 	/* Allocate space and format the variable in the appropriate slot. */
869 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
870 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
871 }
872 
873 /*
874  * Reads environment variables from the given file and adds/overrides them
875  * into the environment.  If the file does not exist, this does nothing.
876  * Otherwise, it must consist of empty lines, comments (line starts with '#')
877  * and assignments of the form name=value.  No other forms are allowed.
878  */
879 static void
880 read_environment_file(char ***env, u_int *envsize,
881 	const char *filename)
882 {
883 	FILE *f;
884 	char buf[4096];
885 	char *cp, *value;
886 
887 	f = fopen(filename, "r");
888 	if (!f)
889 		return;
890 
891 	while (fgets(buf, sizeof(buf), f)) {
892 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
893 			;
894 		if (!*cp || *cp == '#' || *cp == '\n')
895 			continue;
896 		if (strchr(cp, '\n'))
897 			*strchr(cp, '\n') = '\0';
898 		value = strchr(cp, '=');
899 		if (value == NULL) {
900 			fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
901 			continue;
902 		}
903 		/*
904 		 * Replace the equals sign by nul, and advance value to
905 		 * the value string.
906 		 */
907 		*value = '\0';
908 		value++;
909 		child_set_env(env, envsize, cp, value);
910 	}
911 	fclose(f);
912 }
913 
914 #ifdef USE_PAM
915 /*
916  * Sets any environment variables which have been specified by PAM
917  */
918 static void
919 do_pam_environment(char ***env, u_int *envsize)
920 {
921 	char *equals, var_name[512], var_val[512];
922 	char **pam_env;
923 	int i;
924 
925 	if ((pam_env = fetch_pam_environment()) == NULL)
926 		return;
927 
928 	for(i = 0; pam_env[i] != NULL; i++) {
929 		if ((equals = strstr(pam_env[i], "=")) == NULL)
930 			continue;
931 
932 		if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
933 			memset(var_name, '\0', sizeof(var_name));
934 			memset(var_val, '\0', sizeof(var_val));
935 
936 			strncpy(var_name, pam_env[i], equals - pam_env[i]);
937 			strcpy(var_val, equals + 1);
938 
939 			child_set_env(env, envsize, var_name, var_val);
940 		}
941 	}
942 }
943 #endif /* USE_PAM */
944 
945 static char **
946 do_setup_env(char **env, Session *s, const char *shell)
947 {
948 	char buf[256];
949 	u_int i, envsize;
950 	struct passwd *pw = s->pw;
951 
952 	if (env == NULL) {
953 		/* Initialize the environment. */
954 		envsize = 100;
955 		env = xmalloc(envsize * sizeof(char *));
956 		env[0] = NULL;
957 	} else {
958 		for (envsize = 0; env[envsize] != NULL; ++envsize)
959 			;
960 		envsize = (envsize < 100) ? 100 : envsize + 50;
961 		env = xrealloc(env, envsize * sizeof(char *));
962 	}
963 
964 	if (!options.use_login) {
965 		/* Set basic environment. */
966 		child_set_env(&env, &envsize, "USER", pw->pw_name);
967 		child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
968 		child_set_env(&env, &envsize, "HOME", pw->pw_dir);
969 #ifndef HAVE_LOGIN_CAP
970 		child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
971 
972 		snprintf(buf, sizeof buf, "%.200s/%.50s",
973 			 _PATH_MAILDIR, pw->pw_name);
974 		child_set_env(&env, &envsize, "MAIL", buf);
975 #endif /* !HAVE_LOGIN_CAP */
976 
977 		/* Normal systems set SHELL by default. */
978 		child_set_env(&env, &envsize, "SHELL", shell);
979 	}
980 	if (getenv("TZ"))
981 #ifdef HAVE_LOGIN_CAP
982 	    if (options.use_login)
983 #endif /* HAVE_LOGIN_CAP */
984 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
985 
986 	/* Set custom environment options from RSA authentication. */
987 	if (!options.use_login) {
988 		while (custom_environment) {
989 			struct envstring *ce = custom_environment;
990 			char *s = ce->s;
991 
992 			for (i = 0; s[i] != '=' && s[i]; i++)
993 				;
994 			if (s[i] == '=') {
995 				s[i] = 0;
996 				child_set_env(&env, &envsize, s, s + i + 1);
997 			}
998 			custom_environment = ce->next;
999 			xfree(ce->s);
1000 			xfree(ce);
1001 		}
1002 	}
1003 
1004 	snprintf(buf, sizeof buf, "%.50s %d %d",
1005 	    get_remote_ipaddr(), get_remote_port(), get_local_port());
1006 	child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1007 
1008 	if (s->ttyfd != -1)
1009 		child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1010 	if (s->term)
1011 #ifdef HAVE_LOGIN_CAP
1012 	    if (options.use_login)
1013 #endif /* HAVE_LOGIN_CAP */
1014 		child_set_env(&env, &envsize, "TERM", s->term);
1015 	if (s->display)
1016 		child_set_env(&env, &envsize, "DISPLAY", s->display);
1017 	if (original_command)
1018 		child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1019 		    original_command);
1020 #ifdef KRB4
1021 	if (s->authctxt->krb4_ticket_file)
1022 		child_set_env(&env, &envsize, "KRBTKFILE",
1023 		    s->authctxt->krb4_ticket_file);
1024 #endif
1025 #ifdef KRB5
1026 	if (s->authctxt->krb5_ticket_file)
1027 		child_set_env(&env, &envsize, "KRB5CCNAME",
1028 		    s->authctxt->krb5_ticket_file);
1029 #endif
1030 
1031 #ifdef USE_PAM
1032 	/* Pull in any environment variables that may have been set by PAM. */
1033 	do_pam_environment(&env, &envsize);
1034 #endif /* USE_PAM */
1035 
1036 	if (auth_get_socket_name() != NULL)
1037 		child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1038 		    auth_get_socket_name());
1039 
1040 	/* read $HOME/.ssh/environment. */
1041 	if (!options.use_login) {
1042 		snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1043 		    pw->pw_dir);
1044 		read_environment_file(&env, &envsize, buf);
1045 	}
1046 	if (debug_flag) {
1047 		/* dump the environment */
1048 		fprintf(stderr, "Environment:\n");
1049 		for (i = 0; env[i]; i++)
1050 			fprintf(stderr, "  %.200s\n", env[i]);
1051 	}
1052 	return env;
1053 }
1054 
1055 /*
1056  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1057  * first in this order).
1058  */
1059 static void
1060 do_rc_files(Session *s, const char *shell)
1061 {
1062 	FILE *f = NULL;
1063 	char cmd[1024];
1064 	int do_xauth;
1065 	struct stat st;
1066 
1067 	do_xauth =
1068 	    s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1069 
1070 	/* ignore _PATH_SSH_USER_RC for subsystems */
1071 	if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1072 		snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1073 		    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1074 		if (debug_flag)
1075 			fprintf(stderr, "Running %s\n", cmd);
1076 		f = popen(cmd, "w");
1077 		if (f) {
1078 			if (do_xauth)
1079 				fprintf(f, "%s %s\n", s->auth_proto,
1080 				    s->auth_data);
1081 			pclose(f);
1082 		} else
1083 			fprintf(stderr, "Could not run %s\n",
1084 			    _PATH_SSH_USER_RC);
1085 	} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1086 		if (debug_flag)
1087 			fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1088 			    _PATH_SSH_SYSTEM_RC);
1089 		f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1090 		if (f) {
1091 			if (do_xauth)
1092 				fprintf(f, "%s %s\n", s->auth_proto,
1093 				    s->auth_data);
1094 			pclose(f);
1095 		} else
1096 			fprintf(stderr, "Could not run %s\n",
1097 			    _PATH_SSH_SYSTEM_RC);
1098 	} else if (do_xauth && options.xauth_location != NULL) {
1099 		/* Add authority data to .Xauthority if appropriate. */
1100 		if (debug_flag) {
1101 			fprintf(stderr,
1102 			    "Running %.100s add "
1103 			    "%.100s %.100s %.100s\n",
1104 			    options.xauth_location, s->auth_display,
1105 			    s->auth_proto, s->auth_data);
1106 		}
1107 		snprintf(cmd, sizeof cmd, "%s -q -",
1108 		    options.xauth_location);
1109 		f = popen(cmd, "w");
1110 		if (f) {
1111 			fprintf(f, "add %s %s %s\n",
1112 			    s->auth_display, s->auth_proto,
1113 			    s->auth_data);
1114 			pclose(f);
1115 		} else {
1116 			fprintf(stderr, "Could not run %s\n",
1117 			    cmd);
1118 		}
1119 	}
1120 }
1121 
1122 static void
1123 do_nologin(struct passwd *pw)
1124 {
1125 	FILE *f = NULL;
1126 	char buf[1024];
1127 
1128 #ifdef HAVE_LOGIN_CAP
1129 	if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1130 		f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1131 		    _PATH_NOLOGIN), "r");
1132 #else
1133 	if (pw->pw_uid)
1134 		f = fopen(_PATH_NOLOGIN, "r");
1135 #endif
1136 	if (f) {
1137 		/* /etc/nologin exists.  Print its contents and exit. */
1138 		while (fgets(buf, sizeof(buf), f))
1139 			fputs(buf, stderr);
1140 		fclose(f);
1141 		exit(254);
1142 	}
1143 }
1144 
1145 /* Set login name, uid, gid, and groups. */
1146 static char **
1147 do_setusercontext(Session *s)
1148 {
1149 	char **env = NULL;
1150 	struct passwd *pw = s->pw;
1151 #ifdef HAVE_LOGIN_CAP
1152 	char buf[256];
1153 	char **tmpenv;
1154 	u_int envsize;
1155 	extern char **environ;
1156 
1157 	/* Initialize the environment. */
1158 	envsize = 100;
1159 	env = xmalloc(envsize * sizeof(char *));
1160 	env[0] = NULL;
1161 
1162 	child_set_env(&env, &envsize, "PATH",
1163 		      (pw->pw_uid == 0) ?
1164 		      _PATH_STDPATH : _PATH_DEFPATH);
1165 
1166 	snprintf(buf, sizeof buf, "%.200s/%.50s",
1167 		 _PATH_MAILDIR, pw->pw_name);
1168 	child_set_env(&env, &envsize, "MAIL", buf);
1169 
1170 	if (getenv("TZ"))
1171 		child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1172 
1173 	if (s->term)
1174 		child_set_env(&env, &envsize, "TERM", s->term);
1175 
1176 	/* Save parent environment */
1177 	tmpenv = environ;
1178 	/* Switch to env */
1179 	environ = env;
1180 
1181 	if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETALL) < 0)
1182 		fatal("setusercontext failed: %s", strerror(errno));
1183 
1184 	/* NOTE: Modified environment now passed to env! */
1185 	env = environ;
1186 	/* Restore parent environment */
1187 	environ = tmpenv;
1188 
1189 #else   /* !HAVE_LOGIN_CAP */
1190 	if (getuid() == 0 || geteuid() == 0) {
1191 		if (setlogin(pw->pw_name) < 0)
1192 			error("setlogin failed: %s", strerror(errno));
1193 		if (setgid(pw->pw_gid) < 0) {
1194 			perror("setgid");
1195 			exit(1);
1196 		}
1197 		/* Initialize the group list. */
1198 		if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1199 			perror("initgroups");
1200 			exit(1);
1201 		}
1202 		endgrent();
1203 
1204 		/* Permanently switch to the desired uid. */
1205 		permanently_set_uid(pw);
1206 	}
1207 	if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1208 		fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1209 #endif  /* HAVE_LOGIN_CAP */
1210 	return env;
1211 }
1212 
1213 /*
1214  * Performs common processing for the child, such as setting up the
1215  * environment, closing extra file descriptors, setting the user and group
1216  * ids, and executing the command or shell.
1217  */
1218 void
1219 do_child(Session *s, const char *command)
1220 {
1221 	extern char **environ;
1222 	char **env = NULL;
1223 	char *argv[10];
1224 	const char *shell, *shell0, *hostname = NULL;
1225 	struct passwd *pw = s->pw;
1226 	u_int i;
1227 	int ttyfd = s->ttyfd;
1228 #ifdef HAVE_LOGIN_CAP
1229 	int lc_requirehome, lc_nocheckmail;
1230 #endif
1231 
1232 	/* remove hostkey from the child's memory */
1233 	destroy_sensitive_data();
1234 
1235 	/* login(1) is only called if we execute the login shell */
1236 	if (options.use_login && command != NULL)
1237 		options.use_login = 0;
1238 
1239 	/*
1240 	 * Login(1) does this as well, and it needs uid 0 for the "-h"
1241 	 * switch, so we let login(1) to this for us.
1242 	 */
1243 	if (!options.use_login) {
1244 		do_nologin(pw);
1245 		env = do_setusercontext(s);
1246 	}
1247 
1248 	/*
1249 	 * Get the shell from the password data.  An empty shell field is
1250 	 * legal, and means /bin/sh.
1251 	 */
1252 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1253 #ifdef HAVE_LOGIN_CAP
1254 	shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1255 #endif
1256 
1257 	env = do_setup_env(env, s, shell);
1258 
1259 	/* we have to stash the hostname before we close our socket. */
1260 	if (options.use_login)
1261 		hostname = get_remote_name_or_ip(utmp_len,
1262 		    options.verify_reverse_mapping);
1263 	/*
1264 	 * Close the connection descriptors; note that this is the child, and
1265 	 * the server will still have the socket open, and it is important
1266 	 * that we do not shutdown it.  Note that the descriptors cannot be
1267 	 * closed before building the environment, as we call
1268 	 * get_remote_ipaddr there.
1269 	 */
1270 	if (packet_get_connection_in() == packet_get_connection_out())
1271 		close(packet_get_connection_in());
1272 	else {
1273 		close(packet_get_connection_in());
1274 		close(packet_get_connection_out());
1275 	}
1276 	/*
1277 	 * Close all descriptors related to channels.  They will still remain
1278 	 * open in the parent.
1279 	 */
1280 	/* XXX better use close-on-exec? -markus */
1281 	channel_close_all();
1282 
1283 	/*
1284 	 * Close any extra file descriptors.  Note that there may still be
1285 	 * descriptors left by system functions.  They will be closed later.
1286 	 */
1287 	endpwent();
1288 
1289 #ifdef HAVE_LOGIN_CAP
1290 	lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1291 	lc_nocheckmail = login_getcapbool(lc, "nocheckmail", 0);
1292 	login_close(lc);
1293 #endif
1294 
1295 	/*
1296 	 * Close any extra open file descriptors so that we don\'t have them
1297 	 * hanging around in clients.  Note that we want to do this after
1298 	 * initgroups, because at least on Solaris 2.3 it leaves file
1299 	 * descriptors open.
1300 	 */
1301 	for (i = 3; i < getdtablesize(); i++)
1302 		close(i);
1303 
1304 	/*
1305 	 * Must take new environment into use so that .ssh/rc,
1306 	 * /etc/ssh/sshrc and xauth are run in the proper environment.
1307 	 */
1308 	environ = env;
1309 
1310 #ifdef AFS
1311 	/* Try to get AFS tokens for the local cell. */
1312 	if (k_hasafs()) {
1313 		char cell[64];
1314 
1315 		if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1316 			krb_afslog(cell, 0);
1317 
1318 		krb_afslog(0, 0);
1319 	}
1320 #endif /* AFS */
1321 
1322 	/* Change current directory to the user\'s home directory. */
1323 	if (chdir(pw->pw_dir) < 0) {
1324 		fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1325 		    pw->pw_dir, strerror(errno));
1326 #ifdef HAVE_LOGIN_CAP
1327 		if (lc_requirehome)
1328 			exit(1);
1329 #endif
1330 	}
1331 
1332 	if (!options.use_login)
1333 		do_rc_files(s, shell);
1334 
1335 	/* restore SIGPIPE for child */
1336 	signal(SIGPIPE,  SIG_DFL);
1337 
1338 	if (options.use_login) {
1339 		/* Launch login(1). */
1340 
1341 		execl("/usr/bin/login", "login", "-h", hostname,
1342 		    "-p", "-f", "--", pw->pw_name, (char *)NULL);
1343 
1344 		/* Login couldn't be executed, die. */
1345 
1346 		perror("login");
1347 		exit(1);
1348 	}
1349 
1350 	/* Get the last component of the shell name. */
1351 	if ((shell0 = strrchr(shell, '/')) != NULL)
1352 		shell0++;
1353 	else
1354 		shell0 = shell;
1355 
1356 	/*
1357 	 * If we have no command, execute the shell.  In this case, the shell
1358 	 * name to be passed in argv[0] is preceded by '-' to indicate that
1359 	 * this is a login shell.
1360 	 */
1361 	if (!command) {
1362 		char argv0[256];
1363 
1364 		/* Start the shell.  Set initial character to '-'. */
1365 		argv0[0] = '-';
1366 
1367 		if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1368 		    >= sizeof(argv0) - 1) {
1369 			errno = EINVAL;
1370 			perror(shell);
1371 			exit(1);
1372 		}
1373 
1374 		/*
1375 		 * Check for mail if we have a tty and it was enabled
1376 		 * in server options.
1377 		 */
1378 		if (ttyfd != -1 && options.check_mail
1379 #ifdef HAVE_LOGIN_CAP
1380 		    && !lc_nocheckmail
1381 #endif
1382 		   ) {
1383 			char *mailbox;
1384 			struct stat mailstat;
1385 
1386 			mailbox = getenv("MAIL");
1387 			if (mailbox != NULL) {
1388 				if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
1389 					;
1390 				else if (mailstat.st_mtime < mailstat.st_atime)
1391 					printf("You have mail.\n");
1392 				else
1393 					printf("You have new mail.\n");
1394 			}
1395 		}
1396 
1397 		/* Execute the shell. */
1398 		argv[0] = argv0;
1399 		argv[1] = NULL;
1400 		execve(shell, argv, env);
1401 
1402 		/* Executing the shell failed. */
1403 		perror(shell);
1404 		exit(1);
1405 	}
1406 	/*
1407 	 * Execute the command using the user's shell.  This uses the -c
1408 	 * option to execute the command.
1409 	 */
1410 	argv[0] = (char *) shell0;
1411 	argv[1] = "-c";
1412 	argv[2] = (char *) command;
1413 	argv[3] = NULL;
1414 	execve(shell, argv, env);
1415 	perror(shell);
1416 	exit(1);
1417 }
1418 
1419 Session *
1420 session_new(void)
1421 {
1422 	int i;
1423 	static int did_init = 0;
1424 	if (!did_init) {
1425 		debug("session_new: init");
1426 		for (i = 0; i < MAX_SESSIONS; i++) {
1427 			sessions[i].used = 0;
1428 		}
1429 		did_init = 1;
1430 	}
1431 	for (i = 0; i < MAX_SESSIONS; i++) {
1432 		Session *s = &sessions[i];
1433 		if (! s->used) {
1434 			memset(s, 0, sizeof(*s));
1435 			s->chanid = -1;
1436 			s->ptyfd = -1;
1437 			s->ttyfd = -1;
1438 			s->used = 1;
1439 			s->self = i;
1440 			debug("session_new: session %d", i);
1441 			return s;
1442 		}
1443 	}
1444 	return NULL;
1445 }
1446 
1447 static void
1448 session_dump(void)
1449 {
1450 	int i;
1451 	for (i = 0; i < MAX_SESSIONS; i++) {
1452 		Session *s = &sessions[i];
1453 		debug("dump: used %d session %d %p channel %d pid %d",
1454 		    s->used,
1455 		    s->self,
1456 		    s,
1457 		    s->chanid,
1458 		    s->pid);
1459 	}
1460 }
1461 
1462 int
1463 session_open(Authctxt *authctxt, int chanid)
1464 {
1465 	Session *s = session_new();
1466 	debug("session_open: channel %d", chanid);
1467 	if (s == NULL) {
1468 		error("no more sessions");
1469 		return 0;
1470 	}
1471 	s->authctxt = authctxt;
1472 	s->pw = authctxt->pw;
1473 	if (s->pw == NULL)
1474 		fatal("no user for session %d", s->self);
1475 	debug("session_open: session %d: link with channel %d", s->self, chanid);
1476 	s->chanid = chanid;
1477 	return 1;
1478 }
1479 
1480 static Session *
1481 session_by_channel(int id)
1482 {
1483 	int i;
1484 	for (i = 0; i < MAX_SESSIONS; i++) {
1485 		Session *s = &sessions[i];
1486 		if (s->used && s->chanid == id) {
1487 			debug("session_by_channel: session %d channel %d", i, id);
1488 			return s;
1489 		}
1490 	}
1491 	debug("session_by_channel: unknown channel %d", id);
1492 	session_dump();
1493 	return NULL;
1494 }
1495 
1496 static Session *
1497 session_by_pid(pid_t pid)
1498 {
1499 	int i;
1500 	debug("session_by_pid: pid %d", pid);
1501 	for (i = 0; i < MAX_SESSIONS; i++) {
1502 		Session *s = &sessions[i];
1503 		if (s->used && s->pid == pid)
1504 			return s;
1505 	}
1506 	error("session_by_pid: unknown pid %d", pid);
1507 	session_dump();
1508 	return NULL;
1509 }
1510 
1511 static int
1512 session_window_change_req(Session *s)
1513 {
1514 	s->col = packet_get_int();
1515 	s->row = packet_get_int();
1516 	s->xpixel = packet_get_int();
1517 	s->ypixel = packet_get_int();
1518 	packet_check_eom();
1519 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1520 	return 1;
1521 }
1522 
1523 static int
1524 session_pty_req(Session *s)
1525 {
1526 	u_int len;
1527 	int n_bytes;
1528 
1529 	if (no_pty_flag) {
1530 		debug("Allocating a pty not permitted for this authentication.");
1531 		return 0;
1532 	}
1533 	if (s->ttyfd != -1) {
1534 		packet_disconnect("Protocol error: you already have a pty.");
1535 		return 0;
1536 	}
1537 
1538 	s->term = packet_get_string(&len);
1539 
1540 	if (compat20) {
1541 		s->col = packet_get_int();
1542 		s->row = packet_get_int();
1543 	} else {
1544 		s->row = packet_get_int();
1545 		s->col = packet_get_int();
1546 	}
1547 	s->xpixel = packet_get_int();
1548 	s->ypixel = packet_get_int();
1549 
1550 	if (strcmp(s->term, "") == 0) {
1551 		xfree(s->term);
1552 		s->term = NULL;
1553 	}
1554 
1555 	/* Allocate a pty and open it. */
1556 	debug("Allocating pty.");
1557 	if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1558 		if (s->term)
1559 			xfree(s->term);
1560 		s->term = NULL;
1561 		s->ptyfd = -1;
1562 		s->ttyfd = -1;
1563 		error("session_pty_req: session %d alloc failed", s->self);
1564 		return 0;
1565 	}
1566 	debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1567 
1568 	/* for SSH1 the tty modes length is not given */
1569 	if (!compat20)
1570 		n_bytes = packet_remaining();
1571 	tty_parse_modes(s->ttyfd, &n_bytes);
1572 
1573 	/*
1574 	 * Add a cleanup function to clear the utmp entry and record logout
1575 	 * time in case we call fatal() (e.g., the connection gets closed).
1576 	 */
1577 	fatal_add_cleanup(session_pty_cleanup, (void *)s);
1578 	pty_setowner(s->pw, s->tty);
1579 
1580 	/* Set window size from the packet. */
1581 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1582 
1583 	packet_check_eom();
1584 	session_proctitle(s);
1585 	return 1;
1586 }
1587 
1588 static int
1589 session_subsystem_req(Session *s)
1590 {
1591 	struct stat st;
1592 	u_int len;
1593 	int success = 0;
1594 	char *cmd, *subsys = packet_get_string(&len);
1595 	int i;
1596 
1597 	packet_check_eom();
1598 	log("subsystem request for %.100s", subsys);
1599 
1600 	for (i = 0; i < options.num_subsystems; i++) {
1601 		if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1602 			cmd = options.subsystem_command[i];
1603 			if (stat(cmd, &st) < 0) {
1604 				error("subsystem: cannot stat %s: %s", cmd,
1605 				    strerror(errno));
1606 				break;
1607 			}
1608 			debug("subsystem: exec() %s", cmd);
1609 			s->is_subsystem = 1;
1610 			do_exec(s, cmd);
1611 			success = 1;
1612 			break;
1613 		}
1614 	}
1615 
1616 	if (!success)
1617 		log("subsystem request for %.100s failed, subsystem not found",
1618 		    subsys);
1619 
1620 	xfree(subsys);
1621 	return success;
1622 }
1623 
1624 static int
1625 session_x11_req(Session *s)
1626 {
1627 	int success;
1628 
1629 	s->single_connection = packet_get_char();
1630 	s->auth_proto = packet_get_string(NULL);
1631 	s->auth_data = packet_get_string(NULL);
1632 	s->screen = packet_get_int();
1633 	packet_check_eom();
1634 
1635 	success = session_setup_x11fwd(s);
1636 	if (!success) {
1637 		xfree(s->auth_proto);
1638 		xfree(s->auth_data);
1639 		s->auth_proto = NULL;
1640 		s->auth_data = NULL;
1641 	}
1642 	return success;
1643 }
1644 
1645 static int
1646 session_shell_req(Session *s)
1647 {
1648 	packet_check_eom();
1649 	do_exec(s, NULL);
1650 	return 1;
1651 }
1652 
1653 static int
1654 session_exec_req(Session *s)
1655 {
1656 	u_int len;
1657 	char *command = packet_get_string(&len);
1658 	packet_check_eom();
1659 	do_exec(s, command);
1660 	xfree(command);
1661 	return 1;
1662 }
1663 
1664 static int
1665 session_auth_agent_req(Session *s)
1666 {
1667 	static int called = 0;
1668 	packet_check_eom();
1669 	if (no_agent_forwarding_flag) {
1670 		debug("session_auth_agent_req: no_agent_forwarding_flag");
1671 		return 0;
1672 	}
1673 	if (called) {
1674 		return 0;
1675 	} else {
1676 		called = 1;
1677 		return auth_input_request_forwarding(s->pw);
1678 	}
1679 }
1680 
1681 int
1682 session_input_channel_req(Channel *c, const char *rtype)
1683 {
1684 	int success = 0;
1685 	Session *s;
1686 
1687 	if ((s = session_by_channel(c->self)) == NULL) {
1688 		log("session_input_channel_req: no session %d req %.100s",
1689 		    c->self, rtype);
1690 		return 0;
1691 	}
1692 	debug("session_input_channel_req: session %d req %s", s->self, rtype);
1693 
1694 	/*
1695 	 * a session is in LARVAL state until a shell, a command
1696 	 * or a subsystem is executed
1697 	 */
1698 	if (c->type == SSH_CHANNEL_LARVAL) {
1699 		if (strcmp(rtype, "shell") == 0) {
1700 			success = session_shell_req(s);
1701 		} else if (strcmp(rtype, "exec") == 0) {
1702 			success = session_exec_req(s);
1703 		} else if (strcmp(rtype, "pty-req") == 0) {
1704 			success =  session_pty_req(s);
1705 		} else if (strcmp(rtype, "x11-req") == 0) {
1706 			success = session_x11_req(s);
1707 		} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1708 			success = session_auth_agent_req(s);
1709 		} else if (strcmp(rtype, "subsystem") == 0) {
1710 			success = session_subsystem_req(s);
1711 		}
1712 	}
1713 	if (strcmp(rtype, "window-change") == 0) {
1714 		success = session_window_change_req(s);
1715 	}
1716 	return success;
1717 }
1718 
1719 void
1720 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1721 {
1722 	if (!compat20)
1723 		fatal("session_set_fds: called for proto != 2.0");
1724 	/*
1725 	 * now that have a child and a pipe to the child,
1726 	 * we can activate our channel and register the fd's
1727 	 */
1728 	if (s->chanid == -1)
1729 		fatal("no channel for session %d", s->self);
1730 	channel_set_fds(s->chanid,
1731 	    fdout, fdin, fderr,
1732 	    fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1733 	    1,
1734 	    CHAN_SES_WINDOW_DEFAULT);
1735 }
1736 
1737 /*
1738  * Function to perform pty cleanup. Also called if we get aborted abnormally
1739  * (e.g., due to a dropped connection).
1740  */
1741 static void
1742 session_pty_cleanup(void *session)
1743 {
1744 	Session *s = session;
1745 
1746 	if (s == NULL) {
1747 		error("session_pty_cleanup: no session");
1748 		return;
1749 	}
1750 	if (s->ttyfd == -1)
1751 		return;
1752 
1753 	debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1754 
1755 	/* Record that the user has logged out. */
1756 	if (s->pid != 0)
1757 		record_logout(s->pid, s->tty);
1758 
1759 	/* Release the pseudo-tty. */
1760 	pty_release(s->tty);
1761 
1762 	/*
1763 	 * Close the server side of the socket pairs.  We must do this after
1764 	 * the pty cleanup, so that another process doesn't get this pty
1765 	 * while we're still cleaning up.
1766 	 */
1767 	if (close(s->ptymaster) < 0)
1768 		error("close(s->ptymaster): %s", strerror(errno));
1769 
1770 	/* unlink pty from session */
1771 	s->ttyfd = -1;
1772 }
1773 
1774 static void
1775 session_exit_message(Session *s, int status)
1776 {
1777 	Channel *c;
1778 
1779 	if ((c = channel_lookup(s->chanid)) == NULL)
1780 		fatal("session_exit_message: session %d: no channel %d",
1781 		    s->self, s->chanid);
1782 	debug("session_exit_message: session %d channel %d pid %d",
1783 	    s->self, s->chanid, s->pid);
1784 
1785 	if (WIFEXITED(status)) {
1786 		channel_request_start(s->chanid, "exit-status", 0);
1787 		packet_put_int(WEXITSTATUS(status));
1788 		packet_send();
1789 	} else if (WIFSIGNALED(status)) {
1790 		channel_request_start(s->chanid, "exit-signal", 0);
1791 		packet_put_int(WTERMSIG(status));
1792 		packet_put_char(WCOREDUMP(status));
1793 		packet_put_cstring("");
1794 		packet_put_cstring("");
1795 		packet_send();
1796 	} else {
1797 		/* Some weird exit cause.  Just exit. */
1798 		packet_disconnect("wait returned status %04x.", status);
1799 	}
1800 
1801 	/* disconnect channel */
1802 	debug("session_exit_message: release channel %d", s->chanid);
1803 	channel_cancel_cleanup(s->chanid);
1804 	/*
1805 	 * emulate a write failure with 'chan_write_failed', nobody will be
1806 	 * interested in data we write.
1807 	 * Note that we must not call 'chan_read_failed', since there could
1808 	 * be some more data waiting in the pipe.
1809 	 */
1810 	if (c->ostate != CHAN_OUTPUT_CLOSED)
1811 		chan_write_failed(c);
1812 	s->chanid = -1;
1813 }
1814 
1815 static void
1816 session_close(Session *s)
1817 {
1818 	debug("session_close: session %d pid %d", s->self, s->pid);
1819 	if (s->ttyfd != -1) {
1820 		fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1821 		session_pty_cleanup(s);
1822 	}
1823 	if (s->term)
1824 		xfree(s->term);
1825 	if (s->display)
1826 		xfree(s->display);
1827 	if (s->auth_display)
1828 		xfree(s->auth_display);
1829 	if (s->auth_data)
1830 		xfree(s->auth_data);
1831 	if (s->auth_proto)
1832 		xfree(s->auth_proto);
1833 	s->used = 0;
1834 	session_proctitle(s);
1835 }
1836 
1837 void
1838 session_close_by_pid(pid_t pid, int status)
1839 {
1840 	Session *s = session_by_pid(pid);
1841 	if (s == NULL) {
1842 		debug("session_close_by_pid: no session for pid %d", pid);
1843 		return;
1844 	}
1845 	if (s->chanid != -1)
1846 		session_exit_message(s, status);
1847 	session_close(s);
1848 }
1849 
1850 /*
1851  * this is called when a channel dies before
1852  * the session 'child' itself dies
1853  */
1854 void
1855 session_close_by_channel(int id, void *arg)
1856 {
1857 	Session *s = session_by_channel(id);
1858 	if (s == NULL) {
1859 		debug("session_close_by_channel: no session for id %d", id);
1860 		return;
1861 	}
1862 	debug("session_close_by_channel: channel %d child %d", id, s->pid);
1863 	if (s->pid != 0) {
1864 		debug("session_close_by_channel: channel %d: has child", id);
1865 		/*
1866 		 * delay detach of session, but release pty, since
1867 		 * the fd's to the child are already closed
1868 		 */
1869 		if (s->ttyfd != -1) {
1870 			fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1871 			session_pty_cleanup(s);
1872 		}
1873 		return;
1874 	}
1875 	/* detach by removing callback */
1876 	channel_cancel_cleanup(s->chanid);
1877 	s->chanid = -1;
1878 	session_close(s);
1879 }
1880 
1881 void
1882 session_destroy_all(void)
1883 {
1884 	int i;
1885 	for (i = 0; i < MAX_SESSIONS; i++) {
1886 		Session *s = &sessions[i];
1887 		if (s->used)
1888 			session_close(s);
1889 	}
1890 }
1891 
1892 static char *
1893 session_tty_list(void)
1894 {
1895 	static char buf[1024];
1896 	int i;
1897 	buf[0] = '\0';
1898 	for (i = 0; i < MAX_SESSIONS; i++) {
1899 		Session *s = &sessions[i];
1900 		if (s->used && s->ttyfd != -1) {
1901 			if (buf[0] != '\0')
1902 				strlcat(buf, ",", sizeof buf);
1903 			strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1904 		}
1905 	}
1906 	if (buf[0] == '\0')
1907 		strlcpy(buf, "notty", sizeof buf);
1908 	return buf;
1909 }
1910 
1911 void
1912 session_proctitle(Session *s)
1913 {
1914 	if (s->pw == NULL)
1915 		error("no user for session %d", s->self);
1916 	else
1917 		setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1918 }
1919 
1920 int
1921 session_setup_x11fwd(Session *s)
1922 {
1923 	struct stat st;
1924 	char display[512], auth_display[512];
1925 	char hostname[MAXHOSTNAMELEN];
1926 
1927 	if (no_x11_forwarding_flag) {
1928 		packet_send_debug("X11 forwarding disabled in user configuration file.");
1929 		return 0;
1930 	}
1931 	if (!options.x11_forwarding) {
1932 		debug("X11 forwarding disabled in server configuration file.");
1933 		return 0;
1934 	}
1935 	if (!options.xauth_location ||
1936 	    (stat(options.xauth_location, &st) == -1)) {
1937 		packet_send_debug("No xauth program; cannot forward with spoofing.");
1938 		return 0;
1939 	}
1940 	if (options.use_login) {
1941 		packet_send_debug("X11 forwarding disabled; "
1942 		    "not compatible with UseLogin=yes.");
1943 		return 0;
1944 	}
1945 	if (s->display != NULL) {
1946 		debug("X11 display already set.");
1947 		return 0;
1948 	}
1949 	s->display_number = x11_create_display_inet(options.x11_display_offset,
1950 	    options.x11_use_localhost, s->single_connection);
1951 	if (s->display_number == -1) {
1952 		debug("x11_create_display_inet failed.");
1953 		return 0;
1954 	}
1955 
1956 	/* Set up a suitable value for the DISPLAY variable. */
1957 	if (gethostname(hostname, sizeof(hostname)) < 0)
1958 		fatal("gethostname: %.100s", strerror(errno));
1959 	/*
1960 	 * auth_display must be used as the displayname when the
1961 	 * authorization entry is added with xauth(1).  This will be
1962 	 * different than the DISPLAY string for localhost displays.
1963 	 */
1964 	if (options.x11_use_localhost) {
1965 		snprintf(display, sizeof display, "localhost:%d.%d",
1966 		    s->display_number, s->screen);
1967 		snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1968 		    s->display_number, s->screen);
1969 		s->display = xstrdup(display);
1970 		s->auth_display = xstrdup(auth_display);
1971 	} else {
1972 		snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1973 		    s->display_number, s->screen);
1974 		s->display = xstrdup(display);
1975 		s->auth_display = xstrdup(display);
1976 	}
1977 
1978 	return 1;
1979 }
1980 
1981 static void
1982 do_authenticated2(Authctxt *authctxt)
1983 {
1984 	server_loop2(authctxt);
1985 }
1986