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