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