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