]> andersk Git - openssh.git/blame - session.c
- (djm) Added --with-cflags, --with-ldflags and --with-libs options to
[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"
71276795 11RCSID("$OpenBSD: session.c,v 1.14 2000/05/25 03:10:18 deraadt 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. */
71276795 648 do_child(command, pw, s->term, s->display, s->auth_proto,
649 s->auth_data, s->tty);
7368a6c8 650 /* NOTREACHED */
651 }
652 if (pid < 0)
653 packet_disconnect("fork failed: %.100s", strerror(errno));
654 s->pid = pid;
655
656 /* Parent. Close the slave side of the pseudo tty. */
657 close(ttyfd);
658
659 /*
660 * Create another descriptor of the pty master side for use as the
661 * standard input. We could use the original descriptor, but this
662 * simplifies code in server_loop. The descriptor is bidirectional.
663 */
664 fdout = dup(ptyfd);
665 if (fdout < 0)
666 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
667
668 /* we keep a reference to the pty master */
669 ptymaster = dup(ptyfd);
670 if (ptymaster < 0)
671 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
672 s->ptymaster = ptymaster;
673
674 /* Enter interactive session. */
e78a59f5 675 if (compat20) {
676 session_set_fds(s, ptyfd, fdout, -1);
677 } else {
678 server_loop(pid, ptyfd, fdout, -1);
679 /* server_loop _has_ closed ptyfd and fdout. */
680 session_pty_cleanup(s);
681 }
7368a6c8 682}
683
684/*
685 * Sets the value of the given variable in the environment. If the variable
686 * already exists, its value is overriden.
687 */
6ae2364d 688void
7368a6c8 689child_set_env(char ***envp, unsigned int *envsizep, const char *name,
690 const char *value)
691{
692 unsigned int i, namelen;
693 char **env;
694
695 /*
696 * Find the slot where the value should be stored. If the variable
697 * already exists, we reuse the slot; otherwise we append a new slot
698 * at the end of the array, expanding if necessary.
699 */
700 env = *envp;
701 namelen = strlen(name);
702 for (i = 0; env[i]; i++)
703 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
704 break;
705 if (env[i]) {
706 /* Reuse the slot. */
707 xfree(env[i]);
708 } else {
709 /* New variable. Expand if necessary. */
710 if (i >= (*envsizep) - 1) {
711 (*envsizep) += 50;
712 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
713 }
714 /* Need to set the NULL pointer at end of array beyond the new slot. */
715 env[i + 1] = NULL;
716 }
717
718 /* Allocate space and format the variable in the appropriate slot. */
719 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
720 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
721}
722
723/*
724 * Reads environment variables from the given file and adds/overrides them
725 * into the environment. If the file does not exist, this does nothing.
726 * Otherwise, it must consist of empty lines, comments (line starts with '#')
727 * and assignments of the form name=value. No other forms are allowed.
728 */
6ae2364d 729void
7368a6c8 730read_environment_file(char ***env, unsigned int *envsize,
731 const char *filename)
732{
733 FILE *f;
734 char buf[4096];
735 char *cp, *value;
736
737 f = fopen(filename, "r");
738 if (!f)
739 return;
740
741 while (fgets(buf, sizeof(buf), f)) {
742 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
743 ;
744 if (!*cp || *cp == '#' || *cp == '\n')
745 continue;
746 if (strchr(cp, '\n'))
747 *strchr(cp, '\n') = '\0';
748 value = strchr(cp, '=');
749 if (value == NULL) {
750 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
751 continue;
752 }
71276795 753 /*
754 * Replace the equals sign by nul, and advance value to
755 * the value string.
756 */
7368a6c8 757 *value = '\0';
758 value++;
759 child_set_env(env, envsize, cp, value);
760 }
761 fclose(f);
762}
763
764#ifdef USE_PAM
765/*
766 * Sets any environment variables which have been specified by PAM
767 */
768void do_pam_environment(char ***env, int *envsize)
769{
770 char *equals, var_name[512], var_val[512];
771 char **pam_env;
772 int i;
773
774 if ((pam_env = fetch_pam_environment()) == NULL)
775 return;
776
777 for(i = 0; pam_env[i] != NULL; i++) {
778 if ((equals = strstr(pam_env[i], "=")) == NULL)
779 continue;
780
781 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
782 memset(var_name, '\0', sizeof(var_name));
783 memset(var_val, '\0', sizeof(var_val));
784
785 strncpy(var_name, pam_env[i], equals - pam_env[i]);
786 strcpy(var_val, equals + 1);
787
788 debug("PAM environment: %s=%s", var_name, var_val);
789
790 child_set_env(env, envsize, var_name, var_val);
791 }
792 }
793}
794#endif /* USE_PAM */
795
796/*
797 * Performs common processing for the child, such as setting up the
798 * environment, closing extra file descriptors, setting the user and group
799 * ids, and executing the command or shell.
800 */
6ae2364d 801void
7368a6c8 802do_child(const char *command, struct passwd * pw, const char *term,
803 const char *display, const char *auth_proto,
804 const char *auth_data, const char *ttyname)
805{
806 const char *shell, *cp = NULL;
807 char buf[256];
808 FILE *f;
809 unsigned int envsize, i;
810 char **env;
811 extern char **environ;
812 struct stat st;
813 char *argv[10];
814
815#ifndef USE_PAM /* pam_nologin handles this */
816 f = fopen("/etc/nologin", "r");
817 if (f) {
818 /* /etc/nologin exists. Print its contents and exit. */
819 while (fgets(buf, sizeof(buf), f))
820 fputs(buf, stderr);
821 fclose(f);
822 if (pw->pw_uid != 0)
823 exit(254);
824 }
825#endif /* USE_PAM */
826
827 /* Set login name in the kernel. */
828 if (setlogin(pw->pw_name) < 0)
829 error("setlogin failed: %s", strerror(errno));
830
831 /* Set uid, gid, and groups. */
832 /* Login(1) does this as well, and it needs uid 0 for the "-h"
833 switch, so we let login(1) to this for us. */
834 if (!options.use_login) {
835 if (getuid() == 0 || geteuid() == 0) {
836 if (setgid(pw->pw_gid) < 0) {
837 perror("setgid");
838 exit(1);
839 }
840 /* Initialize the group list. */
841 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
842 perror("initgroups");
843 exit(1);
844 }
845 endgrent();
846
847 /* Permanently switch to the desired uid. */
848 permanently_set_uid(pw->pw_uid);
849 }
850 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
851 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
852 }
853 /*
854 * Get the shell from the password data. An empty shell field is
855 * legal, and means /bin/sh.
856 */
857 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
858
859#ifdef AFS
860 /* Try to get AFS tokens for the local cell. */
861 if (k_hasafs()) {
862 char cell[64];
863
864 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
865 krb_afslog(cell, 0);
866
867 krb_afslog(0, 0);
868 }
869#endif /* AFS */
870
871 /* Initialize the environment. */
872 envsize = 100;
873 env = xmalloc(envsize * sizeof(char *));
874 env[0] = NULL;
875
876 if (!options.use_login) {
877 /* Set basic environment. */
878 child_set_env(&env, &envsize, "USER", pw->pw_name);
879 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
880 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
881 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
882
883 snprintf(buf, sizeof buf, "%.200s/%.50s",
884 _PATH_MAILDIR, pw->pw_name);
885 child_set_env(&env, &envsize, "MAIL", buf);
886
887 /* Normal systems set SHELL by default. */
888 child_set_env(&env, &envsize, "SHELL", shell);
889 }
890 if (getenv("TZ"))
891 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
892
893 /* Set custom environment options from RSA authentication. */
894 while (custom_environment) {
895 struct envstring *ce = custom_environment;
896 char *s = ce->s;
897 int i;
898 for (i = 0; s[i] != '=' && s[i]; i++);
899 if (s[i] == '=') {
900 s[i] = 0;
901 child_set_env(&env, &envsize, s, s + i + 1);
902 }
903 custom_environment = ce->next;
904 xfree(ce->s);
905 xfree(ce);
906 }
907
908 snprintf(buf, sizeof buf, "%.50s %d %d",
909 get_remote_ipaddr(), get_remote_port(), get_local_port());
910 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
911
912 if (ttyname)
913 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
914 if (term)
915 child_set_env(&env, &envsize, "TERM", term);
916 if (display)
917 child_set_env(&env, &envsize, "DISPLAY", display);
918
919#ifdef _AIX
920 {
921 char *authstate,*krb5cc;
922
923 if ((authstate = getenv("AUTHSTATE")) != NULL)
924 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
925
926 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
927 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
928 }
929#endif
930
931#ifdef KRB4
932 {
933 extern char *ticket;
934
935 if (ticket)
936 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
937 }
938#endif /* KRB4 */
939
940#ifdef USE_PAM
941 /* Pull in any environment variables that may have been set by PAM. */
942 do_pam_environment(&env, &envsize);
943#endif /* USE_PAM */
944
945 read_environment_file(&env,&envsize,"/etc/environment");
946
947 if (xauthfile)
948 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
949 if (auth_get_socket_name() != NULL)
950 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
951 auth_get_socket_name());
952
953 /* read $HOME/.ssh/environment. */
954 if (!options.use_login) {
71276795 955 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
956 pw->pw_dir);
7368a6c8 957 read_environment_file(&env, &envsize, buf);
958 }
959 if (debug_flag) {
960 /* dump the environment */
961 fprintf(stderr, "Environment:\n");
962 for (i = 0; env[i]; i++)
963 fprintf(stderr, " %.200s\n", env[i]);
964 }
965 /*
966 * Close the connection descriptors; note that this is the child, and
967 * the server will still have the socket open, and it is important
968 * that we do not shutdown it. Note that the descriptors cannot be
969 * closed before building the environment, as we call
970 * get_remote_ipaddr there.
971 */
972 if (packet_get_connection_in() == packet_get_connection_out())
973 close(packet_get_connection_in());
974 else {
975 close(packet_get_connection_in());
976 close(packet_get_connection_out());
977 }
978 /*
979 * Close all descriptors related to channels. They will still remain
980 * open in the parent.
981 */
982 /* XXX better use close-on-exec? -markus */
983 channel_close_all();
984
985 /*
986 * Close any extra file descriptors. Note that there may still be
987 * descriptors left by system functions. They will be closed later.
988 */
989 endpwent();
990
991 /*
992 * Close any extra open file descriptors so that we don\'t have them
993 * hanging around in clients. Note that we want to do this after
994 * initgroups, because at least on Solaris 2.3 it leaves file
995 * descriptors open.
996 */
997 for (i = 3; i < 64; i++)
998 close(i);
999
1000 /* Change current directory to the user\'s home directory. */
1001 if (chdir(pw->pw_dir) < 0)
1002 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1003 pw->pw_dir, strerror(errno));
1004
1005 /*
1006 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1007 * xauth are run in the proper environment.
1008 */
1009 environ = env;
1010
1011 /*
1012 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1013 * in this order).
1014 */
1015 if (!options.use_login) {
1016 if (stat(SSH_USER_RC, &st) >= 0) {
1017 if (debug_flag)
1018 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
1019
1020 f = popen("/bin/sh " SSH_USER_RC, "w");
1021 if (f) {
1022 if (auth_proto != NULL && auth_data != NULL)
1023 fprintf(f, "%s %s\n", auth_proto, auth_data);
1024 pclose(f);
1025 } else
1026 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1027 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1028 if (debug_flag)
1029 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1030
1031 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1032 if (f) {
1033 if (auth_proto != NULL && auth_data != NULL)
1034 fprintf(f, "%s %s\n", auth_proto, auth_data);
1035 pclose(f);
1036 } else
1037 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1038 }
1039#ifdef XAUTH_PATH
1040 else {
1041 /* Add authority data to .Xauthority if appropriate. */
1042 if (auth_proto != NULL && auth_data != NULL) {
29611d9c 1043 char *screen = strchr(display, ':');
1044 if (debug_flag) {
71276795 1045 fprintf(stderr,
1046 "Running %.100s add %.100s %.100s %.100s\n",
29611d9c 1047 XAUTH_PATH, display, auth_proto, auth_data);
1048 if (screen != NULL)
71276795 1049 fprintf(stderr,
1050 "Adding %.*s/unix%s %s %s\n",
1051 screen-display, display,
1052 screen, auth_proto, auth_data);
29611d9c 1053 }
7368a6c8 1054 f = popen(XAUTH_PATH " -q -", "w");
1055 if (f) {
71276795 1056 fprintf(f, "add %s %s %s\n", display,
1057 auth_proto, auth_data);
29611d9c 1058 if (screen != NULL)
1059 fprintf(f, "add %.*s/unix%s %s %s\n",
71276795 1060 screen-display, display,
1061 screen, auth_proto, auth_data);
7368a6c8 1062 pclose(f);
1063 } else
71276795 1064 fprintf(stderr, "Could not run %s -q -\n",
1065 XAUTH_PATH);
7368a6c8 1066 }
1067 }
1068#endif /* XAUTH_PATH */
1069
1070 /* Get the last component of the shell name. */
1071 cp = strrchr(shell, '/');
1072 if (cp)
1073 cp++;
1074 else
1075 cp = shell;
1076 }
1077 /*
1078 * If we have no command, execute the shell. In this case, the shell
1079 * name to be passed in argv[0] is preceded by '-' to indicate that
1080 * this is a login shell.
1081 */
1082 if (!command) {
1083 if (!options.use_login) {
1084 char buf[256];
1085
1086 /*
1087 * Check for mail if we have a tty and it was enabled
1088 * in server options.
1089 */
1090 if (ttyname && options.check_mail) {
1091 char *mailbox;
1092 struct stat mailstat;
1093 mailbox = getenv("MAIL");
1094 if (mailbox != NULL) {
71276795 1095 if (stat(mailbox, &mailstat) != 0 ||
1096 mailstat.st_size == 0)
7368a6c8 1097 printf("No mail.\n");
1098 else if (mailstat.st_mtime < mailstat.st_atime)
1099 printf("You have mail.\n");
1100 else
1101 printf("You have new mail.\n");
1102 }
1103 }
1104 /* Start the shell. Set initial character to '-'. */
1105 buf[0] = '-';
1106 strncpy(buf + 1, cp, sizeof(buf) - 1);
1107 buf[sizeof(buf) - 1] = 0;
1108
1109 /* Execute the shell. */
1110 argv[0] = buf;
1111 argv[1] = NULL;
1112 execve(shell, argv, env);
1113
1114 /* Executing the shell failed. */
1115 perror(shell);
1116 exit(1);
1117
1118 } else {
1119 /* Launch login(1). */
1120
1121 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1122 "-p", "-f", "--", pw->pw_name, NULL);
1123
1124 /* Login couldn't be executed, die. */
1125
1126 perror("login");
1127 exit(1);
1128 }
1129 }
1130 /*
1131 * Execute the command using the user's shell. This uses the -c
1132 * option to execute the command.
1133 */
1134 argv[0] = (char *) cp;
1135 argv[1] = "-c";
1136 argv[2] = (char *) command;
1137 argv[3] = NULL;
1138 execve(shell, argv, env);
1139 perror(shell);
1140 exit(1);
1141}
1142
1143Session *
1144session_new(void)
1145{
1146 int i;
1147 static int did_init = 0;
1148 if (!did_init) {
1149 debug("session_new: init");
1150 for(i = 0; i < MAX_SESSIONS; i++) {
1151 sessions[i].used = 0;
1152 sessions[i].self = i;
1153 }
1154 did_init = 1;
1155 }
1156 for(i = 0; i < MAX_SESSIONS; i++) {
1157 Session *s = &sessions[i];
1158 if (! s->used) {
1159 s->pid = 0;
0b242b12 1160 s->extended = 0;
7368a6c8 1161 s->chanid = -1;
1162 s->ptyfd = -1;
1163 s->ttyfd = -1;
1164 s->term = NULL;
1165 s->pw = NULL;
1166 s->display = NULL;
1167 s->screen = 0;
1168 s->auth_data = NULL;
1169 s->auth_proto = NULL;
1170 s->used = 1;
0b242b12 1171 s->pw = NULL;
7368a6c8 1172 debug("session_new: session %d", i);
1173 return s;
1174 }
1175 }
1176 return NULL;
1177}
1178
1179void
1180session_dump(void)
1181{
1182 int i;
1183 for(i = 0; i < MAX_SESSIONS; i++) {
1184 Session *s = &sessions[i];
1185 debug("dump: used %d session %d %p channel %d pid %d",
1186 s->used,
1187 s->self,
1188 s,
1189 s->chanid,
1190 s->pid);
1191 }
1192}
1193
e78a59f5 1194int
1195session_open(int chanid)
1196{
1197 Session *s = session_new();
1198 debug("session_open: channel %d", chanid);
1199 if (s == NULL) {
1200 error("no more sessions");
1201 return 0;
1202 }
e78a59f5 1203 s->pw = auth_get_user();
1204 if (s->pw == NULL)
0b242b12 1205 fatal("no user for session %i", s->self);
1206 debug("session_open: session %d: link with channel %d", s->self, chanid);
1207 s->chanid = chanid;
e78a59f5 1208 return 1;
1209}
1210
1211Session *
1212session_by_channel(int id)
1213{
1214 int i;
1215 for(i = 0; i < MAX_SESSIONS; i++) {
1216 Session *s = &sessions[i];
1217 if (s->used && s->chanid == id) {
1218 debug("session_by_channel: session %d channel %d", i, id);
1219 return s;
1220 }
1221 }
1222 debug("session_by_channel: unknown channel %d", id);
1223 session_dump();
1224 return NULL;
1225}
1226
1227Session *
1228session_by_pid(pid_t pid)
1229{
1230 int i;
1231 debug("session_by_pid: pid %d", pid);
1232 for(i = 0; i < MAX_SESSIONS; i++) {
1233 Session *s = &sessions[i];
1234 if (s->used && s->pid == pid)
1235 return s;
1236 }
1237 error("session_by_pid: unknown pid %d", pid);
1238 session_dump();
1239 return NULL;
1240}
1241
1242int
1243session_window_change_req(Session *s)
1244{
1245 s->col = packet_get_int();
1246 s->row = packet_get_int();
1247 s->xpixel = packet_get_int();
1248 s->ypixel = packet_get_int();
6ae2364d 1249 packet_done();
e78a59f5 1250 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1251 return 1;
1252}
1253
1254int
1255session_pty_req(Session *s)
1256{
1257 unsigned int len;
6ae2364d 1258 char *term_modes; /* encoded terminal modes */
e78a59f5 1259
1260 if (s->ttyfd != -1)
6ae2364d 1261 return 0;
e78a59f5 1262 s->term = packet_get_string(&len);
1263 s->col = packet_get_int();
1264 s->row = packet_get_int();
1265 s->xpixel = packet_get_int();
1266 s->ypixel = packet_get_int();
6ae2364d 1267 term_modes = packet_get_string(&len);
1268 packet_done();
e78a59f5 1269
1270 if (strcmp(s->term, "") == 0) {
1271 xfree(s->term);
1272 s->term = NULL;
1273 }
1274 /* Allocate a pty and open it. */
1275 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1276 xfree(s->term);
1277 s->term = NULL;
1278 s->ptyfd = -1;
1279 s->ttyfd = -1;
1280 error("session_pty_req: session %d alloc failed", s->self);
6ae2364d 1281 xfree(term_modes);
1282 return 0;
e78a59f5 1283 }
1284 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1285 /*
1286 * Add a cleanup function to clear the utmp entry and record logout
1287 * time in case we call fatal() (e.g., the connection gets closed).
1288 */
1289 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1290 pty_setowner(s->pw, s->tty);
1291 /* Get window size from the packet. */
1292 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1293
1d1ffb87 1294 session_proctitle(s);
1295
35484284 1296 /* XXX parse and set terminal modes */
1297 xfree(term_modes);
e78a59f5 1298 return 1;
1299}
1300
0b242b12 1301int
1302session_subsystem_req(Session *s)
1303{
1304 unsigned int len;
1305 int success = 0;
1306 char *subsys = packet_get_string(&len);
1307
1308 packet_done();
1309 log("subsystem request for %s", subsys);
1310
1311 xfree(subsys);
1312 return success;
1313}
1314
1315int
1316session_x11_req(Session *s)
1317{
1318 if (!options.x11_forwarding) {
1319 debug("X11 forwarding disabled in server configuration file.");
1320 return 0;
1321 }
1322 if (xauthfile != NULL) {
1323 debug("X11 fwd already started.");
1324 return 0;
1325 }
1326
1327 debug("Received request for X11 forwarding with auth spoofing.");
1328 if (s->display != NULL)
1329 packet_disconnect("Protocol error: X11 display already set.");
1330
1331 s->single_connection = packet_get_char();
1332 s->auth_proto = packet_get_string(NULL);
1333 s->auth_data = packet_get_string(NULL);
1334 s->screen = packet_get_int();
1335 packet_done();
1336
1337 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1338 if (s->display == NULL) {
1339 xfree(s->auth_proto);
1340 xfree(s->auth_data);
1341 return 0;
1342 }
1343 xauthfile = xmalloc(MAXPATHLEN);
1344 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1345 temporarily_use_uid(s->pw->pw_uid);
1346 if (mkdtemp(xauthfile) == NULL) {
1347 restore_uid();
1348 error("private X11 dir: mkdtemp %s failed: %s",
1349 xauthfile, strerror(errno));
1350 xfree(xauthfile);
1351 xauthfile = NULL;
1352 xfree(s->auth_proto);
1353 xfree(s->auth_data);
1354 /* XXXX remove listening channels */
1355 return 0;
1356 }
1357 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1358 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1359 restore_uid();
1360 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1361 return 1;
1362}
1363
e78a59f5 1364void
1365session_input_channel_req(int id, void *arg)
1366{
1367 unsigned int len;
1368 int reply;
1369 int success = 0;
1370 char *rtype;
1371 Session *s;
1372 Channel *c;
1373
1374 rtype = packet_get_string(&len);
1375 reply = packet_get_char();
1376
1377 s = session_by_channel(id);
1378 if (s == NULL)
1379 fatal("session_input_channel_req: channel %d: no session", id);
1380 c = channel_lookup(id);
1381 if (c == NULL)
1382 fatal("session_input_channel_req: channel %d: bad channel", id);
1383
1384 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1385 s->self, id, rtype, reply);
1386
1387 /*
1388 * a session is in LARVAL state until a shell
1389 * or programm is executed
1390 */
1391 if (c->type == SSH_CHANNEL_LARVAL) {
1392 if (strcmp(rtype, "shell") == 0) {
34bce9a5 1393 packet_done();
1394 s->extended = 1;
e78a59f5 1395 if (s->ttyfd == -1)
1396 do_exec_no_pty(s, NULL, s->pw);
1397 else
1398 do_exec_pty(s, NULL, s->pw);
1399 success = 1;
1400 } else if (strcmp(rtype, "exec") == 0) {
1401 char *command = packet_get_string(&len);
35484284 1402 packet_done();
0b242b12 1403 s->extended = 1;
e78a59f5 1404 if (s->ttyfd == -1)
1405 do_exec_no_pty(s, command, s->pw);
1406 else
1407 do_exec_pty(s, command, s->pw);
1408 xfree(command);
1409 success = 1;
1410 } else if (strcmp(rtype, "pty-req") == 0) {
35484284 1411 success = session_pty_req(s);
0b242b12 1412 } else if (strcmp(rtype, "x11-req") == 0) {
1413 success = session_x11_req(s);
1414 } else if (strcmp(rtype, "subsystem") == 0) {
1415 success = session_subsystem_req(s);
e78a59f5 1416 }
1417 }
1418 if (strcmp(rtype, "window-change") == 0) {
1419 success = session_window_change_req(s);
1420 }
1421
1422 if (reply) {
1423 packet_start(success ?
1424 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1425 packet_put_int(c->remote_id);
1426 packet_send();
1427 }
1428 xfree(rtype);
1429}
1430
1431void
1432session_set_fds(Session *s, int fdin, int fdout, int fderr)
1433{
1434 if (!compat20)
1435 fatal("session_set_fds: called for proto != 2.0");
1436 /*
1437 * now that have a child and a pipe to the child,
1438 * we can activate our channel and register the fd's
1439 */
1440 if (s->chanid == -1)
1441 fatal("no channel for session %d", s->self);
1442 channel_set_fds(s->chanid,
1443 fdout, fdin, fderr,
1444 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1445}
1446
7368a6c8 1447void
1448session_pty_cleanup(Session *s)
1449{
1450 if (s == NULL || s->ttyfd == -1)
1451 return;
1452
1453 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1454
1455 /* Cancel the cleanup function. */
1456 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1457
1458 /* Record that the user has logged out. */
1459 record_logout(s->pid, s->tty);
1460
1461 /* Release the pseudo-tty. */
1462 pty_release(s->tty);
1463
1464 /*
1465 * Close the server side of the socket pairs. We must do this after
1466 * the pty cleanup, so that another process doesn't get this pty
1467 * while we're still cleaning up.
1468 */
1469 if (close(s->ptymaster) < 0)
1470 error("close(s->ptymaster): %s", strerror(errno));
1471}
e78a59f5 1472
1473void
1474session_exit_message(Session *s, int status)
1475{
1476 Channel *c;
1477 if (s == NULL)
1478 fatal("session_close: no session");
1479 c = channel_lookup(s->chanid);
1480 if (c == NULL)
1481 fatal("session_close: session %d: no channel %d",
1482 s->self, s->chanid);
1483 debug("session_exit_message: session %d channel %d pid %d",
1484 s->self, s->chanid, s->pid);
1485
1486 if (WIFEXITED(status)) {
1487 channel_request_start(s->chanid,
1488 "exit-status", 0);
1489 packet_put_int(WEXITSTATUS(status));
1490 packet_send();
1491 } else if (WIFSIGNALED(status)) {
1492 channel_request_start(s->chanid,
1493 "exit-signal", 0);
1494 packet_put_int(WTERMSIG(status));
a64009ad 1495#ifdef WCOREDUMP
e78a59f5 1496 packet_put_char(WCOREDUMP(status));
a64009ad 1497#else /* WCOREDUMP */
1498 packet_put_char(0);
1499#endif /* WCOREDUMP */
e78a59f5 1500 packet_put_cstring("");
1501 packet_put_cstring("");
1502 packet_send();
1503 } else {
1504 /* Some weird exit cause. Just exit. */
1505 packet_disconnect("wait returned status %04x.", status);
1506 }
1507
1508 /* disconnect channel */
1509 debug("session_exit_message: release channel %d", s->chanid);
1510 channel_cancel_cleanup(s->chanid);
9da5c3c9 1511 /*
1512 * emulate a write failure with 'chan_write_failed', nobody will be
1513 * interested in data we write.
1514 * Note that we must not call 'chan_read_failed', since there could
1515 * be some more data waiting in the pipe.
1516 */
0b242b12 1517 if (c->ostate != CHAN_OUTPUT_CLOSED)
1518 chan_write_failed(c);
e78a59f5 1519 s->chanid = -1;
1520}
1521
1522void
1523session_free(Session *s)
1524{
1525 debug("session_free: session %d pid %d", s->self, s->pid);
1526 if (s->term)
1527 xfree(s->term);
1528 if (s->display)
1529 xfree(s->display);
1530 if (s->auth_data)
1531 xfree(s->auth_data);
1532 if (s->auth_proto)
1533 xfree(s->auth_proto);
1534 s->used = 0;
1535}
1536
1537void
1538session_close(Session *s)
1539{
1540 session_pty_cleanup(s);
1541 session_free(s);
1d1ffb87 1542 session_proctitle(s);
e78a59f5 1543}
1544
1545void
1546session_close_by_pid(pid_t pid, int status)
1547{
1548 Session *s = session_by_pid(pid);
1549 if (s == NULL) {
1550 debug("session_close_by_pid: no session for pid %d", s->pid);
1551 return;
1552 }
1553 if (s->chanid != -1)
1554 session_exit_message(s, status);
1555 session_close(s);
1556}
1557
1558/*
1559 * this is called when a channel dies before
1560 * the session 'child' itself dies
1561 */
1562void
1563session_close_by_channel(int id, void *arg)
1564{
1565 Session *s = session_by_channel(id);
1566 if (s == NULL) {
1567 debug("session_close_by_channel: no session for channel %d", id);
1568 return;
1569 }
1570 /* disconnect channel */
1571 channel_cancel_cleanup(s->chanid);
1572 s->chanid = -1;
1573
1574 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1575 if (s->pid == 0) {
1576 /* close session immediately */
1577 session_close(s);
1578 } else {
1579 /* notify child, delay session cleanup */
1580 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1581 error("session_close_by_channel: kill %d: %s",
1582 s->pid, strerror(errno));
1583 }
1584}
1585
1d1ffb87 1586char *
1587session_tty_list(void)
1588{
1589 static char buf[1024];
1590 int i;
1591 buf[0] = '\0';
1592 for(i = 0; i < MAX_SESSIONS; i++) {
1593 Session *s = &sessions[i];
1594 if (s->used && s->ttyfd != -1) {
1595 if (buf[0] != '\0')
1596 strlcat(buf, ",", sizeof buf);
1597 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1598 }
1599 }
1600 if (buf[0] == '\0')
1601 strlcpy(buf, "notty", sizeof buf);
1602 return buf;
1603}
1604
1605void
1606session_proctitle(Session *s)
1607{
1608 if (s->pw == NULL)
1609 error("no user for session %d", s->self);
1610 else
1611 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1612}
1613
e78a59f5 1614void
1615do_authenticated2(void)
1616{
1617 /*
1618 * Cancel the alarm we set to limit the time taken for
1619 * authentication.
1620 */
1621 alarm(0);
e78a59f5 1622 server_loop2();
34bce9a5 1623 if (xauthfile)
1624 xauthfile_cleanup_proc(NULL);
e78a59f5 1625}
This page took 0.302241 seconds and 5 git commands to generate.