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