1 /* $OpenBSD: session.c,v 1.246 2009/04/17 19:23:06 stevesk Exp $ */
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 <sys/param.h>
37 #include <sys/wait.h>
38 #include <sys/un.h>
39 #include <sys/stat.h>
40 #include <sys/socket.h>
41 #include <sys/queue.h>
42
43 #include <errno.h>
44 #include <grp.h>
45 #include <login_cap.h>
46 #include <paths.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #include "xmalloc.h"
55 #include "ssh.h"
56 #include "ssh1.h"
57 #include "ssh2.h"
58 #include "sshpty.h"
59 #include "packet.h"
60 #include "buffer.h"
61 #include "match.h"
62 #include "uidswap.h"
63 #include "compat.h"
64 #include "channels.h"
65 #include "key.h"
66 #include "cipher.h"
67 #include "kex.h"
68 #include "hostfile.h"
69 #include "auth.h"
70 #include "auth-options.h"
71 #include "pathnames.h"
72 #include "log.h"
73 #include "servconf.h"
74 #include "sshlogin.h"
75 #include "serverloop.h"
76 #include "canohost.h"
77 #include "misc.h"
78 #include "session.h"
79 #include "monitor_wrap.h"
80 #include "sftp.h"
81
82 __RCSID("$MirOS: src/usr.bin/ssh/session.c,v 1.23 2009/10/04 14:29:07 tg Exp $");
83
84 #define IS_INTERNAL_SFTP(c) \
85 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
86 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
87 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
88 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
89
90 /* func */
91
92 void session_set_fds(Session *, int, int, int, int);
93 void session_pty_cleanup(Session *);
94 void session_proctitle(Session *);
95 int session_setup_x11fwd(Session *);
96 int do_exec_pty(Session *, const char *);
97 int do_exec_no_pty(Session *, const char *);
98 int do_exec(Session *, const char *);
99 void do_login(Session *, const char *);
100 void do_child(Session *, const char *) __dead;
101 void do_motd(void);
102 int check_quietlogin(Session *, const char *);
103
104 static void do_authenticated1(Authctxt *);
105 static void do_authenticated2(Authctxt *);
106
107 static int session_pty_req(Session *);
108
109 /* import */
110 extern ServerOptions options;
111 extern char *__progname;
112 extern int log_stderr;
113 extern int debug_flag;
114 extern u_int utmp_len;
115 extern int startup_pipe;
116 extern void destroy_sensitive_data(void);
117 extern Buffer loginmsg;
118
119 /* original command from peer. */
120 const char *original_command = NULL;
121
122 /* data */
123 static int sessions_first_unused = -1;
124 static int sessions_nalloc = 0;
125 static Session *sessions = NULL;
126
127 #define SUBSYSTEM_NONE 0
128 #define SUBSYSTEM_EXT 1
129 #define SUBSYSTEM_INT_SFTP 2
130
131 login_cap_t *lc;
132
133 static int is_child = 0;
134
135 /* Name and directory of socket for authentication agent forwarding. */
136 static char *auth_sock_name = NULL;
137 static char *auth_sock_dir = NULL;
138
139 /* removes the agent forwarding socket */
140
141 static void
auth_sock_cleanup_proc(struct passwd * pw)142 auth_sock_cleanup_proc(struct passwd *pw)
143 {
144 if (auth_sock_name != NULL) {
145 temporarily_use_uid(pw);
146 unlink(auth_sock_name);
147 rmdir(auth_sock_dir);
148 auth_sock_name = NULL;
149 restore_uid();
150 }
151 }
152
153 static int
auth_input_request_forwarding(struct passwd * pw)154 auth_input_request_forwarding(struct passwd * pw)
155 {
156 Channel *nc;
157 int sock = -1;
158 struct sockaddr_un sunaddr;
159
160 if (auth_sock_name != NULL) {
161 error("authentication forwarding requested twice.");
162 return 0;
163 }
164
165 /* Temporarily drop privileged uid for mkdir/bind. */
166 temporarily_use_uid(pw);
167
168 /* Allocate a buffer for the socket name, and format the name. */
169 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
170
171 /* Create private directory for socket */
172 if (mkdtemp(auth_sock_dir) == NULL) {
173 packet_send_debug("Agent forwarding disabled: "
174 "mkdtemp() failed: %.100s", strerror(errno));
175 restore_uid();
176 xfree(auth_sock_dir);
177 auth_sock_dir = NULL;
178 goto authsock_err;
179 }
180
181 xasprintf(&auth_sock_name, "%s/agent.%ld",
182 auth_sock_dir, (long) getpid());
183
184 /* Create the socket. */
185 sock = socket(AF_UNIX, SOCK_STREAM, 0);
186 if (sock < 0) {
187 error("socket: %.100s", strerror(errno));
188 restore_uid();
189 goto authsock_err;
190 }
191
192 /* Bind it to the name. */
193 memset(&sunaddr, 0, sizeof(sunaddr));
194 sunaddr.sun_family = AF_UNIX;
195 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
196
197 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
198 error("bind: %.100s", strerror(errno));
199 restore_uid();
200 goto authsock_err;
201 }
202
203 /* Restore the privileged uid. */
204 restore_uid();
205
206 /* Start listening on the socket. */
207 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
208 error("listen: %.100s", strerror(errno));
209 goto authsock_err;
210 }
211
212 /* Allocate a channel for the authentication agent socket. */
213 nc = channel_new("auth socket",
214 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
215 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
216 0, "auth socket", 1);
217 nc->path = xstrdup(auth_sock_name);
218 return 1;
219
220 authsock_err:
221 if (auth_sock_name != NULL)
222 xfree(auth_sock_name);
223 if (auth_sock_dir != NULL) {
224 rmdir(auth_sock_dir);
225 xfree(auth_sock_dir);
226 }
227 if (sock != -1)
228 close(sock);
229 auth_sock_name = NULL;
230 auth_sock_dir = NULL;
231 return 0;
232 }
233
234 static void
display_loginmsg(void)235 display_loginmsg(void)
236 {
237 if (buffer_len(&loginmsg) > 0) {
238 buffer_append(&loginmsg, "\0", 1);
239 printf("%s", (char *)buffer_ptr(&loginmsg));
240 buffer_clear(&loginmsg);
241 }
242 }
243
244 void
do_authenticated(Authctxt * authctxt)245 do_authenticated(Authctxt *authctxt)
246 {
247 setproctitle("%s", authctxt->pw->pw_name);
248
249 /* setup the channel layer */
250 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
251 channel_permit_all_opens();
252
253 if (compat20)
254 do_authenticated2(authctxt);
255 else
256 do_authenticated1(authctxt);
257
258 do_cleanup(authctxt);
259 }
260
261 /*
262 * Prepares for an interactive session. This is called after the user has
263 * been successfully authenticated. During this message exchange, pseudo
264 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
265 * are requested, etc.
266 */
267 static void
do_authenticated1(Authctxt * authctxt)268 do_authenticated1(Authctxt *authctxt)
269 {
270 Session *s;
271 char *command;
272 int success, type, screen_flag;
273 int enable_compression_after_reply = 0;
274 u_int proto_len, data_len, dlen, compression_level = 0;
275
276 s = session_new();
277 if (s == NULL) {
278 error("no more sessions");
279 return;
280 }
281 s->authctxt = authctxt;
282 s->pw = authctxt->pw;
283
284 /*
285 * We stay in this loop until the client requests to execute a shell
286 * or a command.
287 */
288 for (;;) {
289 success = 0;
290
291 /* Get a packet from the client. */
292 type = packet_read();
293
294 /* Process the packet. */
295 switch (type) {
296 case SSH_CMSG_REQUEST_COMPRESSION:
297 compression_level = packet_get_int();
298 packet_check_eom();
299 if (compression_level < 1 || compression_level > 9) {
300 packet_send_debug("Received invalid compression level %d.",
301 compression_level);
302 break;
303 }
304 if (options.compression == COMP_NONE) {
305 debug2("compression disabled");
306 break;
307 }
308 /* Enable compression after we have responded with SUCCESS. */
309 enable_compression_after_reply = 1;
310 success = 1;
311 break;
312
313 case SSH_CMSG_REQUEST_PTY:
314 success = session_pty_req(s);
315 break;
316
317 case SSH_CMSG_X11_REQUEST_FORWARDING:
318 s->auth_proto = packet_get_string(&proto_len);
319 s->auth_data = packet_get_string(&data_len);
320
321 screen_flag = packet_get_protocol_flags() &
322 SSH_PROTOFLAG_SCREEN_NUMBER;
323 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
324
325 if (packet_remaining() == 4) {
326 if (!screen_flag)
327 debug2("Buggy client: "
328 "X11 screen flag missing");
329 s->screen = packet_get_int();
330 } else {
331 s->screen = 0;
332 }
333 packet_check_eom();
334 success = session_setup_x11fwd(s);
335 if (!success) {
336 xfree(s->auth_proto);
337 xfree(s->auth_data);
338 s->auth_proto = NULL;
339 s->auth_data = NULL;
340 }
341 break;
342
343 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
344 if (!options.allow_agent_forwarding ||
345 no_agent_forwarding_flag || compat13) {
346 debug("Authentication agent forwarding not permitted for this authentication.");
347 break;
348 }
349 debug("Received authentication agent forwarding request.");
350 success = auth_input_request_forwarding(s->pw);
351 break;
352
353 case SSH_CMSG_PORT_FORWARD_REQUEST:
354 if (no_port_forwarding_flag) {
355 debug("Port forwarding not permitted for this authentication.");
356 break;
357 }
358 if (!options.allow_tcp_forwarding) {
359 debug("Port forwarding not permitted.");
360 break;
361 }
362 debug("Received TCP/IP port forwarding request.");
363 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
364 options.gateway_ports) < 0) {
365 debug("Port forwarding failed.");
366 break;
367 }
368 success = 1;
369 break;
370
371 case SSH_CMSG_MAX_PACKET_SIZE:
372 if (packet_set_maxsize(packet_get_int()) > 0)
373 success = 1;
374 break;
375
376 case SSH_CMSG_EXEC_SHELL:
377 case SSH_CMSG_EXEC_CMD:
378 if (type == SSH_CMSG_EXEC_CMD) {
379 command = packet_get_string(&dlen);
380 debug("Exec command '%.500s'", command);
381 if (do_exec(s, command) != 0)
382 packet_disconnect(
383 "command execution failed");
384 xfree(command);
385 } else {
386 if (do_exec(s, NULL) != 0)
387 packet_disconnect(
388 "shell execution failed");
389 }
390 packet_check_eom();
391 session_close(s);
392 return;
393
394 default:
395 /*
396 * Any unknown messages in this phase are ignored,
397 * and a failure message is returned.
398 */
399 logit("Unknown packet type received after authentication: %d", type);
400 }
401 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
402 packet_send();
403 packet_write_wait();
404
405 /* Enable compression now that we have replied if appropriate. */
406 if (enable_compression_after_reply) {
407 enable_compression_after_reply = 0;
408 packet_start_compression(compression_level);
409 }
410 }
411 }
412
413 #define USE_PIPES
414 /*
415 * This is called to fork and execute a command when we have no tty. This
416 * will call do_child from the child, and server_loop from the parent after
417 * setting up file descriptors and such.
418 */
419 int
do_exec_no_pty(Session * s,const char * command)420 do_exec_no_pty(Session *s, const char *command)
421 {
422 pid_t pid;
423 #ifdef USE_PIPES
424 int pin[2], pout[2], perr[2];
425
426 /* Allocate pipes for communicating with the program. */
427 if (pipe(pin) < 0) {
428 error("%s: pipe in: %.100s", __func__, strerror(errno));
429 return -1;
430 }
431 if (pipe(pout) < 0) {
432 error("%s: pipe out: %.100s", __func__, strerror(errno));
433 close(pin[0]);
434 close(pin[1]);
435 return -1;
436 }
437 if (pipe(perr) < 0) {
438 error("%s: pipe err: %.100s", __func__, strerror(errno));
439 close(pin[0]);
440 close(pin[1]);
441 close(pout[0]);
442 close(pout[1]);
443 return -1;
444 }
445 #else
446 int inout[2], err[2];
447
448 /* Uses socket pairs to communicate with the program. */
449 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
450 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
451 return -1;
452 }
453 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
454 error("%s: socketpair #2: %.100s", __func__, strerror(errno));
455 close(inout[0]);
456 close(inout[1]);
457 return -1;
458 }
459 #endif
460
461 if (s == NULL)
462 fatal("do_exec_no_pty: no session");
463
464 session_proctitle(s);
465
466 /* Fork the child. */
467 switch ((pid = fork())) {
468 case -1:
469 error("%s: fork: %.100s", __func__, strerror(errno));
470 #ifdef USE_PIPES
471 close(pin[0]);
472 close(pin[1]);
473 close(pout[0]);
474 close(pout[1]);
475 close(perr[0]);
476 close(perr[1]);
477 #else
478 close(inout[0]);
479 close(inout[1]);
480 close(err[0]);
481 close(err[1]);
482 #endif
483 return -1;
484 case 0:
485 is_child = 1;
486
487 /* Child. Reinitialize the log since the pid has changed. */
488 log_init(__progname, options.log_level,
489 options.log_facility, log_stderr);
490
491 /*
492 * Create a new session and process group since the 4.4BSD
493 * setlogin() affects the entire process group.
494 */
495 if (setsid() < 0)
496 error("setsid failed: %.100s", strerror(errno));
497
498 #ifdef USE_PIPES
499 /*
500 * Redirect stdin. We close the parent side of the socket
501 * pair, and make the child side the standard input.
502 */
503 close(pin[1]);
504 if (dup2(pin[0], 0) < 0)
505 perror("dup2 stdin");
506 close(pin[0]);
507
508 /* Redirect stdout. */
509 close(pout[0]);
510 if (dup2(pout[1], 1) < 0)
511 perror("dup2 stdout");
512 close(pout[1]);
513
514 /* Redirect stderr. */
515 close(perr[0]);
516 if (dup2(perr[1], 2) < 0)
517 perror("dup2 stderr");
518 close(perr[1]);
519 #else
520 /*
521 * Redirect stdin, stdout, and stderr. Stdin and stdout will
522 * use the same socket, as some programs (particularly rdist)
523 * seem to depend on it.
524 */
525 close(inout[1]);
526 close(err[1]);
527 if (dup2(inout[0], 0) < 0) /* stdin */
528 perror("dup2 stdin");
529 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
530 perror("dup2 stdout");
531 close(inout[0]);
532 if (dup2(err[0], 2) < 0) /* stderr */
533 perror("dup2 stderr");
534 close(err[0]);
535 #endif
536
537 /* Do processing for the child (exec command etc). */
538 do_child(s, command);
539 /* NOTREACHED */
540 default:
541 break;
542 }
543
544 s->pid = pid;
545 /* Set interactive/non-interactive mode. */
546 packet_set_interactive(s->display != NULL);
547
548 #ifdef USE_PIPES
549 /* We are the parent. Close the child sides of the pipes. */
550 close(pin[0]);
551 close(pout[1]);
552 close(perr[1]);
553
554 if (compat20) {
555 if (s->is_subsystem) {
556 close(perr[0]);
557 perr[0] = -1;
558 }
559 session_set_fds(s, pin[1], pout[0], perr[0], 0);
560 } else {
561 /* Enter the interactive session. */
562 server_loop(pid, pin[1], pout[0], perr[0]);
563 /* server_loop has closed pin[1], pout[0], and perr[0]. */
564 }
565 #else
566 /* We are the parent. Close the child sides of the socket pairs. */
567 close(inout[0]);
568 close(err[0]);
569
570 /*
571 * Enter the interactive session. Note: server_loop must be able to
572 * handle the case that fdin and fdout are the same.
573 */
574 if (compat20) {
575 session_set_fds(s, inout[1], inout[1],
576 s->is_subsystem ? -1 : err[1], 0);
577 if (s->is_subsystem)
578 close(err[1]);
579 } else {
580 server_loop(pid, inout[1], inout[1], err[1]);
581 /* server_loop has closed inout[1] and err[1]. */
582 }
583 #endif
584 return 0;
585 }
586
587 /*
588 * This is called to fork and execute a command when we have a tty. This
589 * will call do_child from the child, and server_loop from the parent after
590 * setting up file descriptors, controlling tty, updating wtmp, utmp,
591 * lastlog, and other such operations.
592 */
593 int
do_exec_pty(Session * s,const char * command)594 do_exec_pty(Session *s, const char *command)
595 {
596 int fdout, ptyfd, ttyfd, ptymaster;
597 pid_t pid;
598
599 if (s == NULL)
600 fatal("do_exec_pty: no session");
601 ptyfd = s->ptyfd;
602 ttyfd = s->ttyfd;
603
604 /*
605 * Create another descriptor of the pty master side for use as the
606 * standard input. We could use the original descriptor, but this
607 * simplifies code in server_loop. The descriptor is bidirectional.
608 * Do this before forking (and cleanup in the child) so as to
609 * detect and gracefully fail out-of-fd conditions.
610 */
611 if ((fdout = dup(ptyfd)) < 0) {
612 error("%s: dup #1: %s", __func__, strerror(errno));
613 close(ttyfd);
614 close(ptyfd);
615 return -1;
616 }
617 /* we keep a reference to the pty master */
618 if ((ptymaster = dup(ptyfd)) < 0) {
619 error("%s: dup #2: %s", __func__, strerror(errno));
620 close(ttyfd);
621 close(ptyfd);
622 close(fdout);
623 return -1;
624 }
625
626 /* Fork the child. */
627 switch ((pid = fork())) {
628 case -1:
629 error("%s: fork: %.100s", __func__, strerror(errno));
630 close(fdout);
631 close(ptymaster);
632 close(ttyfd);
633 close(ptyfd);
634 return -1;
635 case 0:
636 is_child = 1;
637
638 close(fdout);
639 close(ptymaster);
640
641 /* Child. Reinitialize the log because the pid has changed. */
642 log_init(__progname, options.log_level,
643 options.log_facility, log_stderr);
644 /* Close the master side of the pseudo tty. */
645 close(ptyfd);
646
647 /* Make the pseudo tty our controlling tty. */
648 pty_make_controlling_tty(&ttyfd, s->tty);
649
650 /* Redirect stdin/stdout/stderr from the pseudo tty. */
651 if (dup2(ttyfd, 0) < 0)
652 error("dup2 stdin: %s", strerror(errno));
653 if (dup2(ttyfd, 1) < 0)
654 error("dup2 stdout: %s", strerror(errno));
655 if (dup2(ttyfd, 2) < 0)
656 error("dup2 stderr: %s", strerror(errno));
657
658 /* Close the extra descriptor for the pseudo tty. */
659 close(ttyfd);
660
661 /* record login, etc. similar to login(1) */
662 if (!(options.use_login && command == NULL))
663 do_login(s, command);
664
665 /*
666 * Do common processing for the child, such as execing
667 * the command.
668 */
669 do_child(s, command);
670 /* NOTREACHED */
671 default:
672 break;
673 }
674 s->pid = pid;
675
676 /* Parent. Close the slave side of the pseudo tty. */
677 close(ttyfd);
678
679 /* Enter interactive session. */
680 s->ptymaster = ptymaster;
681 packet_set_interactive(1);
682 if (compat20) {
683 session_set_fds(s, ptyfd, fdout, -1, 1);
684 } else {
685 server_loop(pid, ptyfd, fdout, -1);
686 /* server_loop _has_ closed ptyfd and fdout. */
687 }
688 return 0;
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 int
do_exec(Session * s,const char * command)696 do_exec(Session *s, const char *command)
697 {
698 int ret;
699
700 if (options.adm_forced_command) {
701 original_command = command;
702 command = options.adm_forced_command;
703 #ifndef SMALL
704 if (IS_INTERNAL_SFTP(command))
705 s->is_subsystem = SUBSYSTEM_INT_SFTP;
706 else
707 #endif
708 if (s->is_subsystem)
709 s->is_subsystem = SUBSYSTEM_EXT;
710 debug("Forced command (config) '%.900s'", command);
711 } else if (forced_command) {
712 original_command = command;
713 command = forced_command;
714 #ifndef SMALL
715 if (IS_INTERNAL_SFTP(command))
716 s->is_subsystem = SUBSYSTEM_INT_SFTP;
717 else
718 #endif
719 if (s->is_subsystem)
720 s->is_subsystem = SUBSYSTEM_EXT;
721 debug("Forced command (key option) '%.900s'", command);
722 }
723
724 if (s->ttyfd != -1)
725 ret = do_exec_pty(s, command);
726 else
727 ret = do_exec_no_pty(s, command);
728
729 original_command = NULL;
730
731 /*
732 * Clear loginmsg: it's the child's responsibility to display
733 * it to the user, otherwise multiple sessions may accumulate
734 * multiple copies of the login messages.
735 */
736 buffer_clear(&loginmsg);
737
738 return ret;
739 }
740
741
742 /* administrative, login(1)-like work */
743 void
do_login(Session * s,const char * command)744 do_login(Session *s, const char *command)
745 {
746 socklen_t fromlen;
747 struct sockaddr_storage from;
748 struct passwd * pw = s->pw;
749 pid_t pid = getpid();
750
751 /*
752 * Get IP address of client. If the connection is not a socket, let
753 * the address be 0.0.0.0.
754 */
755 memset(&from, 0, sizeof(from));
756 fromlen = sizeof(from);
757 if (packet_connection_is_on_socket()) {
758 if (getpeername(packet_get_connection_in(),
759 (struct sockaddr *)&from, &fromlen) < 0) {
760 debug("getpeername: %.100s", strerror(errno));
761 cleanup_exit(255);
762 }
763 }
764
765 /* Record that there was a login on that tty from the remote host. */
766 if (!use_privsep)
767 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
768 get_remote_name_or_ip(utmp_len,
769 options.use_dns),
770 (struct sockaddr *)&from, fromlen);
771
772 if (check_quietlogin(s, command))
773 return;
774
775 display_loginmsg();
776
777 do_motd();
778 }
779
780 /*
781 * Display the message of the day.
782 */
783 void
do_motd(void)784 do_motd(void)
785 {
786 FILE *f;
787 char buf[256];
788
789 if (options.print_motd) {
790 f = fopen(login_getcapstr(lc, (char *)"welcome",
791 (char *)"/etc/motd", (char *)"/etc/motd"), "r");
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 */
804 int
check_quietlogin(Session * s,const char * command)805 check_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 if (login_getcapbool(lc, (char *)"hushlogin", 0) || stat(buf, &st) >= 0)
816 return 1;
817 return 0;
818 }
819
820 /*
821 * Sets the value of the given variable in the environment. If the variable
822 * already exists, its value is overridden.
823 */
824 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)825 child_set_env(char ***envp, u_int *envsizep, const char *name,
826 const char *value)
827 {
828 char **env;
829 u_int envsize;
830 u_int i, namelen;
831
832 /*
833 * Find the slot where the value should be stored. If the variable
834 * already exists, we reuse the slot; otherwise we append a new slot
835 * at the end of the array, expanding if necessary.
836 */
837 env = *envp;
838 namelen = strlen(name);
839 for (i = 0; env[i]; i++)
840 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
841 break;
842 if (env[i]) {
843 /* Reuse the slot. */
844 xfree(env[i]);
845 } else {
846 /* New variable. Expand if necessary. */
847 envsize = *envsizep;
848 if (i >= envsize - 1) {
849 if (envsize >= 1000)
850 fatal("child_set_env: too many env vars");
851 envsize += 50;
852 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
853 *envsizep = envsize;
854 }
855 /* Need to set the NULL pointer at end of array beyond the new slot. */
856 env[i + 1] = NULL;
857 }
858
859 /* Allocate space and format the variable in the appropriate slot. */
860 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
861 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
862 }
863
864 /*
865 * Reads environment variables from the given file and adds/overrides them
866 * into the environment. If the file does not exist, this does nothing.
867 * Otherwise, it must consist of empty lines, comments (line starts with '#')
868 * and assignments of the form name=value. No other forms are allowed.
869 */
870 static void
read_environment_file(char *** env,u_int * envsize,const char * filename)871 read_environment_file(char ***env, u_int *envsize,
872 const char *filename)
873 {
874 FILE *f;
875 char buf[4096];
876 char *cp, *value;
877 u_int lineno = 0;
878
879 f = fopen(filename, "r");
880 if (!f)
881 return;
882
883 while (fgets(buf, sizeof(buf), f)) {
884 if (++lineno > 1000)
885 fatal("Too many lines in environment file %s", filename);
886 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
887 ;
888 if (!*cp || *cp == '#' || *cp == '\n')
889 continue;
890
891 cp[strcspn(cp, "\n")] = '\0';
892
893 value = strchr(cp, '=');
894 if (value == NULL) {
895 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
896 filename);
897 continue;
898 }
899 /*
900 * Replace the equals sign by nul, and advance value to
901 * the value string.
902 */
903 *value = '\0';
904 value++;
905 child_set_env(env, envsize, cp, value);
906 }
907 fclose(f);
908 }
909
910 static char **
do_setup_env(Session * s,const char * shell)911 do_setup_env(Session *s, const char *shell)
912 {
913 char buf[256];
914 u_int i, envsize;
915 char **env, *laddr;
916 struct passwd *pw = s->pw;
917
918 /* Initialize the environment. */
919 envsize = 100;
920 env = xcalloc(envsize, sizeof(char *));
921 env[0] = NULL;
922
923 if (!options.use_login) {
924 /* Set basic environment. */
925 for (i = 0; i < s->num_env; i++)
926 child_set_env(&env, &envsize, s->env[i].name,
927 s->env[i].val);
928
929 child_set_env(&env, &envsize, "USER", pw->pw_name);
930 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
931 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
932 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
933 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
934 else
935 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
936
937 snprintf(buf, sizeof buf, "%.200s/%.50s",
938 _PATH_MAILDIR, pw->pw_name);
939 child_set_env(&env, &envsize, "MAIL", buf);
940
941 /* Normal systems set SHELL by default. */
942 child_set_env(&env, &envsize, "SHELL", shell);
943 }
944 if (getenv("TZ"))
945 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
946
947 /* Set custom environment options from RSA authentication. */
948 if (!options.use_login) {
949 while (custom_environment) {
950 struct envstring *ce = custom_environment;
951 char *str = ce->s;
952
953 for (i = 0; str[i] != '=' && str[i]; i++)
954 ;
955 if (str[i] == '=') {
956 str[i] = 0;
957 child_set_env(&env, &envsize, str, str + i + 1);
958 }
959 custom_environment = ce->next;
960 xfree(ce->s);
961 xfree(ce);
962 }
963 }
964
965 /* SSH_CLIENT deprecated */
966 snprintf(buf, sizeof buf, "%.50s %d %d",
967 get_remote_ipaddr(), get_remote_port(), get_local_port());
968 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
969
970 laddr = get_local_ipaddr(packet_get_connection_in());
971 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
972 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
973 xfree(laddr);
974 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
975
976 if (s->ttyfd != -1)
977 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
978 if (s->term)
979 child_set_env(&env, &envsize, "TERM", s->term);
980 if (s->display)
981 child_set_env(&env, &envsize, "DISPLAY", s->display);
982 if (original_command)
983 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
984 original_command);
985 if (auth_sock_name != NULL)
986 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
987 auth_sock_name);
988
989 /* read $HOME/.etc/ssh/environment. */
990 if (options.permit_user_env && !options.use_login) {
991 snprintf(buf, sizeof buf, "%.200s/.etc/ssh/environment",
992 pw->pw_dir);
993 read_environment_file(&env, &envsize, buf);
994 }
995 if (debug_flag) {
996 /* dump the environment */
997 fprintf(stderr, "Environment:\n");
998 for (i = 0; env[i]; i++)
999 fprintf(stderr, " %.200s\n", env[i]);
1000 }
1001 return env;
1002 }
1003
1004 /*
1005 * Run $HOME/.etc/ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1006 * first in this order).
1007 */
1008 static void
do_rc_files(Session * s,const char * shell)1009 do_rc_files(Session *s, const char *shell)
1010 {
1011 FILE *f = NULL;
1012 char cmd[1024];
1013 int do_xauth;
1014 struct stat st;
1015
1016 do_xauth =
1017 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1018
1019 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1020 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1021 !no_user_rc && stat(_PATH_SSH_USER_RC, &st) >= 0) {
1022 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1023 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1024 if (debug_flag)
1025 fprintf(stderr, "Running %s\n", cmd);
1026 f = popen(cmd, "w");
1027 if (f) {
1028 if (do_xauth)
1029 fprintf(f, "%s %s\n", s->auth_proto,
1030 s->auth_data);
1031 pclose(f);
1032 } else
1033 fprintf(stderr, "Could not run %s\n",
1034 _PATH_SSH_USER_RC);
1035 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1036 if (debug_flag)
1037 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1038 _PATH_SSH_SYSTEM_RC);
1039 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1040 if (f) {
1041 if (do_xauth)
1042 fprintf(f, "%s %s\n", s->auth_proto,
1043 s->auth_data);
1044 pclose(f);
1045 } else
1046 fprintf(stderr, "Could not run %s\n",
1047 _PATH_SSH_SYSTEM_RC);
1048 } else if (do_xauth && options.xauth_location != NULL) {
1049 /* Add authority data to .Xauthority if appropriate. */
1050 if (debug_flag) {
1051 fprintf(stderr,
1052 "Running %.500s remove %.100s\n",
1053 options.xauth_location, s->auth_display);
1054 fprintf(stderr,
1055 "%.500s add %.100s %.100s %.100s\n",
1056 options.xauth_location, s->auth_display,
1057 s->auth_proto, s->auth_data);
1058 }
1059 snprintf(cmd, sizeof cmd, "%s -q -",
1060 options.xauth_location);
1061 f = popen(cmd, "w");
1062 if (f) {
1063 fprintf(f, "remove %s\n",
1064 s->auth_display);
1065 fprintf(f, "add %s %s %s\n",
1066 s->auth_display, s->auth_proto,
1067 s->auth_data);
1068 pclose(f);
1069 } else {
1070 fprintf(stderr, "Could not run %s\n",
1071 cmd);
1072 }
1073 }
1074 }
1075
1076 static void
do_nologin(struct passwd * pw)1077 do_nologin(struct passwd *pw)
1078 {
1079 FILE *f = NULL;
1080 char buf[1024];
1081
1082 if (!login_getcapbool(lc, (char *)"ignorenologin", 0) && pw->pw_uid)
1083 f = fopen(login_getcapstr(lc, (char *)"nologin",
1084 (char *)_PATH_NOLOGIN, (char *)_PATH_NOLOGIN), (char *)"r");
1085 if (f) {
1086 /* /etc/nologin exists. Print its contents and exit. */
1087 logit("User %.100s not allowed because %s exists",
1088 pw->pw_name, _PATH_NOLOGIN);
1089 while (fgets(buf, sizeof(buf), f))
1090 fputs(buf, stderr);
1091 fclose(f);
1092 exit(254);
1093 }
1094 }
1095
1096 /*
1097 * Chroot into a directory after checking it for safety: all path components
1098 * must be root-owned directories with strict permissions.
1099 */
1100 static void
safely_chroot(const char * path,uid_t uid)1101 safely_chroot(const char *path, uid_t uid)
1102 {
1103 const char *cp;
1104 char component[MAXPATHLEN];
1105 struct stat st;
1106
1107 if (*path != '/')
1108 fatal("chroot path does not begin at root");
1109 if (strlen(path) >= sizeof(component))
1110 fatal("chroot path too long");
1111
1112 /*
1113 * Descend the path, checking that each component is a
1114 * root-owned directory with strict permissions.
1115 */
1116 for (cp = path; cp != NULL;) {
1117 if ((cp = strchr(cp, '/')) == NULL)
1118 strlcpy(component, path, sizeof(component));
1119 else {
1120 cp++;
1121 memcpy(component, path, cp - path);
1122 component[cp - path] = '\0';
1123 }
1124
1125 debug3("%s: checking '%s'", __func__, component);
1126
1127 if (stat(component, &st) != 0)
1128 fatal("%s: stat(\"%s\"): %s", __func__,
1129 component, strerror(errno));
1130 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1131 fatal("bad ownership or modes for chroot "
1132 "directory %s\"%s\"",
1133 cp == NULL ? "" : "component ", component);
1134 if (!S_ISDIR(st.st_mode))
1135 fatal("chroot path %s\"%s\" is not a directory",
1136 cp == NULL ? "" : "component ", component);
1137
1138 }
1139
1140 if (chdir(path) == -1)
1141 fatal("Unable to chdir to chroot path \"%s\": "
1142 "%s", path, strerror(errno));
1143 if (chroot(path) == -1)
1144 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1145 if (chdir("/") == -1)
1146 fatal("%s: chdir(/) after chroot: %s",
1147 __func__, strerror(errno));
1148 verbose("Changed root directory to \"%s\"", path);
1149 }
1150
1151 /* Set login name, uid, gid, and groups. */
1152 void
do_setusercontext(struct passwd * pw)1153 do_setusercontext(struct passwd *pw)
1154 {
1155 char *chroot_path, *tmp;
1156
1157 if (getuid() == 0 || geteuid() == 0) {
1158 /* Prepare groups */
1159 if (setusercontext(lc, pw, pw->pw_uid,
1160 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1161 perror("unable to set user context");
1162 exit(1);
1163 }
1164
1165 if (options.chroot_directory != NULL &&
1166 strcasecmp(options.chroot_directory, "none") != 0) {
1167 tmp = tilde_expand_filename(options.chroot_directory,
1168 pw->pw_uid);
1169 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1170 "u", pw->pw_name, (char *)NULL);
1171 safely_chroot(chroot_path, pw->pw_uid);
1172 free(tmp);
1173 free(chroot_path);
1174 }
1175
1176 /* Set UID */
1177 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1178 perror("unable to set user context (setuser)");
1179 exit(1);
1180 }
1181 }
1182 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1183 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1184 }
1185
1186 static void
do_pwchange(Session * s)1187 do_pwchange(Session *s)
1188 {
1189 fflush(NULL);
1190 fprintf(stderr, "WARNING: Your password has expired.\n");
1191 if (s->ttyfd != -1) {
1192 fprintf(stderr,
1193 "You must change your password now and login again!\n");
1194 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1195 perror("passwd");
1196 } else {
1197 fprintf(stderr,
1198 "Password change required but no TTY available.\n");
1199 }
1200 exit(1);
1201 }
1202
1203 static void
launch_login(struct passwd * pw,const char * hostname)1204 launch_login(struct passwd *pw, const char *hostname)
1205 {
1206 /* Launch login(1). */
1207
1208 execl("/usr/bin/login", "login", "-h", hostname,
1209 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1210
1211 /* Login couldn't be executed, die. */
1212
1213 perror("login");
1214 exit(1);
1215 }
1216
1217 static void
child_close_fds(void)1218 child_close_fds(void)
1219 {
1220 int i;
1221
1222 if (packet_get_connection_in() == packet_get_connection_out())
1223 close(packet_get_connection_in());
1224 else {
1225 close(packet_get_connection_in());
1226 close(packet_get_connection_out());
1227 }
1228 /*
1229 * Close all descriptors related to channels. They will still remain
1230 * open in the parent.
1231 */
1232 /* XXX better use close-on-exec? -markus */
1233 channel_close_all();
1234
1235 /*
1236 * Close any extra file descriptors. Note that there may still be
1237 * descriptors left by system functions. They will be closed later.
1238 */
1239 endpwent();
1240
1241 /*
1242 * Close any extra open file descriptors so that we don't have them
1243 * hanging around in clients. Note that we want to do this after
1244 * initgroups, because at least on Solaris 2.3 it leaves file
1245 * descriptors open.
1246 */
1247 for (i = 3; i < 64; i++)
1248 close(i);
1249 }
1250
1251 /*
1252 * Performs common processing for the child, such as setting up the
1253 * environment, closing extra file descriptors, setting the user and group
1254 * ids, and executing the command or shell.
1255 */
1256 #define ARGV_MAX 10
1257 void
do_child(Session * s,const char * command)1258 do_child(Session *s, const char *command)
1259 {
1260 extern char **environ;
1261 char **env;
1262 char *argv[ARGV_MAX];
1263 const char *shell, *shell0, *hostname = NULL;
1264 struct passwd *pw = s->pw;
1265 int r = 0;
1266
1267 /* remove hostkey from the child's memory */
1268 destroy_sensitive_data();
1269
1270 /* Force a password change */
1271 if (s->authctxt->force_pwchange) {
1272 do_setusercontext(pw);
1273 child_close_fds();
1274 do_pwchange(s);
1275 exit(1);
1276 }
1277
1278 /* login(1) is only called if we execute the login shell */
1279 if (options.use_login && command != NULL)
1280 options.use_login = 0;
1281
1282 /*
1283 * Login(1) does this as well, and it needs uid 0 for the "-h"
1284 * switch, so we let login(1) to this for us.
1285 */
1286 if (!options.use_login) {
1287 do_nologin(pw);
1288 do_setusercontext(pw);
1289 }
1290
1291 /*
1292 * Get the shell from the password data. An empty shell field is
1293 * legal, and means /bin/sh.
1294 */
1295 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1296
1297 /*
1298 * Make sure $SHELL points to the shell from the password file,
1299 * even if shell is overridden from login.conf
1300 */
1301 env = do_setup_env(s, shell);
1302
1303 shell = login_getcapstr(lc, (char *)"shell", (char *)shell, (char *)shell);
1304
1305 /* we have to stash the hostname before we close our socket. */
1306 if (options.use_login)
1307 hostname = get_remote_name_or_ip(utmp_len,
1308 options.use_dns);
1309 /*
1310 * Close the connection descriptors; note that this is the child, and
1311 * the server will still have the socket open, and it is important
1312 * that we do not shutdown it. Note that the descriptors cannot be
1313 * closed before building the environment, as we call
1314 * get_remote_ipaddr there.
1315 */
1316 child_close_fds();
1317
1318 /*
1319 * Must take new environment into use so that .etc/ssh/rc,
1320 * /etc/ssh/sshrc and xauth are run in the proper environment.
1321 */
1322 environ = env;
1323
1324 /* Change current directory to the user's home directory. */
1325 if (chdir(pw->pw_dir) < 0) {
1326 /* Suppress missing homedir warning for chroot case */
1327 r = login_getcapbool(lc, (char *)"requirehome", 0);
1328 if (r || options.chroot_directory == NULL)
1329 fprintf(stderr, "Could not chdir to home "
1330 "directory %s: %s\n", pw->pw_dir,
1331 strerror(errno));
1332 if (r)
1333 exit(1);
1334 }
1335
1336 closefrom(STDERR_FILENO + 1);
1337
1338 if (!options.use_login)
1339 do_rc_files(s, shell);
1340
1341 /* restore SIGPIPE for child */
1342 signal(SIGPIPE, SIG_DFL);
1343
1344 #ifndef SMALL
1345 if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1346 int i;
1347 char *p, *args;
1348
1349 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1350 args = xstrdup(command ? command : "sftp-server");
1351 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1352 if (i < ARGV_MAX - 1)
1353 argv[i++] = p;
1354 argv[i] = NULL;
1355 optind = optreset = 1;
1356 __progname = argv[0];
1357 exit(sftp_server_main(i, argv, s->pw));
1358 }
1359 #endif
1360
1361 if (options.use_login) {
1362 launch_login(pw, hostname);
1363 /* NEVERREACHED */
1364 }
1365
1366 /* Get the last component of the shell name. */
1367 if ((shell0 = strrchr(shell, '/')) != NULL)
1368 shell0++;
1369 else
1370 shell0 = shell;
1371
1372 /*
1373 * If we have no command, execute the shell. In this case, the shell
1374 * name to be passed in argv[0] is preceded by '-' to indicate that
1375 * this is a login shell.
1376 */
1377 if (!command) {
1378 char argv0[256];
1379
1380 /* Start the shell. Set initial character to '-'. */
1381 argv0[0] = '-';
1382
1383 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1384 >= sizeof(argv0) - 1) {
1385 errno = EINVAL;
1386 perror(shell);
1387 exit(1);
1388 }
1389
1390 /* Execute the shell. */
1391 argv[0] = argv0;
1392 argv[1] = NULL;
1393 execve(shell, argv, env);
1394
1395 /* Executing the shell failed. */
1396 perror(shell);
1397 exit(1);
1398 }
1399 /*
1400 * Execute the command using the user's shell. This uses the -c
1401 * option to execute the command.
1402 */
1403 argv[0] = (char *) shell0;
1404 argv[1] = (char *)"-c";
1405 argv[2] = (char *) command;
1406 argv[3] = NULL;
1407 execve(shell, argv, env);
1408 perror(shell);
1409 exit(1);
1410 }
1411
1412 void
session_unused(int id)1413 session_unused(int id)
1414 {
1415 debug3("%s: session id %d unused", __func__, id);
1416 if (id >= options.max_sessions ||
1417 id >= sessions_nalloc) {
1418 fatal("%s: insane session id %d (max %d nalloc %d)",
1419 __func__, id, options.max_sessions, sessions_nalloc);
1420 }
1421 bzero(&sessions[id], sizeof(*sessions));
1422 sessions[id].self = id;
1423 sessions[id].used = 0;
1424 sessions[id].chanid = -1;
1425 sessions[id].ptyfd = -1;
1426 sessions[id].ttyfd = -1;
1427 sessions[id].ptymaster = -1;
1428 sessions[id].x11_chanids = NULL;
1429 sessions[id].next_unused = sessions_first_unused;
1430 sessions_first_unused = id;
1431 }
1432
1433 Session *
session_new(void)1434 session_new(void)
1435 {
1436 Session *s, *tmp;
1437
1438 if (sessions_first_unused == -1) {
1439 if (sessions_nalloc >= options.max_sessions)
1440 return NULL;
1441 debug2("%s: allocate (allocated %d max %d)",
1442 __func__, sessions_nalloc, options.max_sessions);
1443 tmp = xrealloc(sessions, sessions_nalloc + 1,
1444 sizeof(*sessions));
1445 if (tmp == NULL) {
1446 error("%s: cannot allocate %d sessions",
1447 __func__, sessions_nalloc + 1);
1448 return NULL;
1449 }
1450 sessions = tmp;
1451 session_unused(sessions_nalloc++);
1452 }
1453
1454 if (sessions_first_unused >= sessions_nalloc ||
1455 sessions_first_unused < 0) {
1456 fatal("%s: insane first_unused %d max %d nalloc %d",
1457 __func__, sessions_first_unused, options.max_sessions,
1458 sessions_nalloc);
1459 }
1460
1461 s = &sessions[sessions_first_unused];
1462 if (s->used) {
1463 fatal("%s: session %d already used",
1464 __func__, sessions_first_unused);
1465 }
1466 sessions_first_unused = s->next_unused;
1467 s->used = 1;
1468 s->next_unused = -1;
1469 debug("session_new: session %d", s->self);
1470
1471 return s;
1472 }
1473
1474 static void
session_dump(void)1475 session_dump(void)
1476 {
1477 int i;
1478 for (i = 0; i < sessions_nalloc; i++) {
1479 Session *s = &sessions[i];
1480
1481 debug("dump: used %d next_unused %d session %d %p "
1482 "channel %d pid %ld",
1483 s->used,
1484 s->next_unused,
1485 s->self,
1486 s,
1487 s->chanid,
1488 (long)s->pid);
1489 }
1490 }
1491
1492 int
session_open(Authctxt * authctxt,int chanid)1493 session_open(Authctxt *authctxt, int chanid)
1494 {
1495 Session *s = session_new();
1496 debug("session_open: channel %d", chanid);
1497 if (s == NULL) {
1498 error("no more sessions");
1499 return 0;
1500 }
1501 s->authctxt = authctxt;
1502 s->pw = authctxt->pw;
1503 if (s->pw == NULL || !authctxt->valid)
1504 fatal("no user for session %d", s->self);
1505 debug("session_open: session %d: link with channel %d", s->self, chanid);
1506 s->chanid = chanid;
1507 return 1;
1508 }
1509
1510 Session *
session_by_tty(char * tty)1511 session_by_tty(char *tty)
1512 {
1513 int i;
1514 for (i = 0; i < sessions_nalloc; i++) {
1515 Session *s = &sessions[i];
1516 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1517 debug("session_by_tty: session %d tty %s", i, tty);
1518 return s;
1519 }
1520 }
1521 debug("session_by_tty: unknown tty %.100s", tty);
1522 session_dump();
1523 return NULL;
1524 }
1525
1526 static Session *
session_by_channel(int id)1527 session_by_channel(int id)
1528 {
1529 int i;
1530 for (i = 0; i < sessions_nalloc; i++) {
1531 Session *s = &sessions[i];
1532 if (s->used && s->chanid == id) {
1533 debug("session_by_channel: session %d channel %d",
1534 i, id);
1535 return s;
1536 }
1537 }
1538 debug("session_by_channel: unknown channel %d", id);
1539 session_dump();
1540 return NULL;
1541 }
1542
1543 static Session *
session_by_x11_channel(int id)1544 session_by_x11_channel(int id)
1545 {
1546 int i, j;
1547
1548 for (i = 0; i < sessions_nalloc; i++) {
1549 Session *s = &sessions[i];
1550
1551 if (s->x11_chanids == NULL || !s->used)
1552 continue;
1553 for (j = 0; s->x11_chanids[j] != -1; j++) {
1554 if (s->x11_chanids[j] == id) {
1555 debug("session_by_x11_channel: session %d "
1556 "channel %d", s->self, id);
1557 return s;
1558 }
1559 }
1560 }
1561 debug("session_by_x11_channel: unknown channel %d", id);
1562 session_dump();
1563 return NULL;
1564 }
1565
1566 static Session *
session_by_pid(pid_t pid)1567 session_by_pid(pid_t pid)
1568 {
1569 int i;
1570 debug("session_by_pid: pid %ld", (long)pid);
1571 for (i = 0; i < sessions_nalloc; i++) {
1572 Session *s = &sessions[i];
1573 if (s->used && s->pid == pid)
1574 return s;
1575 }
1576 error("session_by_pid: unknown pid %ld", (long)pid);
1577 session_dump();
1578 return NULL;
1579 }
1580
1581 static int
session_window_change_req(Session * s)1582 session_window_change_req(Session *s)
1583 {
1584 s->col = packet_get_int();
1585 s->row = packet_get_int();
1586 s->xpixel = packet_get_int();
1587 s->ypixel = packet_get_int();
1588 packet_check_eom();
1589 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1590 return 1;
1591 }
1592
1593 static int
session_pty_req(Session * s)1594 session_pty_req(Session *s)
1595 {
1596 u_int len;
1597 int n_bytes;
1598
1599 if (no_pty_flag) {
1600 debug("Allocating a pty not permitted for this authentication.");
1601 return 0;
1602 }
1603 if (s->ttyfd != -1) {
1604 packet_disconnect("Protocol error: you already have a pty.");
1605 return 0;
1606 }
1607
1608 s->term = packet_get_string(&len);
1609
1610 if (compat20) {
1611 s->col = packet_get_int();
1612 s->row = packet_get_int();
1613 } else {
1614 s->row = packet_get_int();
1615 s->col = packet_get_int();
1616 }
1617 s->xpixel = packet_get_int();
1618 s->ypixel = packet_get_int();
1619
1620 if (strcmp(s->term, "") == 0) {
1621 xfree(s->term);
1622 s->term = NULL;
1623 }
1624
1625 /* Allocate a pty and open it. */
1626 debug("Allocating pty.");
1627 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1628 sizeof(s->tty)))) {
1629 if (s->term)
1630 xfree(s->term);
1631 s->term = NULL;
1632 s->ptyfd = -1;
1633 s->ttyfd = -1;
1634 error("session_pty_req: session %d alloc failed", s->self);
1635 return 0;
1636 }
1637 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1638
1639 /* for SSH1 the tty modes length is not given */
1640 if (!compat20)
1641 n_bytes = packet_remaining();
1642 tty_parse_modes(s->ttyfd, &n_bytes);
1643
1644 if (!use_privsep)
1645 pty_setowner(s->pw, s->tty);
1646
1647 /* Set window size from the packet. */
1648 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1649
1650 packet_check_eom();
1651 session_proctitle(s);
1652 return 1;
1653 }
1654
1655 static int
session_subsystem_req(Session * s)1656 session_subsystem_req(Session *s)
1657 {
1658 struct stat st;
1659 u_int len;
1660 int success = 0;
1661 char *prog, *cmd, *subsys = packet_get_string(&len);
1662 u_int i;
1663
1664 packet_check_eom();
1665 logit("subsystem request for %.100s", subsys);
1666
1667 for (i = 0; i < options.num_subsystems; i++) {
1668 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1669 prog = options.subsystem_command[i];
1670 cmd = options.subsystem_args[i];
1671 #ifndef SMALL
1672 if (!strcmp(INTERNAL_SFTP_NAME, prog)) {
1673 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1674 } else
1675 #endif
1676 if (stat(prog, &st) < 0) {
1677 error("subsystem: cannot stat %s: %s", prog,
1678 strerror(errno));
1679 break;
1680 } else {
1681 s->is_subsystem = SUBSYSTEM_EXT;
1682 }
1683 debug("subsystem: exec() %s", cmd);
1684 success = do_exec(s, cmd) == 0;
1685 break;
1686 }
1687 }
1688
1689 if (!success)
1690 logit("subsystem request for %.100s failed, subsystem not found",
1691 subsys);
1692
1693 xfree(subsys);
1694 return success;
1695 }
1696
1697 static int
session_x11_req(Session * s)1698 session_x11_req(Session *s)
1699 {
1700 int success;
1701
1702 if (s->auth_proto != NULL || s->auth_data != NULL) {
1703 error("session_x11_req: session %d: "
1704 "x11 forwarding already active", s->self);
1705 return 0;
1706 }
1707 s->single_connection = packet_get_char();
1708 s->auth_proto = packet_get_string(NULL);
1709 s->auth_data = packet_get_string(NULL);
1710 s->screen = packet_get_int();
1711 packet_check_eom();
1712
1713 success = session_setup_x11fwd(s);
1714 if (!success) {
1715 xfree(s->auth_proto);
1716 xfree(s->auth_data);
1717 s->auth_proto = NULL;
1718 s->auth_data = NULL;
1719 }
1720 return success;
1721 }
1722
1723 static int
session_shell_req(Session * s)1724 session_shell_req(Session *s)
1725 {
1726 packet_check_eom();
1727 return do_exec(s, NULL) == 0;
1728 }
1729
1730 static int
session_exec_req(Session * s)1731 session_exec_req(Session *s)
1732 {
1733 u_int len, success;
1734
1735 char *command = packet_get_string(&len);
1736 packet_check_eom();
1737 success = do_exec(s, command) == 0;
1738 xfree(command);
1739 return success;
1740 }
1741
1742 static int
session_break_req(Session * s)1743 session_break_req(Session *s)
1744 {
1745
1746 packet_get_int(); /* ignored */
1747 packet_check_eom();
1748
1749 if (s->ttyfd == -1 || tcsendbreak(s->ttyfd, 0) < 0)
1750 return 0;
1751 return 1;
1752 }
1753
1754 static int
session_env_req(Session * s)1755 session_env_req(Session *s)
1756 {
1757 char *name, *val;
1758 u_int name_len, val_len, i;
1759
1760 name = packet_get_string(&name_len);
1761 val = packet_get_string(&val_len);
1762 packet_check_eom();
1763
1764 /* Don't set too many environment variables */
1765 if (s->num_env > 128) {
1766 debug2("Ignoring env request %s: too many env vars", name);
1767 goto fail;
1768 }
1769
1770 for (i = 0; i < options.num_accept_env; i++) {
1771 if (match_pattern(name, options.accept_env[i])) {
1772 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1773 s->env = xrealloc(s->env, s->num_env + 1,
1774 sizeof(*s->env));
1775 s->env[s->num_env].name = name;
1776 s->env[s->num_env].val = val;
1777 s->num_env++;
1778 return (1);
1779 }
1780 }
1781 debug2("Ignoring env request %s: disallowed name", name);
1782
1783 fail:
1784 xfree(name);
1785 xfree(val);
1786 return (0);
1787 }
1788
1789 static int
session_auth_agent_req(Session * s)1790 session_auth_agent_req(Session *s)
1791 {
1792 static int called = 0;
1793 packet_check_eom();
1794 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
1795 debug("session_auth_agent_req: no_agent_forwarding_flag");
1796 return 0;
1797 }
1798 if (called) {
1799 return 0;
1800 } else {
1801 called = 1;
1802 return auth_input_request_forwarding(s->pw);
1803 }
1804 }
1805
1806 int
session_input_channel_req(Channel * c,const char * rtype)1807 session_input_channel_req(Channel *c, const char *rtype)
1808 {
1809 int success = 0;
1810 Session *s;
1811
1812 if ((s = session_by_channel(c->self)) == NULL) {
1813 logit("session_input_channel_req: no session %d req %.100s",
1814 c->self, rtype);
1815 return 0;
1816 }
1817 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1818
1819 /*
1820 * a session is in LARVAL state until a shell, a command
1821 * or a subsystem is executed
1822 */
1823 if (c->type == SSH_CHANNEL_LARVAL) {
1824 if (strcmp(rtype, "shell") == 0) {
1825 success = session_shell_req(s);
1826 } else if (strcmp(rtype, "exec") == 0) {
1827 success = session_exec_req(s);
1828 } else if (strcmp(rtype, "pty-req") == 0) {
1829 success = session_pty_req(s);
1830 } else if (strcmp(rtype, "x11-req") == 0) {
1831 success = session_x11_req(s);
1832 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1833 success = session_auth_agent_req(s);
1834 } else if (strcmp(rtype, "subsystem") == 0) {
1835 success = session_subsystem_req(s);
1836 } else if (strcmp(rtype, "env") == 0) {
1837 success = session_env_req(s);
1838 }
1839 }
1840 if (strcmp(rtype, "window-change") == 0) {
1841 success = session_window_change_req(s);
1842 } else if (strcmp(rtype, "break") == 0) {
1843 success = session_break_req(s);
1844 }
1845
1846 return success;
1847 }
1848
1849 void
session_set_fds(Session * s,int fdin,int fdout,int fderr,int is_tty)1850 session_set_fds(Session *s, int fdin, int fdout, int fderr, int is_tty)
1851 {
1852 if (!compat20)
1853 fatal("session_set_fds: called for proto != 2.0");
1854 /*
1855 * now that have a child and a pipe to the child,
1856 * we can activate our channel and register the fd's
1857 */
1858 if (s->chanid == -1)
1859 fatal("no channel for session %d", s->self);
1860 channel_set_fds(s->chanid,
1861 fdout, fdin, fderr,
1862 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1863 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
1864 }
1865
1866 /*
1867 * Function to perform pty cleanup. Also called if we get aborted abnormally
1868 * (e.g., due to a dropped connection).
1869 */
1870 void
session_pty_cleanup2(Session * s)1871 session_pty_cleanup2(Session *s)
1872 {
1873 if (s == NULL) {
1874 error("session_pty_cleanup: no session");
1875 return;
1876 }
1877 if (s->ttyfd == -1)
1878 return;
1879
1880 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1881
1882 /* Record that the user has logged out. */
1883 if (s->pid != 0)
1884 record_logout(s->pid, s->tty);
1885
1886 /* Release the pseudo-tty. */
1887 if (getuid() == 0)
1888 pty_release(s->tty);
1889
1890 /*
1891 * Close the server side of the socket pairs. We must do this after
1892 * the pty cleanup, so that another process doesn't get this pty
1893 * while we're still cleaning up.
1894 */
1895 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
1896 error("close(s->ptymaster/%d): %s",
1897 s->ptymaster, strerror(errno));
1898
1899 /* unlink pty from session */
1900 s->ttyfd = -1;
1901 }
1902
1903 void
session_pty_cleanup(Session * s)1904 session_pty_cleanup(Session *s)
1905 {
1906 PRIVSEP(session_pty_cleanup2(s));
1907 }
1908
1909 static const char *
sig2name(int sig)1910 sig2name(int sig)
1911 {
1912 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1913 SSH_SIG(ABRT);
1914 SSH_SIG(ALRM);
1915 SSH_SIG(FPE);
1916 SSH_SIG(HUP);
1917 SSH_SIG(ILL);
1918 SSH_SIG(INT);
1919 SSH_SIG(KILL);
1920 SSH_SIG(PIPE);
1921 SSH_SIG(QUIT);
1922 SSH_SIG(SEGV);
1923 SSH_SIG(TERM);
1924 SSH_SIG(USR1);
1925 SSH_SIG(USR2);
1926 #undef SSH_SIG
1927 return "SIG@openssh.com";
1928 }
1929
1930 static void
session_close_x11(int id)1931 session_close_x11(int id)
1932 {
1933 Channel *c;
1934
1935 if ((c = channel_by_id(id)) == NULL) {
1936 debug("session_close_x11: x11 channel %d missing", id);
1937 } else {
1938 /* Detach X11 listener */
1939 debug("session_close_x11: detach x11 channel %d", id);
1940 channel_cancel_cleanup(id);
1941 if (c->ostate != CHAN_OUTPUT_CLOSED)
1942 chan_mark_dead(c);
1943 }
1944 }
1945
1946 static void
session_close_single_x11(int id,void * arg)1947 session_close_single_x11(int id, void *arg)
1948 {
1949 Session *s;
1950 u_int i;
1951
1952 debug3("session_close_single_x11: channel %d", id);
1953 channel_cancel_cleanup(id);
1954 if ((s = session_by_x11_channel(id)) == NULL)
1955 fatal("session_close_single_x11: no x11 channel %d", id);
1956 for (i = 0; s->x11_chanids[i] != -1; i++) {
1957 debug("session_close_single_x11: session %d: "
1958 "closing channel %d", s->self, s->x11_chanids[i]);
1959 /*
1960 * The channel "id" is already closing, but make sure we
1961 * close all of its siblings.
1962 */
1963 if (s->x11_chanids[i] != id)
1964 session_close_x11(s->x11_chanids[i]);
1965 }
1966 xfree(s->x11_chanids);
1967 s->x11_chanids = NULL;
1968 if (s->display) {
1969 xfree(s->display);
1970 s->display = NULL;
1971 }
1972 if (s->auth_proto) {
1973 xfree(s->auth_proto);
1974 s->auth_proto = NULL;
1975 }
1976 if (s->auth_data) {
1977 xfree(s->auth_data);
1978 s->auth_data = NULL;
1979 }
1980 if (s->auth_display) {
1981 xfree(s->auth_display);
1982 s->auth_display = NULL;
1983 }
1984 }
1985
1986 static void
session_exit_message(Session * s,int status)1987 session_exit_message(Session *s, int status)
1988 {
1989 Channel *c;
1990
1991 if ((c = channel_lookup(s->chanid)) == NULL)
1992 fatal("session_exit_message: session %d: no channel %d",
1993 s->self, s->chanid);
1994 debug("session_exit_message: session %d channel %d pid %ld",
1995 s->self, s->chanid, (long)s->pid);
1996
1997 if (WIFEXITED(status)) {
1998 channel_request_start(s->chanid, "exit-status", 0);
1999 packet_put_int(WEXITSTATUS(status));
2000 packet_send();
2001 } else if (WIFSIGNALED(status)) {
2002 channel_request_start(s->chanid, "exit-signal", 0);
2003 packet_put_cstring(sig2name(WTERMSIG(status)));
2004 packet_put_char(WCOREDUMP(status)? 1 : 0);
2005 packet_put_cstring("");
2006 packet_put_cstring("");
2007 packet_send();
2008 } else {
2009 /* Some weird exit cause. Just exit. */
2010 packet_disconnect("wait returned status %04x.", status);
2011 }
2012
2013 /* disconnect channel */
2014 debug("session_exit_message: release channel %d", s->chanid);
2015
2016 /*
2017 * Adjust cleanup callback attachment to send close messages when
2018 * the channel gets EOF. The session will be then be closed
2019 * by session_close_by_channel when the childs close their fds.
2020 */
2021 channel_register_cleanup(c->self, session_close_by_channel, 1);
2022
2023 /*
2024 * emulate a write failure with 'chan_write_failed', nobody will be
2025 * interested in data we write.
2026 * Note that we must not call 'chan_read_failed', since there could
2027 * be some more data waiting in the pipe.
2028 */
2029 if (c->ostate != CHAN_OUTPUT_CLOSED)
2030 chan_write_failed(c);
2031 }
2032
2033 void
session_close(Session * s)2034 session_close(Session *s)
2035 {
2036 u_int i;
2037
2038 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2039 if (s->ttyfd != -1)
2040 session_pty_cleanup(s);
2041 if (s->term)
2042 xfree(s->term);
2043 if (s->display)
2044 xfree(s->display);
2045 if (s->x11_chanids)
2046 xfree(s->x11_chanids);
2047 if (s->auth_display)
2048 xfree(s->auth_display);
2049 if (s->auth_data)
2050 xfree(s->auth_data);
2051 if (s->auth_proto)
2052 xfree(s->auth_proto);
2053 if (s->env != NULL) {
2054 for (i = 0; i < s->num_env; i++) {
2055 xfree(s->env[i].name);
2056 xfree(s->env[i].val);
2057 }
2058 xfree(s->env);
2059 }
2060 session_proctitle(s);
2061 session_unused(s->self);
2062 }
2063
2064 void
session_close_by_pid(pid_t pid,int status)2065 session_close_by_pid(pid_t pid, int status)
2066 {
2067 Session *s = session_by_pid(pid);
2068 if (s == NULL) {
2069 debug("session_close_by_pid: no session for pid %ld",
2070 (long)pid);
2071 return;
2072 }
2073 if (s->chanid != -1)
2074 session_exit_message(s, status);
2075 if (s->ttyfd != -1)
2076 session_pty_cleanup(s);
2077 s->pid = 0;
2078 }
2079
2080 /*
2081 * this is called when a channel dies before
2082 * the session 'child' itself dies
2083 */
2084 void
session_close_by_channel(int id,void * arg)2085 session_close_by_channel(int id, void *arg)
2086 {
2087 Session *s = session_by_channel(id);
2088 u_int i;
2089
2090 if (s == NULL) {
2091 debug("session_close_by_channel: no session for id %d", id);
2092 return;
2093 }
2094 debug("session_close_by_channel: channel %d child %ld",
2095 id, (long)s->pid);
2096 if (s->pid != 0) {
2097 debug("session_close_by_channel: channel %d: has child", id);
2098 /*
2099 * delay detach of session, but release pty, since
2100 * the fd's to the child are already closed
2101 */
2102 if (s->ttyfd != -1)
2103 session_pty_cleanup(s);
2104 return;
2105 }
2106 /* detach by removing callback */
2107 channel_cancel_cleanup(s->chanid);
2108
2109 /* Close any X11 listeners associated with this session */
2110 if (s->x11_chanids != NULL) {
2111 for (i = 0; s->x11_chanids[i] != -1; i++) {
2112 session_close_x11(s->x11_chanids[i]);
2113 s->x11_chanids[i] = -1;
2114 }
2115 }
2116
2117 s->chanid = -1;
2118 session_close(s);
2119 }
2120
2121 void
session_destroy_all(void (* closefunc)(Session *))2122 session_destroy_all(void (*closefunc)(Session *))
2123 {
2124 int i;
2125 for (i = 0; i < sessions_nalloc; i++) {
2126 Session *s = &sessions[i];
2127 if (s->used) {
2128 if (closefunc != NULL)
2129 closefunc(s);
2130 else
2131 session_close(s);
2132 }
2133 }
2134 }
2135
2136 static char *
session_tty_list(void)2137 session_tty_list(void)
2138 {
2139 static char buf[1024];
2140 int i;
2141 buf[0] = '\0';
2142 for (i = 0; i < sessions_nalloc; i++) {
2143 Session *s = &sessions[i];
2144 if (s->used && s->ttyfd != -1) {
2145 if (buf[0] != '\0')
2146 strlcat(buf, ",", sizeof buf);
2147 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
2148 }
2149 }
2150 if (buf[0] == '\0')
2151 strlcpy(buf, "notty", sizeof buf);
2152 return buf;
2153 }
2154
2155 void
session_proctitle(Session * s)2156 session_proctitle(Session *s)
2157 {
2158 if (s->pw == NULL)
2159 error("no user for session %d", s->self);
2160 else
2161 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2162 }
2163
2164 int
session_setup_x11fwd(Session * s)2165 session_setup_x11fwd(Session *s)
2166 {
2167 struct stat st;
2168 char display[512], auth_display[512];
2169 char hostname[MAXHOSTNAMELEN];
2170 u_int i;
2171
2172 if (no_x11_forwarding_flag) {
2173 packet_send_debug("X11 forwarding disabled in user configuration file.");
2174 return 0;
2175 }
2176 if (!options.x11_forwarding) {
2177 debug("X11 forwarding disabled in server configuration file.");
2178 return 0;
2179 }
2180 if (!options.xauth_location ||
2181 (stat(options.xauth_location, &st) == -1)) {
2182 packet_send_debug("No xauth program; cannot forward with spoofing.");
2183 return 0;
2184 }
2185 if (options.use_login) {
2186 packet_send_debug("X11 forwarding disabled; "
2187 "not compatible with UseLogin=yes.");
2188 return 0;
2189 }
2190 if (s->display != NULL) {
2191 debug("X11 display already set.");
2192 return 0;
2193 }
2194 if (x11_create_display_inet(options.x11_display_offset,
2195 options.x11_use_localhost, s->single_connection,
2196 &s->display_number, &s->x11_chanids) == -1) {
2197 debug("x11_create_display_inet failed.");
2198 return 0;
2199 }
2200 for (i = 0; s->x11_chanids[i] != -1; i++) {
2201 channel_register_cleanup(s->x11_chanids[i],
2202 session_close_single_x11, 0);
2203 }
2204
2205 /* Set up a suitable value for the DISPLAY variable. */
2206 if (gethostname(hostname, sizeof(hostname)) < 0)
2207 fatal("gethostname: %.100s", strerror(errno));
2208 /*
2209 * auth_display must be used as the displayname when the
2210 * authorisation entry is added with xauth(1). This will be
2211 * different than the DISPLAY string for localhost displays.
2212 */
2213 if (options.x11_use_localhost) {
2214 snprintf(display, sizeof display, "localhost:%u.%u",
2215 s->display_number, s->screen);
2216 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2217 s->display_number, s->screen);
2218 s->display = xstrdup(display);
2219 s->auth_display = xstrdup(auth_display);
2220 } else {
2221 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2222 s->display_number, s->screen);
2223 s->display = xstrdup(display);
2224 s->auth_display = xstrdup(display);
2225 }
2226
2227 return 1;
2228 }
2229
2230 static void
do_authenticated2(Authctxt * authctxt)2231 do_authenticated2(Authctxt *authctxt)
2232 {
2233 server_loop2(authctxt);
2234 }
2235
2236 void
do_cleanup(Authctxt * authctxt)2237 do_cleanup(Authctxt *authctxt)
2238 {
2239 static int called = 0;
2240
2241 debug("do_cleanup");
2242
2243 /* no cleanup if we're in the child for login shell */
2244 if (is_child)
2245 return;
2246
2247 /* avoid double cleanup */
2248 if (called)
2249 return;
2250 called = 1;
2251
2252 if (authctxt == NULL || !authctxt->authenticated)
2253 return;
2254
2255 /* remove agent socket */
2256 auth_sock_cleanup_proc(authctxt->pw);
2257
2258 /*
2259 * Cleanup ptys/utmp only if privsep is disabled,
2260 * or if running in monitor.
2261 */
2262 if (!use_privsep || mm_is_monitor())
2263 session_destroy_all(session_pty_cleanup2);
2264 }
2265