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