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