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