1 /*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
4 *
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose. Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
10 *
11 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34 /*
35 * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
36 * Use is subject to license terms.
37 */
38
39 #include "includes.h"
40 RCSID("$OpenBSD: session.c,v 1.150 2002/09/16 19:55:33 stevesk Exp $");
41
42 #ifdef HAVE_DEFOPEN
43 #include <deflt.h>
44 #include <ulimit.h>
45 #endif /* HAVE_DEFOPEN */
46
47 #ifdef HAVE_LIBGEN_H
48 #include <libgen.h>
49 #endif
50
51 #include <priv.h>
52
53 #include "ssh.h"
54 #include "ssh1.h"
55 #include "ssh2.h"
56 #include "xmalloc.h"
57 #include "sshpty.h"
58 #include "packet.h"
59 #include "buffer.h"
60 #include "mpaux.h"
61 #include "uidswap.h"
62 #include "compat.h"
63 #include "channels.h"
64 #include "bufaux.h"
65 #include "auth.h"
66 #include "auth-options.h"
67 #include "pathnames.h"
68 #include "log.h"
69 #include "servconf.h"
70 #include "sshlogin.h"
71 #include "serverloop.h"
72 #include "canohost.h"
73 #include "session.h"
74 #include "tildexpand.h"
75 #include "misc.h"
76 #include "sftp.h"
77
78 #ifdef USE_PAM
79 #include <security/pam_appl.h>
80 #endif /* USE_PAM */
81
82 #ifdef GSSAPI
83 #include "ssh-gss.h"
84 #endif
85
86 #ifdef ALTPRIVSEP
87 #include "altprivsep.h"
88 #endif /* ALTPRIVSEP */
89
90 #ifdef HAVE_CYGWIN
91 #include <windows.h>
92 #include <sys/cygwin.h>
93 #define is_winnt (GetVersion() < 0x80000000)
94 #endif
95
96 /* func */
97
98 Session *session_new(void);
99 void session_set_fds(Session *, int, int, int);
100 void session_pty_cleanup(void *);
101 void session_xauthfile_cleanup(void *s);
102 void session_proctitle(Session *);
103 int session_setup_x11fwd(Session *);
104 void do_exec_pty(Session *, const char *);
105 void do_exec_no_pty(Session *, const char *);
106 void do_exec(Session *, const char *);
107 void do_login(Session *, const char *);
108 void do_child(Session *, const char *);
109 void do_motd(void);
110 int check_quietlogin(Session *, const char *);
111
112 static void do_authenticated1(Authctxt *);
113 static void do_authenticated2(Authctxt *);
114
115 static int session_pty_req(Session *);
116 static int session_env_req(Session *s);
117 static void session_free_env(char ***envp);
118 static void safely_chroot(const char *path, uid_t uid);
119 static void drop_privs(uid_t uid);
120
121 #ifdef USE_PAM
122 static void session_do_pam(Session *, int);
123 #endif /* USE_PAM */
124
125 /* import */
126 extern ServerOptions options;
127 extern char *__progname;
128 extern int log_stderr;
129 extern int debug_flag;
130 extern u_int utmp_len;
131 extern void destroy_sensitive_data(void);
132
133 #ifdef GSSAPI
134 extern Gssctxt *xxx_gssctxt;
135 #endif /* GSSAPI */
136
137 /* original command from peer. */
138 const char *original_command = NULL;
139
140 /* data */
141 #define MAX_SESSIONS 10
142 Session sessions[MAX_SESSIONS];
143
144 #define SUBSYSTEM_NONE 0
145 #define SUBSYSTEM_EXT 1
146 #define SUBSYSTEM_INT_SFTP 2
147
148 #ifdef HAVE_LOGIN_CAP
149 login_cap_t *lc;
150 #endif
151
152 /* Name and directory of socket for authentication agent forwarding. */
153 static char *auth_sock_name = NULL;
154 static char *auth_sock_dir = NULL;
155
156 /* removes the agent forwarding socket */
157
158 static void
159 auth_sock_cleanup_proc(void *_pw)
160 {
161 struct passwd *pw = _pw;
162
163 if (auth_sock_name != NULL) {
164 temporarily_use_uid(pw);
165 unlink(auth_sock_name);
166 rmdir(auth_sock_dir);
167 auth_sock_name = NULL;
168 restore_uid();
169 }
170 }
171
172 static int
173 auth_input_request_forwarding(struct passwd * pw)
174 {
175 Channel *nc;
176 int sock;
177 struct sockaddr_un sunaddr;
178
179 if (auth_sock_name != NULL) {
180 error("authentication forwarding requested twice.");
181 return 0;
182 }
183
184 /* Temporarily drop privileged uid for mkdir/bind. */
185 temporarily_use_uid(pw);
186
187 /* Allocate a buffer for the socket name, and format the name. */
188 auth_sock_name = xmalloc(MAXPATHLEN);
189 auth_sock_dir = xmalloc(MAXPATHLEN);
190 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
191
192 /* Create private directory for socket */
193 if (mkdtemp(auth_sock_dir) == NULL) {
194 packet_send_debug("Agent forwarding disabled: "
195 "mkdtemp() failed: %.100s", strerror(errno));
196 restore_uid();
197 xfree(auth_sock_name);
198 xfree(auth_sock_dir);
199 auth_sock_name = NULL;
200 auth_sock_dir = NULL;
201 return 0;
202 }
203 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
204 auth_sock_dir, (long) getpid());
205
206 /* delete agent socket on fatal() */
207 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
208
209 /* Create the socket. */
210 sock = socket(AF_UNIX, SOCK_STREAM, 0);
211 if (sock < 0)
212 packet_disconnect("socket: %.100s", strerror(errno));
213
214 /* Bind it to the name. */
215 memset(&sunaddr, 0, sizeof(sunaddr));
216 sunaddr.sun_family = AF_UNIX;
217 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
218
219 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
220 packet_disconnect("bind: %.100s", strerror(errno));
221
222 /* Restore the privileged uid. */
223 restore_uid();
224
225 /* Start listening on the socket. */
226 if (listen(sock, 5) < 0)
227 packet_disconnect("listen: %.100s", strerror(errno));
228
229 /* Allocate a channel for the authentication agent socket. */
230 nc = channel_new("auth socket",
231 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
232 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
233 0, xstrdup("auth socket"), 1);
234 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
235 return 1;
236 }
237
238
239 void
240 do_authenticated(Authctxt *authctxt)
241 {
242 /* setup the channel layer */
243 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
244 channel_permit_all_opens();
245
246 if (compat20)
247 do_authenticated2(authctxt);
248 else
249 do_authenticated1(authctxt);
250
251 /* remove agent socket */
252 if (auth_sock_name != NULL)
253 auth_sock_cleanup_proc(authctxt->pw);
254 #ifdef KRB4
255 if (options.kerberos_ticket_cleanup)
256 krb4_cleanup_proc(authctxt);
257 #endif
258 #ifdef KRB5
259 if (options.kerberos_ticket_cleanup)
260 krb5_cleanup_proc(authctxt);
261 #endif
262 }
263
264 /*
265 * Prepares for an interactive session. This is called after the user has
266 * been successfully authenticated. During this message exchange, pseudo
267 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
268 * are requested, etc.
269 */
270 static void
271 do_authenticated1(Authctxt *authctxt)
272 {
273 Session *s;
274 char *command;
275 int success, type, screen_flag;
276 int enable_compression_after_reply = 0;
277 u_int proto_len, data_len, dlen, compression_level = 0;
278
279 s = session_new();
280 s->authctxt = authctxt;
281 s->pw = authctxt->pw;
282
283 /*
284 * We stay in this loop until the client requests to execute a shell
285 * or a command.
286 */
287 for (;;) {
288 success = 0;
289
290 /* Get a packet from the client. */
291 type = packet_read();
292
293 /* Process the packet. */
294 switch (type) {
295 case SSH_CMSG_REQUEST_COMPRESSION:
296 compression_level = packet_get_int();
297 packet_check_eom();
298 if (compression_level < 1 || compression_level > 9) {
299 packet_send_debug("Received illegal compression level %d.",
300 compression_level);
301 break;
302 }
303 if (!options.compression) {
304 debug2("compression disabled");
305 break;
306 }
307 /* Enable compression after we have responded with SUCCESS. */
308 enable_compression_after_reply = 1;
309 success = 1;
310 break;
311
312 case SSH_CMSG_REQUEST_PTY:
313 success = session_pty_req(s);
314 break;
315
316 case SSH_CMSG_X11_REQUEST_FORWARDING:
317 s->auth_proto = packet_get_string(&proto_len);
318 s->auth_data = packet_get_string(&data_len);
319
320 screen_flag = packet_get_protocol_flags() &
321 SSH_PROTOFLAG_SCREEN_NUMBER;
322 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
323
324 if (packet_remaining() == 4) {
325 if (!screen_flag)
326 debug2("Buggy client: "
327 "X11 screen flag missing");
328 s->screen = packet_get_int();
329 } else {
330 s->screen = 0;
331 }
332 packet_check_eom();
333 success = session_setup_x11fwd(s);
334 if (!success) {
335 xfree(s->auth_proto);
336 xfree(s->auth_data);
337 s->auth_proto = NULL;
338 s->auth_data = NULL;
339 }
340 break;
341
342 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
343 if (no_agent_forwarding_flag || compat13) {
344 debug("Authentication agent forwarding not permitted for this authentication.");
345 break;
346 }
347 debug("Received authentication agent forwarding request.");
348 success = auth_input_request_forwarding(s->pw);
349 break;
350
351 case SSH_CMSG_PORT_FORWARD_REQUEST:
352 if (no_port_forwarding_flag) {
353 debug("Port forwarding not permitted for this authentication.");
354 break;
355 }
356 if (!options.allow_tcp_forwarding) {
357 debug("Port forwarding not permitted.");
358 break;
359 }
360 debug("Received TCP/IP port forwarding request.");
361 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
362 success = 1;
363 break;
364
365 case SSH_CMSG_MAX_PACKET_SIZE:
366 if (packet_set_maxsize(packet_get_int()) > 0)
367 success = 1;
368 break;
369
370 #if defined(AFS) || defined(KRB5)
371 case SSH_CMSG_HAVE_KERBEROS_TGT:
372 if (!options.kerberos_tgt_passing) {
373 verbose("Kerberos TGT passing disabled.");
374 } else {
375 char *kdata = packet_get_string(&dlen);
376 packet_check_eom();
377
378 /* XXX - 0x41, see creds_to_radix version */
379 if (kdata[0] != 0x41) {
380 #ifdef KRB5
381 krb5_data tgt;
382 tgt.data = kdata;
383 tgt.length = dlen;
384
385 if (auth_krb5_tgt(s->authctxt, &tgt))
386 success = 1;
387 else
388 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
389 #endif /* KRB5 */
390 } else {
391 #ifdef AFS
392 if (auth_krb4_tgt(s->authctxt, kdata))
393 success = 1;
394 else
395 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
396 #endif /* AFS */
397 }
398 xfree(kdata);
399 }
400 break;
401 #endif /* AFS || KRB5 */
402
403 #ifdef AFS
404 case SSH_CMSG_HAVE_AFS_TOKEN:
405 if (!options.afs_token_passing || !k_hasafs()) {
406 verbose("AFS token passing disabled.");
407 } else {
408 /* Accept AFS token. */
409 char *token = packet_get_string(&dlen);
410 packet_check_eom();
411
412 if (auth_afs_token(s->authctxt, token))
413 success = 1;
414 else
415 verbose("AFS token refused for %.100s",
416 s->authctxt->user);
417 xfree(token);
418 }
419 break;
420 #endif /* AFS */
421
422 case SSH_CMSG_EXEC_SHELL:
423 case SSH_CMSG_EXEC_CMD:
424 if (type == SSH_CMSG_EXEC_CMD) {
425 command = packet_get_string(&dlen);
426 debug("Exec command '%.500s'", command);
427 do_exec(s, command);
428 xfree(command);
429 } else {
430 do_exec(s, NULL);
431 }
432 packet_check_eom();
433 session_close(s);
434 return;
435
436 default:
437 /*
438 * Any unknown messages in this phase are ignored,
439 * and a failure message is returned.
440 */
441 log("Unknown packet type received after authentication: %d", type);
442 }
443 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
444 packet_send();
445 packet_write_wait();
446
447 /* Enable compression now that we have replied if appropriate. */
448 if (enable_compression_after_reply) {
449 enable_compression_after_reply = 0;
450 packet_start_compression(compression_level);
451 }
452 }
453 }
454
455 /*
456 * This is called to fork and execute a command when we have no tty. This
457 * will call do_child from the child, and server_loop from the parent after
458 * setting up file descriptors and such.
459 */
460 void
461 do_exec_no_pty(Session *s, const char *command)
462 {
463 pid_t pid;
464
465 int inout[2], err[2];
466 /* Uses socket pairs to communicate with the program. */
467 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
468 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
469 packet_disconnect("Could not create socket pairs: %.100s",
470 strerror(errno));
471 if (s == NULL)
472 fatal("do_exec_no_pty: no session");
473
474 session_proctitle(s);
475
476 /* Fork the child. */
477 if ((pid = fork()) == 0) {
478 fatal_remove_all_cleanups();
479
480 /* Child. Reinitialize the log since the pid has changed. */
481 log_init(__progname, options.log_level, options.log_facility, log_stderr);
482
483 /*
484 * Create a new session and process group since the 4.4BSD
485 * setlogin() affects the entire process group.
486 */
487 if (setsid() < 0)
488 error("setsid failed: %.100s", strerror(errno));
489
490 /*
491 * Redirect stdin, stdout, and stderr. Stdin and stdout will
492 * use the same socket, as some programs (particularly rdist)
493 * seem to depend on it.
494 */
495 close(inout[1]);
496 close(err[1]);
497 if (dup2(inout[0], 0) < 0) /* stdin */
498 perror("dup2 stdin");
499 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
500 perror("dup2 stdout");
501 if (s->is_subsystem) {
502 /*
503 * Redirect the subsystem's stderr to /dev/null. We might send it
504 * over to the other side but changing that might break existing
505 * SSH clients.
506 */
507 close(err[0]);
508 if ((err[0] = open(_PATH_DEVNULL, O_WRONLY)) == -1)
509 fatal("Cannot open /dev/null: %.100s", strerror(errno));
510 }
511 if (dup2(err[0], 2) < 0) /* stderr */
512 perror("dup2 stderr");
513
514 #ifdef _UNICOS
515 cray_init_job(s->pw); /* set up cray jid and tmpdir */
516 #endif
517
518 /* Do processing for the child (exec command etc). */
519 do_child(s, command);
520 /* NOTREACHED */
521 }
522 #ifdef _UNICOS
523 signal(WJSIGNAL, cray_job_termination_handler);
524 #endif /* _UNICOS */
525 #ifdef HAVE_CYGWIN
526 if (is_winnt)
527 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
528 #endif
529 if (pid < 0)
530 packet_disconnect("fork failed: %.100s", strerror(errno));
531
532 s->pid = pid;
533 /* Set interactive/non-interactive mode. */
534 packet_set_interactive(s->display != NULL);
535
536 /* We are the parent. Close the child sides of the socket pairs. */
537 close(inout[0]);
538 close(err[0]);
539
540 /*
541 * Enter the interactive session. Note: server_loop must be able to
542 * handle the case that fdin and fdout are the same.
543 */
544 if (compat20) {
545 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
546 if (s->is_subsystem)
547 close(err[1]);
548 /* Don't close channel before sending exit-status! */
549 channel_set_wait_for_exit(s->chanid, 1);
550 } else {
551 server_loop(pid, inout[1], inout[1], err[1]);
552 /* server_loop has closed inout[1] and err[1]. */
553 }
554 }
555
556 /*
557 * This is called to fork and execute a command when we have a tty. This
558 * will call do_child from the child, and server_loop from the parent after
559 * setting up file descriptors, controlling tty, updating wtmp, utmp,
560 * lastlog, and other such operations.
561 */
562 void
563 do_exec_pty(Session *s, const char *command)
564 {
565 int fdout, ptyfd, ttyfd, ptymaster, pipe_fds[2];
566 pid_t pid;
567
568 if (s == NULL)
569 fatal("do_exec_pty: no session");
570 ptyfd = s->ptyfd;
571 ttyfd = s->ttyfd;
572
573 #ifdef USE_PAM
574 session_do_pam(s, 1); /* pam_open_session() */
575 #endif /* USE_PAM */
576
577 /*
578 * This pipe lets sshd wait for child to exec or exit. This is
579 * particularly important for ALTPRIVSEP because the child is
580 * the one to call the monitor to request a record_login() and
581 * we don't want the child and the parent to compete for the
582 * monitor's attention. But this is generic code and doesn't
583 * hurt to have here even if ALTPRIVSEP is not used.
584 */
585 if (pipe(pipe_fds) != 0)
586 packet_disconnect("pipe failed: %.100s", strerror(errno));
587
588 (void) fcntl(pipe_fds[0], F_SETFD, FD_CLOEXEC);
589 (void) fcntl(pipe_fds[1], F_SETFD, FD_CLOEXEC);
590
591 /* Fork the child. */
592 if ((pid = fork()) == 0) {
593 (void) close(pipe_fds[0]);
594
595 fatal_remove_all_cleanups();
596
597 /* Child. Reinitialize the log because the pid has changed. */
598 log_init(__progname, options.log_level, options.log_facility, log_stderr);
599 /* Close the master side of the pseudo tty. */
600 close(ptyfd);
601
602 /* Make the pseudo tty our controlling tty. */
603 pty_make_controlling_tty(&ttyfd, s->tty);
604
605 /* Redirect stdin/stdout/stderr from the pseudo tty. */
606 if (dup2(ttyfd, 0) < 0)
607 error("dup2 stdin: %s", strerror(errno));
608 if (dup2(ttyfd, 1) < 0)
609 error("dup2 stdout: %s", strerror(errno));
610 if (dup2(ttyfd, 2) < 0)
611 error("dup2 stderr: %s", strerror(errno));
612
613 /* Close the extra descriptor for the pseudo tty. */
614 close(ttyfd);
615
616 /* record login, etc. similar to login(1) */
617 do_login(s, command);
618
619 /*
620 * Close the pipe to the parent so it can re-enter its event
621 * loop and service the ptm; if enough debug messages get
622 * written to the pty before this happens there will be a
623 * deadlock.
624 */
625 close(pipe_fds[1]);
626
627 /*
628 * do_motd() was called originally in do_login(). However,
629 * when the /etc/motd file is large, a deadlock would happen,
630 * because
631 * - The child is blocked at fputs() to pty, when pty buffer
632 * is full.
633 * - The parent can not consume the pty buffer, because it is
634 * still blocked at read(pipe_fds[0]).
635 *
636 * To resolve the deadlock issue, we defer do_motd() after
637 * close(pipe_fds[1]).
638 */
639 do_motd();
640
641 /* Do common processing for the child, such as execing the command. */
642 do_child(s, command);
643 /* NOTREACHED */
644 }
645
646 /* Wait for child to exec() or exit() */
647 (void) close(pipe_fds[1]);
648 (void) read(pipe_fds[0], &pipe_fds[1], sizeof(int));
649
650 #ifdef _UNICOS
651 signal(WJSIGNAL, cray_job_termination_handler);
652 #endif /* _UNICOS */
653 #ifdef HAVE_CYGWIN
654 if (is_winnt)
655 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
656 #endif
657 if (pid < 0)
658 packet_disconnect("fork failed: %.100s", strerror(errno));
659 s->pid = pid;
660
661 /* Parent. Close the slave side of the pseudo tty. */
662 close(ttyfd);
663
664 /*
665 * Create another descriptor of the pty master side for use as the
666 * standard input. We could use the original descriptor, but this
667 * simplifies code in server_loop. The descriptor is bidirectional.
668 */
669 fdout = dup(ptyfd);
670 if (fdout < 0)
671 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
672
673 /* we keep a reference to the pty master */
674 ptymaster = dup(ptyfd);
675 if (ptymaster < 0)
676 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
677 s->ptymaster = ptymaster;
678
679 /* Enter interactive session. */
680 packet_set_interactive(1);
681 if (compat20) {
682 session_set_fds(s, ptyfd, fdout, -1);
683 /* Don't close channel before sending exit-status! */
684 channel_set_wait_for_exit(s->chanid, 1);
685 } else {
686 server_loop(pid, ptyfd, fdout, -1);
687 /* server_loop _has_ closed ptyfd and fdout. */
688 }
689 }
690
691 /*
692 * This is called to fork and execute a command. If another command is
693 * to be forced, execute that instead.
694 */
695 void
696 do_exec(Session *s, const char *command)
697 {
698 if (command)
699 s->command = xstrdup(command);
700
701 if (forced_command) {
702 original_command = command;
703 command = forced_command;
704 debug("Forced command '%.900s'", command);
705 }
706
707 if (s->ttyfd != -1)
708 do_exec_pty(s, command);
709 else
710 do_exec_no_pty(s, command);
711
712 original_command = NULL;
713 }
714
715
716 /* administrative, login(1)-like work */
717 void
718 do_login(Session *s, const char *command)
719 {
720 #ifndef ALTPRIVSEP
721 struct passwd * pw = s->pw;
722 #endif /* ALTPRIVSEP*/
723 pid_t pid = getpid();
724
725 /* Record that there was a login on that tty from the remote host. */
726 #ifdef ALTPRIVSEP
727 debug3("Recording SSHv2 channel login in utmpx/wtmpx");
728 altprivsep_record_login(pid, s->tty);
729 #endif /* ALTPRIVSEP*/
730
731 if (check_quietlogin(s, command))
732 return;
733
734 #ifdef USE_PAM
735 print_pam_messages();
736 #endif /* USE_PAM */
737 #ifdef WITH_AIXAUTHENTICATE
738 if (aixloginmsg && *aixloginmsg)
739 printf("%s\n", aixloginmsg);
740 #endif /* WITH_AIXAUTHENTICATE */
741 }
742
743 /*
744 * Display the message of the day.
745 */
746 void
747 do_motd(void)
748 {
749 FILE *f;
750 char buf[256];
751
752 if (options.print_motd) {
753 #ifdef HAVE_LOGIN_CAP
754 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
755 "/etc/motd"), "r");
756 #else
757 f = fopen("/etc/motd", "r");
758 #endif
759 if (f) {
760 while (fgets(buf, sizeof(buf), f))
761 fputs(buf, stdout);
762 fclose(f);
763 }
764 }
765 }
766
767
768 /*
769 * Check for quiet login, either .hushlogin or command given.
770 */
771 int
772 check_quietlogin(Session *s, const char *command)
773 {
774 char buf[256];
775 struct passwd *pw = s->pw;
776 struct stat st;
777
778 /* Return 1 if .hushlogin exists or a command given. */
779 if (command != NULL)
780 return 1;
781 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
782 #ifdef HAVE_LOGIN_CAP
783 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
784 return 1;
785 #else
786 if (stat(buf, &st) >= 0)
787 return 1;
788 #endif
789 return 0;
790 }
791
792 /*
793 * Sets the value of the given variable in the environment. If the variable
794 * already exists, its value is overriden.
795 */
796 void
797 child_set_env(char ***envp, u_int *envsizep, const char *name,
798 const char *value)
799 {
800 debug3("child_set_env(%s, %s)", name, value);
801 child_set_env_silent(envp, envsizep, name, value);
802 }
803
804
805 void
806 child_set_env_silent(char ***envp, u_int *envsizep, const char *name,
807 const char *value)
808 {
809 u_int i, namelen;
810 char **env;
811
812 /*
813 * Find the slot where the value should be stored. If the variable
814 * already exists, we reuse the slot; otherwise we append a new slot
815 * at the end of the array, expanding if necessary.
816 */
817 env = *envp;
818 namelen = strlen(name);
819 for (i = 0; env[i]; i++)
820 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
821 break;
822 if (env[i]) {
823 /* Reuse the slot. */
824 xfree(env[i]);
825 } else {
826 /* New variable. Expand if necessary. */
827 if (i >= (*envsizep) - 1) {
828 if (*envsizep >= 1000)
829 fatal("child_set_env: too many env vars,"
830 " skipping: %.100s", name);
831 (*envsizep) += 50;
832 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
833 }
834 /* Need to set the NULL pointer at end of array beyond the new slot. */
835 env[i + 1] = NULL;
836 }
837
838 /* Allocate space and format the variable in the appropriate slot. */
839 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
840 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
841 }
842
843 /*
844 * Reads environment variables from the given file and adds/overrides them
845 * into the environment. If the file does not exist, this does nothing.
846 * Otherwise, it must consist of empty lines, comments (line starts with '#')
847 * and assignments of the form name=value. No other forms are allowed.
848 */
849 static void
850 read_environment_file(char ***env, u_int *envsize,
851 const char *filename)
852 {
853 FILE *f;
854 char buf[4096];
855 char *cp, *value;
856 u_int lineno = 0;
857
858 f = fopen(filename, "r");
859 if (!f)
860 return;
861
862 while (fgets(buf, sizeof(buf), f)) {
863 if (++lineno > 1000)
864 fatal("Too many lines in environment file %s", filename);
865 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
866 ;
867 if (!*cp || *cp == '#' || *cp == '\n')
868 continue;
869 if (strchr(cp, '\n'))
870 *strchr(cp, '\n') = '\0';
871 value = strchr(cp, '=');
872 if (value == NULL) {
873 fprintf(stderr, gettext("Bad line %u in %.100s\n"),
874 lineno, filename);
875 continue;
876 }
877 /*
878 * Replace the equals sign by nul, and advance value to
879 * the value string.
880 */
881 *value = '\0';
882 value++;
883 child_set_env(env, envsize, cp, value);
884 }
885 fclose(f);
886 }
887
888 void copy_environment(char **source, char ***env, u_int *envsize)
889 {
890 char *var_name, *var_val;
891 int i;
892
893 if (source == NULL)
894 return;
895
896 for(i = 0; source[i] != NULL; i++) {
897 var_name = xstrdup(source[i]);
898 if ((var_val = strstr(var_name, "=")) == NULL) {
899 xfree(var_name);
900 continue;
901 }
902 *var_val++ = '\0';
903
904 debug3("Copy environment: %s=%s", var_name, var_val);
905 child_set_env(env, envsize, var_name, var_val);
906
907 xfree(var_name);
908 }
909 }
910
911 #ifdef HAVE_DEFOPEN
912 static
913 void
914 deflt_do_setup_env(Session *s, const char *shell, char ***env, u_int *envsize)
915 {
916 int flags;
917 char *ptr;
918 mode_t Umask = 022;
919
920 if (defopen(_PATH_DEFAULT_LOGIN))
921 return;
922
923 /* Ignore case */
924 flags = defcntl(DC_GETFLAGS, 0);
925 TURNOFF(flags, DC_CASE);
926 (void) defcntl(DC_SETFLAGS, flags);
927
928 /* TZ & HZ */
929 if ((ptr = defread("TIMEZONE=")) != NULL)
930 child_set_env(env, envsize, "TZ", ptr);
931 if ((ptr = defread("HZ=")) != NULL)
932 child_set_env(env, envsize, "HZ", ptr);
933
934 /* PATH */
935 if (s->pw->pw_uid != 0 && (ptr = defread("PATH=")) != NULL)
936 child_set_env(env, envsize, "PATH", ptr);
937 if (s->pw->pw_uid == 0 && (ptr = defread("SUPATH=")) != NULL)
938 child_set_env(env, envsize, "PATH", ptr);
939
940 /* SHELL */
941 if ((ptr = defread("ALTSHELL=")) != NULL) {
942 if (strcasecmp("YES", ptr) == 0)
943 child_set_env(env, envsize, "SHELL", shell);
944 else
945 child_set_env(env, envsize, "SHELL", "");
946 }
947
948 /* UMASK */
949 if ((ptr = defread("UMASK=")) != NULL &&
950 sscanf(ptr, "%lo", &Umask) == 1 &&
951 Umask <= (mode_t)0777)
952 (void) umask(Umask);
953 else
954 (void) umask(022);
955
956 /* ULIMIT */
957 if ((ptr = defread("ULIMIT=")) != NULL && atol(ptr) > 0L &&
958 ulimit(UL_SETFSIZE, atol(ptr)) < 0L)
959 error("Could not set ULIMIT to %ld from %s\n", atol(ptr),
960 _PATH_DEFAULT_LOGIN);
961
962 (void) defopen(NULL);
963 }
964 #endif /* HAVE_DEFOPEN */
965
966 static char **
967 do_setup_env(Session *s, const char *shell)
968 {
969 char buf[256];
970 char path_maildir[] = _PATH_MAILDIR;
971 u_int i, envsize, pm_len;
972 char **env;
973 struct passwd *pw = s->pw;
974
975 /* Initialize the environment. */
976 envsize = 100;
977 env = xmalloc(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 copy_environment(environ, &env, &envsize);
986 #endif
987
988 #ifdef GSSAPI
989 /* Allow any GSSAPI methods that we've used to alter
990 * the childs environment as they see fit
991 */
992 ssh_gssapi_do_child(xxx_gssctxt, &env,&envsize);
993 #endif
994
995 /* Set basic environment. */
996 child_set_env(&env, &envsize, "USER", pw->pw_name);
997 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
998 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
999 #ifdef HAVE_LOGIN_CAP
1000 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1001 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1002 else
1003 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1004 #else /* HAVE_LOGIN_CAP */
1005 # ifndef HAVE_CYGWIN
1006 /*
1007 * There's no standard path on Windows. The path contains
1008 * important components pointing to the system directories,
1009 * needed for loading shared libraries. So the path better
1010 * remains intact here.
1011 */
1012 # ifdef SUPERUSER_PATH
1013 child_set_env(&env, &envsize, "PATH",
1014 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
1015 # else
1016 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1017 # endif /* SUPERUSER_PATH */
1018 # endif /* HAVE_CYGWIN */
1019 #endif /* HAVE_LOGIN_CAP */
1020
1021 pm_len = strlen(path_maildir);
1022 if (path_maildir[pm_len - 1] == '/' && pm_len > 1)
1023 path_maildir[pm_len - 1] = NULL;
1024 snprintf(buf, sizeof buf, "%.200s/%.50s",
1025 path_maildir, pw->pw_name);
1026 child_set_env(&env, &envsize, "MAIL", buf);
1027
1028 /* Normal systems set SHELL by default. */
1029 child_set_env(&env, &envsize, "SHELL", shell);
1030
1031 #ifdef HAVE_DEFOPEN
1032 deflt_do_setup_env(s, shell, &env, &envsize);
1033 #endif /* HAVE_DEFOPEN */
1034
1035 #define PASS_ENV(x) \
1036 if (getenv(x)) \
1037 child_set_env(&env, &envsize, x, getenv(x));
1038
1039 if (getenv("TZ"))
1040 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1041
1042 if (s->auth_file != NULL)
1043 child_set_env(&env, &envsize, "XAUTHORITY", s->auth_file);
1044
1045 PASS_ENV("LANG")
1046 PASS_ENV("LC_ALL")
1047 PASS_ENV("LC_CTYPE")
1048 PASS_ENV("LC_COLLATE")
1049 PASS_ENV("LC_TIME")
1050 PASS_ENV("LC_NUMERIC")
1051 PASS_ENV("LC_MONETARY")
1052 PASS_ENV("LC_MESSAGES")
1053
1054 #undef PASS_ENV
1055
1056 if (s->env != NULL)
1057 copy_environment(s->env, &env, &envsize);
1058
1059 /* Set custom environment options from RSA authentication. */
1060 while (custom_environment) {
1061 struct envstring *ce = custom_environment;
1062 char *str = ce->s;
1063
1064 for (i = 0; str[i] != '=' && str[i]; i++)
1065 ;
1066 if (str[i] == '=') {
1067 str[i] = 0;
1068 child_set_env(&env, &envsize, str, str + i + 1);
1069 }
1070 custom_environment = ce->next;
1071 xfree(ce->s);
1072 xfree(ce);
1073 }
1074
1075 /* SSH_CLIENT deprecated */
1076 snprintf(buf, sizeof buf, "%.50s %d %d",
1077 get_remote_ipaddr(), get_remote_port(), get_local_port());
1078 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1079
1080 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1081 get_remote_ipaddr(), get_remote_port(),
1082 get_local_ipaddr(packet_get_connection_in()), get_local_port());
1083 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1084
1085 if (s->ttyfd != -1)
1086 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1087 if (s->term)
1088 child_set_env(&env, &envsize, "TERM", s->term);
1089 if (s->display)
1090 child_set_env(&env, &envsize, "DISPLAY", s->display);
1091 if (original_command)
1092 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1093 original_command);
1094
1095 #ifdef _UNICOS
1096 if (cray_tmpdir[0] != '\0')
1097 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1098 #endif /* _UNICOS */
1099
1100 #ifdef _AIX
1101 {
1102 char *cp;
1103
1104 if ((cp = getenv("AUTHSTATE")) != NULL)
1105 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1106 if ((cp = getenv("KRB5CCNAME")) != NULL)
1107 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1108 read_environment_file(&env, &envsize, "/etc/environment");
1109 }
1110 #endif
1111 #ifdef KRB4
1112 if (s->authctxt->krb4_ticket_file)
1113 child_set_env(&env, &envsize, "KRBTKFILE",
1114 s->authctxt->krb4_ticket_file);
1115 #endif
1116 #ifdef KRB5
1117 if (s->authctxt->krb5_ticket_file)
1118 child_set_env(&env, &envsize, "KRB5CCNAME",
1119 s->authctxt->krb5_ticket_file);
1120 #endif
1121 #ifdef USE_PAM
1122 /*
1123 * Pull in any environment variables that may have
1124 * been set by PAM.
1125 */
1126 {
1127 char **p;
1128
1129 p = fetch_pam_environment(s->authctxt);
1130 copy_environment(p, &env, &envsize);
1131 free_pam_environment(p);
1132 }
1133 #endif /* USE_PAM */
1134
1135 if (auth_sock_name != NULL)
1136 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1137 auth_sock_name);
1138
1139 /* read $HOME/.ssh/environment. */
1140 if (options.permit_user_env) {
1141 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1142 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1143 read_environment_file(&env, &envsize, buf);
1144 }
1145 if (debug_flag) {
1146 /* dump the environment */
1147 fprintf(stderr, gettext("Environment:\n"));
1148 for (i = 0; env[i]; i++)
1149 fprintf(stderr, " %.200s\n", env[i]);
1150 }
1151 return env;
1152 }
1153
1154 /*
1155 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1156 * first in this order).
1157 */
1158 static void
1159 do_rc_files(Session *s, const char *shell)
1160 {
1161 FILE *f = NULL;
1162 char cmd[1024];
1163 int do_xauth;
1164 struct stat st;
1165
1166 do_xauth =
1167 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1168
1169 /* ignore _PATH_SSH_USER_RC for subsystems */
1170 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1171 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1172 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1173 if (debug_flag)
1174 fprintf(stderr, "Running %s\n", cmd);
1175 f = popen(cmd, "w");
1176 if (f) {
1177 if (do_xauth)
1178 fprintf(f, "%s %s\n", s->auth_proto,
1179 s->auth_data);
1180 pclose(f);
1181 } else
1182 fprintf(stderr, "Could not run %s\n",
1183 _PATH_SSH_USER_RC);
1184 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1185 if (debug_flag)
1186 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1187 _PATH_SSH_SYSTEM_RC);
1188 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "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_SYSTEM_RC);
1197 } else if (do_xauth && options.xauth_location != NULL) {
1198 /* Add authority data to .Xauthority if appropriate. */
1199 if (debug_flag) {
1200 fprintf(stderr,
1201 "Running %.500s add "
1202 "%.100s %.100s %.100s\n",
1203 options.xauth_location, s->auth_display,
1204 s->auth_proto, s->auth_data);
1205 }
1206 snprintf(cmd, sizeof cmd, "%s -q -",
1207 options.xauth_location);
1208 f = popen(cmd, "w");
1209 if (f) {
1210 fprintf(f, "add %s %s %s\n",
1211 s->auth_display, s->auth_proto,
1212 s->auth_data);
1213 pclose(f);
1214 } else {
1215 fprintf(stderr, "Could not run %s\n",
1216 cmd);
1217 }
1218 }
1219 }
1220
1221 /* Disallow logins if /etc/nologin exists. This does not apply to root. */
1222 static void
1223 do_nologin(struct passwd *pw)
1224 {
1225 FILE *f = NULL;
1226 char buf[1024];
1227 struct stat sb;
1228
1229 if (pw->pw_uid == 0)
1230 return;
1231
1232 if (stat(_PATH_NOLOGIN, &sb) == -1)
1233 return;
1234
1235 /* /etc/nologin exists. Print its contents if we can and exit. */
1236 log("User %.100s not allowed because %s exists.", pw->pw_name,
1237 _PATH_NOLOGIN);
1238 if ((f = fopen(_PATH_NOLOGIN, "r")) != NULL) {
1239 while (fgets(buf, sizeof(buf), f))
1240 fputs(buf, stderr);
1241 fclose(f);
1242 }
1243 exit(254);
1244 }
1245
1246 /* Chroot into ChrootDirectory if the option is set. */
1247 void
1248 chroot_if_needed(struct passwd *pw)
1249 {
1250 char *chroot_path, *tmp;
1251
1252 if (chroot_requested(options.chroot_directory)) {
1253 tmp = tilde_expand_filename(options.chroot_directory,
1254 pw->pw_uid);
1255 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1256 "u", pw->pw_name, (char *)NULL);
1257 safely_chroot(chroot_path, pw->pw_uid);
1258 free(tmp);
1259 free(chroot_path);
1260 }
1261 }
1262
1263 /*
1264 * Chroot into a directory after checking it for safety: all path components
1265 * must be root-owned directories with strict permissions.
1266 */
1267 static void
1268 safely_chroot(const char *path, uid_t uid)
1269 {
1270 const char *cp;
1271 char component[MAXPATHLEN];
1272 struct stat st;
1273
1274 if (*path != '/')
1275 fatal("chroot path does not begin at root");
1276 if (strlen(path) >= sizeof(component))
1277 fatal("chroot path too long");
1278
1279 /*
1280 * Descend the path, checking that each component is a
1281 * root-owned directory with strict permissions.
1282 */
1283 for (cp = path; cp != NULL;) {
1284 if ((cp = strchr(cp, '/')) == NULL)
1285 strlcpy(component, path, sizeof(component));
1286 else {
1287 cp++;
1288 memcpy(component, path, cp - path);
1289 component[cp - path] = '\0';
1290 }
1291
1292 debug3("%s: checking '%s'", __func__, component);
1293
1294 if (stat(component, &st) != 0)
1295 fatal("%s: stat(\"%s\"): %s", __func__,
1296 component, strerror(errno));
1297 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1298 fatal("bad ownership or modes for chroot "
1299 "directory %s\"%s\"",
1300 cp == NULL ? "" : "component ", component);
1301 if (!S_ISDIR(st.st_mode))
1302 fatal("chroot path %s\"%s\" is not a directory",
1303 cp == NULL ? "" : "component ", component);
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 static void
1318 launch_login(struct passwd *pw, const char *hostname)
1319 {
1320 /* Launch login(1). */
1321
1322 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1323 #ifdef xxxLOGIN_NEEDS_TERM
1324 (s->term ? s->term : "unknown"),
1325 #endif /* LOGIN_NEEDS_TERM */
1326 #ifdef LOGIN_NO_ENDOPT
1327 "-p", "-f", pw->pw_name, (char *)NULL);
1328 #else
1329 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1330 #endif
1331
1332 /* Login couldn't be executed, die. */
1333
1334 perror("login");
1335 exit(1);
1336 }
1337
1338 /*
1339 * Performs common processing for the child, such as setting up the
1340 * environment, closing extra file descriptors, setting the user and group
1341 * ids, and executing the command or shell.
1342 */
1343 #define ARGV_MAX 10
1344 void
1345 do_child(Session *s, const char *command)
1346 {
1347 extern char **environ;
1348 char **env;
1349 char *argv[ARGV_MAX];
1350 const char *shell, *shell0;
1351 struct passwd *pw = s->pw;
1352
1353 /* remove hostkey from the child's memory */
1354 destroy_sensitive_data();
1355
1356 do_nologin(pw);
1357 chroot_if_needed(pw);
1358
1359 /*
1360 * Get the shell from the password data. An empty shell field is
1361 * legal, and means /bin/sh.
1362 */
1363 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1364 #ifdef HAVE_LOGIN_CAP
1365 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1366 #endif
1367
1368 env = do_setup_env(s, shell);
1369
1370 /*
1371 * Close the connection descriptors; note that this is the child, and
1372 * the server will still have the socket open, and it is important
1373 * that we do not shutdown it. Note that the descriptors cannot be
1374 * closed before building the environment, as we call
1375 * get_remote_ipaddr there.
1376 */
1377 if (packet_get_connection_in() == packet_get_connection_out())
1378 close(packet_get_connection_in());
1379 else {
1380 close(packet_get_connection_in());
1381 close(packet_get_connection_out());
1382 }
1383 /*
1384 * Close all descriptors related to channels. They will still remain
1385 * open in the parent.
1386 */
1387 /* XXX better use close-on-exec? -markus */
1388 channel_close_all();
1389
1390 /*
1391 * Close any extra file descriptors. Note that there may still be
1392 * descriptors left by system functions. They will be closed later.
1393 */
1394 endpwent();
1395
1396 /*
1397 * Must switch to the new environment variables so that .ssh/rc,
1398 * /etc/ssh/sshrc, and xauth are run in the proper environment.
1399 */
1400 environ = env;
1401
1402 /*
1403 * New environment has been installed. We need to update locale
1404 * so that error messages beyond this point have the proper
1405 * character encoding.
1406 */
1407 (void) setlocale(LC_ALL, "");
1408
1409 /*
1410 * Close any extra open file descriptors so that we don\'t have them
1411 * hanging around in clients. Note that we want to do this after
1412 * initgroups, because at least on Solaris 2.3 it leaves file
1413 * descriptors open.
1414 */
1415 closefrom(STDERR_FILENO + 1);
1416
1417 #ifdef AFS
1418 /* Try to get AFS tokens for the local cell. */
1419 if (k_hasafs()) {
1420 char cell[64];
1421
1422 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1423 krb_afslog(cell, 0);
1424
1425 krb_afslog(0, 0);
1426 }
1427 #endif /* AFS */
1428
1429 /* Change current directory to the user's home directory. */
1430 if (chdir(pw->pw_dir) < 0) {
1431 /* Suppress missing homedir warning for chroot case */
1432 if (!chroot_requested(options.chroot_directory))
1433 fprintf(stderr, "Could not chdir to home "
1434 "directory %s: %s\n", pw->pw_dir,
1435 strerror(errno));
1436 }
1437
1438 do_rc_files(s, shell);
1439
1440 /* restore SIGPIPE for child */
1441 signal(SIGPIPE, SIG_DFL);
1442
1443 if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1444 int i;
1445 char *p, *args;
1446 extern int optind, optreset;
1447
1448 /* This will set the E/P sets here, simulating exec(2). */
1449 drop_privs(pw->pw_uid);
1450
1451 setproctitle("%s@internal-sftp-server", s->pw->pw_name);
1452 args = xstrdup(command ? command : "sftp-server");
1453
1454 i = 0;
1455 for ((p = strtok(args, " ")); p != NULL; (p = strtok(NULL, " "))) {
1456 if (i < ARGV_MAX - 1)
1457 argv[i++] = p;
1458 }
1459
1460 argv[i] = NULL;
1461 optind = optreset = 1;
1462 __progname = argv[0];
1463 exit(sftp_server_main(i, argv, s->pw));
1464 }
1465
1466 /* Get the last component of the shell name. */
1467 if ((shell0 = strrchr(shell, '/')) != NULL)
1468 shell0++;
1469 else
1470 shell0 = shell;
1471
1472 /*
1473 * If we have no command, execute the shell. In this case, the shell
1474 * name to be passed in argv[0] is preceded by '-' to indicate that
1475 * this is a login shell.
1476 */
1477 if (!command) {
1478 char argv0[256];
1479
1480 /* Start the shell. Set initial character to '-'. */
1481 argv0[0] = '-';
1482
1483 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1484 >= sizeof(argv0) - 1) {
1485 errno = EINVAL;
1486 perror(shell);
1487 exit(1);
1488 }
1489
1490 /* Execute the shell. */
1491 argv[0] = argv0;
1492 argv[1] = NULL;
1493 execve(shell, argv, env);
1494
1495 /* Executing the shell failed. */
1496 perror(shell);
1497 exit(1);
1498 }
1499 /*
1500 * Execute the command using the user's shell. This uses the -c
1501 * option to execute the command.
1502 */
1503 argv[0] = (char *) shell0;
1504 argv[1] = "-c";
1505 argv[2] = (char *) command;
1506 argv[3] = NULL;
1507 execve(shell, argv, env);
1508 perror(shell);
1509 exit(1);
1510 }
1511
1512 Session *
1513 session_new(void)
1514 {
1515 int i;
1516 static int did_init = 0;
1517 if (!did_init) {
1518 debug("session_new: init");
1519 for (i = 0; i < MAX_SESSIONS; i++) {
1520 sessions[i].used = 0;
1521 }
1522 did_init = 1;
1523 }
1524 for (i = 0; i < MAX_SESSIONS; i++) {
1525 Session *s = &sessions[i];
1526 if (! s->used) {
1527 memset(s, 0, sizeof(*s));
1528 s->chanid = -1;
1529 s->ptyfd = -1;
1530 s->ttyfd = -1;
1531 s->used = 1;
1532 s->self = i;
1533 s->env = NULL;
1534 debug("session_new: session %d", i);
1535 return s;
1536 }
1537 }
1538 return NULL;
1539 }
1540
1541 static void
1542 session_dump(void)
1543 {
1544 int i;
1545 for (i = 0; i < MAX_SESSIONS; i++) {
1546 Session *s = &sessions[i];
1547 debug("dump: used %d session %d %p channel %d pid %ld",
1548 s->used,
1549 s->self,
1550 s,
1551 s->chanid,
1552 (long)s->pid);
1553 }
1554 }
1555
1556 int
1557 session_open(Authctxt *authctxt, int chanid)
1558 {
1559 Session *s = session_new();
1560 debug("session_open: channel %d", chanid);
1561 if (s == NULL) {
1562 error("no more sessions");
1563 return 0;
1564 }
1565 s->authctxt = authctxt;
1566 s->pw = authctxt->pw;
1567 if (s->pw == NULL)
1568 fatal("no user for session %d", s->self);
1569 debug("session_open: session %d: link with channel %d", s->self, chanid);
1570 s->chanid = chanid;
1571 return 1;
1572 }
1573
1574 #ifndef lint
1575 Session *
1576 session_by_tty(char *tty)
1577 {
1578 int i;
1579 for (i = 0; i < MAX_SESSIONS; i++) {
1580 Session *s = &sessions[i];
1581 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1582 debug("session_by_tty: session %d tty %s", i, tty);
1583 return s;
1584 }
1585 }
1586 debug("session_by_tty: unknown tty %.100s", tty);
1587 session_dump();
1588 return NULL;
1589 }
1590 #endif /* lint */
1591
1592 static Session *
1593 session_by_channel(int id)
1594 {
1595 int i;
1596 for (i = 0; i < MAX_SESSIONS; i++) {
1597 Session *s = &sessions[i];
1598 if (s->used && s->chanid == id) {
1599 debug("session_by_channel: session %d channel %d", i, id);
1600 return s;
1601 }
1602 }
1603 debug("session_by_channel: unknown channel %d", id);
1604 session_dump();
1605 return NULL;
1606 }
1607
1608 static Session *
1609 session_by_pid(pid_t pid)
1610 {
1611 int i;
1612 debug("session_by_pid: pid %ld", (long)pid);
1613 for (i = 0; i < MAX_SESSIONS; i++) {
1614 Session *s = &sessions[i];
1615 if (s->used && s->pid == pid)
1616 return s;
1617 }
1618 error("session_by_pid: unknown pid %ld", (long)pid);
1619 session_dump();
1620 return NULL;
1621 }
1622
1623 static int
1624 session_window_change_req(Session *s)
1625 {
1626 s->col = packet_get_int();
1627 s->row = packet_get_int();
1628 s->xpixel = packet_get_int();
1629 s->ypixel = packet_get_int();
1630 packet_check_eom();
1631 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1632 return 1;
1633 }
1634
1635 static int
1636 session_pty_req(Session *s)
1637 {
1638 u_int len;
1639 int n_bytes;
1640
1641 if (no_pty_flag) {
1642 debug("Allocating a pty not permitted for this authentication.");
1643 return 0;
1644 }
1645 if (s->ttyfd != -1) {
1646 packet_disconnect("Protocol error: you already have a pty.");
1647 return 0;
1648 }
1649
1650 s->term = packet_get_string(&len);
1651
1652 if (compat20) {
1653 s->col = packet_get_int();
1654 s->row = packet_get_int();
1655 } else {
1656 s->row = packet_get_int();
1657 s->col = packet_get_int();
1658 }
1659 s->xpixel = packet_get_int();
1660 s->ypixel = packet_get_int();
1661
1662 if (strcmp(s->term, "") == 0) {
1663 xfree(s->term);
1664 s->term = NULL;
1665 }
1666
1667 /* Allocate a pty and open it. */
1668 debug("Allocating pty.");
1669 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1670 if (s->term)
1671 xfree(s->term);
1672 s->term = NULL;
1673 s->ptyfd = -1;
1674 s->ttyfd = -1;
1675 error("session_pty_req: session %d alloc failed", s->self);
1676 return 0;
1677 }
1678 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1679
1680 /* for SSH1 the tty modes length is not given */
1681 if (!compat20)
1682 n_bytes = packet_remaining();
1683 tty_parse_modes(s->ttyfd, &n_bytes);
1684
1685 /*
1686 * Add a cleanup function to clear the utmp entry and record logout
1687 * time in case we call fatal() (e.g., the connection gets closed).
1688 */
1689 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1690 pty_setowner(s->pw, s->tty);
1691
1692 /* Set window size from the packet. */
1693 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1694
1695 packet_check_eom();
1696 session_proctitle(s);
1697 return 1;
1698 }
1699
1700 static int
1701 session_subsystem_req(Session *s)
1702 {
1703 struct stat st;
1704 u_int len;
1705 int success = 0;
1706 char *prog, *cmd, *subsys = packet_get_string(&len);
1707 u_int i;
1708
1709 packet_check_eom();
1710 log("subsystem request for %.100s", subsys);
1711
1712 for (i = 0; i < options.num_subsystems; i++) {
1713 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1714 prog = options.subsystem_command[i];
1715 cmd = options.subsystem_args[i];
1716 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1717 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1718 /*
1719 * We must stat(2) the subsystem before we chroot in
1720 * order to be able to send a proper error message.
1721 */
1722 } else if (chroot_requested(options.chroot_directory)) {
1723 char chdirsub[MAXPATHLEN];
1724
1725 strlcpy(chdirsub, options.chroot_directory,
1726 sizeof (chdirsub));
1727 strlcat(chdirsub, "/", sizeof (chdirsub));
1728 strlcat(chdirsub, prog, sizeof (chdirsub));
1729 if (stat(chdirsub, &st) < 0) {
1730 error("subsystem: cannot stat %s under "
1731 "chroot directory %s: %s", prog,
1732 options.chroot_directory,
1733 strerror(errno));
1734 if (strcmp(subsys, "sftp") == 0)
1735 error("subsystem: please see "
1736 "the Subsystem option in "
1737 "sshd_config(4) for an "
1738 "explanation of '%s'.",
1739 INTERNAL_SFTP_NAME);
1740 break;
1741 }
1742 } else if (stat(prog, &st) < 0) {
1743 error("subsystem: cannot stat %s: %s", prog,
1744 strerror(errno));
1745 break;
1746 } else {
1747 s->is_subsystem = SUBSYSTEM_EXT;
1748 }
1749 debug("subsystem: exec() %s", cmd);
1750 do_exec(s, cmd);
1751 success = 1;
1752 break;
1753 }
1754 }
1755
1756 if (!success)
1757 log("subsystem request for %.100s failed, subsystem not found",
1758 subsys);
1759
1760 xfree(subsys);
1761 return success;
1762 }
1763
1764 /*
1765 * Serve "x11-req" channel request for X11 forwarding for the current session
1766 * channel.
1767 */
1768 static int
1769 session_x11_req(Session *s)
1770 {
1771 int success, fd;
1772 char xauthdir[] = "/tmp/ssh-xauth-XXXXXX";
1773
1774 s->single_connection = packet_get_char();
1775 s->auth_proto = packet_get_string(NULL);
1776 s->auth_data = packet_get_string(NULL);
1777 s->screen = packet_get_int();
1778 packet_check_eom();
1779
1780 success = session_setup_x11fwd(s);
1781 if (!success) {
1782 xfree(s->auth_proto);
1783 xfree(s->auth_data);
1784 s->auth_proto = NULL;
1785 s->auth_data = NULL;
1786 return (success);
1787 }
1788
1789 /*
1790 * Create per session X authority file so that different sessions
1791 * don't contend for one common file. The reason for this is that
1792 * xauth(1) locking doesn't work too well over network filesystems.
1793 *
1794 * If mkdtemp() or open() fails then s->auth_file remains NULL which
1795 * means that we won't set XAUTHORITY variable in child's environment
1796 * and xauth(1) will use the default location for the authority file.
1797 */
1798 if (mkdtemp(xauthdir) != NULL) {
1799 s->auth_file = xmalloc(MAXPATHLEN);
1800 snprintf(s->auth_file, MAXPATHLEN, "%s/xauthfile",
1801 xauthdir);
1802 /*
1803 * we don't want that "creating new authority file" message to
1804 * be printed by xauth(1) so we must create that file
1805 * beforehand.
1806 */
1807 if ((fd = open(s->auth_file, O_CREAT | O_EXCL | O_RDONLY,
1808 S_IRUSR | S_IWUSR)) == -1) {
1809 error("failed to create the temporary X authority "
1810 "file %s: %.100s; will use the default one",
1811 s->auth_file, strerror(errno));
1812 xfree(s->auth_file);
1813 s->auth_file = NULL;
1814 if (rmdir(xauthdir) == -1) {
1815 error("cannot remove xauth directory %s: %.100s",
1816 xauthdir, strerror(errno));
1817 }
1818 } else {
1819 close(fd);
1820 debug("temporary X authority file %s created",
1821 s->auth_file);
1822
1823 /*
1824 * add a cleanup function to remove the temporary
1825 * xauth file in case we call fatal() (e.g., the
1826 * connection gets closed).
1827 */
1828 fatal_add_cleanup(session_xauthfile_cleanup, (void *)s);
1829 }
1830 }
1831 else {
1832 error("failed to create a directory for the temporary X "
1833 "authority file: %.100s; will use the default xauth file",
1834 strerror(errno));
1835 }
1836
1837 return (success);
1838 }
1839
1840 static int
1841 session_shell_req(Session *s)
1842 {
1843 packet_check_eom();
1844 do_exec(s, NULL);
1845 return 1;
1846 }
1847
1848 static int
1849 session_exec_req(Session *s)
1850 {
1851 u_int len;
1852 char *command = packet_get_string(&len);
1853 packet_check_eom();
1854 do_exec(s, command);
1855 xfree(command);
1856 return 1;
1857 }
1858
1859 static int
1860 session_auth_agent_req(Session *s)
1861 {
1862 static int called = 0;
1863 packet_check_eom();
1864 if (no_agent_forwarding_flag) {
1865 debug("session_auth_agent_req: no_agent_forwarding_flag");
1866 return 0;
1867 }
1868 if (called) {
1869 return 0;
1870 } else {
1871 called = 1;
1872 return auth_input_request_forwarding(s->pw);
1873 }
1874 }
1875
1876 static int
1877 session_loc_env_check(char *var, char *val)
1878 {
1879 char *current;
1880 int cat, ret;
1881
1882 if (strcmp(var, "LANG") == 0)
1883 cat = LC_ALL;
1884 else if (strcmp(var, "LC_ALL") == 0)
1885 cat = LC_ALL;
1886 else if (strcmp(var, "LC_CTYPE") == 0)
1887 cat = LC_CTYPE;
1888 else if (strcmp(var, "LC_COLLATE") == 0)
1889 cat = LC_COLLATE;
1890 else if (strcmp(var, "LC_TIME") == 0)
1891 cat = LC_TIME;
1892 else if (strcmp(var, "LC_NUMERIC") == 0)
1893 cat = LC_NUMERIC;
1894 else if (strcmp(var, "LC_MONETARY") == 0)
1895 cat = LC_MONETARY;
1896 else if (strcmp(var, "LC_MESSAGES") == 0)
1897 cat = LC_MESSAGES;
1898
1899 current = setlocale(cat, NULL);
1900
1901 ret = (setlocale(cat, val) != NULL);
1902 (void) setlocale(cat, current);
1903 return (ret);
1904 }
1905
1906 static int
1907 session_env_req(Session *s)
1908 {
1909 Channel *c;
1910 char *var, *val, *e;
1911 char **p;
1912 size_t len;
1913 int ret = 0;
1914
1915 /* Get var/val from the rest of this packet */
1916 var = packet_get_string(NULL);
1917 val = packet_get_string(NULL);
1918
1919 /*
1920 * We'll need the channel ID for the packet_send_debug messages,
1921 * so get it now.
1922 */
1923 if ((c = channel_lookup(s->chanid)) == NULL)
1924 goto done; /* shouldn't happen! */
1925
1926 debug2("Received request for environment variable %s=%s", var, val);
1927
1928 /* For now allow only LANG and LC_* */
1929 if (strcmp(var, "LANG") != 0 && strncmp(var, "LC_", 3) != 0) {
1930 debug2("Rejecting request for environment variable %s", var);
1931 goto done;
1932 }
1933
1934 if (!session_loc_env_check(var, val)) {
1935 packet_send_debug(gettext("Missing locale support for %s=%s"),
1936 var, val);
1937 goto done;
1938 }
1939
1940 packet_send_debug(gettext("Channel %d set: %s=%s"), c->remote_id,
1941 var, val);
1942
1943 /*
1944 * Always append new environment variables without regard to old
1945 * ones being overriden. The way these are actually added to
1946 * the environment of the session process later settings
1947 * override earlier ones; see copy_environment().
1948 */
1949 if (s->env == NULL) {
1950 char **env;
1951
1952 env = xmalloc(sizeof (char **) * 2);
1953 memset(env, 0, sizeof (char **) * 2);
1954
1955 s->env = env;
1956 p = env;
1957 } else {
1958 for (p = s->env; *p != NULL ; p++);
1959
1960 s->env = xrealloc(s->env, (p - s->env + 2) * sizeof (char **));
1961
1962 for (p = s->env; *p != NULL ; p++);
1963 }
1964
1965 len = snprintf(NULL, 0, "%s=%s", var, val);
1966 e = xmalloc(len + 1);
1967 (void) snprintf(e, len + 1, "%s=%s", var, val);
1968
1969 (*p++) = e;
1970 *p = NULL;
1971
1972 ret = 1;
1973
1974 done:
1975 xfree(var);
1976 xfree(val);
1977
1978 return (ret);
1979 }
1980
1981 static void
1982 session_free_env(char ***envp)
1983 {
1984 char **env, **p;
1985
1986 if (envp == NULL || *envp == NULL)
1987 return;
1988
1989 env = *envp;
1990
1991 *envp = NULL;
1992
1993 for (p = env; *p != NULL; p++)
1994 xfree(*p);
1995
1996 xfree(env);
1997 }
1998
1999 int
2000 session_input_channel_req(Channel *c, const char *rtype)
2001 {
2002 int success = 0;
2003 Session *s;
2004
2005 if ((s = session_by_channel(c->self)) == NULL) {
2006 log("session_input_channel_req: no session %d req %.100s",
2007 c->self, rtype);
2008 return 0;
2009 }
2010 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2011
2012 /*
2013 * a session is in LARVAL state until a shell, a command
2014 * or a subsystem is executed
2015 */
2016 if (c->type == SSH_CHANNEL_LARVAL) {
2017 if (strcmp(rtype, "shell") == 0) {
2018 success = session_shell_req(s);
2019 } else if (strcmp(rtype, "exec") == 0) {
2020 success = session_exec_req(s);
2021 } else if (strcmp(rtype, "pty-req") == 0) {
2022 success = session_pty_req(s);
2023 } else if (strcmp(rtype, "x11-req") == 0) {
2024 success = session_x11_req(s);
2025 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2026 success = session_auth_agent_req(s);
2027 } else if (strcmp(rtype, "subsystem") == 0) {
2028 success = session_subsystem_req(s);
2029 } else if (strcmp(rtype, "env") == 0) {
2030 success = session_env_req(s);
2031 }
2032 }
2033 if (strcmp(rtype, "window-change") == 0) {
2034 success = session_window_change_req(s);
2035 }
2036 return success;
2037 }
2038
2039 void
2040 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2041 {
2042 if (!compat20)
2043 fatal("session_set_fds: called for proto != 2.0");
2044 /*
2045 * now that have a child and a pipe to the child,
2046 * we can activate our channel and register the fd's
2047 */
2048 if (s->chanid == -1)
2049 fatal("no channel for session %d", s->self);
2050 channel_set_fds(s->chanid,
2051 fdout, fdin, fderr,
2052 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2053 1,
2054 CHAN_SES_WINDOW_DEFAULT);
2055 }
2056
2057 /*
2058 * Function to perform pty cleanup. Also called if we get aborted abnormally
2059 * (e.g., due to a dropped connection).
2060 */
2061 void
2062 session_pty_cleanup2(void *session)
2063 {
2064 Session *s = session;
2065
2066 if (s == NULL) {
2067 error("session_pty_cleanup: no session");
2068 return;
2069 }
2070 if (s->ttyfd == -1)
2071 return;
2072
2073 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2074
2075 #ifdef USE_PAM
2076 session_do_pam(s, 0);
2077 #endif /* USE_PAM */
2078
2079 /* Record that the user has logged out. */
2080 if (s->pid != 0) {
2081 debug3("Recording SSHv2 channel logout in utmpx/wtmpx");
2082 #ifdef ALTPRIVSEP
2083 altprivsep_record_logout(s->pid);
2084 #endif /* ALTPRIVSEP */
2085 }
2086
2087 /* Release the pseudo-tty. */
2088 if (getuid() == 0)
2089 pty_release(s->tty);
2090
2091 /*
2092 * Close the server side of the socket pairs. We must do this after
2093 * the pty cleanup, so that another process doesn't get this pty
2094 * while we're still cleaning up.
2095 */
2096 if (close(s->ptymaster) < 0)
2097 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2098
2099 /* unlink pty from session */
2100 s->ttyfd = -1;
2101 }
2102
2103 void
2104 session_pty_cleanup(void *session)
2105 {
2106 session_pty_cleanup2(session);
2107 }
2108
2109 /*
2110 * We use a different temporary X authority file per every session so we
2111 * should remove those files when fatal() is called.
2112 */
2113 void
2114 session_xauthfile_cleanup(void *session)
2115 {
2116 Session *s = session;
2117
2118 if (s == NULL) {
2119 error("session_xauthfile_cleanup: no session");
2120 return;
2121 }
2122
2123 debug("session_xauthfile_cleanup: session %d removing %s", s->self,
2124 s->auth_file);
2125
2126 if (unlink(s->auth_file) == -1) {
2127 error("session_xauthfile_cleanup: cannot remove xauth file: "
2128 "%.100s", strerror(errno));
2129 return;
2130 }
2131
2132 /* dirname() will modify s->auth_file but that's ok */
2133 if (rmdir(dirname(s->auth_file)) == -1) {
2134 error("session_xauthfile_cleanup: "
2135 "cannot remove xauth directory: %.100s", strerror(errno));
2136 return;
2137 }
2138 }
2139
2140 static char *
2141 sig2name(int sig)
2142 {
2143 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2144 SSH_SIG(ABRT);
2145 SSH_SIG(ALRM);
2146 SSH_SIG(FPE);
2147 SSH_SIG(HUP);
2148 SSH_SIG(ILL);
2149 SSH_SIG(INT);
2150 SSH_SIG(KILL);
2151 SSH_SIG(PIPE);
2152 SSH_SIG(QUIT);
2153 SSH_SIG(SEGV);
2154 SSH_SIG(TERM);
2155 SSH_SIG(USR1);
2156 SSH_SIG(USR2);
2157 #undef SSH_SIG
2158 return "SIG@openssh.com";
2159 }
2160
2161 static void
2162 session_exit_message(Session *s, int status)
2163 {
2164 Channel *c;
2165
2166 if ((c = channel_lookup(s->chanid)) == NULL)
2167 fatal("session_exit_message: session %d: no channel %d",
2168 s->self, s->chanid);
2169 debug("session_exit_message: session %d channel %d pid %ld",
2170 s->self, s->chanid, (long)s->pid);
2171
2172 if (WIFEXITED(status)) {
2173 channel_request_start(s->chanid, "exit-status", 0);
2174 packet_put_int(WEXITSTATUS(status));
2175 packet_send();
2176 } else if (WIFSIGNALED(status)) {
2177 channel_request_start(s->chanid, "exit-signal", 0);
2178 packet_put_cstring(sig2name(WTERMSIG(status)));
2179 #ifdef WCOREDUMP
2180 packet_put_char(WCOREDUMP(status));
2181 #else /* WCOREDUMP */
2182 packet_put_char(0);
2183 #endif /* WCOREDUMP */
2184 packet_put_cstring("");
2185 packet_put_cstring("");
2186 packet_send();
2187 } else {
2188 /* Some weird exit cause. Just exit. */
2189 packet_disconnect("wait returned status %04x.", status);
2190 }
2191
2192 /* Ok to close channel now */
2193 channel_set_wait_for_exit(s->chanid, 0);
2194
2195 /* disconnect channel */
2196 debug("session_exit_message: release channel %d", s->chanid);
2197 channel_cancel_cleanup(s->chanid);
2198 /*
2199 * emulate a write failure with 'chan_write_failed', nobody will be
2200 * interested in data we write.
2201 * Note that we must not call 'chan_read_failed', since there could
2202 * be some more data waiting in the pipe.
2203 */
2204 if (c->ostate != CHAN_OUTPUT_CLOSED)
2205 chan_write_failed(c);
2206 s->chanid = -1;
2207 }
2208
2209 void
2210 session_close(Session *s)
2211 {
2212 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2213 if (s->ttyfd != -1) {
2214 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2215 session_pty_cleanup(s);
2216 }
2217 if (s->auth_file != NULL) {
2218 fatal_remove_cleanup(session_xauthfile_cleanup, (void *)s);
2219 session_xauthfile_cleanup(s);
2220 xfree(s->auth_file);
2221 }
2222 if (s->term)
2223 xfree(s->term);
2224 if (s->display)
2225 xfree(s->display);
2226 if (s->auth_display)
2227 xfree(s->auth_display);
2228 if (s->auth_data)
2229 xfree(s->auth_data);
2230 if (s->auth_proto)
2231 xfree(s->auth_proto);
2232 if (s->command)
2233 xfree(s->command);
2234 session_free_env(&s->env);
2235 s->used = 0;
2236 session_proctitle(s);
2237 }
2238
2239 void
2240 session_close_by_pid(pid_t pid, int status)
2241 {
2242 Session *s = session_by_pid(pid);
2243 if (s == NULL) {
2244 debug("session_close_by_pid: no session for pid %ld",
2245 (long)pid);
2246 return;
2247 }
2248 if (s->chanid != -1)
2249 session_exit_message(s, status);
2250 session_close(s);
2251 }
2252
2253 /*
2254 * This is called when a channel dies before the session 'child' itself dies.
2255 * It can happen for example if we exit from an interactive shell before we
2256 * exit from forwarded X11 applications.
2257 */
2258 void
2259 session_close_by_channel(int id, void *arg)
2260 {
2261 Session *s = session_by_channel(id);
2262 if (s == NULL) {
2263 debug("session_close_by_channel: no session for id %d", id);
2264 return;
2265 }
2266 debug("session_close_by_channel: channel %d child %ld",
2267 id, (long)s->pid);
2268 if (s->pid != 0) {
2269 debug("session_close_by_channel: channel %d: has child", id);
2270 /*
2271 * delay detach of session, but release pty, since
2272 * the fd's to the child are already closed
2273 */
2274 if (s->ttyfd != -1) {
2275 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2276 session_pty_cleanup(s);
2277 }
2278 return;
2279 }
2280 /* detach by removing callback */
2281 channel_cancel_cleanup(s->chanid);
2282 s->chanid = -1;
2283 session_close(s);
2284 }
2285
2286 void
2287 session_destroy_all(void (*closefunc)(Session *))
2288 {
2289 int i;
2290 for (i = 0; i < MAX_SESSIONS; i++) {
2291 Session *s = &sessions[i];
2292 if (s->used) {
2293 if (closefunc != NULL)
2294 closefunc(s);
2295 else
2296 session_close(s);
2297 }
2298 }
2299 }
2300
2301 static char *
2302 session_tty_list(void)
2303 {
2304 static char buf[1024];
2305 int i;
2306 buf[0] = '\0';
2307 for (i = 0; i < MAX_SESSIONS; i++) {
2308 Session *s = &sessions[i];
2309 if (s->used && s->ttyfd != -1) {
2310 if (buf[0] != '\0')
2311 strlcat(buf, ",", sizeof buf);
2312 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2313 }
2314 }
2315 if (buf[0] == '\0')
2316 strlcpy(buf, "notty", sizeof buf);
2317 return buf;
2318 }
2319
2320 void
2321 session_proctitle(Session *s)
2322 {
2323 if (s->pw == NULL)
2324 error("no user for session %d", s->self);
2325 else
2326 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2327 }
2328
2329 int
2330 session_setup_x11fwd(Session *s)
2331 {
2332 struct stat st;
2333 char display[512], auth_display[512];
2334 char hostname[MAXHOSTNAMELEN];
2335
2336 if (no_x11_forwarding_flag) {
2337 packet_send_debug("X11 forwarding disabled in user configuration file.");
2338 return 0;
2339 }
2340 if (!options.x11_forwarding) {
2341 debug("X11 forwarding disabled in server configuration file.");
2342 return 0;
2343 }
2344 if (!options.xauth_location ||
2345 (stat(options.xauth_location, &st) == -1)) {
2346 packet_send_debug("No xauth program; cannot forward with spoofing.");
2347 return 0;
2348 }
2349 if (s->display != NULL) {
2350 debug("X11 display already set.");
2351 return 0;
2352 }
2353 if (x11_create_display_inet(options.x11_display_offset,
2354 options.x11_use_localhost, s->single_connection,
2355 &s->display_number) == -1) {
2356 debug("x11_create_display_inet failed.");
2357 return 0;
2358 }
2359
2360 /* Set up a suitable value for the DISPLAY variable. */
2361 if (gethostname(hostname, sizeof(hostname)) < 0)
2362 fatal("gethostname: %.100s", strerror(errno));
2363 /*
2364 * auth_display must be used as the displayname when the
2365 * authorization entry is added with xauth(1). This will be
2366 * different than the DISPLAY string for localhost displays.
2367 */
2368 if (options.x11_use_localhost) {
2369 snprintf(display, sizeof display, "localhost:%u.%u",
2370 s->display_number, s->screen);
2371 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2372 s->display_number, s->screen);
2373 s->display = xstrdup(display);
2374 s->auth_display = xstrdup(auth_display);
2375 } else {
2376 #ifdef IPADDR_IN_DISPLAY
2377 struct hostent *he;
2378 struct in_addr my_addr;
2379
2380 he = gethostbyname(hostname);
2381 if (he == NULL) {
2382 error("Can't get IP address for X11 DISPLAY.");
2383 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2384 return 0;
2385 }
2386 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2387 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2388 s->display_number, s->screen);
2389 #else
2390 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2391 s->display_number, s->screen);
2392 #endif
2393 s->display = xstrdup(display);
2394 s->auth_display = xstrdup(display);
2395 }
2396
2397 return 1;
2398 }
2399
2400 #ifdef USE_PAM
2401 int session_do_pam_conv(int, struct pam_message **,
2402 struct pam_response **, void *);
2403
2404 static struct pam_conv session_pam_conv = {
2405 session_do_pam_conv,
2406 NULL
2407 };
2408
2409 static void
2410 session_do_pam(Session *s, int do_open)
2411 {
2412 int pam_retval;
2413 char *where, *old_tty, *old_tty_copy = NULL;
2414 struct pam_conv old_conv, *old_conv_ptr;
2415
2416 if (!s || !s->authctxt || !s->authctxt->pam || !s->authctxt->pam->h)
2417 return;
2418
2419 /* Save current PAM item values */
2420 where = "getting PAM_CONV";
2421 pam_retval = pam_get_item(s->authctxt->pam->h, PAM_CONV,
2422 (void **) &old_conv_ptr);
2423 if (pam_retval != PAM_SUCCESS)
2424 goto done;
2425 old_conv = *old_conv_ptr;
2426
2427 where = "getting PAM_TTY";
2428 pam_retval = pam_get_item(s->authctxt->pam->h, PAM_TTY,
2429 (void **) &old_tty);
2430 if (pam_retval != PAM_SUCCESS)
2431 goto done;
2432 old_tty_copy = xstrdup(old_tty);
2433
2434 /* Change PAM_TTY and PAM_CONV items */
2435 where = "setting PAM_TTY";
2436 pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, s->tty);
2437 if (pam_retval != PAM_SUCCESS)
2438 goto done;
2439
2440 where = "setting PAM_CONV";
2441 session_pam_conv.appdata_ptr = s;
2442 pam_retval = pam_set_item(s->authctxt->pam->h,
2443 PAM_CONV, &session_pam_conv);
2444 if (pam_retval != PAM_SUCCESS)
2445 goto done;
2446
2447 /* Call pam_close_session(). pam_open_session was already called during
2448 * authentication, so don't do it again */
2449 if (!do_open) {
2450 where = "calling pam_close_session()";
2451 pam_retval = pam_close_session(s->authctxt->pam->h, 0);
2452 }
2453
2454 /* Reset PAM_TTY and PAM_CONV items to previous values */
2455 where = "setting PAM_TTY";
2456 pam_retval = pam_set_item(s->authctxt->pam->h, PAM_TTY, old_tty_copy);
2457 if (pam_retval != PAM_SUCCESS)
2458 goto done;
2459
2460 where = "setting PAM_CONV";
2461 pam_retval = pam_set_item(s->authctxt->pam->h, PAM_CONV, &old_conv);
2462 if (pam_retval != PAM_SUCCESS)
2463 goto done;
2464
2465 session_pam_conv.appdata_ptr = NULL;
2466
2467 done:
2468 if (old_tty_copy)
2469 xfree(old_tty_copy);
2470
2471 if (pam_retval == PAM_SUCCESS)
2472 return;
2473
2474 /* fatal()? probably not... */
2475 log("PAM failed[%d] while %s: %s", pam_retval, where,
2476 PAM_STRERROR(s->authctxt->pam->h, pam_retval));
2477 }
2478
2479 int
2480 session_do_pam_conv(int num_prompts,
2481 struct pam_message **prompts,
2482 struct pam_response **resp,
2483 void *app_data)
2484 {
2485 Session *s = (Session *) app_data;
2486
2487 struct pam_response *reply;
2488 int count;
2489 char *prompt;
2490
2491 if (channel_lookup(s->chanid) == NULL)
2492 return PAM_CONV_ERR;
2493
2494 /* PAM will free this later */
2495 reply = xmalloc(num_prompts * sizeof(*reply));
2496
2497 (void) memset(reply, 0, num_prompts * sizeof(*reply));
2498 for (count = 0; count < num_prompts; count++) {
2499 switch(PAM_MSG_MEMBER(prompts, count, msg_style)) {
2500 case PAM_TEXT_INFO:
2501 /* Write to stdout of channel */
2502 prompt = PAM_MSG_MEMBER(prompts, count, msg);
2503 if (prompt != NULL && s->ttyfd != -1) {
2504 debug2("session_do_pam_conv: text info "
2505 "prompt: %s", prompt);
2506 (void) write(s->ttyfd, prompt, strlen(prompt));
2507 (void) write(s->ttyfd, "\n", 1);
2508 }
2509 reply[count].resp = xstrdup("");
2510 reply[count].resp_retcode = PAM_SUCCESS;
2511 break;
2512 case PAM_ERROR_MSG:
2513 /* Write to stderr of channel */
2514 prompt = PAM_MSG_MEMBER(prompts, count, msg);
2515 if (prompt != NULL && s->ttyfd != -1) {
2516 debug2("session_do_pam_conv: error "
2517 "prompt: %s", prompt);
2518 (void) write(s->ttyfd, prompt, strlen(prompt));
2519 (void) write(s->ttyfd, "\n", 1);
2520 }
2521 reply[count].resp = xstrdup("");
2522 reply[count].resp_retcode = PAM_SUCCESS;
2523 break;
2524 case PAM_PROMPT_ECHO_ON:
2525 case PAM_PROMPT_ECHO_OFF:
2526 /*
2527 * XXX Someday add support for echo on/off prompts
2528 * here on sessions with ttys.
2529 */
2530 default:
2531 xfree(reply);
2532 return PAM_CONV_ERR;
2533 }
2534 }
2535
2536 *resp = reply;
2537
2538 return PAM_SUCCESS;
2539 }
2540 #endif /* USE_PAM */
2541
2542 static void
2543 do_authenticated2(Authctxt *authctxt)
2544 {
2545 server_loop2(authctxt);
2546 }
2547
2548 /*
2549 * Drop the privileges. We need this for the in-process SFTP server only. For
2550 * the shell and the external subsystem the exec(2) call will do the P = E = I
2551 * assignment itself. Never change the privileges if the connecting user is
2552 * root. See privileges(5) if the terminology used here is not known to you.
2553 */
2554 static void
2555 drop_privs(uid_t uid)
2556 {
2557 priv_set_t *priv_inherit;
2558
2559 /* If root is connecting we are done. */
2560 if (uid == 0)
2561 return;
2562
2563 if ((priv_inherit = priv_allocset()) == NULL)
2564 fatal("priv_allocset: %s", strerror(errno));
2565 if (getppriv(PRIV_INHERITABLE, priv_inherit) != 0)
2566 fatal("getppriv: %s", strerror(errno));
2567
2568 /*
2569 * This will limit E as well. Note that before this P was a
2570 * superset of I, see permanently_set_uid().
2571 */
2572 if (setppriv(PRIV_SET, PRIV_PERMITTED, priv_inherit) == -1)
2573 fatal("setppriv: %s", strerror(errno));
2574
2575 priv_freeset(priv_inherit);
2576
2577 /*
2578 * By manipulating the P set above we entered a PA mode which we
2579 * do not need to retain in.
2580 */
2581 if (setpflags(PRIV_AWARE, 0) == -1)
2582 fatal("setpflags: %s", strerror(errno));
2583 }