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