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