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