]> andersk Git - gssapi-openssh.git/blame - openssh/session.c
Merge from OPENSSH_3_8_1P1_GSSAPI_20040713 to OPENSSH_3_9P1_GSSAPI_20040818.
[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"
1b56ff3d 36RCSID("$OpenBSD: session.c,v 1.180 2004/07/28 09:40:29 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"
1b56ff3d 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"
2980ea68 59#include "monitor_wrap.h"
3c0ef626 60
416fd2a8 61#if defined(KRB5) && defined(USE_AFS)
62#include <kafs.h>
63#endif
64
b9a54c29 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);
416fd2a8 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
88928908 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);
70791e56 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
2980ea68 115login_cap_t *lc;
3c0ef626 116#endif
117
416fd2a8 118static int is_child = 0;
119
ff2d7a98 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
416fd2a8 127auth_sock_cleanup_proc(struct passwd *pw)
ff2d7a98 128{
ff2d7a98 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);
416fd2a8 156 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
ff2d7a98 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
ff2d7a98 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. */
416fd2a8 189 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
ff2d7a98 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,
70791e56 196 0, "auth socket", 1);
ff2d7a98 197 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198 return 1;
199}
200
416fd2a8 201static void
202display_loginmsg(void)
203{
1b56ff3d 204 if (buffer_len(&loginmsg) > 0) {
205 buffer_append(&loginmsg, "\0", 1);
206 printf("%s", (char *)buffer_ptr(&loginmsg));
207 buffer_clear(&loginmsg);
208 }
416fd2a8 209}
ff2d7a98 210
3c0ef626 211void
212do_authenticated(Authctxt *authctxt)
213{
1c14df9e 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
88928908 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
416fd2a8 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;
e9a17296 263 int success, type, screen_flag;
ff2d7a98 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. */
e9a17296 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();
e9a17296 285 packet_check_eom();
3c0ef626 286 if (compression_level < 1 || compression_level > 9) {
1b56ff3d 287 packet_send_debug("Received invalid compression level %d.",
e9a17296 288 compression_level);
3c0ef626 289 break;
290 }
ff2d7a98 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 }
e9a17296 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;
e9a17296 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 }
e9a17296 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 */
70791e56 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{
ff2d7a98 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)
416fd2a8 421 if (options.use_pam && !use_privsep)
70791e56 422 do_pam_setcred(1);
3c0ef626 423#endif /* USE_PAM */
424
425 /* Fork the child. */
426 if ((pid = fork()) == 0) {
416fd2a8 427 is_child = 1;
e54b3d7c 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
e54b3d7c 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 }
e54b3d7c 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) {
1b56ff3d 503 if (s->is_subsystem) {
504 close(perr[0]);
505 perr[0] = -1;
506 }
507 session_set_fds(s, pin[1], pout[0], perr[0]);
3c0ef626 508 } else {
509 /* Enter the interactive session. */
510 server_loop(pid, pin[1], pout[0], perr[0]);
511 /* server_loop has closed pin[1], pout[0], and perr[0]. */
512 }
513#else /* USE_PIPES */
514 /* We are the parent. Close the child sides of the socket pairs. */
515 close(inout[0]);
516 close(err[0]);
517
2a304a95 518 /*
519 * Clear loginmsg, since it's the child's responsibility to display
520 * it to the user, otherwise multiple sessions may accumulate
521 * multiple copies of the login messages.
522 */
523 buffer_clear(&loginmsg);
524
3c0ef626 525 /*
526 * Enter the interactive session. Note: server_loop must be able to
527 * handle the case that fdin and fdout are the same.
528 */
529 if (compat20) {
530 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
531 } else {
532 server_loop(pid, inout[1], inout[1], err[1]);
533 /* server_loop has closed inout[1] and err[1]. */
534 }
535#endif /* USE_PIPES */
536}
537
538/*
539 * This is called to fork and execute a command when we have a tty. This
540 * will call do_child from the child, and server_loop from the parent after
541 * setting up file descriptors, controlling tty, updating wtmp, utmp,
542 * lastlog, and other such operations.
543 */
544void
545do_exec_pty(Session *s, const char *command)
546{
547 int fdout, ptyfd, ttyfd, ptymaster;
548 pid_t pid;
549
550 if (s == NULL)
551 fatal("do_exec_pty: no session");
552 ptyfd = s->ptyfd;
553 ttyfd = s->ttyfd;
554
555#if defined(USE_PAM)
70791e56 556 if (options.use_pam) {
557 do_pam_set_tty(s->tty);
416fd2a8 558 if (!use_privsep)
559 do_pam_setcred(1);
70791e56 560 }
3c0ef626 561#endif
562
563 /* Fork the child. */
564 if ((pid = fork()) == 0) {
416fd2a8 565 is_child = 1;
3c0ef626 566
567 /* Child. Reinitialize the log because the pid has changed. */
568 log_init(__progname, options.log_level, options.log_facility, log_stderr);
569 /* Close the master side of the pseudo tty. */
570 close(ptyfd);
571
572 /* Make the pseudo tty our controlling tty. */
573 pty_make_controlling_tty(&ttyfd, s->tty);
574
575 /* Redirect stdin/stdout/stderr from the pseudo tty. */
576 if (dup2(ttyfd, 0) < 0)
577 error("dup2 stdin: %s", strerror(errno));
578 if (dup2(ttyfd, 1) < 0)
579 error("dup2 stdout: %s", strerror(errno));
580 if (dup2(ttyfd, 2) < 0)
581 error("dup2 stderr: %s", strerror(errno));
582
583 /* Close the extra descriptor for the pseudo tty. */
584 close(ttyfd);
585
586 /* record login, etc. similar to login(1) */
587#ifndef HAVE_OSF_SIA
e54b3d7c 588 if (!(options.use_login && command == NULL)) {
589#ifdef _UNICOS
590 cray_init_job(s->pw); /* set up cray jid and tmpdir */
591#endif /* _UNICOS */
3c0ef626 592 do_login(s, command);
e54b3d7c 593 }
3c0ef626 594# ifdef LOGIN_NEEDS_UTMPX
595 else
596 do_pre_login(s);
597# endif
598#endif
599
600 /* Do common processing for the child, such as execing the command. */
601 do_child(s, command);
602 /* NOTREACHED */
603 }
e54b3d7c 604#ifdef _UNICOS
605 signal(WJSIGNAL, cray_job_termination_handler);
606#endif /* _UNICOS */
3c0ef626 607#ifdef HAVE_CYGWIN
608 if (is_winnt)
609 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
610#endif
611 if (pid < 0)
612 packet_disconnect("fork failed: %.100s", strerror(errno));
613 s->pid = pid;
614
615 /* Parent. Close the slave side of the pseudo tty. */
616 close(ttyfd);
617
618 /*
619 * Create another descriptor of the pty master side for use as the
620 * standard input. We could use the original descriptor, but this
621 * simplifies code in server_loop. The descriptor is bidirectional.
622 */
623 fdout = dup(ptyfd);
624 if (fdout < 0)
625 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
626
627 /* we keep a reference to the pty master */
628 ptymaster = dup(ptyfd);
629 if (ptymaster < 0)
630 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
631 s->ptymaster = ptymaster;
632
633 /* Enter interactive session. */
634 packet_set_interactive(1);
635 if (compat20) {
636 session_set_fds(s, ptyfd, fdout, -1);
637 } else {
638 server_loop(pid, ptyfd, fdout, -1);
639 /* server_loop _has_ closed ptyfd and fdout. */
640 }
641}
642
643#ifdef LOGIN_NEEDS_UTMPX
644static void
645do_pre_login(Session *s)
646{
647 socklen_t fromlen;
648 struct sockaddr_storage from;
649 pid_t pid = getpid();
650
651 /*
652 * Get IP address of client. If the connection is not a socket, let
653 * the address be 0.0.0.0.
654 */
655 memset(&from, 0, sizeof(from));
e54b3d7c 656 fromlen = sizeof(from);
3c0ef626 657 if (packet_connection_is_on_socket()) {
3c0ef626 658 if (getpeername(packet_get_connection_in(),
e9a17296 659 (struct sockaddr *) & from, &fromlen) < 0) {
3c0ef626 660 debug("getpeername: %.100s", strerror(errno));
416fd2a8 661 cleanup_exit(255);
3c0ef626 662 }
663 }
664
665 record_utmp_only(pid, s->tty, s->pw->pw_name,
70791e56 666 get_remote_name_or_ip(utmp_len, options.use_dns),
1c14df9e 667 (struct sockaddr *)&from, fromlen);
3c0ef626 668}
669#endif
670
671/*
672 * This is called to fork and execute a command. If another command is
673 * to be forced, execute that instead.
674 */
675void
676do_exec(Session *s, const char *command)
677{
678 if (forced_command) {
679 original_command = command;
680 command = forced_command;
681 debug("Forced command '%.900s'", command);
682 }
683
70791e56 684#if defined(SESSION_HOOKS)
685 if (options.session_hooks_allow &&
686 (options.session_hooks_startup_cmd ||
687 options.session_hooks_shutdown_cmd))
688 {
689 char env_file[1000];
690 struct stat st;
691 do
692 {
693 snprintf(env_file,
694 sizeof(env_file),
695 "/tmp/ssh_env_%d%d%d",
696 getuid(),
697 getpid(),
698 rand());
699 } while (stat(env_file, &st)==0);
700 s->authctxt->session_env_file = strdup(env_file);
701 }
702#endif
703
704#ifdef GSSAPI
705 if (options.gss_authentication) {
706 temporarily_use_uid(s->pw);
707 ssh_gssapi_storecreds();
708 restore_uid();
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
1b56ff3d 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}
e9a17296 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));
1c14df9e 741 fromlen = sizeof(from);
3c0ef626 742 if (packet_connection_is_on_socket()) {
3c0ef626 743 if (getpeername(packet_get_connection_in(),
e9a17296 744 (struct sockaddr *) & from, &fromlen) < 0) {
3c0ef626 745 debug("getpeername: %.100s", strerror(errno));
416fd2a8 746 cleanup_exit(255);
3c0ef626 747 }
748 }
749
3c0ef626 750 /* Record that there was a login on that tty from the remote host. */
2980ea68 751 if (!use_privsep)
752 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
753 get_remote_name_or_ip(utmp_len,
70791e56 754 options.use_dns),
e54b3d7c 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 */
416fd2a8 762 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
763 display_loginmsg();
3c0ef626 764 do_pam_chauthtok();
416fd2a8 765 s->authctxt->force_pwchange = 0;
70791e56 766 /* XXX - signal [net] parent to enable forwardings */
3c0ef626 767 }
768#endif
769
770 if (check_quietlogin(s, command))
771 return;
772
416fd2a8 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 */
b9a54c29 831void
3c0ef626 832child_set_env(char ***envp, u_int *envsizep, const char *name,
e9a17296 833 const char *value)
3c0ef626 834{
3c0ef626 835 char **env;
70791e56 836 u_int envsize;
837 u_int i, namelen;
838
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 }
3c0ef626 848
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. */
70791e56 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,
e9a17296 889 const char *filename)
3c0ef626 890{
891 FILE *f;
892 char buf[4096];
893 char *cp, *value;
ff2d7a98 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)) {
ff2d7a98 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) {
ff2d7a98 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
88928908 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
70791e56 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;
1062 u_int i, tmpenvsize = 0;
416fd2a8 1063 u_long mask;
70791e56 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
1072 if (tmpenv == NULL)
1073 return;
1074
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);
416fd2a8 1081
70791e56 1082 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1083 if (sscanf(var, "%5lo", &mask) == 1)
416fd2a8 1084 umask((mode_t)mask);
1085
70791e56 1086 for (i = 0; tmpenv[i] != NULL; i++)
1087 xfree(tmpenv[i]);
1088 xfree(tmpenv);
1089}
1090#endif /* HAVE_ETC_DEFAULT_LOGIN */
1091
e9a17296 1092void copy_environment(char **source, char ***env, u_int *envsize)
3c0ef626 1093{
e9a17296 1094 char *var_name, *var_val;
3c0ef626 1095 int i;
1096
e9a17296 1097 if (source == NULL)
3c0ef626 1098 return;
1099
e9a17296 1100 for(i = 0; source[i] != NULL; i++) {
1101 var_name = xstrdup(source[i]);
1102 if ((var_val = strstr(var_name, "=")) == NULL) {
1103 xfree(var_name);
3c0ef626 1104 continue;
3c0ef626 1105 }
e9a17296 1106 *var_val++ = '\0';
3c0ef626 1107
e9a17296 1108 debug3("Copy environment: %s=%s", var_name, var_val);
1109 child_set_env(env, envsize, var_name, var_val);
416fd2a8 1110
e9a17296 1111 xfree(var_name);
3c0ef626 1112 }
1113}
3c0ef626 1114
e9a17296 1115static char **
1116do_setup_env(Session *s, const char *shell)
3c0ef626 1117{
3c0ef626 1118 char buf[256];
e9a17296 1119 u_int i, envsize;
70791e56 1120 char **env, *laddr, *path = NULL;
e9a17296 1121 struct passwd *pw = s->pw;
3c0ef626 1122
1123 /* Initialize the environment. */
1124 envsize = 100;
1125 env = xmalloc(envsize * sizeof(char *));
1126 env[0] = NULL;
1127
1128#ifdef HAVE_CYGWIN
1129 /*
1130 * The Windows environment contains some setting which are
1131 * important for a running system. They must not be dropped.
1132 */
e9a17296 1133 copy_environment(environ, &env, &envsize);
3c0ef626 1134#endif
1135
b9a54c29 1136#ifdef GSSAPI
416fd2a8 1137 /* Allow any GSSAPI methods that we've used to alter
b9a54c29 1138 * the childs environment as they see fit
1139 */
70791e56 1140 ssh_gssapi_do_child(&env, &envsize);
b9a54c29 1141#endif
1142
3c0ef626 1143 if (!options.use_login) {
1144 /* Set basic environment. */
1b56ff3d 1145 for (i = 0; i < s->num_env; i++)
1146 child_set_env(&env, &envsize, s->env[i].name,
1147 s->env[i].val);
1148
3c0ef626 1149 child_set_env(&env, &envsize, "USER", pw->pw_name);
1150 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1c14df9e 1151#ifdef _AIX
1152 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1153#endif
3c0ef626 1154 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1155#ifdef HAVE_LOGIN_CAP
e54b3d7c 1156 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
70791e56 1157 child_set_env(&env, &envsize, "PATH",
1158 _PATH_STDPATH_WITH_SCP);
e54b3d7c 1159 else
1160 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
3c0ef626 1161#else /* HAVE_LOGIN_CAP */
1162# ifndef HAVE_CYGWIN
1163 /*
1164 * There's no standard path on Windows. The path contains
1165 * important components pointing to the system directories,
1166 * needed for loading shared libraries. So the path better
1167 * remains intact here.
1168 */
70791e56 1169# ifdef HAVE_ETC_DEFAULT_LOGIN
1170 read_etc_default_login(&env, &envsize, pw->pw_uid);
1171 path = child_get_env(env, "PATH");
1172# endif /* HAVE_ETC_DEFAULT_LOGIN */
1173 if (path == NULL || *path == '\0') {
416fd2a8 1174 child_set_env(&env, &envsize, "PATH",
70791e56 1175 s->pw->pw_uid == 0 ?
1176 SUPERUSER_PATH : _PATH_STDPATH_WITH_SCP);
1177 }
3c0ef626 1178# endif /* HAVE_CYGWIN */
1179#endif /* HAVE_LOGIN_CAP */
1180
1181 snprintf(buf, sizeof buf, "%.200s/%.50s",
1182 _PATH_MAILDIR, pw->pw_name);
1183 child_set_env(&env, &envsize, "MAIL", buf);
1184
1185 /* Normal systems set SHELL by default. */
1186 child_set_env(&env, &envsize, "SHELL", shell);
1187 }
1188 if (getenv("TZ"))
1189 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1190
2a304a95 1191#ifdef GSI /* GSI shared libs typically installed in non-system locations. */
1192 {
1193 char *cp;
1194
1195 if ((cp = getenv("LD_LIBRARY_PATH")) != NULL)
1196 child_set_env(&env, &envsize, "LD_LIBRARY_PATH", cp);
1197 if ((cp = getenv("LIBPATH")) != NULL)
1198 child_set_env(&env, &envsize, "LIBPATH", cp);
1199 if ((cp = getenv("SHLIB_PATH")) != NULL)
1200 child_set_env(&env, &envsize, "SHLIB_PATH", cp);
1201 if ((cp = getenv("LD_LIBRARYN32_PATH")) != NULL)
1202 child_set_env(&env, &envsize, "LD_LIBRARYN32_PATH",cp);
1203 if ((cp = getenv("LD_LIBRARY64_PATH")) != NULL)
1204 child_set_env(&env, &envsize, "LD_LIBRARY64_PATH",cp);
1205 if ((cp = getenv("GLOBUS_LOCATION")) != NULL)
1206 child_set_env(&env, &envsize, "GLOBUS_LOCATION",cp);
1207 }
93f82cab 1208#endif
1209
3c0ef626 1210 /* Set custom environment options from RSA authentication. */
1211 if (!options.use_login) {
1212 while (custom_environment) {
1213 struct envstring *ce = custom_environment;
e54b3d7c 1214 char *str = ce->s;
e9a17296 1215
e54b3d7c 1216 for (i = 0; str[i] != '=' && str[i]; i++)
3c0ef626 1217 ;
e54b3d7c 1218 if (str[i] == '=') {
1219 str[i] = 0;
1220 child_set_env(&env, &envsize, str, str + i + 1);
3c0ef626 1221 }
1222 custom_environment = ce->next;
1223 xfree(ce->s);
1224 xfree(ce);
1225 }
1226 }
1227
e54b3d7c 1228 /* SSH_CLIENT deprecated */
3c0ef626 1229 snprintf(buf, sizeof buf, "%.50s %d %d",
e9a17296 1230 get_remote_ipaddr(), get_remote_port(), get_local_port());
3c0ef626 1231 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1232
1c14df9e 1233 laddr = get_local_ipaddr(packet_get_connection_in());
e54b3d7c 1234 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1c14df9e 1235 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1236 xfree(laddr);
e54b3d7c 1237 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1238
3c0ef626 1239 if (s->ttyfd != -1)
1240 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1241 if (s->term)
1242 child_set_env(&env, &envsize, "TERM", s->term);
1243 if (s->display)
1244 child_set_env(&env, &envsize, "DISPLAY", s->display);
1245 if (original_command)
1246 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1247 original_command);
1248
e54b3d7c 1249#ifdef _UNICOS
1250 if (cray_tmpdir[0] != '\0')
1251 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1252#endif /* _UNICOS */
1253
3c0ef626 1254#ifdef _AIX
e9a17296 1255 {
1256 char *cp;
1257
1258 if ((cp = getenv("AUTHSTATE")) != NULL)
1259 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1260 if ((cp = getenv("KRB5CCNAME")) != NULL)
1261 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1262 read_environment_file(&env, &envsize, "/etc/environment");
1263 }
3c0ef626 1264#endif
3c0ef626 1265#ifdef KRB5
2a304a95 1266 if (s->authctxt->krb5_ccname)
3c0ef626 1267 child_set_env(&env, &envsize, "KRB5CCNAME",
2a304a95 1268 s->authctxt->krb5_ccname);
3c0ef626 1269#endif
1270#ifdef USE_PAM
e54b3d7c 1271 /*
1272 * Pull in any environment variables that may have
1273 * been set by PAM.
1274 */
70791e56 1275 if (options.use_pam) {
416fd2a8 1276 char **p;
1277
1278 p = fetch_pam_child_environment();
1279 copy_environment(p, &env, &envsize);
1280 free_pam_environment(p);
e54b3d7c 1281
416fd2a8 1282 p = fetch_pam_environment();
e54b3d7c 1283 copy_environment(p, &env, &envsize);
1284 free_pam_environment(p);
1285 }
3c0ef626 1286#endif /* USE_PAM */
1287
ff2d7a98 1288 if (auth_sock_name != NULL)
3c0ef626 1289 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
ff2d7a98 1290 auth_sock_name);
3c0ef626 1291
1292 /* read $HOME/.ssh/environment. */
e54b3d7c 1293 if (options.permit_user_env && !options.use_login) {
3c0ef626 1294 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
e54b3d7c 1295 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
3c0ef626 1296 read_environment_file(&env, &envsize, buf);
1297 }
1298 if (debug_flag) {
1299 /* dump the environment */
1300 fprintf(stderr, "Environment:\n");
1301 for (i = 0; env[i]; i++)
1302 fprintf(stderr, " %.200s\n", env[i]);
1303 }
e9a17296 1304 return env;
1305}
1306
1307/*
1308 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1309 * first in this order).
1310 */
1311static void
1312do_rc_files(Session *s, const char *shell)
1313{
1314 FILE *f = NULL;
1315 char cmd[1024];
1316 int do_xauth;
1317 struct stat st;
1318
1319 do_xauth =
1320 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1321
1322 /* ignore _PATH_SSH_USER_RC for subsystems */
1323 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1324 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1325 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1326 if (debug_flag)
1327 fprintf(stderr, "Running %s\n", cmd);
1328 f = popen(cmd, "w");
1329 if (f) {
1330 if (do_xauth)
1331 fprintf(f, "%s %s\n", s->auth_proto,
1332 s->auth_data);
1333 pclose(f);
1334 } else
1335 fprintf(stderr, "Could not run %s\n",
1336 _PATH_SSH_USER_RC);
1337 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
ae43c103 1338 snprintf(cmd, sizeof cmd, "%s %s", _PATH_BSHELL,
1339 _PATH_SSH_SYSTEM_RC);
e9a17296 1340 if (debug_flag)
ae43c103 1341 fprintf(stderr, "Running %s\n", cmd);
1342 f = popen(cmd, "w");
e9a17296 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_SYSTEM_RC);
1351 } else if (do_xauth && options.xauth_location != NULL) {
1352 /* Add authority data to .Xauthority if appropriate. */
1353 if (debug_flag) {
1354 fprintf(stderr,
1c14df9e 1355 "Running %.500s remove %.100s\n",
416fd2a8 1356 options.xauth_location, s->auth_display);
1c14df9e 1357 fprintf(stderr,
1358 "%.500s add %.100s %.100s %.100s\n",
e9a17296 1359 options.xauth_location, s->auth_display,
1360 s->auth_proto, s->auth_data);
1361 }
1362 snprintf(cmd, sizeof cmd, "%s -q -",
1363 options.xauth_location);
1364 f = popen(cmd, "w");
1365 if (f) {
1c14df9e 1366 fprintf(f, "remove %s\n",
1367 s->auth_display);
e9a17296 1368 fprintf(f, "add %s %s %s\n",
1369 s->auth_display, s->auth_proto,
1370 s->auth_data);
1371 pclose(f);
1372 } else {
1373 fprintf(stderr, "Could not run %s\n",
1374 cmd);
1375 }
1376 }
1377}
1378
1379static void
1380do_nologin(struct passwd *pw)
1381{
1382 FILE *f = NULL;
1383 char buf[1024];
1384
1385#ifdef HAVE_LOGIN_CAP
1386 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1387 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1388 _PATH_NOLOGIN), "r");
1389#else
1390 if (pw->pw_uid)
1391 f = fopen(_PATH_NOLOGIN, "r");
1392#endif
1393 if (f) {
1394 /* /etc/nologin exists. Print its contents and exit. */
70791e56 1395 logit("User %.100s not allowed because %s exists",
e54b3d7c 1396 pw->pw_name, _PATH_NOLOGIN);
e9a17296 1397 while (fgets(buf, sizeof(buf), f))
1398 fputs(buf, stderr);
1399 fclose(f);
1c14df9e 1400 fflush(NULL);
e9a17296 1401 exit(254);
1402 }
1403}
1404
1405/* Set login name, uid, gid, and groups. */
2980ea68 1406void
e9a17296 1407do_setusercontext(struct passwd *pw)
1408{
1c14df9e 1409#ifndef HAVE_CYGWIN
1410 if (getuid() == 0 || geteuid() == 0)
e9a17296 1411#endif /* HAVE_CYGWIN */
1c14df9e 1412 {
1413
ff2d7a98 1414#ifdef HAVE_SETPCRED
70791e56 1415 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1416 fatal("Failed to set process credentials");
ff2d7a98 1417#endif /* HAVE_SETPCRED */
e9a17296 1418#ifdef HAVE_LOGIN_CAP
e54b3d7c 1419# ifdef __bsdi__
ff2d7a98 1420 setpgid(0, 0);
e54b3d7c 1421# endif
416fd2a8 1422# ifdef USE_PAM
1423 if (options.use_pam) {
1424 do_pam_session();
1425 do_pam_setcred(0);
1426 }
1427# endif /* USE_PAM */
e9a17296 1428 if (setusercontext(lc, pw, pw->pw_uid,
1429 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1430 perror("unable to set user context");
1431 exit(1);
1432 }
1433#else
1434# if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1435 /* Sets login uid for accounting */
1436 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1437 error("setluid: %s", strerror(errno));
1438# endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1439
1440 if (setlogin(pw->pw_name) < 0)
1441 error("setlogin failed: %s", strerror(errno));
1442 if (setgid(pw->pw_gid) < 0) {
1443 perror("setgid");
1444 exit(1);
1445 }
1446 /* Initialize the group list. */
1447 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1448 perror("initgroups");
1449 exit(1);
1450 }
1451 endgrent();
1452# ifdef USE_PAM
1453 /*
416fd2a8 1454 * PAM credentials may take the form of supplementary groups.
e9a17296 1455 * These will have been wiped by the above initgroups() call.
1456 * Reestablish them here.
1457 */
70791e56 1458 if (options.use_pam) {
1459 do_pam_session();
1460 do_pam_setcred(0);
1461 }
e9a17296 1462# endif /* USE_PAM */
1463# if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1464 irix_setusercontext(pw);
1465# endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
ff2d7a98 1466# ifdef _AIX
e54b3d7c 1467 aix_usrinfo(pw);
ff2d7a98 1468# endif /* _AIX */
e9a17296 1469 /* Permanently switch to the desired uid. */
1470 permanently_set_uid(pw);
1471#endif
1472 }
1c14df9e 1473
1474#ifdef HAVE_CYGWIN
1475 if (is_winnt)
1476#endif
e9a17296 1477 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1478 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1479}
1480
416fd2a8 1481static void
1482do_pwchange(Session *s)
1483{
1b56ff3d 1484 fflush(NULL);
416fd2a8 1485 fprintf(stderr, "WARNING: Your password has expired.\n");
1486 if (s->ttyfd != -1) {
1b56ff3d 1487 fprintf(stderr,
416fd2a8 1488 "You must change your password now and login again!\n");
1489 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1490 perror("passwd");
1491 } else {
1492 fprintf(stderr,
1493 "Password change required but no TTY available.\n");
1494 }
1495 exit(1);
1496}
1497
2980ea68 1498static void
1499launch_login(struct passwd *pw, const char *hostname)
1500{
1501 /* Launch login(1). */
1502
ff2d7a98 1503 execl(LOGIN_PROGRAM, "login", "-h", hostname,
2980ea68 1504#ifdef xxxLOGIN_NEEDS_TERM
ff2d7a98 1505 (s->term ? s->term : "unknown"),
2980ea68 1506#endif /* LOGIN_NEEDS_TERM */
1507#ifdef LOGIN_NO_ENDOPT
1508 "-p", "-f", pw->pw_name, (char *)NULL);
1509#else
1510 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1511#endif
1512
1513 /* Login couldn't be executed, die. */
1514
1515 perror("login");
1516 exit(1);
1517}
1518
416fd2a8 1519static void
1520child_close_fds(void)
1521{
1522 int i;
1523
1524 if (packet_get_connection_in() == packet_get_connection_out())
1525 close(packet_get_connection_in());
1526 else {
1527 close(packet_get_connection_in());
1528 close(packet_get_connection_out());
1529 }
1530 /*
1531 * Close all descriptors related to channels. They will still remain
1532 * open in the parent.
1533 */
1534 /* XXX better use close-on-exec? -markus */
1535 channel_close_all();
1536
1537 /*
1538 * Close any extra file descriptors. Note that there may still be
1539 * descriptors left by system functions. They will be closed later.
1540 */
1541 endpwent();
1542
1543 /*
1544 * Close any extra open file descriptors so that we don\'t have them
1545 * hanging around in clients. Note that we want to do this after
1546 * initgroups, because at least on Solaris 2.3 it leaves file
1547 * descriptors open.
1548 */
1549 for (i = 3; i < 64; i++)
1550 close(i);
1551}
1552
e9a17296 1553/*
1554 * Performs common processing for the child, such as setting up the
1555 * environment, closing extra file descriptors, setting the user and group
1556 * ids, and executing the command or shell.
1557 */
1558void
1559do_child(Session *s, const char *command)
1560{
1561 extern char **environ;
1562 char **env;
1563 char *argv[10];
1564 const char *shell, *shell0, *hostname = NULL;
1565 struct passwd *pw = s->pw;
e9a17296 1566
f2fd21a2 1567#ifdef AFS_KRB5
1568/* Default place to look for aklog. */
1569#ifdef AKLOG_PATH
1570#define KPROGDIR AKLOG_PATH
1571#else
1572#define KPROGDIR "/usr/bin/aklog"
1573#endif /* AKLOG_PATH */
1574
1575 struct stat st;
1576 char *aklog_path;
1577#endif /* AFS_KRB5 */
1578
e9a17296 1579 /* remove hostkey from the child's memory */
1580 destroy_sensitive_data();
1581
416fd2a8 1582 /* Force a password change */
1583 if (s->authctxt->force_pwchange) {
1584 do_setusercontext(pw);
1585 child_close_fds();
1586 do_pwchange(s);
1587 exit(1);
1588 }
1589
e9a17296 1590 /* login(1) is only called if we execute the login shell */
1591 if (options.use_login && command != NULL)
1592 options.use_login = 0;
1593
e54b3d7c 1594#ifdef _UNICOS
1595 cray_setup(pw->pw_uid, pw->pw_name, command);
1596#endif /* _UNICOS */
1597
e9a17296 1598 /*
1599 * Login(1) does this as well, and it needs uid 0 for the "-h"
1600 * switch, so we let login(1) to this for us.
1601 */
1602 if (!options.use_login) {
1603#ifdef HAVE_OSF_SIA
1c14df9e 1604 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
e9a17296 1605 if (!check_quietlogin(s, command))
1606 do_motd();
1607#else /* HAVE_OSF_SIA */
1608 do_nologin(pw);
e9a17296 1609 do_setusercontext(pw);
1b56ff3d 1610 /*
1611 * PAM session modules in do_setusercontext may have
1612 * generated messages, so if this in an interactive
1613 * login then display them too.
1614 */
1615 if (command == NULL)
1616 display_loginmsg();
e9a17296 1617#endif /* HAVE_OSF_SIA */
1618 }
1619
1620 /*
1621 * Get the shell from the password data. An empty shell field is
1622 * legal, and means /bin/sh.
1623 */
1624 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1c14df9e 1625
1626 /*
1627 * Make sure $SHELL points to the shell from the password file,
1628 * even if shell is overridden from login.conf
1629 */
1630 env = do_setup_env(s, shell);
1631
e9a17296 1632#ifdef HAVE_LOGIN_CAP
1633 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1634#endif
1635
3c0ef626 1636 /* we have to stash the hostname before we close our socket. */
1637 if (options.use_login)
1638 hostname = get_remote_name_or_ip(utmp_len,
70791e56 1639 options.use_dns);
3c0ef626 1640 /*
1641 * Close the connection descriptors; note that this is the child, and
1642 * the server will still have the socket open, and it is important
1643 * that we do not shutdown it. Note that the descriptors cannot be
1644 * closed before building the environment, as we call
1645 * get_remote_ipaddr there.
1646 */
416fd2a8 1647 child_close_fds();
3c0ef626 1648
1649 /*
416fd2a8 1650 * Must take new environment into use so that .ssh/rc,
1651 * /etc/ssh/sshrc and xauth are run in the proper environment.
3c0ef626 1652 */
416fd2a8 1653 environ = env;
3c0ef626 1654
416fd2a8 1655#if defined(KRB5) && defined(USE_AFS)
3c0ef626 1656 /*
416fd2a8 1657 * At this point, we check to see if AFS is active and if we have
1658 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1659 * if we can (and need to) extend the ticket into an AFS token. If
1660 * we don't do this, we run into potential problems if the user's
1661 * home directory is in AFS and it's not world-readable.
3c0ef626 1662 */
3c0ef626 1663
416fd2a8 1664 if (options.kerberos_get_afs_token && k_hasafs() &&
1665 (s->authctxt->krb5_ctx != NULL)) {
1666 char cell[64];
1667
1668 debug("Getting AFS token");
1669
1670 k_setpag();
1671
1672 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1673 krb5_afslog(s->authctxt->krb5_ctx,
1674 s->authctxt->krb5_fwd_ccache, cell, NULL);
1675
1676 krb5_afslog_home(s->authctxt->krb5_ctx,
1677 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1678 }
1679#endif
3c0ef626 1680
f2fd21a2 1681#ifdef AFS_KRB5
1682
1683 /* User has authenticated, and if a ticket was going to be
1684 * passed we would have it. KRB5CCNAME should already be set.
1685 * Now try to get an AFS token using aklog.
1686 */
1687 if (k_hasafs()) { /* Do we have AFS? */
1688
1689 aklog_path = xstrdup(KPROGDIR);
1690
1691 /*
1692 * Make sure it exists before we try to run it
1693 */
1694 if (stat(aklog_path, &st) == 0) {
1695 debug("Running %s to get afs token.",aklog_path);
1696 system(aklog_path);
1697 } else {
1698 debug("%s does not exist.",aklog_path);
1699 }
1700
1701 xfree(aklog_path);
1702 }
1703#endif /* AFS_KRB5 */
1704
88928908 1705#ifdef SESSION_HOOKS
1706 if (options.session_hooks_allow &&
1707 options.session_hooks_startup_cmd)
1708 {
1709 execute_session_hook(options.session_hooks_startup_cmd,
1710 s->authctxt,
1711 /* startup = */ 1,
1712 options.session_hooks_shutdown_cmd != NULL);
1713 }
1714#endif
3c0ef626 1715
1716 /* Change current directory to the user\'s home directory. */
1717 if (chdir(pw->pw_dir) < 0) {
1718 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1719 pw->pw_dir, strerror(errno));
1720#ifdef HAVE_LOGIN_CAP
1721 if (login_getcapbool(lc, "requirehome", 0))
1722 exit(1);
1723#endif
1724 }
1725
e9a17296 1726 if (!options.use_login)
1727 do_rc_files(s, shell);
3c0ef626 1728
1729 /* restore SIGPIPE for child */
1730 signal(SIGPIPE, SIG_DFL);
1731
e9a17296 1732 if (options.use_login) {
2980ea68 1733 launch_login(pw, hostname);
1734 /* NEVERREACHED */
e9a17296 1735 }
1736
1737 /* Get the last component of the shell name. */
1738 if ((shell0 = strrchr(shell, '/')) != NULL)
1739 shell0++;
1740 else
1741 shell0 = shell;
1742
3c0ef626 1743 /*
1744 * If we have no command, execute the shell. In this case, the shell
1745 * name to be passed in argv[0] is preceded by '-' to indicate that
1746 * this is a login shell.
1747 */
1748 if (!command) {
e9a17296 1749 char argv0[256];
3c0ef626 1750
e9a17296 1751 /* Start the shell. Set initial character to '-'. */
1752 argv0[0] = '-';
3c0ef626 1753
e9a17296 1754 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1755 >= sizeof(argv0) - 1) {
1756 errno = EINVAL;
3c0ef626 1757 perror(shell);
1758 exit(1);
e9a17296 1759 }
3c0ef626 1760
e9a17296 1761 /* Execute the shell. */
1762 argv[0] = argv0;
1763 argv[1] = NULL;
574478c5 1764 execve(shell, argv, environ);
3c0ef626 1765
e9a17296 1766 /* Executing the shell failed. */
1767 perror(shell);
1768 exit(1);
3c0ef626 1769 }
1770 /*
1771 * Execute the command using the user's shell. This uses the -c
1772 * option to execute the command.
1773 */
e9a17296 1774 argv[0] = (char *) shell0;
3c0ef626 1775 argv[1] = "-c";
1776 argv[2] = (char *) command;
1777 argv[3] = NULL;
574478c5 1778 execve(shell, argv, environ);
3c0ef626 1779 perror(shell);
1780 exit(1);
1781}
1782
1783Session *
1784session_new(void)
1785{
1786 int i;
1787 static int did_init = 0;
1788 if (!did_init) {
1789 debug("session_new: init");
e9a17296 1790 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1791 sessions[i].used = 0;
1792 }
1793 did_init = 1;
1794 }
e9a17296 1795 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1796 Session *s = &sessions[i];
1797 if (! s->used) {
1798 memset(s, 0, sizeof(*s));
1799 s->chanid = -1;
1800 s->ptyfd = -1;
1801 s->ttyfd = -1;
1802 s->used = 1;
1803 s->self = i;
1804 debug("session_new: session %d", i);
1805 return s;
1806 }
1807 }
1808 return NULL;
1809}
1810
1811static void
1812session_dump(void)
1813{
1814 int i;
e9a17296 1815 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1816 Session *s = &sessions[i];
ff2d7a98 1817 debug("dump: used %d session %d %p channel %d pid %ld",
3c0ef626 1818 s->used,
1819 s->self,
1820 s,
1821 s->chanid,
ff2d7a98 1822 (long)s->pid);
3c0ef626 1823 }
1824}
1825
1826int
1827session_open(Authctxt *authctxt, int chanid)
1828{
1829 Session *s = session_new();
1830 debug("session_open: channel %d", chanid);
1831 if (s == NULL) {
1832 error("no more sessions");
1833 return 0;
1834 }
1835 s->authctxt = authctxt;
1836 s->pw = authctxt->pw;
416fd2a8 1837 if (s->pw == NULL || !authctxt->valid)
3c0ef626 1838 fatal("no user for session %d", s->self);
1839 debug("session_open: session %d: link with channel %d", s->self, chanid);
1840 s->chanid = chanid;
1841 return 1;
1842}
1843
2980ea68 1844Session *
1845session_by_tty(char *tty)
1846{
1847 int i;
1848 for (i = 0; i < MAX_SESSIONS; i++) {
1849 Session *s = &sessions[i];
1850 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1851 debug("session_by_tty: session %d tty %s", i, tty);
1852 return s;
1853 }
1854 }
1855 debug("session_by_tty: unknown tty %.100s", tty);
1856 session_dump();
1857 return NULL;
1858}
1859
3c0ef626 1860static Session *
1861session_by_channel(int id)
1862{
1863 int i;
e9a17296 1864 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1865 Session *s = &sessions[i];
1866 if (s->used && s->chanid == id) {
1867 debug("session_by_channel: session %d channel %d", i, id);
1868 return s;
1869 }
1870 }
1871 debug("session_by_channel: unknown channel %d", id);
1872 session_dump();
1873 return NULL;
1874}
1875
1876static Session *
1877session_by_pid(pid_t pid)
1878{
1879 int i;
ff2d7a98 1880 debug("session_by_pid: pid %ld", (long)pid);
e9a17296 1881 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 1882 Session *s = &sessions[i];
1883 if (s->used && s->pid == pid)
1884 return s;
1885 }
ff2d7a98 1886 error("session_by_pid: unknown pid %ld", (long)pid);
3c0ef626 1887 session_dump();
1888 return NULL;
1889}
1890
1891static int
1892session_window_change_req(Session *s)
1893{
1894 s->col = packet_get_int();
1895 s->row = packet_get_int();
1896 s->xpixel = packet_get_int();
1897 s->ypixel = packet_get_int();
e9a17296 1898 packet_check_eom();
3c0ef626 1899 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1900 return 1;
1901}
1902
1903static int
1904session_pty_req(Session *s)
1905{
1906 u_int len;
1907 int n_bytes;
1908
1909 if (no_pty_flag) {
1910 debug("Allocating a pty not permitted for this authentication.");
1911 return 0;
1912 }
1913 if (s->ttyfd != -1) {
1914 packet_disconnect("Protocol error: you already have a pty.");
1915 return 0;
1916 }
1917
1918 s->term = packet_get_string(&len);
1919
1920 if (compat20) {
1921 s->col = packet_get_int();
1922 s->row = packet_get_int();
1923 } else {
1924 s->row = packet_get_int();
1925 s->col = packet_get_int();
1926 }
1927 s->xpixel = packet_get_int();
1928 s->ypixel = packet_get_int();
1929
1930 if (strcmp(s->term, "") == 0) {
1931 xfree(s->term);
1932 s->term = NULL;
1933 }
1934
1935 /* Allocate a pty and open it. */
1936 debug("Allocating pty.");
2980ea68 1937 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
3c0ef626 1938 if (s->term)
1939 xfree(s->term);
1940 s->term = NULL;
1941 s->ptyfd = -1;
1942 s->ttyfd = -1;
1943 error("session_pty_req: session %d alloc failed", s->self);
1944 return 0;
1945 }
1946 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1947
1948 /* for SSH1 the tty modes length is not given */
1949 if (!compat20)
1950 n_bytes = packet_remaining();
1951 tty_parse_modes(s->ttyfd, &n_bytes);
1952
2980ea68 1953 if (!use_privsep)
1954 pty_setowner(s->pw, s->tty);
3c0ef626 1955
1956 /* Set window size from the packet. */
1957 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1958
e9a17296 1959 packet_check_eom();
3c0ef626 1960 session_proctitle(s);
1961 return 1;
1962}
1963
1964static int
1965session_subsystem_req(Session *s)
1966{
1967 struct stat st;
1968 u_int len;
1969 int success = 0;
1970 char *cmd, *subsys = packet_get_string(&len);
1971 int i;
1972
e9a17296 1973 packet_check_eom();
70791e56 1974 logit("subsystem request for %.100s", subsys);
3c0ef626 1975
1976 for (i = 0; i < options.num_subsystems; i++) {
1977 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1978 cmd = options.subsystem_command[i];
1979 if (stat(cmd, &st) < 0) {
1980 error("subsystem: cannot stat %s: %s", cmd,
1981 strerror(errno));
1982 break;
1983 }
1984 debug("subsystem: exec() %s", cmd);
1985 s->is_subsystem = 1;
1986 do_exec(s, cmd);
1987 success = 1;
e9a17296 1988 break;
3c0ef626 1989 }
1990 }
1991
1992 if (!success)
70791e56 1993 logit("subsystem request for %.100s failed, subsystem not found",
3c0ef626 1994 subsys);
1995
1996 xfree(subsys);
1997 return success;
1998}
1999
2000static int
2001session_x11_req(Session *s)
2002{
2003 int success;
2004
2005 s->single_connection = packet_get_char();
2006 s->auth_proto = packet_get_string(NULL);
2007 s->auth_data = packet_get_string(NULL);
2008 s->screen = packet_get_int();
e9a17296 2009 packet_check_eom();
3c0ef626 2010
2011 success = session_setup_x11fwd(s);
2012 if (!success) {
2013 xfree(s->auth_proto);
2014 xfree(s->auth_data);
2015 s->auth_proto = NULL;
2016 s->auth_data = NULL;
2017 }
2018 return success;
2019}
2020
2021static int
2022session_shell_req(Session *s)
2023{
e9a17296 2024 packet_check_eom();
3c0ef626 2025 do_exec(s, NULL);
2026 return 1;
2027}
2028
2029static int
2030session_exec_req(Session *s)
2031{
2032 u_int len;
2033 char *command = packet_get_string(&len);
e9a17296 2034 packet_check_eom();
3c0ef626 2035 do_exec(s, command);
2036 xfree(command);
2037 return 1;
2038}
2039
70791e56 2040static int
2041session_break_req(Session *s)
2042{
70791e56 2043
1b56ff3d 2044 packet_get_int(); /* ignored */
70791e56 2045 packet_check_eom();
2046
2047 if (s->ttyfd == -1 ||
2048 tcsendbreak(s->ttyfd, 0) < 0)
2049 return 0;
2050 return 1;
2051}
2052
1b56ff3d 2053static int
2054session_env_req(Session *s)
2055{
2056 char *name, *val;
2057 u_int name_len, val_len, i;
2058
2059 name = packet_get_string(&name_len);
2060 val = packet_get_string(&val_len);
2061 packet_check_eom();
2062
2063 /* Don't set too many environment variables */
2064 if (s->num_env > 128) {
2065 debug2("Ignoring env request %s: too many env vars", name);
2066 goto fail;
2067 }
2068
2069 for (i = 0; i < options.num_accept_env; i++) {
2070 if (match_pattern(name, options.accept_env[i])) {
2071 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2072 s->env = xrealloc(s->env, sizeof(*s->env) *
2073 (s->num_env + 1));
2074 s->env[s->num_env].name = name;
2075 s->env[s->num_env].val = val;
2076 s->num_env++;
2077 return (1);
2078 }
2079 }
2080 debug2("Ignoring env request %s: disallowed name", name);
2081
2082 fail:
2083 xfree(name);
2084 xfree(val);
2085 return (0);
2086}
2087
3c0ef626 2088static int
2089session_auth_agent_req(Session *s)
2090{
2091 static int called = 0;
e9a17296 2092 packet_check_eom();
3c0ef626 2093 if (no_agent_forwarding_flag) {
2094 debug("session_auth_agent_req: no_agent_forwarding_flag");
2095 return 0;
2096 }
2097 if (called) {
2098 return 0;
2099 } else {
2100 called = 1;
2101 return auth_input_request_forwarding(s->pw);
2102 }
2103}
2104
e9a17296 2105int
2106session_input_channel_req(Channel *c, const char *rtype)
3c0ef626 2107{
3c0ef626 2108 int success = 0;
3c0ef626 2109 Session *s;
3c0ef626 2110
e9a17296 2111 if ((s = session_by_channel(c->self)) == NULL) {
70791e56 2112 logit("session_input_channel_req: no session %d req %.100s",
e9a17296 2113 c->self, rtype);
2114 return 0;
2115 }
2116 debug("session_input_channel_req: session %d req %s", s->self, rtype);
3c0ef626 2117
2118 /*
2119 * a session is in LARVAL state until a shell, a command
2120 * or a subsystem is executed
2121 */
2122 if (c->type == SSH_CHANNEL_LARVAL) {
2123 if (strcmp(rtype, "shell") == 0) {
2124 success = session_shell_req(s);
2125 } else if (strcmp(rtype, "exec") == 0) {
2126 success = session_exec_req(s);
2127 } else if (strcmp(rtype, "pty-req") == 0) {
2128 success = session_pty_req(s);
2129 } else if (strcmp(rtype, "x11-req") == 0) {
2130 success = session_x11_req(s);
2131 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2132 success = session_auth_agent_req(s);
2133 } else if (strcmp(rtype, "subsystem") == 0) {
2134 success = session_subsystem_req(s);
1b56ff3d 2135 } else if (strcmp(rtype, "env") == 0) {
2136 success = session_env_req(s);
3c0ef626 2137 }
2138 }
2139 if (strcmp(rtype, "window-change") == 0) {
2140 success = session_window_change_req(s);
1b56ff3d 2141 } else if (strcmp(rtype, "break") == 0) {
2142 success = session_break_req(s);
3c0ef626 2143 }
1b56ff3d 2144
e9a17296 2145 return success;
3c0ef626 2146}
2147
2148void
2149session_set_fds(Session *s, int fdin, int fdout, int fderr)
2150{
2151 if (!compat20)
2152 fatal("session_set_fds: called for proto != 2.0");
2153 /*
2154 * now that have a child and a pipe to the child,
2155 * we can activate our channel and register the fd's
2156 */
2157 if (s->chanid == -1)
2158 fatal("no channel for session %d", s->self);
2159 channel_set_fds(s->chanid,
2160 fdout, fdin, fderr,
2161 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
e9a17296 2162 1,
2163 CHAN_SES_WINDOW_DEFAULT);
3c0ef626 2164}
2165
2166/*
2167 * Function to perform pty cleanup. Also called if we get aborted abnormally
2168 * (e.g., due to a dropped connection).
2169 */
2980ea68 2170void
416fd2a8 2171session_pty_cleanup2(Session *s)
3c0ef626 2172{
3c0ef626 2173 if (s == NULL) {
2174 error("session_pty_cleanup: no session");
2175 return;
2176 }
2177 if (s->ttyfd == -1)
2178 return;
2179
2180 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2181
2182 /* Record that the user has logged out. */
2183 if (s->pid != 0)
e9a17296 2184 record_logout(s->pid, s->tty, s->pw->pw_name);
3c0ef626 2185
2186 /* Release the pseudo-tty. */
2980ea68 2187 if (getuid() == 0)
2188 pty_release(s->tty);
3c0ef626 2189
2190 /*
2191 * Close the server side of the socket pairs. We must do this after
2192 * the pty cleanup, so that another process doesn't get this pty
2193 * while we're still cleaning up.
2194 */
2195 if (close(s->ptymaster) < 0)
2980ea68 2196 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
3c0ef626 2197
2198 /* unlink pty from session */
2199 s->ttyfd = -1;
2200}
2201
2980ea68 2202void
416fd2a8 2203session_pty_cleanup(Session *s)
2980ea68 2204{
416fd2a8 2205 PRIVSEP(session_pty_cleanup2(s));
2980ea68 2206}
2207
e54b3d7c 2208static char *
2209sig2name(int sig)
2210{
2211#define SSH_SIG(x) if (sig == SIG ## x) return #x
2212 SSH_SIG(ABRT);
2213 SSH_SIG(ALRM);
2214 SSH_SIG(FPE);
2215 SSH_SIG(HUP);
2216 SSH_SIG(ILL);
2217 SSH_SIG(INT);
2218 SSH_SIG(KILL);
2219 SSH_SIG(PIPE);
2220 SSH_SIG(QUIT);
2221 SSH_SIG(SEGV);
2222 SSH_SIG(TERM);
2223 SSH_SIG(USR1);
2224 SSH_SIG(USR2);
2225#undef SSH_SIG
2226 return "SIG@openssh.com";
2227}
2228
3c0ef626 2229static void
2230session_exit_message(Session *s, int status)
2231{
2232 Channel *c;
e9a17296 2233
2234 if ((c = channel_lookup(s->chanid)) == NULL)
3c0ef626 2235 fatal("session_exit_message: session %d: no channel %d",
2236 s->self, s->chanid);
ff2d7a98 2237 debug("session_exit_message: session %d channel %d pid %ld",
2238 s->self, s->chanid, (long)s->pid);
3c0ef626 2239
2240 if (WIFEXITED(status)) {
e9a17296 2241 channel_request_start(s->chanid, "exit-status", 0);
3c0ef626 2242 packet_put_int(WEXITSTATUS(status));
2243 packet_send();
2244 } else if (WIFSIGNALED(status)) {
e9a17296 2245 channel_request_start(s->chanid, "exit-signal", 0);
e54b3d7c 2246 packet_put_cstring(sig2name(WTERMSIG(status)));
3c0ef626 2247#ifdef WCOREDUMP
2248 packet_put_char(WCOREDUMP(status));
2249#else /* WCOREDUMP */
2250 packet_put_char(0);
2251#endif /* WCOREDUMP */
2252 packet_put_cstring("");
2253 packet_put_cstring("");
2254 packet_send();
2255 } else {
2256 /* Some weird exit cause. Just exit. */
2257 packet_disconnect("wait returned status %04x.", status);
2258 }
2259
2260 /* disconnect channel */
2261 debug("session_exit_message: release channel %d", s->chanid);
2262 channel_cancel_cleanup(s->chanid);
2263 /*
2264 * emulate a write failure with 'chan_write_failed', nobody will be
2265 * interested in data we write.
2266 * Note that we must not call 'chan_read_failed', since there could
2267 * be some more data waiting in the pipe.
2268 */
2269 if (c->ostate != CHAN_OUTPUT_CLOSED)
2270 chan_write_failed(c);
2271 s->chanid = -1;
2272}
2273
2980ea68 2274void
3c0ef626 2275session_close(Session *s)
2276{
1b56ff3d 2277 int i;
2278
ff2d7a98 2279 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
416fd2a8 2280 if (s->ttyfd != -1)
3c0ef626 2281 session_pty_cleanup(s);
3c0ef626 2282 if (s->term)
2283 xfree(s->term);
2284 if (s->display)
2285 xfree(s->display);
e9a17296 2286 if (s->auth_display)
2287 xfree(s->auth_display);
3c0ef626 2288 if (s->auth_data)
2289 xfree(s->auth_data);
2290 if (s->auth_proto)
2291 xfree(s->auth_proto);
2292 s->used = 0;
1b56ff3d 2293 for (i = 0; i < s->num_env; i++) {
2294 xfree(s->env[i].name);
2295 xfree(s->env[i].val);
2296 }
2297 if (s->env != NULL)
2298 xfree(s->env);
3c0ef626 2299 session_proctitle(s);
2300}
2301
2302void
2303session_close_by_pid(pid_t pid, int status)
2304{
2305 Session *s = session_by_pid(pid);
2306 if (s == NULL) {
ff2d7a98 2307 debug("session_close_by_pid: no session for pid %ld",
2308 (long)pid);
3c0ef626 2309 return;
2310 }
2311 if (s->chanid != -1)
2312 session_exit_message(s, status);
2313 session_close(s);
2314}
2315
2316/*
2317 * this is called when a channel dies before
2318 * the session 'child' itself dies
2319 */
2320void
2321session_close_by_channel(int id, void *arg)
2322{
2323 Session *s = session_by_channel(id);
2324 if (s == NULL) {
2325 debug("session_close_by_channel: no session for id %d", id);
2326 return;
2327 }
ff2d7a98 2328 debug("session_close_by_channel: channel %d child %ld",
2329 id, (long)s->pid);
3c0ef626 2330 if (s->pid != 0) {
2331 debug("session_close_by_channel: channel %d: has child", id);
2332 /*
2333 * delay detach of session, but release pty, since
2334 * the fd's to the child are already closed
2335 */
416fd2a8 2336 if (s->ttyfd != -1)
3c0ef626 2337 session_pty_cleanup(s);
3c0ef626 2338 return;
2339 }
2340 /* detach by removing callback */
2341 channel_cancel_cleanup(s->chanid);
2342 s->chanid = -1;
2343 session_close(s);
2344}
2345
2346void
2980ea68 2347session_destroy_all(void (*closefunc)(Session *))
3c0ef626 2348{
2349 int i;
e9a17296 2350 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 2351 Session *s = &sessions[i];
2980ea68 2352 if (s->used) {
2353 if (closefunc != NULL)
2354 closefunc(s);
2355 else
2356 session_close(s);
2357 }
3c0ef626 2358 }
2359}
2360
2361static char *
2362session_tty_list(void)
2363{
2364 static char buf[1024];
2365 int i;
1c14df9e 2366 char *cp;
2367
3c0ef626 2368 buf[0] = '\0';
e9a17296 2369 for (i = 0; i < MAX_SESSIONS; i++) {
3c0ef626 2370 Session *s = &sessions[i];
2371 if (s->used && s->ttyfd != -1) {
416fd2a8 2372
1c14df9e 2373 if (strncmp(s->tty, "/dev/", 5) != 0) {
2374 cp = strrchr(s->tty, '/');
2375 cp = (cp == NULL) ? s->tty : cp + 1;
2376 } else
2377 cp = s->tty + 5;
416fd2a8 2378
3c0ef626 2379 if (buf[0] != '\0')
2380 strlcat(buf, ",", sizeof buf);
1c14df9e 2381 strlcat(buf, cp, sizeof buf);
3c0ef626 2382 }
2383 }
2384 if (buf[0] == '\0')
2385 strlcpy(buf, "notty", sizeof buf);
2386 return buf;
2387}
2388
2389void
2390session_proctitle(Session *s)
2391{
2392 if (s->pw == NULL)
2393 error("no user for session %d", s->self);
2394 else
2395 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2396}
2397
2398int
2399session_setup_x11fwd(Session *s)
2400{
2401 struct stat st;
e9a17296 2402 char display[512], auth_display[512];
2403 char hostname[MAXHOSTNAMELEN];
3c0ef626 2404
2405 if (no_x11_forwarding_flag) {
2406 packet_send_debug("X11 forwarding disabled in user configuration file.");
2407 return 0;
2408 }
2409 if (!options.x11_forwarding) {
2410 debug("X11 forwarding disabled in server configuration file.");
2411 return 0;
2412 }
2413 if (!options.xauth_location ||
2414 (stat(options.xauth_location, &st) == -1)) {
2415 packet_send_debug("No xauth program; cannot forward with spoofing.");
2416 return 0;
2417 }
2418 if (options.use_login) {
2419 packet_send_debug("X11 forwarding disabled; "
2420 "not compatible with UseLogin=yes.");
2421 return 0;
2422 }
2423 if (s->display != NULL) {
2424 debug("X11 display already set.");
2425 return 0;
2426 }
ff2d7a98 2427 if (x11_create_display_inet(options.x11_display_offset,
2428 options.x11_use_localhost, s->single_connection,
2429 &s->display_number) == -1) {
3c0ef626 2430 debug("x11_create_display_inet failed.");
2431 return 0;
2432 }
e9a17296 2433
2434 /* Set up a suitable value for the DISPLAY variable. */
2435 if (gethostname(hostname, sizeof(hostname)) < 0)
2436 fatal("gethostname: %.100s", strerror(errno));
2437 /*
2438 * auth_display must be used as the displayname when the
2439 * authorization entry is added with xauth(1). This will be
2440 * different than the DISPLAY string for localhost displays.
2441 */
2442 if (options.x11_use_localhost) {
ff2d7a98 2443 snprintf(display, sizeof display, "localhost:%u.%u",
e9a17296 2444 s->display_number, s->screen);
ff2d7a98 2445 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
e9a17296 2446 s->display_number, s->screen);
2447 s->display = xstrdup(display);
2448 s->auth_display = xstrdup(auth_display);
2449 } else {
2450#ifdef IPADDR_IN_DISPLAY
2451 struct hostent *he;
2452 struct in_addr my_addr;
2453
2454 he = gethostbyname(hostname);
2455 if (he == NULL) {
2456 error("Can't get IP address for X11 DISPLAY.");
2457 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2458 return 0;
2459 }
2460 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
ff2d7a98 2461 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
e9a17296 2462 s->display_number, s->screen);
2463#else
ff2d7a98 2464 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
e9a17296 2465 s->display_number, s->screen);
2466#endif
2467 s->display = xstrdup(display);
2468 s->auth_display = xstrdup(display);
2469 }
2470
3c0ef626 2471 return 1;
2472}
2473
2474static void
2475do_authenticated2(Authctxt *authctxt)
2476{
2477 server_loop2(authctxt);
416fd2a8 2478}
2479
2480void
2481do_cleanup(Authctxt *authctxt)
2482{
2483 static int called = 0;
2484
2485 debug("do_cleanup");
2486
2487 /* no cleanup if we're in the child for login shell */
2488 if (is_child)
2489 return;
2490
2491 /* avoid double cleanup */
2492 if (called)
2493 return;
2494 called = 1;
2495
2496 if (authctxt == NULL)
2497 return;
2498#ifdef KRB5
2499 if (options.kerberos_ticket_cleanup &&
2500 authctxt->krb5_ctx)
2501 krb5_cleanup_proc(authctxt);
2502#endif
2503
2504#ifdef GSSAPI
2505 if (compat20 && options.gss_cleanup_creds)
2506 ssh_gssapi_cleanup_creds();
b9a54c29 2507#endif
416fd2a8 2508
2509#ifdef USE_PAM
2510 if (options.use_pam) {
2511 sshpam_cleanup();
2512 sshpam_thread_cleanup();
2513 }
2514#endif
2515
2516 /* remove agent socket */
2517 auth_sock_cleanup_proc(authctxt->pw);
2518
2519 /*
2520 * Cleanup ptys/utmp only if privsep is disabled,
2521 * or if running in monitor.
2522 */
2523 if (!use_privsep || mm_is_monitor())
2524 session_destroy_all(session_pty_cleanup2);
3c0ef626 2525}
This page took 1.017092 seconds and 5 git commands to generate.