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