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