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