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