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