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