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