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