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