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