]> andersk Git - gssapi-openssh.git/blame - openssh/session.c
re-fix old bug, re-introduced on re-merge of Simon's code:
[gssapi-openssh.git] / openssh / session.c
CommitLineData
3c0ef626 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"
540d72c3 36RCSID("$OpenBSD: session.c,v 1.172 2004/01/30 09:48:57 markus Exp $");
3c0ef626 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"
350391c5 59#include "monitor_wrap.h"
3c0ef626 60
540d72c3 61#if defined(KRB5) && defined(USE_AFS)
62#include <kafs.h>
63#endif
64
5598e598 65#ifdef GSSAPI
66#include "ssh-gss.h"
67#endif
68
3c0ef626 69/* func */
70
71Session *session_new(void);
72void session_set_fds(Session *, int, int, int);
540d72c3 73void session_pty_cleanup(Session *);
3c0ef626 74void session_proctitle(Session *);
75int session_setup_x11fwd(Session *);
76void do_exec_pty(Session *, const char *);
77void do_exec_no_pty(Session *, const char *);
78void do_exec(Session *, const char *);
79void do_login(Session *, const char *);
80#ifdef LOGIN_NEEDS_UTMPX
81static void do_pre_login(Session *s);
82#endif
83void do_child(Session *, const char *);
84void do_motd(void);
85int check_quietlogin(Session *, const char *);
86
87static void do_authenticated1(Authctxt *);
88static void do_authenticated2(Authctxt *);
89
3c0ef626 90static int session_pty_req(Session *);
91
75be3237 92#ifdef SESSION_HOOKS
93static void execute_session_hook(char* prog, Authctxt *authctxt,
94 int startup, int save);
95#endif
96
3c0ef626 97/* import */
98extern ServerOptions options;
99extern char *__progname;
100extern int log_stderr;
101extern int debug_flag;
102extern u_int utmp_len;
103extern int startup_pipe;
104extern void destroy_sensitive_data(void);
7cac2b65 105extern Buffer loginmsg;
3c0ef626 106
107/* original command from peer. */
108const char *original_command = NULL;
109
110/* data */
111#define MAX_SESSIONS 10
112Session sessions[MAX_SESSIONS];
113
3c0ef626 114#ifdef HAVE_LOGIN_CAP
350391c5 115login_cap_t *lc;
3c0ef626 116#endif
117
540d72c3 118static int is_child = 0;
119
44a053a3 120/* Name and directory of socket for authentication agent forwarding. */
121static char *auth_sock_name = NULL;
122static char *auth_sock_dir = NULL;
123
124/* removes the agent forwarding socket */
125
126static void
540d72c3 127auth_sock_cleanup_proc(struct passwd *pw)
44a053a3 128{
44a053a3 129 if (auth_sock_name != NULL) {
130 temporarily_use_uid(pw);
131 unlink(auth_sock_name);
132 rmdir(auth_sock_dir);
133 auth_sock_name = NULL;
134 restore_uid();
135 }
136}
137
138static int
139auth_input_request_forwarding(struct passwd * pw)
140{
141 Channel *nc;
142 int sock;
143 struct sockaddr_un sunaddr;
144
145 if (auth_sock_name != NULL) {
146 error("authentication forwarding requested twice.");
147 return 0;
148 }
149
150 /* Temporarily drop privileged uid for mkdir/bind. */
151 temporarily_use_uid(pw);
152
153 /* Allocate a buffer for the socket name, and format the name. */
154 auth_sock_name = xmalloc(MAXPATHLEN);
155 auth_sock_dir = xmalloc(MAXPATHLEN);
540d72c3 156 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
44a053a3 157
158 /* Create private directory for socket */
159 if (mkdtemp(auth_sock_dir) == NULL) {
160 packet_send_debug("Agent forwarding disabled: "
161 "mkdtemp() failed: %.100s", strerror(errno));
162 restore_uid();
163 xfree(auth_sock_name);
164 xfree(auth_sock_dir);
165 auth_sock_name = NULL;
166 auth_sock_dir = NULL;
167 return 0;
168 }
169 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
170 auth_sock_dir, (long) getpid());
171
44a053a3 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. */
540d72c3 189 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
44a053a3 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,
7cac2b65 196 0, "auth socket", 1);
44a053a3 197 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198 return 1;
199}
200
540d72c3 201static void
202display_loginmsg(void)
203{
204 if (buffer_len(&loginmsg) > 0) {
205 buffer_append(&loginmsg, "\0", 1);
206 printf("%s\n", (char *)buffer_ptr(&loginmsg));
207 buffer_clear(&loginmsg);
208 }
209}
44a053a3 210
3c0ef626 211void
212do_authenticated(Authctxt *authctxt)
213{
bfe49944 214 setproctitle("%s", authctxt->pw->pw_name);
215
3c0ef626 216 /*
217 * Cancel the alarm we set to limit the time taken for
218 * authentication.
219 */
220 alarm(0);
221 if (startup_pipe != -1) {
222 close(startup_pipe);
223 startup_pipe = -1;
224 }
3c0ef626 225 /* setup the channel layer */
226 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
227 channel_permit_all_opens();
228
229 if (compat20)
230 do_authenticated2(authctxt);
231 else
232 do_authenticated1(authctxt);
233
75be3237 234#ifdef SESSION_HOOKS
235 if (options.session_hooks_allow &&
236 options.session_hooks_shutdown_cmd)
237 {
238 execute_session_hook(options.session_hooks_shutdown_cmd,
239 authctxt,
240 /* startup = */ 0, /* save = */ 0);
241
242 if (authctxt->session_env_file)
243 {
244 free(authctxt->session_env_file);
245 }
246 }
247#endif
540d72c3 248
249 do_cleanup(authctxt);
3c0ef626 250}
251
252/*
253 * Prepares for an interactive session. This is called after the user has
254 * been successfully authenticated. During this message exchange, pseudo
255 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
256 * are requested, etc.
257 */
258static void
259do_authenticated1(Authctxt *authctxt)
260{
261 Session *s;
262 char *command;
e9702f7d 263 int success, type, screen_flag;
276b07a3 264 int enable_compression_after_reply = 0;
265 u_int proto_len, data_len, dlen, compression_level = 0;
3c0ef626 266
267 s = session_new();
268 s->authctxt = authctxt;
269 s->pw = authctxt->pw;
270
271 /*
272 * We stay in this loop until the client requests to execute a shell
273 * or a command.
274 */
275 for (;;) {
276 success = 0;
277
278 /* Get a packet from the client. */
e9702f7d 279 type = packet_read();
3c0ef626 280
281 /* Process the packet. */
282 switch (type) {
283 case SSH_CMSG_REQUEST_COMPRESSION:
3c0ef626 284 compression_level = packet_get_int();
e9702f7d 285 packet_check_eom();
3c0ef626 286 if (compression_level < 1 || compression_level > 9) {
287 packet_send_debug("Received illegal compression level %d.",
e9702f7d 288 compression_level);
3c0ef626 289 break;
290 }
44a053a3 291 if (!options.compression) {
292 debug2("compression disabled");
293 break;
294 }
3c0ef626 295 /* Enable compression after we have responded with SUCCESS. */
296 enable_compression_after_reply = 1;
297 success = 1;
298 break;
299
300 case SSH_CMSG_REQUEST_PTY:
301 success = session_pty_req(s);
302 break;
303
304 case SSH_CMSG_X11_REQUEST_FORWARDING:
305 s->auth_proto = packet_get_string(&proto_len);
306 s->auth_data = packet_get_string(&data_len);
307
308 screen_flag = packet_get_protocol_flags() &
309 SSH_PROTOFLAG_SCREEN_NUMBER;
310 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
311
312 if (packet_remaining() == 4) {
313 if (!screen_flag)
314 debug2("Buggy client: "
315 "X11 screen flag missing");
316 s->screen = packet_get_int();
317 } else {
318 s->screen = 0;
319 }
e9702f7d 320 packet_check_eom();
3c0ef626 321 success = session_setup_x11fwd(s);
322 if (!success) {
323 xfree(s->auth_proto);
324 xfree(s->auth_data);
325 s->auth_proto = NULL;
326 s->auth_data = NULL;
327 }
328 break;
329
330 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
331 if (no_agent_forwarding_flag || compat13) {
332 debug("Authentication agent forwarding not permitted for this authentication.");
333 break;
334 }
335 debug("Received authentication agent forwarding request.");
336 success = auth_input_request_forwarding(s->pw);
337 break;
338
339 case SSH_CMSG_PORT_FORWARD_REQUEST:
340 if (no_port_forwarding_flag) {
341 debug("Port forwarding not permitted for this authentication.");
342 break;
343 }
344 if (!options.allow_tcp_forwarding) {
345 debug("Port forwarding not permitted.");
346 break;
347 }
348 debug("Received TCP/IP port forwarding request.");
349 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
350 success = 1;
351 break;
352
353 case SSH_CMSG_MAX_PACKET_SIZE:
354 if (packet_set_maxsize(packet_get_int()) > 0)
355 success = 1;
356 break;
e9702f7d 357
3c0ef626 358 case SSH_CMSG_EXEC_SHELL:
359 case SSH_CMSG_EXEC_CMD:
360 if (type == SSH_CMSG_EXEC_CMD) {
361 command = packet_get_string(&dlen);
362 debug("Exec command '%.500s'", command);
363 do_exec(s, command);
364 xfree(command);
365 } else {
366 do_exec(s, NULL);
367 }
e9702f7d 368 packet_check_eom();
3c0ef626 369 session_close(s);
370 return;
371
372 default:
373 /*
374 * Any unknown messages in this phase are ignored,
375 * and a failure message is returned.
376 */
7cac2b65 377 logit("Unknown packet type received after authentication: %d", type);
3c0ef626 378 }
379 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
380 packet_send();
381 packet_write_wait();
382
383 /* Enable compression now that we have replied if appropriate. */
384 if (enable_compression_after_reply) {
385 enable_compression_after_reply = 0;
386 packet_start_compression(compression_level);
387 }
388 }
389}
390
391/*
392 * This is called to fork and execute a command when we have no tty. This
393 * will call do_child from the child, and server_loop from the parent after
394 * setting up file descriptors and such.
395 */
396void
397do_exec_no_pty(Session *s, const char *command)
398{
44a053a3 399 pid_t pid;
3c0ef626 400
401#ifdef USE_PIPES
402 int pin[2], pout[2], perr[2];
403 /* Allocate pipes for communicating with the program. */
404 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
405 packet_disconnect("Could not create pipes: %.100s",
406 strerror(errno));
407#else /* USE_PIPES */
408 int inout[2], err[2];
409 /* Uses socket pairs to communicate with the program. */
410 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
411 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
412 packet_disconnect("Could not create socket pairs: %.100s",
413 strerror(errno));
414#endif /* USE_PIPES */
415 if (s == NULL)
416 fatal("do_exec_no_pty: no session");
417
418 session_proctitle(s);
419
420#if defined(USE_PAM)
540d72c3 421 if (options.use_pam && !use_privsep)
7cac2b65 422 do_pam_setcred(1);
3c0ef626 423#endif /* USE_PAM */
424
425 /* Fork the child. */
426 if ((pid = fork()) == 0) {
540d72c3 427 is_child = 1;
d03f4262 428
3c0ef626 429 /* Child. Reinitialize the log since the pid has changed. */
430 log_init(__progname, options.log_level, options.log_facility, log_stderr);
431
432 /*
433 * Create a new session and process group since the 4.4BSD
434 * setlogin() affects the entire process group.
435 */
436 if (setsid() < 0)
437 error("setsid failed: %.100s", strerror(errno));
438
439#ifdef USE_PIPES
440 /*
441 * Redirect stdin. We close the parent side of the socket
442 * pair, and make the child side the standard input.
443 */
444 close(pin[1]);
445 if (dup2(pin[0], 0) < 0)
446 perror("dup2 stdin");
447 close(pin[0]);
448
449 /* Redirect stdout. */
450 close(pout[0]);
451 if (dup2(pout[1], 1) < 0)
452 perror("dup2 stdout");
453 close(pout[1]);
454
455 /* Redirect stderr. */
456 close(perr[0]);
457 if (dup2(perr[1], 2) < 0)
458 perror("dup2 stderr");
459 close(perr[1]);
460#else /* USE_PIPES */
461 /*
462 * Redirect stdin, stdout, and stderr. Stdin and stdout will
463 * use the same socket, as some programs (particularly rdist)
464 * seem to depend on it.
465 */
466 close(inout[1]);
467 close(err[1]);
468 if (dup2(inout[0], 0) < 0) /* stdin */
469 perror("dup2 stdin");
470 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
471 perror("dup2 stdout");
472 if (dup2(err[0], 2) < 0) /* stderr */
473 perror("dup2 stderr");
474#endif /* USE_PIPES */
475
d03f4262 476#ifdef _UNICOS
477 cray_init_job(s->pw); /* set up cray jid and tmpdir */
478#endif
479
3c0ef626 480 /* Do processing for the child (exec command etc). */
481 do_child(s, command);
482 /* NOTREACHED */
483 }
d03f4262 484#ifdef _UNICOS
485 signal(WJSIGNAL, cray_job_termination_handler);
486#endif /* _UNICOS */
3c0ef626 487#ifdef HAVE_CYGWIN
488 if (is_winnt)
489 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
490#endif
491 if (pid < 0)
492 packet_disconnect("fork failed: %.100s", strerror(errno));
493 s->pid = pid;
494 /* Set interactive/non-interactive mode. */
495 packet_set_interactive(s->display != NULL);
496#ifdef USE_PIPES
497 /* We are the parent. Close the child sides of the pipes. */
498 close(pin[0]);
499 close(pout[1]);
500 close(perr[1]);
501
502 if (compat20) {
503 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
504 } else {
505 /* Enter the interactive session. */
506 server_loop(pid, pin[1], pout[0], perr[0]);
507 /* server_loop has closed pin[1], pout[0], and perr[0]. */
508 }
509#else /* USE_PIPES */
510 /* We are the parent. Close the child sides of the socket pairs. */
511 close(inout[0]);
512 close(err[0]);
513
514 /*
515 * Enter the interactive session. Note: server_loop must be able to
516 * handle the case that fdin and fdout are the same.
517 */
518 if (compat20) {
519 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
520 } else {
521 server_loop(pid, inout[1], inout[1], err[1]);
522 /* server_loop has closed inout[1] and err[1]. */
523 }
524#endif /* USE_PIPES */
525}
526
527/*
528 * This is called to fork and execute a command when we have a tty. This
529 * will call do_child from the child, and server_loop from the parent after
530 * setting up file descriptors, controlling tty, updating wtmp, utmp,
531 * lastlog, and other such operations.
532 */
533void
534do_exec_pty(Session *s, const char *command)
535{
536 int fdout, ptyfd, ttyfd, ptymaster;
537 pid_t pid;
538
539 if (s == NULL)
540 fatal("do_exec_pty: no session");
541 ptyfd = s->ptyfd;
542 ttyfd = s->ttyfd;
543
544#if defined(USE_PAM)
7cac2b65 545 if (options.use_pam) {
546 do_pam_set_tty(s->tty);
540d72c3 547 if (!use_privsep)
548 do_pam_setcred(1);
7cac2b65 549 }
3c0ef626 550#endif
551
552 /* Fork the child. */
553 if ((pid = fork()) == 0) {
540d72c3 554 is_child = 1;
3c0ef626 555
556 /* Child. Reinitialize the log because the pid has changed. */
557 log_init(__progname, options.log_level, options.log_facility, log_stderr);
558 /* Close the master side of the pseudo tty. */
559 close(ptyfd);
560
561 /* Make the pseudo tty our controlling tty. */
562 pty_make_controlling_tty(&ttyfd, s->tty);
563
564 /* Redirect stdin/stdout/stderr from the pseudo tty. */
565 if (dup2(ttyfd, 0) < 0)
566 error("dup2 stdin: %s", strerror(errno));
567 if (dup2(ttyfd, 1) < 0)
568 error("dup2 stdout: %s", strerror(errno));
569 if (dup2(ttyfd, 2) < 0)
570 error("dup2 stderr: %s", strerror(errno));
571
572 /* Close the extra descriptor for the pseudo tty. */
573 close(ttyfd);
574
575 /* record login, etc. similar to login(1) */
576#ifndef HAVE_OSF_SIA
d03f4262 577 if (!(options.use_login && command == NULL)) {
578#ifdef _UNICOS
579 cray_init_job(s->pw); /* set up cray jid and tmpdir */
580#endif /* _UNICOS */
3c0ef626 581 do_login(s, command);
d03f4262 582 }
3c0ef626 583# ifdef LOGIN_NEEDS_UTMPX
584 else
585 do_pre_login(s);
586# endif
587#endif
588
589 /* Do common processing for the child, such as execing the command. */
590 do_child(s, command);
591 /* NOTREACHED */
592 }
d03f4262 593#ifdef _UNICOS
594 signal(WJSIGNAL, cray_job_termination_handler);
595#endif /* _UNICOS */
3c0ef626 596#ifdef HAVE_CYGWIN
597 if (is_winnt)
598 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
599#endif
600 if (pid < 0)
601 packet_disconnect("fork failed: %.100s", strerror(errno));
602 s->pid = pid;
603
604 /* Parent. Close the slave side of the pseudo tty. */
605 close(ttyfd);
606
607 /*
608 * Create another descriptor of the pty master side for use as the
609 * standard input. We could use the original descriptor, but this
610 * simplifies code in server_loop. The descriptor is bidirectional.
611 */
612 fdout = dup(ptyfd);
613 if (fdout < 0)
614 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
615
616 /* we keep a reference to the pty master */
617 ptymaster = dup(ptyfd);
618 if (ptymaster < 0)
619 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
620 s->ptymaster = ptymaster;
621
622 /* Enter interactive session. */
623 packet_set_interactive(1);
624 if (compat20) {
625 session_set_fds(s, ptyfd, fdout, -1);
626 } else {
627 server_loop(pid, ptyfd, fdout, -1);
628 /* server_loop _has_ closed ptyfd and fdout. */
629 }
630}
631
632#ifdef LOGIN_NEEDS_UTMPX
633static void
634do_pre_login(Session *s)
635{
636 socklen_t fromlen;
637 struct sockaddr_storage from;
638 pid_t pid = getpid();
639
640 /*
641 * Get IP address of client. If the connection is not a socket, let
642 * the address be 0.0.0.0.
643 */
644 memset(&from, 0, sizeof(from));
d03f4262 645 fromlen = sizeof(from);
3c0ef626 646 if (packet_connection_is_on_socket()) {
3c0ef626 647 if (getpeername(packet_get_connection_in(),
e9702f7d 648 (struct sockaddr *) & from, &fromlen) < 0) {
3c0ef626 649 debug("getpeername: %.100s", strerror(errno));
540d72c3 650 cleanup_exit(255);
3c0ef626 651 }
652 }
653
654 record_utmp_only(pid, s->tty, s->pw->pw_name,
7cac2b65 655 get_remote_name_or_ip(utmp_len, options.use_dns),
bfe49944 656 (struct sockaddr *)&from, fromlen);
3c0ef626 657}
658#endif
659
660/*
661 * This is called to fork and execute a command. If another command is
662 * to be forced, execute that instead.
663 */
664void
665do_exec(Session *s, const char *command)
666{
667 if (forced_command) {
668 original_command = command;
669 command = forced_command;
670 debug("Forced command '%.900s'", command);
671 }
672
7cac2b65 673#if defined(SESSION_HOOKS)
674 if (options.session_hooks_allow &&
675 (options.session_hooks_startup_cmd ||
676 options.session_hooks_shutdown_cmd))
677 {
678 char env_file[1000];
679 struct stat st;
680 do
681 {
682 snprintf(env_file,
683 sizeof(env_file),
684 "/tmp/ssh_env_%d%d%d",
685 getuid(),
686 getpid(),
687 rand());
688 } while (stat(env_file, &st)==0);
689 s->authctxt->session_env_file = strdup(env_file);
690 }
691#endif
692
693#ifdef GSSAPI
694 if (options.gss_authentication) {
695 temporarily_use_uid(s->pw);
696 ssh_gssapi_storecreds();
697 restore_uid();
698 }
699#endif
700
3c0ef626 701 if (s->ttyfd != -1)
702 do_exec_pty(s, command);
703 else
704 do_exec_no_pty(s, command);
705
706 original_command = NULL;
707}
708
e9702f7d 709
3c0ef626 710/* administrative, login(1)-like work */
711void
712do_login(Session *s, const char *command)
713{
714 char *time_string;
3c0ef626 715 socklen_t fromlen;
716 struct sockaddr_storage from;
3c0ef626 717 struct passwd * pw = s->pw;
718 pid_t pid = getpid();
719
720 /*
721 * Get IP address of client. If the connection is not a socket, let
722 * the address be 0.0.0.0.
723 */
724 memset(&from, 0, sizeof(from));
bfe49944 725 fromlen = sizeof(from);
3c0ef626 726 if (packet_connection_is_on_socket()) {
3c0ef626 727 if (getpeername(packet_get_connection_in(),
e9702f7d 728 (struct sockaddr *) & from, &fromlen) < 0) {
3c0ef626 729 debug("getpeername: %.100s", strerror(errno));
540d72c3 730 cleanup_exit(255);
3c0ef626 731 }
732 }
733
3c0ef626 734 /* Record that there was a login on that tty from the remote host. */
350391c5 735 if (!use_privsep)
736 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
737 get_remote_name_or_ip(utmp_len,
7cac2b65 738 options.use_dns),
d03f4262 739 (struct sockaddr *)&from, fromlen);
3c0ef626 740
741#ifdef USE_PAM
742 /*
743 * If password change is needed, do it now.
744 * This needs to occur before the ~/.hushlogin check.
745 */
540d72c3 746 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
747 display_loginmsg();
3c0ef626 748 do_pam_chauthtok();
540d72c3 749 s->authctxt->force_pwchange = 0;
7cac2b65 750 /* XXX - signal [net] parent to enable forwardings */
3c0ef626 751 }
752#endif
753
754 if (check_quietlogin(s, command))
755 return;
756
540d72c3 757 display_loginmsg();
3c0ef626 758
d03f4262 759#ifndef NO_SSH_LASTLOG
350391c5 760 if (options.print_lastlog && s->last_login_time != 0) {
761 time_string = ctime(&s->last_login_time);
3c0ef626 762 if (strchr(time_string, '\n'))
763 *strchr(time_string, '\n') = 0;
350391c5 764 if (strcmp(s->hostname, "") == 0)
3c0ef626 765 printf("Last login: %s\r\n", time_string);
766 else
350391c5 767 printf("Last login: %s from %s\r\n", time_string,
768 s->hostname);
3c0ef626 769 }
d03f4262 770#endif /* NO_SSH_LASTLOG */
3c0ef626 771
772 do_motd();
773}
774
775/*
776 * Display the message of the day.
777 */
778void
779do_motd(void)
780{
781 FILE *f;
782 char buf[256];
783
784 if (options.print_motd) {
785#ifdef HAVE_LOGIN_CAP
786 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
787 "/etc/motd"), "r");
788#else
789 f = fopen("/etc/motd", "r");
790#endif
791 if (f) {
792 while (fgets(buf, sizeof(buf), f))
793 fputs(buf, stdout);
794 fclose(f);
795 }
796 }
797}
798
799
800/*
801 * Check for quiet login, either .hushlogin or command given.
802 */
803int
804check_quietlogin(Session *s, const char *command)
805{
806 char buf[256];
807 struct passwd *pw = s->pw;
808 struct stat st;
809
810 /* Return 1 if .hushlogin exists or a command given. */
811 if (command != NULL)
812 return 1;
813 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
814#ifdef HAVE_LOGIN_CAP
815 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
816 return 1;
817#else
818 if (stat(buf, &st) >= 0)
819 return 1;
820#endif
821 return 0;
822}
823
824/*
825 * Sets the value of the given variable in the environment. If the variable
826 * already exists, its value is overriden.
827 */
5598e598 828void
3c0ef626 829child_set_env(char ***envp, u_int *envsizep, const char *name,
e9702f7d 830 const char *value)
3c0ef626 831{
3c0ef626 832 char **env;
29d88157 833 u_int envsize;
834 u_int i, namelen;
3c0ef626 835
7cac2b65 836 /*
837 * If we're passed an uninitialized list, allocate a single null
838 * entry before continuing.
839 */
840 if (*envp == NULL && *envsizep == 0) {
841 *envp = xmalloc(sizeof(char *));
842 *envp[0] = NULL;
843 *envsizep = 1;
844 }
845
3c0ef626 846 /*
847 * Find the slot where the value should be stored. If the variable
848 * already exists, we reuse the slot; otherwise we append a new slot
849 * at the end of the array, expanding if necessary.
850 */
851 env = *envp;
852 namelen = strlen(name);
853 for (i = 0; env[i]; i++)
854 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
855 break;
856 if (env[i]) {
857 /* Reuse the slot. */
858 xfree(env[i]);
859 } else {
860 /* New variable. Expand if necessary. */
29d88157 861 envsize = *envsizep;
862 if (i >= envsize - 1) {
863 if (envsize >= 1000)
864 fatal("child_set_env: too many env vars");
865 envsize += 50;
866 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
867 *envsizep = envsize;
3c0ef626 868 }
869 /* Need to set the NULL pointer at end of array beyond the new slot. */
870 env[i + 1] = NULL;
871 }
872
873 /* Allocate space and format the variable in the appropriate slot. */
874 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
875 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
876}
877
878/*
879 * Reads environment variables from the given file and adds/overrides them
880 * into the environment. If the file does not exist, this does nothing.
881 * Otherwise, it must consist of empty lines, comments (line starts with '#')
882 * and assignments of the form name=value. No other forms are allowed.
883 */
884static void
885read_environment_file(char ***env, u_int *envsize,
e9702f7d 886 const char *filename)
3c0ef626 887{
888 FILE *f;
889 char buf[4096];
890 char *cp, *value;
276b07a3 891 u_int lineno = 0;
3c0ef626 892
893 f = fopen(filename, "r");
894 if (!f)
895 return;
896
897 while (fgets(buf, sizeof(buf), f)) {
276b07a3 898 if (++lineno > 1000)
899 fatal("Too many lines in environment file %s", filename);
3c0ef626 900 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
901 ;
902 if (!*cp || *cp == '#' || *cp == '\n')
903 continue;
904 if (strchr(cp, '\n'))
905 *strchr(cp, '\n') = '\0';
906 value = strchr(cp, '=');
907 if (value == NULL) {
276b07a3 908 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
909 filename);
3c0ef626 910 continue;
911 }
912 /*
913 * Replace the equals sign by nul, and advance value to
914 * the value string.
915 */
916 *value = '\0';
917 value++;
918 child_set_env(env, envsize, cp, value);
919 }
920 fclose(f);
921}
922
75be3237 923#ifdef SESSION_HOOKS
924#define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
925
926typedef enum { no_op, execute, clear_env, restore_env,
927 read_env, save_or_rm_env } session_action_t;
928
929static session_action_t action_order[2][5] = {
930 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
931 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
932};
933
934static
935void execute_session_hook(char* prog, Authctxt *authctxt,
936 int startup, int save)
937{
938 extern char **environ;
939
940 struct stat st;
941 char **saved_env, **tmpenv;
942 char *env_file = authctxt->session_env_file;
943 int i, status = 0;
944
945 for (i=0; i<5; i++)
946 {
947 switch (action_order[startup][i])
948 {
949 case no_op:
950 break;
951
952 case execute:
953 {
954 FILE* fp;
955 char buf[1000];
956
957 snprintf(buf,
958 sizeof(buf),
959 "%s -c '%s'",
960 authctxt->pw->pw_shell,
961 prog);
962
963 debug("executing session hook: [%s]", buf);
964 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
965
966 /* flusing is recommended in the popen(3) man page, to avoid
967 intermingling of output */
968 fflush(stdout);
969 fflush(stderr);
970 if ((fp=popen(buf, "w")) == NULL)
971 {
972 perror("Unable to run session hook");
973 return;
974 }
975 status = pclose(fp);
976 debug2("session hook executed, status=%d", status);
977 unsetenv(SSH_SESSION_ENV_FILE);
978 }
979 break;
980
981 case clear_env:
982 saved_env = environ;
983 tmpenv = (char**) malloc(sizeof(char*));
984 tmpenv[0] = NULL;
985 environ = tmpenv;
986 break;
987
988 case restore_env:
989 environ = saved_env;
990 free(tmpenv);
991 break;
992
993 case read_env:
994 if (status==0 && stat(env_file, &st)==0)
995 {
996 int envsize = 0;
997
998 debug("reading environment from %s", env_file);
999 while (environ[envsize++]) ;
1000 read_environment_file(&environ, &envsize, env_file);
1001 }
1002 break;
1003
1004 case save_or_rm_env:
1005 if (status==0 && save)
1006 {
1007 FILE* fp;
1008 int envcount=0;
1009
1010 debug2("saving environment to %s", env_file);
1011 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1012 {
1013 perror("Unable to save session hook info");
1014 }
1015 while (environ[envcount])
1016 {
1017 fprintf(fp, "%s\n", environ[envcount++]);
1018 }
1019 fflush(fp);
1020 fclose(fp);
1021 }
1022 else if (stat(env_file, &st)==0)
1023 {
1024 debug2("removing environment file %s", env_file);
1025 remove(env_file);
1026 }
1027 break;
1028 }
1029 }
1030
1031}
1032#endif
1033
7cac2b65 1034#ifdef HAVE_ETC_DEFAULT_LOGIN
1035/*
1036 * Return named variable from specified environment, or NULL if not present.
1037 */
1038static char *
1039child_get_env(char **env, const char *name)
1040{
1041 int i;
1042 size_t len;
1043
1044 len = strlen(name);
1045 for (i=0; env[i] != NULL; i++)
1046 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1047 return(env[i] + len + 1);
1048 return NULL;
1049}
1050
1051/*
1052 * Read /etc/default/login.
1053 * We pick up the PATH (or SUPATH for root) and UMASK.
1054 */
1055static void
1056read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1057{
1058 char **tmpenv = NULL, *var;
29d88157 1059 u_int i, tmpenvsize = 0;
540d72c3 1060 u_long mask;
7cac2b65 1061
1062 /*
1063 * We don't want to copy the whole file to the child's environment,
1064 * so we use a temporary environment and copy the variables we're
1065 * interested in.
1066 */
1067 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1068
29d88157 1069 if (tmpenv == NULL)
1070 return;
1071
7cac2b65 1072 if (uid == 0)
1073 var = child_get_env(tmpenv, "SUPATH");
1074 else
1075 var = child_get_env(tmpenv, "PATH");
1076 if (var != NULL)
1077 child_set_env(env, envsize, "PATH", var);
540d72c3 1078
7cac2b65 1079 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1080 if (sscanf(var, "%5lo", &mask) == 1)
540d72c3 1081 umask((mode_t)mask);
1082
7cac2b65 1083 for (i = 0; tmpenv[i] != NULL; i++)
1084 xfree(tmpenv[i]);
1085 xfree(tmpenv);
1086}
1087#endif /* HAVE_ETC_DEFAULT_LOGIN */
1088
e9702f7d 1089void copy_environment(char **source, char ***env, u_int *envsize)
3c0ef626 1090{
e9702f7d 1091 char *var_name, *var_val;
3c0ef626 1092 int i;
1093
e9702f7d 1094 if (source == NULL)
3c0ef626 1095 return;
1096
e9702f7d 1097 for(i = 0; source[i] != NULL; i++) {
1098 var_name = xstrdup(source[i]);
1099 if ((var_val = strstr(var_name, "=")) == NULL) {
1100 xfree(var_name);
3c0ef626 1101 continue;
3c0ef626 1102 }
e9702f7d 1103 *var_val++ = '\0';
3c0ef626 1104
e9702f7d 1105 debug3("Copy environment: %s=%s", var_name, var_val);
1106 child_set_env(env, envsize, var_name, var_val);
540d72c3 1107
e9702f7d 1108 xfree(var_name);
3c0ef626 1109 }
3c0ef626 1110}
1111
e9702f7d 1112static char **
1113do_setup_env(Session *s, const char *shell)
3c0ef626 1114{
3c0ef626 1115 char buf[256];
e9702f7d 1116 u_int i, envsize;
7cac2b65 1117 char **env, *laddr, *path = NULL;
e9702f7d 1118 struct passwd *pw = s->pw;
3c0ef626 1119
1120 /* Initialize the environment. */
1121 envsize = 100;
1122 env = xmalloc(envsize * sizeof(char *));
1123 env[0] = NULL;
1124
1125#ifdef HAVE_CYGWIN
1126 /*
1127 * The Windows environment contains some setting which are
1128 * important for a running system. They must not be dropped.
1129 */
e9702f7d 1130 copy_environment(environ, &env, &envsize);
3c0ef626 1131#endif
1132
5598e598 1133#ifdef GSSAPI
540d72c3 1134 /* Allow any GSSAPI methods that we've used to alter
5598e598 1135 * the childs environment as they see fit
1136 */
7cac2b65 1137 ssh_gssapi_do_child(&env, &envsize);
5598e598 1138#endif
1139
3c0ef626 1140 if (!options.use_login) {
1141 /* Set basic environment. */
1142 child_set_env(&env, &envsize, "USER", pw->pw_name);
1143 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
bfe49944 1144#ifdef _AIX
1145 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1146#endif
3c0ef626 1147 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1148#ifdef HAVE_LOGIN_CAP
d03f4262 1149 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1150 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1151 else
1152 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
3c0ef626 1153#else /* HAVE_LOGIN_CAP */
1154# ifndef HAVE_CYGWIN
1155 /*
1156 * There's no standard path on Windows. The path contains
1157 * important components pointing to the system directories,
1158 * needed for loading shared libraries. So the path better
1159 * remains intact here.
1160 */
2a67a1d1 1161 if (getenv("LD_LIBRARY_PATH"))
1162 child_set_env(&env, &envsize, "LD_LIBRARY_PATH",
1163 getenv("LD_LIBRARY_PATH"));
7cac2b65 1164# ifdef HAVE_ETC_DEFAULT_LOGIN
1165 read_etc_default_login(&env, &envsize, pw->pw_uid);
1166 path = child_get_env(env, "PATH");
1167# endif /* HAVE_ETC_DEFAULT_LOGIN */
1168 if (path == NULL || *path == '\0') {
540d72c3 1169 child_set_env(&env, &envsize, "PATH",
7cac2b65 1170 s->pw->pw_uid == 0 ?
1171 SUPERUSER_PATH : _PATH_STDPATH);
1172 }
3c0ef626 1173# endif /* HAVE_CYGWIN */
1174#endif /* HAVE_LOGIN_CAP */
1175
1176 snprintf(buf, sizeof buf, "%.200s/%.50s",
1177 _PATH_MAILDIR, pw->pw_name);
1178 child_set_env(&env, &envsize, "MAIL", buf);
1179
1180 /* Normal systems set SHELL by default. */
1181 child_set_env(&env, &envsize, "SHELL", shell);
1182 }
1183 if (getenv("TZ"))
1184 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1185
1186 /* Set custom environment options from RSA authentication. */
1187 if (!options.use_login) {
1188 while (custom_environment) {
1189 struct envstring *ce = custom_environment;
d03f4262 1190 char *str = ce->s;
e9702f7d 1191
d03f4262 1192 for (i = 0; str[i] != '=' && str[i]; i++)
3c0ef626 1193 ;
d03f4262 1194 if (str[i] == '=') {
1195 str[i] = 0;
1196 child_set_env(&env, &envsize, str, str + i + 1);
3c0ef626 1197 }
1198 custom_environment = ce->next;
1199 xfree(ce->s);
1200 xfree(ce);
1201 }
1202 }
1203
d03f4262 1204 /* SSH_CLIENT deprecated */
3c0ef626 1205 snprintf(buf, sizeof buf, "%.50s %d %d",
e9702f7d 1206 get_remote_ipaddr(), get_remote_port(), get_local_port());
3c0ef626 1207 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1208
bfe49944 1209 laddr = get_local_ipaddr(packet_get_connection_in());
d03f4262 1210 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
bfe49944 1211 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1212 xfree(laddr);
d03f4262 1213 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1214
3c0ef626 1215 if (s->ttyfd != -1)
1216 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1217 if (s->term)
1218 child_set_env(&env, &envsize, "TERM", s->term);
1219 if (s->display)
1220 child_set_env(&env, &envsize, "DISPLAY", s->display);
1221 if (original_command)
1222 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1223 original_command);
1224
d03f4262 1225#ifdef _UNICOS
1226 if (cray_tmpdir[0] != '\0')
1227 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1228#endif /* _UNICOS */
1229
3c0ef626 1230#ifdef _AIX
e9702f7d 1231 {
1232 char *cp;
1233
1234 if ((cp = getenv("AUTHSTATE")) != NULL)
1235 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1236 if ((cp = getenv("KRB5CCNAME")) != NULL)
1237 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1238 read_environment_file(&env, &envsize, "/etc/environment");
1239 }
3c0ef626 1240#endif
3c0ef626 1241#ifdef KRB5
1242 if (s->authctxt->krb5_ticket_file)
1243 child_set_env(&env, &envsize, "KRB5CCNAME",
1244 s->authctxt->krb5_ticket_file);
1245#endif
1246#ifdef USE_PAM
d03f4262 1247 /*
1248 * Pull in any environment variables that may have
1249 * been set by PAM.
1250 */
7cac2b65 1251 if (options.use_pam) {
540d72c3 1252 char **p;
d03f4262 1253
540d72c3 1254 p = fetch_pam_child_environment();
1255 copy_environment(p, &env, &envsize);
1256 free_pam_environment(p);
1257
1258 p = fetch_pam_environment();
d03f4262 1259 copy_environment(p, &env, &envsize);
1260 free_pam_environment(p);
1261 }
3c0ef626 1262#endif /* USE_PAM */
1263
44a053a3 1264 if (auth_sock_name != NULL)
3c0ef626 1265 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
44a053a3 1266 auth_sock_name);
3c0ef626 1267
1268 /* read $HOME/.ssh/environment. */
d03f4262 1269 if (options.permit_user_env && !options.use_login) {
3c0ef626 1270 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
d03f4262 1271 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
3c0ef626 1272 read_environment_file(&env, &envsize, buf);
1273 }
1274 if (debug_flag) {
1275 /* dump the environment */
1276 fprintf(stderr, "Environment:\n");
1277 for (i = 0; env[i]; i++)
1278 fprintf(stderr, " %.200s\n", env[i]);
1279 }
e9702f7d 1280 return env;
1281}
1282
1283/*
1284 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1285 * first in this order).
1286 */
1287static void
1288do_rc_files(Session *s, const char *shell)
1289{
1290 FILE *f = NULL;
1291 char cmd[1024];
1292 int do_xauth;
1293 struct stat st;
1294
1295 do_xauth =
1296 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1297
1298 /* ignore _PATH_SSH_USER_RC for subsystems */
1299 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1300 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1301 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1302 if (debug_flag)
1303 fprintf(stderr, "Running %s\n", cmd);
1304 f = popen(cmd, "w");
1305 if (f) {
1306 if (do_xauth)
1307 fprintf(f, "%s %s\n", s->auth_proto,
1308 s->auth_data);
1309 pclose(f);
1310 } else
1311 fprintf(stderr, "Could not run %s\n",
1312 _PATH_SSH_USER_RC);
1313 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1314 if (debug_flag)
1315 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1316 _PATH_SSH_SYSTEM_RC);
1317 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1318 if (f) {
1319 if (do_xauth)
1320 fprintf(f, "%s %s\n", s->auth_proto,
1321 s->auth_data);
1322 pclose(f);
1323 } else
1324 fprintf(stderr, "Could not run %s\n",
1325 _PATH_SSH_SYSTEM_RC);
1326 } else if (do_xauth && options.xauth_location != NULL) {
1327 /* Add authority data to .Xauthority if appropriate. */
1328 if (debug_flag) {
1329 fprintf(stderr,
bfe49944 1330 "Running %.500s remove %.100s\n",
540d72c3 1331 options.xauth_location, s->auth_display);
bfe49944 1332 fprintf(stderr,
1333 "%.500s add %.100s %.100s %.100s\n",
e9702f7d 1334 options.xauth_location, s->auth_display,
1335 s->auth_proto, s->auth_data);
1336 }
1337 snprintf(cmd, sizeof cmd, "%s -q -",
1338 options.xauth_location);
1339 f = popen(cmd, "w");
1340 if (f) {
bfe49944 1341 fprintf(f, "remove %s\n",
1342 s->auth_display);
e9702f7d 1343 fprintf(f, "add %s %s %s\n",
1344 s->auth_display, s->auth_proto,
1345 s->auth_data);
1346 pclose(f);
1347 } else {
1348 fprintf(stderr, "Could not run %s\n",
1349 cmd);
1350 }
1351 }
1352}
1353
1354static void
1355do_nologin(struct passwd *pw)
1356{
1357 FILE *f = NULL;
1358 char buf[1024];
1359
1360#ifdef HAVE_LOGIN_CAP
1361 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1362 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1363 _PATH_NOLOGIN), "r");
1364#else
1365 if (pw->pw_uid)
1366 f = fopen(_PATH_NOLOGIN, "r");
1367#endif
1368 if (f) {
1369 /* /etc/nologin exists. Print its contents and exit. */
7cac2b65 1370 logit("User %.100s not allowed because %s exists",
d03f4262 1371 pw->pw_name, _PATH_NOLOGIN);
e9702f7d 1372 while (fgets(buf, sizeof(buf), f))
1373 fputs(buf, stderr);
1374 fclose(f);
bfe49944 1375 fflush(NULL);
e9702f7d 1376 exit(254);
1377 }
1378}
1379
1380/* Set login name, uid, gid, and groups. */
350391c5 1381void
e9702f7d 1382do_setusercontext(struct passwd *pw)
1383{
bfe49944 1384#ifndef HAVE_CYGWIN
1385 if (getuid() == 0 || geteuid() == 0)
e9702f7d 1386#endif /* HAVE_CYGWIN */
bfe49944 1387 {
1388
44a053a3 1389#ifdef HAVE_SETPCRED
7cac2b65 1390 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1391 fatal("Failed to set process credentials");
44a053a3 1392#endif /* HAVE_SETPCRED */
e9702f7d 1393#ifdef HAVE_LOGIN_CAP
d03f4262 1394# ifdef __bsdi__
276b07a3 1395 setpgid(0, 0);
d03f4262 1396# endif
540d72c3 1397# ifdef USE_PAM
1398 if (options.use_pam) {
1399 do_pam_session();
1400 do_pam_setcred(0);
1401 }
1402# endif /* USE_PAM */
e9702f7d 1403 if (setusercontext(lc, pw, pw->pw_uid,
1404 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1405 perror("unable to set user context");
1406 exit(1);
1407 }
1408#else
1409# if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1410 /* Sets login uid for accounting */
1411 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1412 error("setluid: %s", strerror(errno));
1413# endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1414
1415 if (setlogin(pw->pw_name) < 0)
1416 error("setlogin failed: %s", strerror(errno));
1417 if (setgid(pw->pw_gid) < 0) {
1418 perror("setgid");
1419 exit(1);
1420 }
1421 /* Initialize the group list. */
1422 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1423 perror("initgroups");
1424 exit(1);
1425 }
1426 endgrent();
1427# ifdef USE_PAM
1428 /*
540d72c3 1429 * PAM credentials may take the form of supplementary groups.
e9702f7d 1430 * These will have been wiped by the above initgroups() call.
1431 * Reestablish them here.
1432 */
7cac2b65 1433 if (options.use_pam) {
1434 do_pam_session();
1435 do_pam_setcred(0);
1436 }
e9702f7d 1437# endif /* USE_PAM */
1438# if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1439 irix_setusercontext(pw);
1440# endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
276b07a3 1441# ifdef _AIX
d03f4262 1442 aix_usrinfo(pw);
276b07a3 1443# endif /* _AIX */
e9702f7d 1444 /* Permanently switch to the desired uid. */
1445 permanently_set_uid(pw);
1446#endif
1447 }
bfe49944 1448
1449#ifdef HAVE_CYGWIN
1450 if (is_winnt)
1451#endif
e9702f7d 1452 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1453 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1454}
1455
540d72c3 1456static void
1457do_pwchange(Session *s)
1458{
1459 fprintf(stderr, "WARNING: Your password has expired.\n");
1460 if (s->ttyfd != -1) {
1461 fprintf(stderr,
1462 "You must change your password now and login again!\n");
1463 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1464 perror("passwd");
1465 } else {
1466 fprintf(stderr,
1467 "Password change required but no TTY available.\n");
1468 }
1469 exit(1);
1470}
1471
350391c5 1472static void
1473launch_login(struct passwd *pw, const char *hostname)
1474{
1475 /* Launch login(1). */
1476
44a053a3 1477 execl(LOGIN_PROGRAM, "login", "-h", hostname,
350391c5 1478#ifdef xxxLOGIN_NEEDS_TERM
44a053a3 1479 (s->term ? s->term : "unknown"),
350391c5 1480#endif /* LOGIN_NEEDS_TERM */
1481#ifdef LOGIN_NO_ENDOPT
1482 "-p", "-f", pw->pw_name, (char *)NULL);
1483#else
1484 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1485#endif
1486
1487 /* Login couldn't be executed, die. */
1488
1489 perror("login");
1490 exit(1);
1491}
1492
540d72c3 1493static void
1494child_close_fds(void)
1495{
1496 int i;
1497
1498 if (packet_get_connection_in() == packet_get_connection_out())
1499 close(packet_get_connection_in());
1500 else {
1501 close(packet_get_connection_in());
1502 close(packet_get_connection_out());
1503 }
1504 /*
1505 * Close all descriptors related to channels. They will still remain
1506 * open in the parent.
1507 */
1508 /* XXX better use close-on-exec? -markus */
1509 channel_close_all();
1510
1511 /*
1512 * Close any extra file descriptors. Note that there may still be
1513 * descriptors left by system functions. They will be closed later.
1514 */
1515 endpwent();
1516
1517 /*
1518 * Close any extra open file descriptors so that we don\'t have them
1519 * hanging around in clients. Note that we want to do this after
1520 * initgroups, because at least on Solaris 2.3 it leaves file
1521 * descriptors open.
1522 */
1523 for (i = 3; i < 64; i++)
1524 close(i);
1525}
1526
e9702f7d 1527/*
1528 * Performs common processing for the child, such as setting up the
1529 * environment, closing extra file descriptors, setting the user and group
1530 * ids, and executing the command or shell.
1531 */
1532void
1533do_child(Session *s, const char *command)
1534{
1535 extern char **environ;
1536 char **env;
1537 char *argv[10];
1538 const char *shell, *shell0, *hostname = NULL;
1539 struct passwd *pw = s->pw;
e9702f7d 1540
62eb343a 1541#ifdef AFS_KRB5
1542/* Default place to look for aklog. */
1543#ifdef AKLOG_PATH
1544#define KPROGDIR AKLOG_PATH
1545#else
1546#define KPROGDIR "/usr/bin/aklog"
1547#endif /* AKLOG_PATH */
1548
1549 struct stat st;
1550 char *aklog_path;
1551#endif /* AFS_KRB5 */
1552
e9702f7d 1553 /* remove hostkey from the child's memory */
1554 destroy_sensitive_data();
1555
540d72c3 1556 /* Force a password change */
1557 if (s->authctxt->force_pwchange) {
1558 do_setusercontext(pw);
1559 child_close_fds();
1560 do_pwchange(s);
1561 exit(1);
1562 }
1563
e9702f7d 1564 /* login(1) is only called if we execute the login shell */
1565 if (options.use_login && command != NULL)
1566 options.use_login = 0;
1567
d03f4262 1568#ifdef _UNICOS
1569 cray_setup(pw->pw_uid, pw->pw_name, command);
1570#endif /* _UNICOS */
1571
e9702f7d 1572 /*
1573 * Login(1) does this as well, and it needs uid 0 for the "-h"
1574 * switch, so we let login(1) to this for us.
1575 */
1576 if (!options.use_login) {
1577#ifdef HAVE_OSF_SIA
bfe49944 1578 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
e9702f7d 1579 if (!check_quietlogin(s, command))
1580 do_motd();
1581#else /* HAVE_OSF_SIA */
1582 do_nologin(pw);
e9702f7d 1583 do_setusercontext(pw);
1584#endif /* HAVE_OSF_SIA */
1585 }
1586
1587 /*
1588 * Get the shell from the password data. An empty shell field is
1589 * legal, and means /bin/sh.
1590 */
1591 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
bfe49944 1592
1593 /*
1594 * Make sure $SHELL points to the shell from the password file,
1595 * even if shell is overridden from login.conf
1596 */
1597 env = do_setup_env(s, shell);
1598
e9702f7d 1599#ifdef HAVE_LOGIN_CAP
1600 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1601#endif
1602
3c0ef626 1603 /* we have to stash the hostname before we close our socket. */
1604 if (options.use_login)
1605 hostname = get_remote_name_or_ip(utmp_len,
7cac2b65 1606 options.use_dns);
3c0ef626 1607 /*
1608 * Close the connection descriptors; note that this is the child, and
1609 * the server will still have the socket open, and it is important
1610 * that we do not shutdown it. Note that the descriptors cannot be
1611 * closed before building the environment, as we call
1612 * get_remote_ipaddr there.
1613 */
540d72c3 1614 child_close_fds();
3c0ef626 1615
1616 /*
540d72c3 1617 * Must take new environment into use so that .ssh/rc,
1618 * /etc/ssh/sshrc and xauth are run in the proper environment.
3c0ef626 1619 */
540d72c3 1620 environ = env;
3c0ef626 1621
540d72c3 1622#if defined(KRB5) && defined(USE_AFS)
3c0ef626 1623 /*
540d72c3 1624 * At this point, we check to see if AFS is active and if we have
1625 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1626 * if we can (and need to) extend the ticket into an AFS token. If
1627 * we don't do this, we run into potential problems if the user's
1628 * home directory is in AFS and it's not world-readable.
3c0ef626 1629 */
3c0ef626 1630
540d72c3 1631 if (options.kerberos_get_afs_token && k_hasafs() &&
1632 (s->authctxt->krb5_ctx != NULL)) {
1633 char cell[64];
1634
1635 debug("Getting AFS token");
1636
1637 k_setpag();
1638
1639 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1640 krb5_afslog(s->authctxt->krb5_ctx,
1641 s->authctxt->krb5_fwd_ccache, cell, NULL);
1642
1643 krb5_afslog_home(s->authctxt->krb5_ctx,
1644 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1645 }
1646#endif
3c0ef626 1647
62eb343a 1648#ifdef AFS_KRB5
1649
1650 /* User has authenticated, and if a ticket was going to be
1651 * passed we would have it. KRB5CCNAME should already be set.
1652 * Now try to get an AFS token using aklog.
1653 */
1654 if (k_hasafs()) { /* Do we have AFS? */
1655
1656 aklog_path = xstrdup(KPROGDIR);
1657
1658 /*
1659 * Make sure it exists before we try to run it
1660 */
1661 if (stat(aklog_path, &st) == 0) {
1662 debug("Running %s to get afs token.",aklog_path);
1663 system(aklog_path);
1664 } else {
1665 debug("%s does not exist.",aklog_path);
1666 }
1667
1668 xfree(aklog_path);
1669 }
1670#endif /* AFS_KRB5 */
1671
75be3237 1672#ifdef SESSION_HOOKS
1673 if (options.session_hooks_allow &&
1674 options.session_hooks_startup_cmd)
1675 {
1676 execute_session_hook(options.session_hooks_startup_cmd,
1677 s->authctxt,
1678 /* startup = */ 1,
1679 options.session_hooks_shutdown_cmd != NULL);
1680 }
1681#endif
3c0ef626 1682
1683 /* Change current directory to the user\'s home directory. */
1684 if (chdir(pw->pw_dir) < 0) {
1685 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1686 pw->pw_dir, strerror(errno));
1687#ifdef HAVE_LOGIN_CAP
1688 if (login_getcapbool(lc, "requirehome", 0))
1689 exit(1);
1690#endif
1691 }
1692
e9702f7d 1693 if (!options.use_login)
1694 do_rc_files(s, shell);
3c0ef626 1695
1696 /* restore SIGPIPE for child */
1697 signal(SIGPIPE, SIG_DFL);
1698
e9702f7d 1699 if (options.use_login) {
350391c5 1700 launch_login(pw, hostname);
1701 /* NEVERREACHED */
e9702f7d 1702 }
1703
1704 /* Get the last component of the shell name. */
1705 if ((shell0 = strrchr(shell, '/')) != NULL)
1706 shell0++;
1707 else
1708 shell0 = shell;
1709
3c0ef626 1710 /*
1711 * If we have no command, execute the shell. In this case, the shell
1712 * name to be passed in argv[0] is preceded by '-' to indicate that
1713 * this is a login shell.
1714 */
1715 if (!command) {
e9702f7d 1716 char argv0[256];
3c0ef626 1717
e9702f7d 1718 /* Start the shell. Set initial character to '-'. */
1719 argv0[0] = '-';
3c0ef626 1720
e9702f7d 1721 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1722 >= sizeof(argv0) - 1) {
1723 errno = EINVAL;
3c0ef626 1724 perror(shell);
1725 exit(1);
e9702f7d 1726 }
3c0ef626 1727
e9702f7d 1728 /* Execute the shell. */
1729 argv[0] = argv0;
1730 argv[1] = NULL;
5ab1e3bd 1731 execve(shell, argv, environ);
3c0ef626 1732
e9702f7d 1733 /* Executing the shell failed. */
1734 perror(shell);
1735 exit(1);
3c0ef626 1736 }
1737 /*
1738 * Execute the command using the user's shell. This uses the -c
1739 * option to execute the command.
1740 */
e9702f7d 1741 argv[0] = (char *) shell0;
3c0ef626 1742 argv[1] = "-c";
1743 argv[2] = (char *) command;
1744 argv[3] = NULL;
5ab1e3bd 1745 execve(shell, argv, environ);
3c0ef626 1746 perror(shell);
1747 exit(1);
1748}
1749
1750Session *
1751session_new(void)
1752{
1753 int i;
1754 static int did_init = 0;
1755 if (!did_init) {
1756 debug("session_new: init");
e9702f7d 1757 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1758 sessions[i].used = 0;
1759 }
1760 did_init = 1;
1761 }
e9702f7d 1762 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1763 Session *s = &sessions[i];
1764 if (! s->used) {
1765 memset(s, 0, sizeof(*s));
1766 s->chanid = -1;
1767 s->ptyfd = -1;
1768 s->ttyfd = -1;
1769 s->used = 1;
1770 s->self = i;
1771 debug("session_new: session %d", i);
1772 return s;
1773 }
1774 }
1775 return NULL;
1776}
1777
1778static void
1779session_dump(void)
1780{
1781 int i;
e9702f7d 1782 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1783 Session *s = &sessions[i];
44a053a3 1784 debug("dump: used %d session %d %p channel %d pid %ld",
3c0ef626 1785 s->used,
1786 s->self,
1787 s,
1788 s->chanid,
44a053a3 1789 (long)s->pid);
3c0ef626 1790 }
1791}
1792
1793int
1794session_open(Authctxt *authctxt, int chanid)
1795{
1796 Session *s = session_new();
1797 debug("session_open: channel %d", chanid);
1798 if (s == NULL) {
1799 error("no more sessions");
1800 return 0;
1801 }
1802 s->authctxt = authctxt;
1803 s->pw = authctxt->pw;
540d72c3 1804 if (s->pw == NULL || !authctxt->valid)
3c0ef626 1805 fatal("no user for session %d", s->self);
1806 debug("session_open: session %d: link with channel %d", s->self, chanid);
1807 s->chanid = chanid;
1808 return 1;
1809}
1810
350391c5 1811Session *
1812session_by_tty(char *tty)
1813{
1814 int i;
1815 for (i = 0; i < MAX_SESSIONS; i++) {
1816 Session *s = &sessions[i];
1817 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1818 debug("session_by_tty: session %d tty %s", i, tty);
1819 return s;
1820 }
1821 }
1822 debug("session_by_tty: unknown tty %.100s", tty);
1823 session_dump();
1824 return NULL;
1825}
1826
3c0ef626 1827static Session *
1828session_by_channel(int id)
1829{
1830 int i;
e9702f7d 1831 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1832 Session *s = &sessions[i];
1833 if (s->used && s->chanid == id) {
1834 debug("session_by_channel: session %d channel %d", i, id);
1835 return s;
1836 }
1837 }
1838 debug("session_by_channel: unknown channel %d", id);
1839 session_dump();
1840 return NULL;
1841}
1842
1843static Session *
1844session_by_pid(pid_t pid)
1845{
1846 int i;
44a053a3 1847 debug("session_by_pid: pid %ld", (long)pid);
e9702f7d 1848 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1849 Session *s = &sessions[i];
1850 if (s->used && s->pid == pid)
1851 return s;
1852 }
44a053a3 1853 error("session_by_pid: unknown pid %ld", (long)pid);
3c0ef626 1854 session_dump();
1855 return NULL;
1856}
1857
1858static int
1859session_window_change_req(Session *s)
1860{
1861 s->col = packet_get_int();
1862 s->row = packet_get_int();
1863 s->xpixel = packet_get_int();
1864 s->ypixel = packet_get_int();
e9702f7d 1865 packet_check_eom();
3c0ef626 1866 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1867 return 1;
1868}
1869
1870static int
1871session_pty_req(Session *s)
1872{
1873 u_int len;
1874 int n_bytes;
1875
1876 if (no_pty_flag) {
1877 debug("Allocating a pty not permitted for this authentication.");
1878 return 0;
1879 }
1880 if (s->ttyfd != -1) {
1881 packet_disconnect("Protocol error: you already have a pty.");
1882 return 0;
1883 }
350391c5 1884 /* Get the time and hostname when the user last logged in. */
1885 if (options.print_lastlog) {
1886 s->hostname[0] = '\0';
1887 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1888 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1889 }
3c0ef626 1890
1891 s->term = packet_get_string(&len);
1892
1893 if (compat20) {
1894 s->col = packet_get_int();
1895 s->row = packet_get_int();
1896 } else {
1897 s->row = packet_get_int();
1898 s->col = packet_get_int();
1899 }
1900 s->xpixel = packet_get_int();
1901 s->ypixel = packet_get_int();
1902
1903 if (strcmp(s->term, "") == 0) {
1904 xfree(s->term);
1905 s->term = NULL;
1906 }
1907
1908 /* Allocate a pty and open it. */
1909 debug("Allocating pty.");
350391c5 1910 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
3c0ef626 1911 if (s->term)
1912 xfree(s->term);
1913 s->term = NULL;
1914 s->ptyfd = -1;
1915 s->ttyfd = -1;
1916 error("session_pty_req: session %d alloc failed", s->self);
1917 return 0;
1918 }
1919 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1920
1921 /* for SSH1 the tty modes length is not given */
1922 if (!compat20)
1923 n_bytes = packet_remaining();
1924 tty_parse_modes(s->ttyfd, &n_bytes);
1925
350391c5 1926 if (!use_privsep)
1927 pty_setowner(s->pw, s->tty);
3c0ef626 1928
1929 /* Set window size from the packet. */
1930 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1931
e9702f7d 1932 packet_check_eom();
3c0ef626 1933 session_proctitle(s);
1934 return 1;
1935}
1936
1937static int
1938session_subsystem_req(Session *s)
1939{
1940 struct stat st;
1941 u_int len;
1942 int success = 0;
1943 char *cmd, *subsys = packet_get_string(&len);
1944 int i;
1945
e9702f7d 1946 packet_check_eom();
7cac2b65 1947 logit("subsystem request for %.100s", subsys);
3c0ef626 1948
1949 for (i = 0; i < options.num_subsystems; i++) {
1950 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1951 cmd = options.subsystem_command[i];
1952 if (stat(cmd, &st) < 0) {
1953 error("subsystem: cannot stat %s: %s", cmd,
1954 strerror(errno));
1955 break;
1956 }
1957 debug("subsystem: exec() %s", cmd);
1958 s->is_subsystem = 1;
1959 do_exec(s, cmd);
1960 success = 1;
e9702f7d 1961 break;
3c0ef626 1962 }
1963 }
1964
1965 if (!success)
7cac2b65 1966 logit("subsystem request for %.100s failed, subsystem not found",
3c0ef626 1967 subsys);
1968
1969 xfree(subsys);
1970 return success;
1971}
1972
1973static int
1974session_x11_req(Session *s)
1975{
1976 int success;
1977
1978 s->single_connection = packet_get_char();
1979 s->auth_proto = packet_get_string(NULL);
1980 s->auth_data = packet_get_string(NULL);
1981 s->screen = packet_get_int();
e9702f7d 1982 packet_check_eom();
3c0ef626 1983
1984 success = session_setup_x11fwd(s);
1985 if (!success) {
1986 xfree(s->auth_proto);
1987 xfree(s->auth_data);
1988 s->auth_proto = NULL;
1989 s->auth_data = NULL;
1990 }
1991 return success;
1992}
1993
1994static int
1995session_shell_req(Session *s)
1996{
e9702f7d 1997 packet_check_eom();
3c0ef626 1998 do_exec(s, NULL);
1999 return 1;
2000}
2001
2002static int
2003session_exec_req(Session *s)
2004{
2005 u_int len;
2006 char *command = packet_get_string(&len);
e9702f7d 2007 packet_check_eom();
3c0ef626 2008 do_exec(s, command);
2009 xfree(command);
2010 return 1;
2011}
2012
7cac2b65 2013static int
2014session_break_req(Session *s)
2015{
2016 u_int break_length;
2017
2018 break_length = packet_get_int(); /* ignored */
2019 packet_check_eom();
2020
2021 if (s->ttyfd == -1 ||
2022 tcsendbreak(s->ttyfd, 0) < 0)
2023 return 0;
2024 return 1;
2025}
2026
3c0ef626 2027static int
2028session_auth_agent_req(Session *s)
2029{
2030 static int called = 0;
e9702f7d 2031 packet_check_eom();
3c0ef626 2032 if (no_agent_forwarding_flag) {
2033 debug("session_auth_agent_req: no_agent_forwarding_flag");
2034 return 0;
2035 }
2036 if (called) {
2037 return 0;
2038 } else {
2039 called = 1;
2040 return auth_input_request_forwarding(s->pw);
2041 }
2042}
2043
e9702f7d 2044int
2045session_input_channel_req(Channel *c, const char *rtype)
3c0ef626 2046{
3c0ef626 2047 int success = 0;
3c0ef626 2048 Session *s;
3c0ef626 2049
e9702f7d 2050 if ((s = session_by_channel(c->self)) == NULL) {
7cac2b65 2051 logit("session_input_channel_req: no session %d req %.100s",
e9702f7d 2052 c->self, rtype);
2053 return 0;
2054 }
2055 debug("session_input_channel_req: session %d req %s", s->self, rtype);
3c0ef626 2056
2057 /*
2058 * a session is in LARVAL state until a shell, a command
2059 * or a subsystem is executed
2060 */
2061 if (c->type == SSH_CHANNEL_LARVAL) {
2062 if (strcmp(rtype, "shell") == 0) {
2063 success = session_shell_req(s);
2064 } else if (strcmp(rtype, "exec") == 0) {
2065 success = session_exec_req(s);
2066 } else if (strcmp(rtype, "pty-req") == 0) {
2067 success = session_pty_req(s);
2068 } else if (strcmp(rtype, "x11-req") == 0) {
2069 success = session_x11_req(s);
2070 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2071 success = session_auth_agent_req(s);
2072 } else if (strcmp(rtype, "subsystem") == 0) {
2073 success = session_subsystem_req(s);
7cac2b65 2074 } else if (strcmp(rtype, "break") == 0) {
2075 success = session_break_req(s);
3c0ef626 2076 }
2077 }
2078 if (strcmp(rtype, "window-change") == 0) {
2079 success = session_window_change_req(s);
2080 }
e9702f7d 2081 return success;
3c0ef626 2082}
2083
2084void
2085session_set_fds(Session *s, int fdin, int fdout, int fderr)
2086{
2087 if (!compat20)
2088 fatal("session_set_fds: called for proto != 2.0");
2089 /*
2090 * now that have a child and a pipe to the child,
2091 * we can activate our channel and register the fd's
2092 */
2093 if (s->chanid == -1)
2094 fatal("no channel for session %d", s->self);
2095 channel_set_fds(s->chanid,
2096 fdout, fdin, fderr,
2097 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
e9702f7d 2098 1,
2099 CHAN_SES_WINDOW_DEFAULT);
3c0ef626 2100}
2101
2102/*
2103 * Function to perform pty cleanup. Also called if we get aborted abnormally
2104 * (e.g., due to a dropped connection).
2105 */
350391c5 2106void
540d72c3 2107session_pty_cleanup2(Session *s)
3c0ef626 2108{
3c0ef626 2109 if (s == NULL) {
2110 error("session_pty_cleanup: no session");
2111 return;
2112 }
2113 if (s->ttyfd == -1)
2114 return;
2115
2116 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2117
2118 /* Record that the user has logged out. */
2119 if (s->pid != 0)
e9702f7d 2120 record_logout(s->pid, s->tty, s->pw->pw_name);
3c0ef626 2121
2122 /* Release the pseudo-tty. */
350391c5 2123 if (getuid() == 0)
2124 pty_release(s->tty);
3c0ef626 2125
2126 /*
2127 * Close the server side of the socket pairs. We must do this after
2128 * the pty cleanup, so that another process doesn't get this pty
2129 * while we're still cleaning up.
2130 */
2131 if (close(s->ptymaster) < 0)
350391c5 2132 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
3c0ef626 2133
2134 /* unlink pty from session */
2135 s->ttyfd = -1;
2136}
2137
350391c5 2138void
540d72c3 2139session_pty_cleanup(Session *s)
350391c5 2140{
540d72c3 2141 PRIVSEP(session_pty_cleanup2(s));
350391c5 2142}
2143
d03f4262 2144static char *
2145sig2name(int sig)
2146{
2147#define SSH_SIG(x) if (sig == SIG ## x) return #x
2148 SSH_SIG(ABRT);
2149 SSH_SIG(ALRM);
2150 SSH_SIG(FPE);
2151 SSH_SIG(HUP);
2152 SSH_SIG(ILL);
2153 SSH_SIG(INT);
2154 SSH_SIG(KILL);
2155 SSH_SIG(PIPE);
2156 SSH_SIG(QUIT);
2157 SSH_SIG(SEGV);
2158 SSH_SIG(TERM);
2159 SSH_SIG(USR1);
2160 SSH_SIG(USR2);
2161#undef SSH_SIG
2162 return "SIG@openssh.com";
2163}
2164
3c0ef626 2165static void
2166session_exit_message(Session *s, int status)
2167{
2168 Channel *c;
e9702f7d 2169
2170 if ((c = channel_lookup(s->chanid)) == NULL)
3c0ef626 2171 fatal("session_exit_message: session %d: no channel %d",
2172 s->self, s->chanid);
44a053a3 2173 debug("session_exit_message: session %d channel %d pid %ld",
2174 s->self, s->chanid, (long)s->pid);
3c0ef626 2175
2176 if (WIFEXITED(status)) {
e9702f7d 2177 channel_request_start(s->chanid, "exit-status", 0);
3c0ef626 2178 packet_put_int(WEXITSTATUS(status));
2179 packet_send();
2180 } else if (WIFSIGNALED(status)) {
e9702f7d 2181 channel_request_start(s->chanid, "exit-signal", 0);
d03f4262 2182 packet_put_cstring(sig2name(WTERMSIG(status)));
3c0ef626 2183#ifdef WCOREDUMP
2184 packet_put_char(WCOREDUMP(status));
2185#else /* WCOREDUMP */
2186 packet_put_char(0);
2187#endif /* WCOREDUMP */
2188 packet_put_cstring("");
2189 packet_put_cstring("");
2190 packet_send();
2191 } else {
2192 /* Some weird exit cause. Just exit. */
2193 packet_disconnect("wait returned status %04x.", status);
2194 }
2195
2196 /* disconnect channel */
2197 debug("session_exit_message: release channel %d", s->chanid);
2198 channel_cancel_cleanup(s->chanid);
2199 /*
2200 * emulate a write failure with 'chan_write_failed', nobody will be
2201 * interested in data we write.
2202 * Note that we must not call 'chan_read_failed', since there could
2203 * be some more data waiting in the pipe.
2204 */
2205 if (c->ostate != CHAN_OUTPUT_CLOSED)
2206 chan_write_failed(c);
2207 s->chanid = -1;
2208}
2209
350391c5 2210void
3c0ef626 2211session_close(Session *s)
2212{
44a053a3 2213 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
540d72c3 2214 if (s->ttyfd != -1)
3c0ef626 2215 session_pty_cleanup(s);
3c0ef626 2216 if (s->term)
2217 xfree(s->term);
2218 if (s->display)
2219 xfree(s->display);
e9702f7d 2220 if (s->auth_display)
2221 xfree(s->auth_display);
3c0ef626 2222 if (s->auth_data)
2223 xfree(s->auth_data);
2224 if (s->auth_proto)
2225 xfree(s->auth_proto);
2226 s->used = 0;
2227 session_proctitle(s);
2228}
2229
2230void
2231session_close_by_pid(pid_t pid, int status)
2232{
2233 Session *s = session_by_pid(pid);
2234 if (s == NULL) {
44a053a3 2235 debug("session_close_by_pid: no session for pid %ld",
2236 (long)pid);
3c0ef626 2237 return;
2238 }
2239 if (s->chanid != -1)
2240 session_exit_message(s, status);
2241 session_close(s);
2242}
2243
2244/*
2245 * this is called when a channel dies before
2246 * the session 'child' itself dies
2247 */
2248void
2249session_close_by_channel(int id, void *arg)
2250{
2251 Session *s = session_by_channel(id);
2252 if (s == NULL) {
2253 debug("session_close_by_channel: no session for id %d", id);
2254 return;
2255 }
44a053a3 2256 debug("session_close_by_channel: channel %d child %ld",
2257 id, (long)s->pid);
3c0ef626 2258 if (s->pid != 0) {
2259 debug("session_close_by_channel: channel %d: has child", id);
2260 /*
2261 * delay detach of session, but release pty, since
2262 * the fd's to the child are already closed
2263 */
540d72c3 2264 if (s->ttyfd != -1)
3c0ef626 2265 session_pty_cleanup(s);
3c0ef626 2266 return;
2267 }
2268 /* detach by removing callback */
2269 channel_cancel_cleanup(s->chanid);
2270 s->chanid = -1;
2271 session_close(s);
2272}
2273
2274void
350391c5 2275session_destroy_all(void (*closefunc)(Session *))
3c0ef626 2276{
2277 int i;
e9702f7d 2278 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 2279 Session *s = &sessions[i];
350391c5 2280 if (s->used) {
2281 if (closefunc != NULL)
2282 closefunc(s);
2283 else
2284 session_close(s);
2285 }
3c0ef626 2286 }
2287}
2288
2289static char *
2290session_tty_list(void)
2291{
2292 static char buf[1024];
2293 int i;
bfe49944 2294 char *cp;
2295
3c0ef626 2296 buf[0] = '\0';
e9702f7d 2297 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 2298 Session *s = &sessions[i];
2299 if (s->used && s->ttyfd != -1) {
540d72c3 2300
bfe49944 2301 if (strncmp(s->tty, "/dev/", 5) != 0) {
2302 cp = strrchr(s->tty, '/');
2303 cp = (cp == NULL) ? s->tty : cp + 1;
2304 } else
2305 cp = s->tty + 5;
540d72c3 2306
3c0ef626 2307 if (buf[0] != '\0')
2308 strlcat(buf, ",", sizeof buf);
bfe49944 2309 strlcat(buf, cp, sizeof buf);
3c0ef626 2310 }
2311 }
2312 if (buf[0] == '\0')
2313 strlcpy(buf, "notty", sizeof buf);
2314 return buf;
2315}
2316
2317void
2318session_proctitle(Session *s)
2319{
2320 if (s->pw == NULL)
2321 error("no user for session %d", s->self);
2322 else
2323 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2324}
2325
2326int
2327session_setup_x11fwd(Session *s)
2328{
2329 struct stat st;
e9702f7d 2330 char display[512], auth_display[512];
2331 char hostname[MAXHOSTNAMELEN];
3c0ef626 2332
2333 if (no_x11_forwarding_flag) {
2334 packet_send_debug("X11 forwarding disabled in user configuration file.");
2335 return 0;
2336 }
2337 if (!options.x11_forwarding) {
2338 debug("X11 forwarding disabled in server configuration file.");
2339 return 0;
2340 }
2341 if (!options.xauth_location ||
2342 (stat(options.xauth_location, &st) == -1)) {
2343 packet_send_debug("No xauth program; cannot forward with spoofing.");
2344 return 0;
2345 }
2346 if (options.use_login) {
2347 packet_send_debug("X11 forwarding disabled; "
2348 "not compatible with UseLogin=yes.");
2349 return 0;
2350 }
2351 if (s->display != NULL) {
2352 debug("X11 display already set.");
2353 return 0;
2354 }
276b07a3 2355 if (x11_create_display_inet(options.x11_display_offset,
2356 options.x11_use_localhost, s->single_connection,
2357 &s->display_number) == -1) {
3c0ef626 2358 debug("x11_create_display_inet failed.");
2359 return 0;
2360 }
e9702f7d 2361
2362 /* Set up a suitable value for the DISPLAY variable. */
2363 if (gethostname(hostname, sizeof(hostname)) < 0)
2364 fatal("gethostname: %.100s", strerror(errno));
2365 /*
2366 * auth_display must be used as the displayname when the
2367 * authorization entry is added with xauth(1). This will be
2368 * different than the DISPLAY string for localhost displays.
2369 */
2370 if (options.x11_use_localhost) {
276b07a3 2371 snprintf(display, sizeof display, "localhost:%u.%u",
e9702f7d 2372 s->display_number, s->screen);
276b07a3 2373 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
e9702f7d 2374 s->display_number, s->screen);
2375 s->display = xstrdup(display);
2376 s->auth_display = xstrdup(auth_display);
2377 } else {
2378#ifdef IPADDR_IN_DISPLAY
2379 struct hostent *he;
2380 struct in_addr my_addr;
2381
2382 he = gethostbyname(hostname);
2383 if (he == NULL) {
2384 error("Can't get IP address for X11 DISPLAY.");
2385 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2386 return 0;
2387 }
2388 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
276b07a3 2389 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
e9702f7d 2390 s->display_number, s->screen);
2391#else
276b07a3 2392 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
e9702f7d 2393 s->display_number, s->screen);
2394#endif
2395 s->display = xstrdup(display);
2396 s->auth_display = xstrdup(display);
2397 }
2398
3c0ef626 2399 return 1;
2400}
2401
2402static void
2403do_authenticated2(Authctxt *authctxt)
2404{
2405 server_loop2(authctxt);
540d72c3 2406}
2407
2408void
2409do_cleanup(Authctxt *authctxt)
2410{
2411 static int called = 0;
2412
2413 debug("do_cleanup");
2414
2415 /* no cleanup if we're in the child for login shell */
2416 if (is_child)
2417 return;
2418
2419 /* avoid double cleanup */
2420 if (called)
2421 return;
2422 called = 1;
2423
2424 if (authctxt == NULL)
2425 return;
2426#ifdef KRB5
2427 if (options.kerberos_ticket_cleanup &&
2428 authctxt->krb5_ctx)
2429 krb5_cleanup_proc(authctxt);
5598e598 2430#endif
540d72c3 2431
2432#ifdef GSSAPI
2433 if (compat20 && options.gss_cleanup_creds)
2434 ssh_gssapi_cleanup_creds();
2435#endif
2436
2437#ifdef USE_PAM
2438 if (options.use_pam) {
2439 sshpam_cleanup();
2440 sshpam_thread_cleanup();
2441 }
2442#endif
2443
2444 /* remove agent socket */
2445 auth_sock_cleanup_proc(authctxt->pw);
2446
2447 /*
2448 * Cleanup ptys/utmp only if privsep is disabled,
2449 * or if running in monitor.
2450 */
2451 if (!use_privsep || mm_is_monitor())
2452 session_destroy_all(session_pty_cleanup2);
3c0ef626 2453}
This page took 1.018448 seconds and 5 git commands to generate.