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