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