]> andersk Git - openssh.git/blame_incremental - session.c
- provos@cvs.openbsd.org 2002/03/18 17:31:54
[openssh.git] / session.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
4 *
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose. Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
10 *
11 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35#include "includes.h"
36RCSID("$OpenBSD: session.c,v 1.129 2002/03/18 03:41:08 provos Exp $");
37
38#include "ssh.h"
39#include "ssh1.h"
40#include "ssh2.h"
41#include "xmalloc.h"
42#include "sshpty.h"
43#include "packet.h"
44#include "buffer.h"
45#include "mpaux.h"
46#include "uidswap.h"
47#include "compat.h"
48#include "channels.h"
49#include "bufaux.h"
50#include "auth.h"
51#include "auth-options.h"
52#include "pathnames.h"
53#include "log.h"
54#include "servconf.h"
55#include "sshlogin.h"
56#include "serverloop.h"
57#include "canohost.h"
58#include "session.h"
59
60#ifdef HAVE_CYGWIN
61#include <windows.h>
62#include <sys/cygwin.h>
63#define is_winnt (GetVersion() < 0x80000000)
64#endif
65
66/* types */
67
68#define TTYSZ 64
69typedef struct Session Session;
70struct Session {
71 int used;
72 int self;
73 struct passwd *pw;
74 Authctxt *authctxt;
75 pid_t pid;
76 /* tty */
77 char *term;
78 int ptyfd, ttyfd, ptymaster;
79 int row, col, xpixel, ypixel;
80 char tty[TTYSZ];
81 /* X11 */
82 int display_number;
83 char *display;
84 int screen;
85 char *auth_display;
86 char *auth_proto;
87 char *auth_data;
88 int single_connection;
89 /* proto 2 */
90 int chanid;
91 int is_subsystem;
92};
93
94/* func */
95
96Session *session_new(void);
97void session_set_fds(Session *, int, int, int);
98static void session_pty_cleanup(void *);
99void session_proctitle(Session *);
100int session_setup_x11fwd(Session *);
101void do_exec_pty(Session *, const char *);
102void do_exec_no_pty(Session *, const char *);
103void do_exec(Session *, const char *);
104void do_login(Session *, const char *);
105#ifdef LOGIN_NEEDS_UTMPX
106static void do_pre_login(Session *s);
107#endif
108void do_child(Session *, const char *);
109void do_motd(void);
110int check_quietlogin(Session *, const char *);
111
112static void do_authenticated1(Authctxt *);
113static void do_authenticated2(Authctxt *);
114
115static void session_close(Session *);
116static int session_pty_req(Session *);
117
118/* import */
119extern ServerOptions options;
120extern char *__progname;
121extern int log_stderr;
122extern int debug_flag;
123extern u_int utmp_len;
124extern int startup_pipe;
125extern void destroy_sensitive_data(void);
126
127/* original command from peer. */
128const char *original_command = NULL;
129
130/* data */
131#define MAX_SESSIONS 10
132Session sessions[MAX_SESSIONS];
133
134#ifdef WITH_AIXAUTHENTICATE
135char *aixloginmsg;
136#endif /* WITH_AIXAUTHENTICATE */
137
138#ifdef HAVE_LOGIN_CAP
139login_cap_t *lc;
140#endif
141
142void
143do_authenticated(Authctxt *authctxt)
144{
145 /*
146 * Cancel the alarm we set to limit the time taken for
147 * authentication.
148 */
149 alarm(0);
150 if (startup_pipe != -1) {
151 close(startup_pipe);
152 startup_pipe = -1;
153 }
154#ifdef WITH_AIXAUTHENTICATE
155 /* We don't have a pty yet, so just label the line as "ssh" */
156 if (loginsuccess(authctxt->user,
157 get_canonical_hostname(options.verify_reverse_mapping),
158 "ssh", &aixloginmsg) < 0)
159 aixloginmsg = NULL;
160#endif /* WITH_AIXAUTHENTICATE */
161
162 /* setup the channel layer */
163 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
164 channel_permit_all_opens();
165
166 if (compat20)
167 do_authenticated2(authctxt);
168 else
169 do_authenticated1(authctxt);
170
171 /* remove agent socket */
172 if (auth_get_socket_name())
173 auth_sock_cleanup_proc(authctxt->pw);
174#ifdef KRB4
175 if (options.kerberos_ticket_cleanup)
176 krb4_cleanup_proc(authctxt);
177#endif
178#ifdef KRB5
179 if (options.kerberos_ticket_cleanup)
180 krb5_cleanup_proc(authctxt);
181#endif
182}
183
184/*
185 * Prepares for an interactive session. This is called after the user has
186 * been successfully authenticated. During this message exchange, pseudo
187 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
188 * are requested, etc.
189 */
190static void
191do_authenticated1(Authctxt *authctxt)
192{
193 Session *s;
194 char *command;
195 int success, type, screen_flag;
196 int compression_level = 0, enable_compression_after_reply = 0;
197 u_int proto_len, data_len, dlen;
198
199 s = session_new();
200 s->authctxt = authctxt;
201 s->pw = authctxt->pw;
202
203 /*
204 * We stay in this loop until the client requests to execute a shell
205 * or a command.
206 */
207 for (;;) {
208 success = 0;
209
210 /* Get a packet from the client. */
211 type = packet_read();
212
213 /* Process the packet. */
214 switch (type) {
215 case SSH_CMSG_REQUEST_COMPRESSION:
216 compression_level = packet_get_int();
217 packet_check_eom();
218 if (compression_level < 1 || compression_level > 9) {
219 packet_send_debug("Received illegal compression level %d.",
220 compression_level);
221 break;
222 }
223 /* Enable compression after we have responded with SUCCESS. */
224 enable_compression_after_reply = 1;
225 success = 1;
226 break;
227
228 case SSH_CMSG_REQUEST_PTY:
229 success = session_pty_req(s);
230 break;
231
232 case SSH_CMSG_X11_REQUEST_FORWARDING:
233 s->auth_proto = packet_get_string(&proto_len);
234 s->auth_data = packet_get_string(&data_len);
235
236 screen_flag = packet_get_protocol_flags() &
237 SSH_PROTOFLAG_SCREEN_NUMBER;
238 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
239
240 if (packet_remaining() == 4) {
241 if (!screen_flag)
242 debug2("Buggy client: "
243 "X11 screen flag missing");
244 s->screen = packet_get_int();
245 } else {
246 s->screen = 0;
247 }
248 packet_check_eom();
249 success = session_setup_x11fwd(s);
250 if (!success) {
251 xfree(s->auth_proto);
252 xfree(s->auth_data);
253 s->auth_proto = NULL;
254 s->auth_data = NULL;
255 }
256 break;
257
258 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
259 if (no_agent_forwarding_flag || compat13) {
260 debug("Authentication agent forwarding not permitted for this authentication.");
261 break;
262 }
263 debug("Received authentication agent forwarding request.");
264 success = auth_input_request_forwarding(s->pw);
265 break;
266
267 case SSH_CMSG_PORT_FORWARD_REQUEST:
268 if (no_port_forwarding_flag) {
269 debug("Port forwarding not permitted for this authentication.");
270 break;
271 }
272 if (!options.allow_tcp_forwarding) {
273 debug("Port forwarding not permitted.");
274 break;
275 }
276 debug("Received TCP/IP port forwarding request.");
277 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
278 success = 1;
279 break;
280
281 case SSH_CMSG_MAX_PACKET_SIZE:
282 if (packet_set_maxsize(packet_get_int()) > 0)
283 success = 1;
284 break;
285
286#if defined(AFS) || defined(KRB5)
287 case SSH_CMSG_HAVE_KERBEROS_TGT:
288 if (!options.kerberos_tgt_passing) {
289 verbose("Kerberos TGT passing disabled.");
290 } else {
291 char *kdata = packet_get_string(&dlen);
292 packet_check_eom();
293
294 /* XXX - 0x41, see creds_to_radix version */
295 if (kdata[0] != 0x41) {
296#ifdef KRB5
297 krb5_data tgt;
298 tgt.data = kdata;
299 tgt.length = dlen;
300
301 if (auth_krb5_tgt(s->authctxt, &tgt))
302 success = 1;
303 else
304 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
305#endif /* KRB5 */
306 } else {
307#ifdef AFS
308 if (auth_krb4_tgt(s->authctxt, kdata))
309 success = 1;
310 else
311 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
312#endif /* AFS */
313 }
314 xfree(kdata);
315 }
316 break;
317#endif /* AFS || KRB5 */
318
319#ifdef AFS
320 case SSH_CMSG_HAVE_AFS_TOKEN:
321 if (!options.afs_token_passing || !k_hasafs()) {
322 verbose("AFS token passing disabled.");
323 } else {
324 /* Accept AFS token. */
325 char *token = packet_get_string(&dlen);
326 packet_check_eom();
327
328 if (auth_afs_token(s->authctxt, token))
329 success = 1;
330 else
331 verbose("AFS token refused for %.100s",
332 s->authctxt->user);
333 xfree(token);
334 }
335 break;
336#endif /* AFS */
337
338 case SSH_CMSG_EXEC_SHELL:
339 case SSH_CMSG_EXEC_CMD:
340 if (type == SSH_CMSG_EXEC_CMD) {
341 command = packet_get_string(&dlen);
342 debug("Exec command '%.500s'", command);
343 do_exec(s, command);
344 xfree(command);
345 } else {
346 do_exec(s, NULL);
347 }
348 packet_check_eom();
349 session_close(s);
350 return;
351
352 default:
353 /*
354 * Any unknown messages in this phase are ignored,
355 * and a failure message is returned.
356 */
357 log("Unknown packet type received after authentication: %d", type);
358 }
359 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
360 packet_send();
361 packet_write_wait();
362
363 /* Enable compression now that we have replied if appropriate. */
364 if (enable_compression_after_reply) {
365 enable_compression_after_reply = 0;
366 packet_start_compression(compression_level);
367 }
368 }
369}
370
371/*
372 * This is called to fork and execute a command when we have no tty. This
373 * will call do_child from the child, and server_loop from the parent after
374 * setting up file descriptors and such.
375 */
376void
377do_exec_no_pty(Session *s, const char *command)
378{
379 int pid;
380
381#ifdef USE_PIPES
382 int pin[2], pout[2], perr[2];
383 /* Allocate pipes for communicating with the program. */
384 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
385 packet_disconnect("Could not create pipes: %.100s",
386 strerror(errno));
387#else /* USE_PIPES */
388 int inout[2], err[2];
389 /* Uses socket pairs to communicate with the program. */
390 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
391 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
392 packet_disconnect("Could not create socket pairs: %.100s",
393 strerror(errno));
394#endif /* USE_PIPES */
395 if (s == NULL)
396 fatal("do_exec_no_pty: no session");
397
398 session_proctitle(s);
399
400#if defined(USE_PAM)
401 do_pam_session(s->pw->pw_name, NULL);
402 do_pam_setcred(1);
403 if (is_pam_password_change_required())
404 packet_disconnect("Password change required but no "
405 "TTY available");
406#endif /* USE_PAM */
407
408 /* Fork the child. */
409 if ((pid = fork()) == 0) {
410 /* Child. Reinitialize the log since the pid has changed. */
411 log_init(__progname, options.log_level, options.log_facility, log_stderr);
412
413 /*
414 * Create a new session and process group since the 4.4BSD
415 * setlogin() affects the entire process group.
416 */
417 if (setsid() < 0)
418 error("setsid failed: %.100s", strerror(errno));
419
420#ifdef USE_PIPES
421 /*
422 * Redirect stdin. We close the parent side of the socket
423 * pair, and make the child side the standard input.
424 */
425 close(pin[1]);
426 if (dup2(pin[0], 0) < 0)
427 perror("dup2 stdin");
428 close(pin[0]);
429
430 /* Redirect stdout. */
431 close(pout[0]);
432 if (dup2(pout[1], 1) < 0)
433 perror("dup2 stdout");
434 close(pout[1]);
435
436 /* Redirect stderr. */
437 close(perr[0]);
438 if (dup2(perr[1], 2) < 0)
439 perror("dup2 stderr");
440 close(perr[1]);
441#else /* USE_PIPES */
442 /*
443 * Redirect stdin, stdout, and stderr. Stdin and stdout will
444 * use the same socket, as some programs (particularly rdist)
445 * seem to depend on it.
446 */
447 close(inout[1]);
448 close(err[1]);
449 if (dup2(inout[0], 0) < 0) /* stdin */
450 perror("dup2 stdin");
451 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
452 perror("dup2 stdout");
453 if (dup2(err[0], 2) < 0) /* stderr */
454 perror("dup2 stderr");
455#endif /* USE_PIPES */
456
457 /* Do processing for the child (exec command etc). */
458 do_child(s, command);
459 /* NOTREACHED */
460 }
461#ifdef HAVE_CYGWIN
462 if (is_winnt)
463 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
464#endif
465 if (pid < 0)
466 packet_disconnect("fork failed: %.100s", strerror(errno));
467 s->pid = pid;
468 /* Set interactive/non-interactive mode. */
469 packet_set_interactive(s->display != NULL);
470#ifdef USE_PIPES
471 /* We are the parent. Close the child sides of the pipes. */
472 close(pin[0]);
473 close(pout[1]);
474 close(perr[1]);
475
476 if (compat20) {
477 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
478 } else {
479 /* Enter the interactive session. */
480 server_loop(pid, pin[1], pout[0], perr[0]);
481 /* server_loop has closed pin[1], pout[0], and perr[0]. */
482 }
483#else /* USE_PIPES */
484 /* We are the parent. Close the child sides of the socket pairs. */
485 close(inout[0]);
486 close(err[0]);
487
488 /*
489 * Enter the interactive session. Note: server_loop must be able to
490 * handle the case that fdin and fdout are the same.
491 */
492 if (compat20) {
493 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
494 } else {
495 server_loop(pid, inout[1], inout[1], err[1]);
496 /* server_loop has closed inout[1] and err[1]. */
497 }
498#endif /* USE_PIPES */
499}
500
501/*
502 * This is called to fork and execute a command when we have a tty. This
503 * will call do_child from the child, and server_loop from the parent after
504 * setting up file descriptors, controlling tty, updating wtmp, utmp,
505 * lastlog, and other such operations.
506 */
507void
508do_exec_pty(Session *s, const char *command)
509{
510 int fdout, ptyfd, ttyfd, ptymaster;
511 pid_t pid;
512
513 if (s == NULL)
514 fatal("do_exec_pty: no session");
515 ptyfd = s->ptyfd;
516 ttyfd = s->ttyfd;
517
518#if defined(USE_PAM)
519 do_pam_session(s->pw->pw_name, s->tty);
520 do_pam_setcred(1);
521#endif
522
523 /* Fork the child. */
524 if ((pid = fork()) == 0) {
525
526 /* Child. Reinitialize the log because the pid has changed. */
527 log_init(__progname, options.log_level, options.log_facility, log_stderr);
528 /* Close the master side of the pseudo tty. */
529 close(ptyfd);
530
531 /* Make the pseudo tty our controlling tty. */
532 pty_make_controlling_tty(&ttyfd, s->tty);
533
534 /* Redirect stdin/stdout/stderr from the pseudo tty. */
535 if (dup2(ttyfd, 0) < 0)
536 error("dup2 stdin: %s", strerror(errno));
537 if (dup2(ttyfd, 1) < 0)
538 error("dup2 stdout: %s", strerror(errno));
539 if (dup2(ttyfd, 2) < 0)
540 error("dup2 stderr: %s", strerror(errno));
541
542 /* Close the extra descriptor for the pseudo tty. */
543 close(ttyfd);
544
545 /* record login, etc. similar to login(1) */
546#ifndef HAVE_OSF_SIA
547 if (!(options.use_login && command == NULL))
548 do_login(s, command);
549# ifdef LOGIN_NEEDS_UTMPX
550 else
551 do_pre_login(s);
552# endif
553#endif
554
555 /* Do common processing for the child, such as execing the command. */
556 do_child(s, command);
557 /* NOTREACHED */
558 }
559#ifdef HAVE_CYGWIN
560 if (is_winnt)
561 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
562#endif
563 if (pid < 0)
564 packet_disconnect("fork failed: %.100s", strerror(errno));
565 s->pid = pid;
566
567 /* Parent. Close the slave side of the pseudo tty. */
568 close(ttyfd);
569
570 /*
571 * Create another descriptor of the pty master side for use as the
572 * standard input. We could use the original descriptor, but this
573 * simplifies code in server_loop. The descriptor is bidirectional.
574 */
575 fdout = dup(ptyfd);
576 if (fdout < 0)
577 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
578
579 /* we keep a reference to the pty master */
580 ptymaster = dup(ptyfd);
581 if (ptymaster < 0)
582 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
583 s->ptymaster = ptymaster;
584
585 /* Enter interactive session. */
586 packet_set_interactive(1);
587 if (compat20) {
588 session_set_fds(s, ptyfd, fdout, -1);
589 } else {
590 server_loop(pid, ptyfd, fdout, -1);
591 /* server_loop _has_ closed ptyfd and fdout. */
592 }
593}
594
595#ifdef LOGIN_NEEDS_UTMPX
596static void
597do_pre_login(Session *s)
598{
599 socklen_t fromlen;
600 struct sockaddr_storage from;
601 pid_t pid = getpid();
602
603 /*
604 * Get IP address of client. If the connection is not a socket, let
605 * the address be 0.0.0.0.
606 */
607 memset(&from, 0, sizeof(from));
608 if (packet_connection_is_on_socket()) {
609 fromlen = sizeof(from);
610 if (getpeername(packet_get_connection_in(),
611 (struct sockaddr *) & from, &fromlen) < 0) {
612 debug("getpeername: %.100s", strerror(errno));
613 fatal_cleanup();
614 }
615 }
616
617 record_utmp_only(pid, s->tty, s->pw->pw_name,
618 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
619 (struct sockaddr *)&from);
620}
621#endif
622
623/*
624 * This is called to fork and execute a command. If another command is
625 * to be forced, execute that instead.
626 */
627void
628do_exec(Session *s, const char *command)
629{
630 if (forced_command) {
631 original_command = command;
632 command = forced_command;
633 debug("Forced command '%.900s'", command);
634 }
635
636 if (s->ttyfd != -1)
637 do_exec_pty(s, command);
638 else
639 do_exec_no_pty(s, command);
640
641 original_command = NULL;
642}
643
644
645/* administrative, login(1)-like work */
646void
647do_login(Session *s, const char *command)
648{
649 char *time_string;
650 char hostname[MAXHOSTNAMELEN];
651 socklen_t fromlen;
652 struct sockaddr_storage from;
653 time_t last_login_time;
654 struct passwd * pw = s->pw;
655 pid_t pid = getpid();
656
657 /*
658 * Get IP address of client. If the connection is not a socket, let
659 * the address be 0.0.0.0.
660 */
661 memset(&from, 0, sizeof(from));
662 if (packet_connection_is_on_socket()) {
663 fromlen = sizeof(from);
664 if (getpeername(packet_get_connection_in(),
665 (struct sockaddr *) & from, &fromlen) < 0) {
666 debug("getpeername: %.100s", strerror(errno));
667 fatal_cleanup();
668 }
669 }
670
671 /* Get the time and hostname when the user last logged in. */
672 if (options.print_lastlog) {
673 hostname[0] = '\0';
674 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
675 hostname, sizeof(hostname));
676 }
677
678 /* Record that there was a login on that tty from the remote host. */
679 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
680 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
681 (struct sockaddr *)&from);
682
683#ifdef USE_PAM
684 /*
685 * If password change is needed, do it now.
686 * This needs to occur before the ~/.hushlogin check.
687 */
688 if (is_pam_password_change_required()) {
689 print_pam_messages();
690 do_pam_chauthtok();
691 }
692#endif
693
694 if (check_quietlogin(s, command))
695 return;
696
697#ifdef USE_PAM
698 if (!is_pam_password_change_required())
699 print_pam_messages();
700#endif /* USE_PAM */
701#ifdef WITH_AIXAUTHENTICATE
702 if (aixloginmsg && *aixloginmsg)
703 printf("%s\n", aixloginmsg);
704#endif /* WITH_AIXAUTHENTICATE */
705
706 if (options.print_lastlog && last_login_time != 0) {
707 time_string = ctime(&last_login_time);
708 if (strchr(time_string, '\n'))
709 *strchr(time_string, '\n') = 0;
710 if (strcmp(hostname, "") == 0)
711 printf("Last login: %s\r\n", time_string);
712 else
713 printf("Last login: %s from %s\r\n", time_string, hostname);
714 }
715
716 do_motd();
717}
718
719/*
720 * Display the message of the day.
721 */
722void
723do_motd(void)
724{
725 FILE *f;
726 char buf[256];
727
728 if (options.print_motd) {
729#ifdef HAVE_LOGIN_CAP
730 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
731 "/etc/motd"), "r");
732#else
733 f = fopen("/etc/motd", "r");
734#endif
735 if (f) {
736 while (fgets(buf, sizeof(buf), f))
737 fputs(buf, stdout);
738 fclose(f);
739 }
740 }
741}
742
743
744/*
745 * Check for quiet login, either .hushlogin or command given.
746 */
747int
748check_quietlogin(Session *s, const char *command)
749{
750 char buf[256];
751 struct passwd *pw = s->pw;
752 struct stat st;
753
754 /* Return 1 if .hushlogin exists or a command given. */
755 if (command != NULL)
756 return 1;
757 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
758#ifdef HAVE_LOGIN_CAP
759 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
760 return 1;
761#else
762 if (stat(buf, &st) >= 0)
763 return 1;
764#endif
765 return 0;
766}
767
768/*
769 * Sets the value of the given variable in the environment. If the variable
770 * already exists, its value is overriden.
771 */
772static void
773child_set_env(char ***envp, u_int *envsizep, const char *name,
774 const char *value)
775{
776 u_int i, namelen;
777 char **env;
778
779 /*
780 * Find the slot where the value should be stored. If the variable
781 * already exists, we reuse the slot; otherwise we append a new slot
782 * at the end of the array, expanding if necessary.
783 */
784 env = *envp;
785 namelen = strlen(name);
786 for (i = 0; env[i]; i++)
787 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
788 break;
789 if (env[i]) {
790 /* Reuse the slot. */
791 xfree(env[i]);
792 } else {
793 /* New variable. Expand if necessary. */
794 if (i >= (*envsizep) - 1) {
795 (*envsizep) += 50;
796 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
797 }
798 /* Need to set the NULL pointer at end of array beyond the new slot. */
799 env[i + 1] = NULL;
800 }
801
802 /* Allocate space and format the variable in the appropriate slot. */
803 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
804 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
805}
806
807/*
808 * Reads environment variables from the given file and adds/overrides them
809 * into the environment. If the file does not exist, this does nothing.
810 * Otherwise, it must consist of empty lines, comments (line starts with '#')
811 * and assignments of the form name=value. No other forms are allowed.
812 */
813static void
814read_environment_file(char ***env, u_int *envsize,
815 const char *filename)
816{
817 FILE *f;
818 char buf[4096];
819 char *cp, *value;
820
821 f = fopen(filename, "r");
822 if (!f)
823 return;
824
825 while (fgets(buf, sizeof(buf), f)) {
826 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
827 ;
828 if (!*cp || *cp == '#' || *cp == '\n')
829 continue;
830 if (strchr(cp, '\n'))
831 *strchr(cp, '\n') = '\0';
832 value = strchr(cp, '=');
833 if (value == NULL) {
834 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
835 continue;
836 }
837 /*
838 * Replace the equals sign by nul, and advance value to
839 * the value string.
840 */
841 *value = '\0';
842 value++;
843 child_set_env(env, envsize, cp, value);
844 }
845 fclose(f);
846}
847
848void copy_environment(char **source, char ***env, u_int *envsize)
849{
850 char *var_name, *var_val;
851 int i;
852
853 if (source == NULL)
854 return;
855
856 for(i = 0; source[i] != NULL; i++) {
857 var_name = xstrdup(source[i]);
858 if ((var_val = strstr(var_name, "=")) == NULL) {
859 xfree(var_name);
860 continue;
861 }
862 *var_val++ = '\0';
863
864 debug3("Copy environment: %s=%s", var_name, var_val);
865 child_set_env(env, envsize, var_name, var_val);
866
867 xfree(var_name);
868 }
869}
870
871static char **
872do_setup_env(Session *s, const char *shell)
873{
874 char buf[256];
875 u_int i, envsize;
876 char **env;
877 struct passwd *pw = s->pw;
878
879 /* Initialize the environment. */
880 envsize = 100;
881 env = xmalloc(envsize * sizeof(char *));
882 env[0] = NULL;
883
884#ifdef HAVE_CYGWIN
885 /*
886 * The Windows environment contains some setting which are
887 * important for a running system. They must not be dropped.
888 */
889 copy_environment(environ, &env, &envsize);
890#endif
891
892 if (!options.use_login) {
893 /* Set basic environment. */
894 child_set_env(&env, &envsize, "USER", pw->pw_name);
895 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
896 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
897#ifdef HAVE_LOGIN_CAP
898 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
899 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
900#else /* HAVE_LOGIN_CAP */
901# ifndef HAVE_CYGWIN
902 /*
903 * There's no standard path on Windows. The path contains
904 * important components pointing to the system directories,
905 * needed for loading shared libraries. So the path better
906 * remains intact here.
907 */
908 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
909# endif /* HAVE_CYGWIN */
910#endif /* HAVE_LOGIN_CAP */
911
912 snprintf(buf, sizeof buf, "%.200s/%.50s",
913 _PATH_MAILDIR, pw->pw_name);
914 child_set_env(&env, &envsize, "MAIL", buf);
915
916 /* Normal systems set SHELL by default. */
917 child_set_env(&env, &envsize, "SHELL", shell);
918 }
919 if (getenv("TZ"))
920 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
921
922 /* Set custom environment options from RSA authentication. */
923 if (!options.use_login) {
924 while (custom_environment) {
925 struct envstring *ce = custom_environment;
926 char *s = ce->s;
927
928 for (i = 0; s[i] != '=' && s[i]; i++)
929 ;
930 if (s[i] == '=') {
931 s[i] = 0;
932 child_set_env(&env, &envsize, s, s + i + 1);
933 }
934 custom_environment = ce->next;
935 xfree(ce->s);
936 xfree(ce);
937 }
938 }
939
940 snprintf(buf, sizeof buf, "%.50s %d %d",
941 get_remote_ipaddr(), get_remote_port(), get_local_port());
942 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
943
944 if (s->ttyfd != -1)
945 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
946 if (s->term)
947 child_set_env(&env, &envsize, "TERM", s->term);
948 if (s->display)
949 child_set_env(&env, &envsize, "DISPLAY", s->display);
950 if (original_command)
951 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
952 original_command);
953
954#ifdef _AIX
955 {
956 char *cp;
957
958 if ((cp = getenv("AUTHSTATE")) != NULL)
959 child_set_env(&env, &envsize, "AUTHSTATE", cp);
960 if ((cp = getenv("KRB5CCNAME")) != NULL)
961 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
962 read_environment_file(&env, &envsize, "/etc/environment");
963 }
964#endif
965#ifdef KRB4
966 if (s->authctxt->krb4_ticket_file)
967 child_set_env(&env, &envsize, "KRBTKFILE",
968 s->authctxt->krb4_ticket_file);
969#endif
970#ifdef KRB5
971 if (s->authctxt->krb5_ticket_file)
972 child_set_env(&env, &envsize, "KRB5CCNAME",
973 s->authctxt->krb5_ticket_file);
974#endif
975#ifdef USE_PAM
976 /* Pull in any environment variables that may have been set by PAM. */
977 copy_environment(fetch_pam_environment(), &env, &envsize);
978#endif /* USE_PAM */
979
980 if (auth_get_socket_name() != NULL)
981 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
982 auth_get_socket_name());
983
984 /* read $HOME/.ssh/environment. */
985 if (!options.use_login) {
986 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
987 pw->pw_dir);
988 read_environment_file(&env, &envsize, buf);
989 }
990 if (debug_flag) {
991 /* dump the environment */
992 fprintf(stderr, "Environment:\n");
993 for (i = 0; env[i]; i++)
994 fprintf(stderr, " %.200s\n", env[i]);
995 }
996 return env;
997}
998
999/*
1000 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1001 * first in this order).
1002 */
1003static void
1004do_rc_files(Session *s, const char *shell)
1005{
1006 FILE *f = NULL;
1007 char cmd[1024];
1008 int do_xauth;
1009 struct stat st;
1010
1011 do_xauth =
1012 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1013
1014 /* ignore _PATH_SSH_USER_RC for subsystems */
1015 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1016 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1017 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1018 if (debug_flag)
1019 fprintf(stderr, "Running %s\n", cmd);
1020 f = popen(cmd, "w");
1021 if (f) {
1022 if (do_xauth)
1023 fprintf(f, "%s %s\n", s->auth_proto,
1024 s->auth_data);
1025 pclose(f);
1026 } else
1027 fprintf(stderr, "Could not run %s\n",
1028 _PATH_SSH_USER_RC);
1029 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1030 if (debug_flag)
1031 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1032 _PATH_SSH_SYSTEM_RC);
1033 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1034 if (f) {
1035 if (do_xauth)
1036 fprintf(f, "%s %s\n", s->auth_proto,
1037 s->auth_data);
1038 pclose(f);
1039 } else
1040 fprintf(stderr, "Could not run %s\n",
1041 _PATH_SSH_SYSTEM_RC);
1042 } else if (do_xauth && options.xauth_location != NULL) {
1043 /* Add authority data to .Xauthority if appropriate. */
1044 if (debug_flag) {
1045 fprintf(stderr,
1046 "Running %.100s add "
1047 "%.100s %.100s %.100s\n",
1048 options.xauth_location, s->auth_display,
1049 s->auth_proto, s->auth_data);
1050 }
1051 snprintf(cmd, sizeof cmd, "%s -q -",
1052 options.xauth_location);
1053 f = popen(cmd, "w");
1054 if (f) {
1055 fprintf(f, "add %s %s %s\n",
1056 s->auth_display, s->auth_proto,
1057 s->auth_data);
1058 pclose(f);
1059 } else {
1060 fprintf(stderr, "Could not run %s\n",
1061 cmd);
1062 }
1063 }
1064}
1065
1066static void
1067do_nologin(struct passwd *pw)
1068{
1069 FILE *f = NULL;
1070 char buf[1024];
1071
1072#ifdef HAVE_LOGIN_CAP
1073 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1074 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1075 _PATH_NOLOGIN), "r");
1076#else
1077 if (pw->pw_uid)
1078 f = fopen(_PATH_NOLOGIN, "r");
1079#endif
1080 if (f) {
1081 /* /etc/nologin exists. Print its contents and exit. */
1082 while (fgets(buf, sizeof(buf), f))
1083 fputs(buf, stderr);
1084 fclose(f);
1085 exit(254);
1086 }
1087}
1088
1089/* Set login name, uid, gid, and groups. */
1090static void
1091do_setusercontext(struct passwd *pw)
1092{
1093#ifdef HAVE_CYGWIN
1094 if (is_winnt) {
1095#else /* HAVE_CYGWIN */
1096 if (getuid() == 0 || geteuid() == 0) {
1097#endif /* HAVE_CYGWIN */
1098#ifdef HAVE_GETUSERATTR
1099 set_limits_from_userattr(pw->pw_name);
1100#endif /* HAVE_GETUSERATTR */
1101#ifdef HAVE_LOGIN_CAP
1102 if (setusercontext(lc, pw, pw->pw_uid,
1103 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1104 perror("unable to set user context");
1105 exit(1);
1106 }
1107#else
1108# if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1109 /* Sets login uid for accounting */
1110 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1111 error("setluid: %s", strerror(errno));
1112# endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1113
1114 if (setlogin(pw->pw_name) < 0)
1115 error("setlogin failed: %s", strerror(errno));
1116 if (setgid(pw->pw_gid) < 0) {
1117 perror("setgid");
1118 exit(1);
1119 }
1120 /* Initialize the group list. */
1121 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1122 perror("initgroups");
1123 exit(1);
1124 }
1125 endgrent();
1126# ifdef USE_PAM
1127 /*
1128 * PAM credentials may take the form of supplementary groups.
1129 * These will have been wiped by the above initgroups() call.
1130 * Reestablish them here.
1131 */
1132 do_pam_setcred(0);
1133# endif /* USE_PAM */
1134# if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1135 irix_setusercontext(pw);
1136# endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1137 /* Permanently switch to the desired uid. */
1138 permanently_set_uid(pw);
1139#endif
1140 }
1141 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1142 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1143}
1144
1145/*
1146 * Performs common processing for the child, such as setting up the
1147 * environment, closing extra file descriptors, setting the user and group
1148 * ids, and executing the command or shell.
1149 */
1150void
1151do_child(Session *s, const char *command)
1152{
1153 extern char **environ;
1154 char **env;
1155 char *argv[10];
1156 const char *shell, *shell0, *hostname = NULL;
1157 struct passwd *pw = s->pw;
1158 u_int i;
1159
1160 /* remove hostkey from the child's memory */
1161 destroy_sensitive_data();
1162
1163 /* login(1) is only called if we execute the login shell */
1164 if (options.use_login && command != NULL)
1165 options.use_login = 0;
1166
1167 /*
1168 * Login(1) does this as well, and it needs uid 0 for the "-h"
1169 * switch, so we let login(1) to this for us.
1170 */
1171 if (!options.use_login) {
1172#ifdef HAVE_OSF_SIA
1173 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1174 if (!check_quietlogin(s, command))
1175 do_motd();
1176#else /* HAVE_OSF_SIA */
1177 do_nologin(pw);
1178# ifdef _AIX
1179 aix_usrinfo(pw, s->tty, s->ttyfd);
1180# endif /* _AIX */
1181 do_setusercontext(pw);
1182#endif /* HAVE_OSF_SIA */
1183 }
1184
1185 /*
1186 * Get the shell from the password data. An empty shell field is
1187 * legal, and means /bin/sh.
1188 */
1189 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1190#ifdef HAVE_LOGIN_CAP
1191 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1192#endif
1193
1194 env = do_setup_env(s, shell);
1195
1196 /* we have to stash the hostname before we close our socket. */
1197 if (options.use_login)
1198 hostname = get_remote_name_or_ip(utmp_len,
1199 options.verify_reverse_mapping);
1200 /*
1201 * Close the connection descriptors; note that this is the child, and
1202 * the server will still have the socket open, and it is important
1203 * that we do not shutdown it. Note that the descriptors cannot be
1204 * closed before building the environment, as we call
1205 * get_remote_ipaddr there.
1206 */
1207 if (packet_get_connection_in() == packet_get_connection_out())
1208 close(packet_get_connection_in());
1209 else {
1210 close(packet_get_connection_in());
1211 close(packet_get_connection_out());
1212 }
1213 /*
1214 * Close all descriptors related to channels. They will still remain
1215 * open in the parent.
1216 */
1217 /* XXX better use close-on-exec? -markus */
1218 channel_close_all();
1219
1220 /*
1221 * Close any extra file descriptors. Note that there may still be
1222 * descriptors left by system functions. They will be closed later.
1223 */
1224 endpwent();
1225
1226 /*
1227 * Close any extra open file descriptors so that we don\'t have them
1228 * hanging around in clients. Note that we want to do this after
1229 * initgroups, because at least on Solaris 2.3 it leaves file
1230 * descriptors open.
1231 */
1232 for (i = 3; i < 64; i++)
1233 close(i);
1234
1235 /*
1236 * Must take new environment into use so that .ssh/rc,
1237 * /etc/ssh/sshrc and xauth are run in the proper environment.
1238 */
1239 environ = env;
1240
1241#ifdef AFS
1242 /* Try to get AFS tokens for the local cell. */
1243 if (k_hasafs()) {
1244 char cell[64];
1245
1246 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1247 krb_afslog(cell, 0);
1248
1249 krb_afslog(0, 0);
1250 }
1251#endif /* AFS */
1252
1253 /* Change current directory to the user\'s home directory. */
1254 if (chdir(pw->pw_dir) < 0) {
1255 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1256 pw->pw_dir, strerror(errno));
1257#ifdef HAVE_LOGIN_CAP
1258 if (login_getcapbool(lc, "requirehome", 0))
1259 exit(1);
1260#endif
1261 }
1262
1263 if (!options.use_login)
1264 do_rc_files(s, shell);
1265
1266 /* restore SIGPIPE for child */
1267 signal(SIGPIPE, SIG_DFL);
1268
1269 if (options.use_login) {
1270 /* Launch login(1). */
1271
1272 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1273#ifdef LOGIN_NEEDS_TERM
1274 (s->term ? s->term : "unknown"),
1275#endif /* LOGIN_NEEDS_TERM */
1276 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1277
1278 /* Login couldn't be executed, die. */
1279
1280 perror("login");
1281 exit(1);
1282 }
1283
1284 /* Get the last component of the shell name. */
1285 if ((shell0 = strrchr(shell, '/')) != NULL)
1286 shell0++;
1287 else
1288 shell0 = shell;
1289
1290 /*
1291 * If we have no command, execute the shell. In this case, the shell
1292 * name to be passed in argv[0] is preceded by '-' to indicate that
1293 * this is a login shell.
1294 */
1295 if (!command) {
1296 char argv0[256];
1297
1298 /* Start the shell. Set initial character to '-'. */
1299 argv0[0] = '-';
1300
1301 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1302 >= sizeof(argv0) - 1) {
1303 errno = EINVAL;
1304 perror(shell);
1305 exit(1);
1306 }
1307
1308 /* Execute the shell. */
1309 argv[0] = argv0;
1310 argv[1] = NULL;
1311 execve(shell, argv, env);
1312
1313 /* Executing the shell failed. */
1314 perror(shell);
1315 exit(1);
1316 }
1317 /*
1318 * Execute the command using the user's shell. This uses the -c
1319 * option to execute the command.
1320 */
1321 argv[0] = (char *) shell0;
1322 argv[1] = "-c";
1323 argv[2] = (char *) command;
1324 argv[3] = NULL;
1325 execve(shell, argv, env);
1326 perror(shell);
1327 exit(1);
1328}
1329
1330Session *
1331session_new(void)
1332{
1333 int i;
1334 static int did_init = 0;
1335 if (!did_init) {
1336 debug("session_new: init");
1337 for (i = 0; i < MAX_SESSIONS; i++) {
1338 sessions[i].used = 0;
1339 }
1340 did_init = 1;
1341 }
1342 for (i = 0; i < MAX_SESSIONS; i++) {
1343 Session *s = &sessions[i];
1344 if (! s->used) {
1345 memset(s, 0, sizeof(*s));
1346 s->chanid = -1;
1347 s->ptyfd = -1;
1348 s->ttyfd = -1;
1349 s->used = 1;
1350 s->self = i;
1351 debug("session_new: session %d", i);
1352 return s;
1353 }
1354 }
1355 return NULL;
1356}
1357
1358static void
1359session_dump(void)
1360{
1361 int i;
1362 for (i = 0; i < MAX_SESSIONS; i++) {
1363 Session *s = &sessions[i];
1364 debug("dump: used %d session %d %p channel %d pid %d",
1365 s->used,
1366 s->self,
1367 s,
1368 s->chanid,
1369 s->pid);
1370 }
1371}
1372
1373int
1374session_open(Authctxt *authctxt, int chanid)
1375{
1376 Session *s = session_new();
1377 debug("session_open: channel %d", chanid);
1378 if (s == NULL) {
1379 error("no more sessions");
1380 return 0;
1381 }
1382 s->authctxt = authctxt;
1383 s->pw = authctxt->pw;
1384 if (s->pw == NULL)
1385 fatal("no user for session %d", s->self);
1386 debug("session_open: session %d: link with channel %d", s->self, chanid);
1387 s->chanid = chanid;
1388 return 1;
1389}
1390
1391static Session *
1392session_by_channel(int id)
1393{
1394 int i;
1395 for (i = 0; i < MAX_SESSIONS; i++) {
1396 Session *s = &sessions[i];
1397 if (s->used && s->chanid == id) {
1398 debug("session_by_channel: session %d channel %d", i, id);
1399 return s;
1400 }
1401 }
1402 debug("session_by_channel: unknown channel %d", id);
1403 session_dump();
1404 return NULL;
1405}
1406
1407static Session *
1408session_by_pid(pid_t pid)
1409{
1410 int i;
1411 debug("session_by_pid: pid %d", pid);
1412 for (i = 0; i < MAX_SESSIONS; i++) {
1413 Session *s = &sessions[i];
1414 if (s->used && s->pid == pid)
1415 return s;
1416 }
1417 error("session_by_pid: unknown pid %d", pid);
1418 session_dump();
1419 return NULL;
1420}
1421
1422static int
1423session_window_change_req(Session *s)
1424{
1425 s->col = packet_get_int();
1426 s->row = packet_get_int();
1427 s->xpixel = packet_get_int();
1428 s->ypixel = packet_get_int();
1429 packet_check_eom();
1430 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1431 return 1;
1432}
1433
1434static int
1435session_pty_req(Session *s)
1436{
1437 u_int len;
1438 int n_bytes;
1439
1440 if (no_pty_flag) {
1441 debug("Allocating a pty not permitted for this authentication.");
1442 return 0;
1443 }
1444 if (s->ttyfd != -1) {
1445 packet_disconnect("Protocol error: you already have a pty.");
1446 return 0;
1447 }
1448
1449 s->term = packet_get_string(&len);
1450
1451 if (compat20) {
1452 s->col = packet_get_int();
1453 s->row = packet_get_int();
1454 } else {
1455 s->row = packet_get_int();
1456 s->col = packet_get_int();
1457 }
1458 s->xpixel = packet_get_int();
1459 s->ypixel = packet_get_int();
1460
1461 if (strcmp(s->term, "") == 0) {
1462 xfree(s->term);
1463 s->term = NULL;
1464 }
1465
1466 /* Allocate a pty and open it. */
1467 debug("Allocating pty.");
1468 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1469 if (s->term)
1470 xfree(s->term);
1471 s->term = NULL;
1472 s->ptyfd = -1;
1473 s->ttyfd = -1;
1474 error("session_pty_req: session %d alloc failed", s->self);
1475 return 0;
1476 }
1477 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1478
1479 /* for SSH1 the tty modes length is not given */
1480 if (!compat20)
1481 n_bytes = packet_remaining();
1482 tty_parse_modes(s->ttyfd, &n_bytes);
1483
1484 /*
1485 * Add a cleanup function to clear the utmp entry and record logout
1486 * time in case we call fatal() (e.g., the connection gets closed).
1487 */
1488 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1489 pty_setowner(s->pw, s->tty);
1490
1491 /* Set window size from the packet. */
1492 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1493
1494 packet_check_eom();
1495 session_proctitle(s);
1496 return 1;
1497}
1498
1499static int
1500session_subsystem_req(Session *s)
1501{
1502 struct stat st;
1503 u_int len;
1504 int success = 0;
1505 char *cmd, *subsys = packet_get_string(&len);
1506 int i;
1507
1508 packet_check_eom();
1509 log("subsystem request for %.100s", subsys);
1510
1511 for (i = 0; i < options.num_subsystems; i++) {
1512 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1513 cmd = options.subsystem_command[i];
1514 if (stat(cmd, &st) < 0) {
1515 error("subsystem: cannot stat %s: %s", cmd,
1516 strerror(errno));
1517 break;
1518 }
1519 debug("subsystem: exec() %s", cmd);
1520 s->is_subsystem = 1;
1521 do_exec(s, cmd);
1522 success = 1;
1523 break;
1524 }
1525 }
1526
1527 if (!success)
1528 log("subsystem request for %.100s failed, subsystem not found",
1529 subsys);
1530
1531 xfree(subsys);
1532 return success;
1533}
1534
1535static int
1536session_x11_req(Session *s)
1537{
1538 int success;
1539
1540 s->single_connection = packet_get_char();
1541 s->auth_proto = packet_get_string(NULL);
1542 s->auth_data = packet_get_string(NULL);
1543 s->screen = packet_get_int();
1544 packet_check_eom();
1545
1546 success = session_setup_x11fwd(s);
1547 if (!success) {
1548 xfree(s->auth_proto);
1549 xfree(s->auth_data);
1550 s->auth_proto = NULL;
1551 s->auth_data = NULL;
1552 }
1553 return success;
1554}
1555
1556static int
1557session_shell_req(Session *s)
1558{
1559 packet_check_eom();
1560 do_exec(s, NULL);
1561 return 1;
1562}
1563
1564static int
1565session_exec_req(Session *s)
1566{
1567 u_int len;
1568 char *command = packet_get_string(&len);
1569 packet_check_eom();
1570 do_exec(s, command);
1571 xfree(command);
1572 return 1;
1573}
1574
1575static int
1576session_auth_agent_req(Session *s)
1577{
1578 static int called = 0;
1579 packet_check_eom();
1580 if (no_agent_forwarding_flag) {
1581 debug("session_auth_agent_req: no_agent_forwarding_flag");
1582 return 0;
1583 }
1584 if (called) {
1585 return 0;
1586 } else {
1587 called = 1;
1588 return auth_input_request_forwarding(s->pw);
1589 }
1590}
1591
1592int
1593session_input_channel_req(Channel *c, const char *rtype)
1594{
1595 int success = 0;
1596 Session *s;
1597
1598 if ((s = session_by_channel(c->self)) == NULL) {
1599 log("session_input_channel_req: no session %d req %.100s",
1600 c->self, rtype);
1601 return 0;
1602 }
1603 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1604
1605 /*
1606 * a session is in LARVAL state until a shell, a command
1607 * or a subsystem is executed
1608 */
1609 if (c->type == SSH_CHANNEL_LARVAL) {
1610 if (strcmp(rtype, "shell") == 0) {
1611 success = session_shell_req(s);
1612 } else if (strcmp(rtype, "exec") == 0) {
1613 success = session_exec_req(s);
1614 } else if (strcmp(rtype, "pty-req") == 0) {
1615 success = session_pty_req(s);
1616 } else if (strcmp(rtype, "x11-req") == 0) {
1617 success = session_x11_req(s);
1618 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1619 success = session_auth_agent_req(s);
1620 } else if (strcmp(rtype, "subsystem") == 0) {
1621 success = session_subsystem_req(s);
1622 }
1623 }
1624 if (strcmp(rtype, "window-change") == 0) {
1625 success = session_window_change_req(s);
1626 }
1627 return success;
1628}
1629
1630void
1631session_set_fds(Session *s, int fdin, int fdout, int fderr)
1632{
1633 if (!compat20)
1634 fatal("session_set_fds: called for proto != 2.0");
1635 /*
1636 * now that have a child and a pipe to the child,
1637 * we can activate our channel and register the fd's
1638 */
1639 if (s->chanid == -1)
1640 fatal("no channel for session %d", s->self);
1641 channel_set_fds(s->chanid,
1642 fdout, fdin, fderr,
1643 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1644 1,
1645 CHAN_SES_WINDOW_DEFAULT);
1646}
1647
1648/*
1649 * Function to perform pty cleanup. Also called if we get aborted abnormally
1650 * (e.g., due to a dropped connection).
1651 */
1652static void
1653session_pty_cleanup(void *session)
1654{
1655 Session *s = session;
1656
1657 if (s == NULL) {
1658 error("session_pty_cleanup: no session");
1659 return;
1660 }
1661 if (s->ttyfd == -1)
1662 return;
1663
1664 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1665
1666 /* Record that the user has logged out. */
1667 if (s->pid != 0)
1668 record_logout(s->pid, s->tty, s->pw->pw_name);
1669
1670 /* Release the pseudo-tty. */
1671 pty_release(s->tty);
1672
1673 /*
1674 * Close the server side of the socket pairs. We must do this after
1675 * the pty cleanup, so that another process doesn't get this pty
1676 * while we're still cleaning up.
1677 */
1678 if (close(s->ptymaster) < 0)
1679 error("close(s->ptymaster): %s", strerror(errno));
1680
1681 /* unlink pty from session */
1682 s->ttyfd = -1;
1683}
1684
1685static void
1686session_exit_message(Session *s, int status)
1687{
1688 Channel *c;
1689
1690 if ((c = channel_lookup(s->chanid)) == NULL)
1691 fatal("session_exit_message: session %d: no channel %d",
1692 s->self, s->chanid);
1693 debug("session_exit_message: session %d channel %d pid %d",
1694 s->self, s->chanid, s->pid);
1695
1696 if (WIFEXITED(status)) {
1697 channel_request_start(s->chanid, "exit-status", 0);
1698 packet_put_int(WEXITSTATUS(status));
1699 packet_send();
1700 } else if (WIFSIGNALED(status)) {
1701 channel_request_start(s->chanid, "exit-signal", 0);
1702 packet_put_int(WTERMSIG(status));
1703#ifdef WCOREDUMP
1704 packet_put_char(WCOREDUMP(status));
1705#else /* WCOREDUMP */
1706 packet_put_char(0);
1707#endif /* WCOREDUMP */
1708 packet_put_cstring("");
1709 packet_put_cstring("");
1710 packet_send();
1711 } else {
1712 /* Some weird exit cause. Just exit. */
1713 packet_disconnect("wait returned status %04x.", status);
1714 }
1715
1716 /* disconnect channel */
1717 debug("session_exit_message: release channel %d", s->chanid);
1718 channel_cancel_cleanup(s->chanid);
1719 /*
1720 * emulate a write failure with 'chan_write_failed', nobody will be
1721 * interested in data we write.
1722 * Note that we must not call 'chan_read_failed', since there could
1723 * be some more data waiting in the pipe.
1724 */
1725 if (c->ostate != CHAN_OUTPUT_CLOSED)
1726 chan_write_failed(c);
1727 s->chanid = -1;
1728}
1729
1730static void
1731session_close(Session *s)
1732{
1733 debug("session_close: session %d pid %d", s->self, s->pid);
1734 if (s->ttyfd != -1) {
1735 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1736 session_pty_cleanup(s);
1737 }
1738 if (s->term)
1739 xfree(s->term);
1740 if (s->display)
1741 xfree(s->display);
1742 if (s->auth_display)
1743 xfree(s->auth_display);
1744 if (s->auth_data)
1745 xfree(s->auth_data);
1746 if (s->auth_proto)
1747 xfree(s->auth_proto);
1748 s->used = 0;
1749 session_proctitle(s);
1750}
1751
1752void
1753session_close_by_pid(pid_t pid, int status)
1754{
1755 Session *s = session_by_pid(pid);
1756 if (s == NULL) {
1757 debug("session_close_by_pid: no session for pid %d", pid);
1758 return;
1759 }
1760 if (s->chanid != -1)
1761 session_exit_message(s, status);
1762 session_close(s);
1763}
1764
1765/*
1766 * this is called when a channel dies before
1767 * the session 'child' itself dies
1768 */
1769void
1770session_close_by_channel(int id, void *arg)
1771{
1772 Session *s = session_by_channel(id);
1773 if (s == NULL) {
1774 debug("session_close_by_channel: no session for id %d", id);
1775 return;
1776 }
1777 debug("session_close_by_channel: channel %d child %d", id, s->pid);
1778 if (s->pid != 0) {
1779 debug("session_close_by_channel: channel %d: has child", id);
1780 /*
1781 * delay detach of session, but release pty, since
1782 * the fd's to the child are already closed
1783 */
1784 if (s->ttyfd != -1) {
1785 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1786 session_pty_cleanup(s);
1787 }
1788 return;
1789 }
1790 /* detach by removing callback */
1791 channel_cancel_cleanup(s->chanid);
1792 s->chanid = -1;
1793 session_close(s);
1794}
1795
1796void
1797session_destroy_all(void)
1798{
1799 int i;
1800 for (i = 0; i < MAX_SESSIONS; i++) {
1801 Session *s = &sessions[i];
1802 if (s->used)
1803 session_close(s);
1804 }
1805}
1806
1807static char *
1808session_tty_list(void)
1809{
1810 static char buf[1024];
1811 int i;
1812 buf[0] = '\0';
1813 for (i = 0; i < MAX_SESSIONS; i++) {
1814 Session *s = &sessions[i];
1815 if (s->used && s->ttyfd != -1) {
1816 if (buf[0] != '\0')
1817 strlcat(buf, ",", sizeof buf);
1818 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1819 }
1820 }
1821 if (buf[0] == '\0')
1822 strlcpy(buf, "notty", sizeof buf);
1823 return buf;
1824}
1825
1826void
1827session_proctitle(Session *s)
1828{
1829 if (s->pw == NULL)
1830 error("no user for session %d", s->self);
1831 else
1832 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1833}
1834
1835int
1836session_setup_x11fwd(Session *s)
1837{
1838 struct stat st;
1839 char display[512], auth_display[512];
1840 char hostname[MAXHOSTNAMELEN];
1841
1842 if (no_x11_forwarding_flag) {
1843 packet_send_debug("X11 forwarding disabled in user configuration file.");
1844 return 0;
1845 }
1846 if (!options.x11_forwarding) {
1847 debug("X11 forwarding disabled in server configuration file.");
1848 return 0;
1849 }
1850 if (!options.xauth_location ||
1851 (stat(options.xauth_location, &st) == -1)) {
1852 packet_send_debug("No xauth program; cannot forward with spoofing.");
1853 return 0;
1854 }
1855 if (options.use_login) {
1856 packet_send_debug("X11 forwarding disabled; "
1857 "not compatible with UseLogin=yes.");
1858 return 0;
1859 }
1860 if (s->display != NULL) {
1861 debug("X11 display already set.");
1862 return 0;
1863 }
1864 s->display_number = x11_create_display_inet(options.x11_display_offset,
1865 options.x11_use_localhost, s->single_connection);
1866 if (s->display_number == -1) {
1867 debug("x11_create_display_inet failed.");
1868 return 0;
1869 }
1870
1871 /* Set up a suitable value for the DISPLAY variable. */
1872 if (gethostname(hostname, sizeof(hostname)) < 0)
1873 fatal("gethostname: %.100s", strerror(errno));
1874 /*
1875 * auth_display must be used as the displayname when the
1876 * authorization entry is added with xauth(1). This will be
1877 * different than the DISPLAY string for localhost displays.
1878 */
1879 if (options.x11_use_localhost) {
1880 snprintf(display, sizeof display, "localhost:%d.%d",
1881 s->display_number, s->screen);
1882 snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1883 s->display_number, s->screen);
1884 s->display = xstrdup(display);
1885 s->auth_display = xstrdup(auth_display);
1886 } else {
1887#ifdef IPADDR_IN_DISPLAY
1888 struct hostent *he;
1889 struct in_addr my_addr;
1890
1891 he = gethostbyname(hostname);
1892 if (he == NULL) {
1893 error("Can't get IP address for X11 DISPLAY.");
1894 packet_send_debug("Can't get IP address for X11 DISPLAY.");
1895 return 0;
1896 }
1897 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1898 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
1899 s->display_number, s->screen);
1900#else
1901 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1902 s->display_number, s->screen);
1903#endif
1904 s->display = xstrdup(display);
1905 s->auth_display = xstrdup(display);
1906 }
1907
1908 return 1;
1909}
1910
1911static void
1912do_authenticated2(Authctxt *authctxt)
1913{
1914 server_loop2(authctxt);
1915}
This page took 0.115006 seconds and 5 git commands to generate.