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