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