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