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