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