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