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