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