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