Annotation of src/usr.bin/ssh/sshd.c, Revision 1.15
1.1 deraadt 1: /*
2:
3: sshd.c
4:
5: Author: Tatu Ylonen <ylo@cs.hut.fi>
6:
7: Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
8: All rights reserved
9:
10: Created: Fri Mar 17 17:09:28 1995 ylo
11:
12: This program is the ssh daemon. It listens for connections from clients, and
13: performs authentication, executes use commands or shell, and forwards
14: information to/from the application to the user client over an encrypted
15: connection. This can also handle forwarding of X11, TCP/IP, and authentication
16: agent connections.
17:
18: */
19:
20: #include "includes.h"
1.15 ! aaron 21: RCSID("$Id: sshd.c,v 1.14 1999/09/30 08:34:25 deraadt Exp $");
1.1 deraadt 22:
23: #include "xmalloc.h"
24: #include "rsa.h"
25: #include "ssh.h"
26: #include "pty.h"
27: #include "packet.h"
28: #include "buffer.h"
29: #include "cipher.h"
30: #include "mpaux.h"
31: #include "servconf.h"
32: #include "uidswap.h"
33:
34: #ifdef LIBWRAP
35: #include <tcpd.h>
36: #include <syslog.h>
37: #include <sys/syslog.h>
38: int allow_severity = LOG_INFO;
39: int deny_severity = LOG_WARNING;
40: #endif /* LIBWRAP */
41:
42: #ifndef O_NOCTTY
43: #define O_NOCTTY 0
44: #endif
45:
46: #ifdef KRB4
47: char *ticket = NULL;
48: #endif /* KRB4 */
49:
50: /* Local Xauthority file. */
51: char *xauthfile = NULL;
52:
53: /* Server configuration options. */
54: ServerOptions options;
55:
56: /* Name of the server configuration file. */
57: char *config_file_name = SERVER_CONFIG_FILE;
58:
59: /* Debug mode flag. This can be set on the command line. If debug
60: mode is enabled, extra debugging output will be sent to the system
61: log, the daemon will not go to background, and will exit after processing
62: the first connection. */
63: int debug_flag = 0;
64:
65: /* Flag indicating that the daemon is being started from inetd. */
66: int inetd_flag = 0;
67:
68: /* argv[0] without path. */
69: char *av0;
70:
71: /* Saved arguments to main(). */
72: char **saved_argv;
73:
74: /* This is set to the socket that the server is listening; this is used in
75: the SIGHUP signal handler. */
76: int listen_sock;
77:
78: /* Flags set in auth-rsa from authorized_keys flags. These are set in
79: 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: char *forced_command = NULL; /* RSA authentication "command=" option. */
85: struct envstring *custom_environment = NULL;
86: /* RSA authentication "environment=" options. */
87:
88: /* Session id for the current session. */
89: unsigned char session_id[16];
90:
91: /* Any really sensitive data in the application is contained in this structure.
92: The idea is that this structure could be locked into memory so that the
93: pages do not get written into swap. However, there are some problems.
1.2 provos 94: The private key contains BIGNUMs, and we do not (in principle) have
1.1 deraadt 95: access to the internals of them, and locking just the structure is not
96: very useful. Currently, memory locking is not implemented. */
97: struct
98: {
99: /* Private part of server key. */
1.2 provos 100: RSA *private_key;
1.1 deraadt 101:
102: /* Private part of host key. */
1.2 provos 103: RSA *host_key;
1.1 deraadt 104: } sensitive_data;
105:
106: /* Flag indicating whether the current session key has been used. This flag
107: is set whenever the key is used, and cleared when the key is regenerated. */
108: int key_used = 0;
109:
110: /* This is set to true when SIGHUP is received. */
111: int received_sighup = 0;
112:
113: /* Public side of the server key. This value is regenerated regularly with
114: the private key. */
1.2 provos 115: RSA *public_key;
1.1 deraadt 116:
117: /* Prototypes for various functions defined later in this file. */
118: void do_connection(int privileged_port);
119: void do_authentication(char *user, int privileged_port);
120: void do_authenticated(struct passwd *pw);
121: void do_exec_pty(const char *command, int ptyfd, int ttyfd,
122: const char *ttyname, struct passwd *pw, const char *term,
123: const char *display, const char *auth_proto,
124: const char *auth_data);
125: void do_exec_no_pty(const char *command, struct passwd *pw,
126: const char *display, const char *auth_proto,
127: const char *auth_data);
128: void do_child(const char *command, struct passwd *pw, const char *term,
129: const char *display, const char *auth_proto,
130: const char *auth_data, const char *ttyname);
131:
132: /* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
133: the effect is to reread the configuration file (and to regenerate
134: the server key). */
135:
1.14 deraadt 136: void sighup_handler(int sig)
1.1 deraadt 137: {
138: received_sighup = 1;
139: signal(SIGHUP, sighup_handler);
140: }
141:
142: /* Called from the main program after receiving SIGHUP. Restarts the
143: server. */
144:
145: void sighup_restart()
146: {
147: log("Received SIGHUP; restarting.");
148: close(listen_sock);
149: execv(saved_argv[0], saved_argv);
150: log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
151: exit(1);
152: }
153:
154: /* Generic signal handler for terminating signals in the master daemon.
155: These close the listen socket; not closing it seems to cause "Address
156: already in use" problems on some machines, which is inconvenient. */
157:
1.14 deraadt 158: void sigterm_handler(int sig)
1.1 deraadt 159: {
160: log("Received signal %d; terminating.", sig);
161: close(listen_sock);
162: exit(255);
163: }
164:
165: /* SIGCHLD handler. This is called whenever a child dies. This will then
166: reap any zombies left by exited c. */
167:
1.14 deraadt 168: void main_sigchld_handler(int sig)
1.1 deraadt 169: {
170: int status;
171: wait(&status);
172: signal(SIGCHLD, main_sigchld_handler);
173: }
174:
175: /* Signal handler for the alarm after the login grace period has expired. */
176:
1.14 deraadt 177: void grace_alarm_handler(int sig)
1.1 deraadt 178: {
179: /* Close the connection. */
180: packet_close();
181:
182: /* Log error and exit. */
183: fatal("Timeout before authentication.");
184: }
185:
186: /* Signal handler for the key regeneration alarm. Note that this
187: alarm only occurs in the daemon waiting for connections, and it does not
188: do anything with the private key or random state before forking. Thus there
189: should be no concurrency control/asynchronous execution problems. */
190:
1.14 deraadt 191: void key_regeneration_alarm(int sig)
1.1 deraadt 192: {
193: /* Check if we should generate a new key. */
194: if (key_used)
195: {
196: /* This should really be done in the background. */
197: log("Generating new %d bit RSA key.", options.server_key_bits);
1.2 provos 198:
199: if (sensitive_data.private_key != NULL)
200: RSA_free(sensitive_data.private_key);
201: sensitive_data.private_key = RSA_new();
202:
203: if (public_key != NULL)
204: RSA_free(public_key);
205: public_key = RSA_new();
206:
207: rsa_generate_key(sensitive_data.private_key, public_key,
208: options.server_key_bits);
209: arc4random_stir();
1.1 deraadt 210: key_used = 0;
211: log("RSA key generation complete.");
212: }
213:
214: /* Reschedule the alarm. */
215: signal(SIGALRM, key_regeneration_alarm);
216: alarm(options.key_regeneration_time);
217: }
218:
219: /* Main program for the daemon. */
220:
1.2 provos 221: int
222: main(int ac, char **av)
1.1 deraadt 223: {
224: extern char *optarg;
225: extern int optind;
226: int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
227: int remote_major, remote_minor;
228: struct sockaddr_in sin;
229: char buf[100]; /* Must not be larger than remote_version. */
230: char remote_version[100]; /* Must be at least as big as buf. */
231: char *comment;
232: FILE *f;
233: struct linger linger;
234:
235: /* Save argv[0]. */
236: saved_argv = av;
237: if (strchr(av[0], '/'))
238: av0 = strrchr(av[0], '/') + 1;
239: else
240: av0 = av[0];
1.3 deraadt 241:
242: /* check if RSA support exists */
243: if (rsa_alive() == 0) {
244: log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
245: exit(1);
246: }
1.1 deraadt 247:
248: /* Initialize configuration options to their default values. */
249: initialize_server_options(&options);
250:
251: /* Parse command-line arguments. */
252: while ((opt = getopt(ac, av, "f:p:b:k:h:g:diq")) != EOF)
253: {
254: switch (opt)
255: {
256: case 'f':
257: config_file_name = optarg;
258: break;
259: case 'd':
260: debug_flag = 1;
261: break;
262: case 'i':
263: inetd_flag = 1;
264: break;
265: case 'q':
266: options.quiet_mode = 1;
267: break;
268: case 'b':
269: options.server_key_bits = atoi(optarg);
270: break;
271: case 'p':
272: options.port = atoi(optarg);
273: break;
274: case 'g':
275: options.login_grace_time = atoi(optarg);
276: break;
277: case 'k':
278: options.key_regeneration_time = atoi(optarg);
279: break;
280: case 'h':
281: options.host_key_file = optarg;
282: break;
283: case '?':
284: default:
285: fprintf(stderr, "sshd version %s\n", SSH_VERSION);
286: fprintf(stderr, "Usage: %s [options]\n", av0);
287: fprintf(stderr, "Options:\n");
288: fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
289: fprintf(stderr, " -d Debugging mode\n");
290: fprintf(stderr, " -i Started from inetd\n");
291: fprintf(stderr, " -q Quiet (no logging)\n");
292: fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
293: fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
294: fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
295: fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
296: fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
297: HOST_KEY_FILE);
298: exit(1);
299: }
300: }
301:
302: /* Read server configuration options from the configuration file. */
303: read_server_config(&options, config_file_name);
304:
305: /* Fill in default values for those options not explicitly set. */
306: fill_default_server_options(&options);
307:
308: /* Check certain values for sanity. */
309: if (options.server_key_bits < 512 ||
310: options.server_key_bits > 32768)
311: {
312: fprintf(stderr, "Bad server key size.\n");
313: exit(1);
314: }
315: if (options.port < 1 || options.port > 65535)
316: {
317: fprintf(stderr, "Bad port number.\n");
318: exit(1);
319: }
320:
321: /* Check that there are no remaining arguments. */
322: if (optind < ac)
323: {
324: fprintf(stderr, "Extra argument %s.\n", av[optind]);
325: exit(1);
326: }
327:
328: /* Initialize the log (it is reinitialized below in case we forked). */
329: log_init(av0, debug_flag && !inetd_flag,
330: debug_flag || options.fascist_logging,
331: options.quiet_mode, options.log_facility);
332:
333: debug("sshd version %.100s", SSH_VERSION);
334:
1.2 provos 335: sensitive_data.host_key = RSA_new();
1.1 deraadt 336: /* Load the host key. It must have empty passphrase. */
337: if (!load_private_key(options.host_key_file, "",
1.2 provos 338: sensitive_data.host_key, &comment))
1.1 deraadt 339: {
340: if (debug_flag)
341: fprintf(stderr, "Could not load host key: %s: %s\n",
342: options.host_key_file, strerror(errno));
343: else
344: {
345: int err = errno;
346: log_init(av0, !inetd_flag, 1, 0, options.log_facility);
347: error("Could not load host key: %.200s: %.100s",
348: options.host_key_file, strerror(err));
349: }
350: exit(1);
351: }
352: xfree(comment);
353:
354: /* If not in debugging mode, and not started from inetd, disconnect from
355: the controlling terminal, and fork. The original process exits. */
356: if (!debug_flag && !inetd_flag)
357: {
358: #ifdef TIOCNOTTY
359: int fd;
360: #endif /* TIOCNOTTY */
361:
362: /* Fork, and have the parent exit. The child becomes the server. */
363: if (fork())
364: exit(0);
365:
366: /* Redirect stdin, stdout, and stderr to /dev/null. */
367: freopen("/dev/null", "r", stdin);
368: freopen("/dev/null", "w", stdout);
369: freopen("/dev/null", "w", stderr);
370:
371: /* Disconnect from the controlling tty. */
372: #ifdef TIOCNOTTY
373: fd = open("/dev/tty", O_RDWR|O_NOCTTY);
374: if (fd >= 0)
375: {
376: (void)ioctl(fd, TIOCNOTTY, NULL);
377: close(fd);
378: }
379: #endif /* TIOCNOTTY */
380: (void)setsid();
381: }
382:
383: /* Reinitialize the log (because of the fork above). */
384: log_init(av0, debug_flag && !inetd_flag,
385: debug_flag || options.fascist_logging,
386: options.quiet_mode, options.log_facility);
387:
388: /* Check that server and host key lengths differ sufficiently. This is
389: necessary to make double encryption work with rsaref. Oh, I hate
1.2 provos 390: software patents. I dont know if this can go? Niels */
1.1 deraadt 391: if (options.server_key_bits >
1.2 provos 392: BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
1.1 deraadt 393: options.server_key_bits <
1.2 provos 394: BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
1.1 deraadt 395: {
396: options.server_key_bits =
1.2 provos 397: BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
1.1 deraadt 398: debug("Forcing server key to %d bits to make it differ from host key.",
399: options.server_key_bits);
400: }
401:
402: /* Do not display messages to stdout in RSA code. */
403: rsa_set_verbose(0);
404:
405: /* Initialize the random number generator. */
1.2 provos 406: arc4random_stir();
1.1 deraadt 407:
408: /* Chdir to the root directory so that the current disk can be unmounted
409: if desired. */
410: chdir("/");
411:
412: /* Close connection cleanly after attack. */
413: cipher_attack_detected = packet_disconnect;
414:
415: /* Start listening for a socket, unless started from inetd. */
416: if (inetd_flag)
417: {
418: int s1, s2;
419: s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
420: s2 = dup(s1);
421: sock_in = dup(0);
422: sock_out = dup(1);
423: /* We intentionally do not close the descriptors 0, 1, and 2 as our
424: code for setting the descriptors won\'t work if ttyfd happens to
425: be one of those. */
426: debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
427:
1.2 provos 428: public_key = RSA_new();
429: sensitive_data.private_key = RSA_new();
1.1 deraadt 430: /* Generate an rsa key. */
431: log("Generating %d bit RSA key.", options.server_key_bits);
1.2 provos 432: rsa_generate_key(sensitive_data.private_key, public_key,
433: options.server_key_bits);
434: arc4random_stir();
1.1 deraadt 435: log("RSA key generation complete.");
436: }
437: else
438: {
439: /* Create socket for listening. */
440: listen_sock = socket(AF_INET, SOCK_STREAM, 0);
441: if (listen_sock < 0)
442: fatal("socket: %.100s", strerror(errno));
443:
444: /* Set socket options. We try to make the port reusable and have it
445: close as fast as possible without waiting in unnecessary wait states
446: on close. */
447: setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
448: sizeof(on));
449: linger.l_onoff = 1;
450: linger.l_linger = 5;
451: setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
452: sizeof(linger));
453:
454: /* Initialize the socket address. */
455: memset(&sin, 0, sizeof(sin));
456: sin.sin_family = AF_INET;
457: sin.sin_addr = options.listen_addr;
458: sin.sin_port = htons(options.port);
459:
460: /* Bind the socket to the desired port. */
461: if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
462: {
463: error("bind: %.100s", strerror(errno));
464: shutdown(listen_sock, 2);
465: close(listen_sock);
466: fatal("Bind to port %d failed.", options.port);
467: }
468:
469: if (!debug_flag)
470: {
471: /* Record our pid in /etc/sshd_pid to make it easier to kill the
472: correct sshd. We don\'t want to do this before the bind above
473: because the bind will fail if there already is a daemon, and this
474: will overwrite any old pid in the file. */
475: f = fopen(SSH_DAEMON_PID_FILE, "w");
476: if (f)
477: {
478: fprintf(f, "%u\n", (unsigned int)getpid());
479: fclose(f);
480: }
481: }
482:
483: /* Start listening on the port. */
484: log("Server listening on port %d.", options.port);
485: if (listen(listen_sock, 5) < 0)
486: fatal("listen: %.100s", strerror(errno));
487:
1.2 provos 488: public_key = RSA_new();
489: sensitive_data.private_key = RSA_new();
1.1 deraadt 490: /* Generate an rsa key. */
491: log("Generating %d bit RSA key.", options.server_key_bits);
1.2 provos 492: rsa_generate_key(sensitive_data.private_key, public_key,
1.1 deraadt 493: options.server_key_bits);
1.2 provos 494: arc4random_stir();
1.1 deraadt 495: log("RSA key generation complete.");
496:
497: /* Schedule server key regeneration alarm. */
498: signal(SIGALRM, key_regeneration_alarm);
499: alarm(options.key_regeneration_time);
500:
501: /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
502: signal(SIGHUP, sighup_handler);
503: signal(SIGTERM, sigterm_handler);
504: signal(SIGQUIT, sigterm_handler);
505:
506: /* Arrange SIGCHLD to be caught. */
507: signal(SIGCHLD, main_sigchld_handler);
508:
509: /* Stay listening for connections until the system crashes or the
510: daemon is killed with a signal. */
511: for (;;)
512: {
513: if (received_sighup)
514: sighup_restart();
515: /* Wait in accept until there is a connection. */
516: aux = sizeof(sin);
517: newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
518: if (received_sighup)
519: sighup_restart();
520: if (newsock < 0)
521: {
522: if (errno == EINTR)
523: continue;
524: error("accept: %.100s", strerror(errno));
525: continue;
526: }
527:
528: #ifdef LIBWRAP
529: {
530: struct request_info req;
531: request_init(&req, RQ_DAEMON, av0, RQ_FILE, newsock, NULL);
532: fromhost(&req);
533: if (!hosts_access(&req))
534: {
535: error("Connection from %.500s refused by tcp_wrappers.",
536: eval_client(&req));
537: shutdown(newsock, 2);
538: close(newsock);
539: continue;
540: }
541: /* if from inet: refuse(&req); */
542: log("connect from %.500s", eval_client(&req));
543: }
544: #endif /* LIBWRAP */
545:
546: /* Got connection. Fork a child to handle it, unless we are in
547: debugging mode. */
548: if (debug_flag)
549: {
550: /* In debugging mode. Close the listening socket, and start
551: processing the connection without forking. */
552: debug("Server will not fork when running in debugging mode.");
553: close(listen_sock);
554: sock_in = newsock;
555: sock_out = newsock;
556: pid = getpid();
557: break;
558: }
559: else
560: {
561: /* Normal production daemon. Fork, and have the child process
562: the connection. The parent continues listening. */
563: if ((pid = fork()) == 0)
564: {
565: /* Child. Close the listening socket, and start using
566: the accepted socket. Reinitialize logging (since our
567: pid has changed). We break out of the loop to handle
568: the connection. */
569: close(listen_sock);
570: sock_in = newsock;
571: sock_out = newsock;
572: log_init(av0, debug_flag && !inetd_flag,
573: options.fascist_logging || debug_flag,
574: options.quiet_mode, options.log_facility);
575: break;
576: }
577: }
578:
579: /* Parent. Stay in the loop. */
580: if (pid < 0)
581: error("fork: %.100s", strerror(errno));
582: else
583: debug("Forked child %d.", pid);
584:
585: /* Mark that the key has been used (it was "given" to the child). */
586: key_used = 1;
587:
588: /* Close the new socket (the child is now taking care of it). */
589: close(newsock);
590: }
591: }
592:
593: /* This is the child processing a new connection. */
594:
595: /* Disable the key regeneration alarm. We will not regenerate the key
596: since we are no longer in a position to give it to anyone. We will
597: not restart on SIGHUP since it no longer makes sense. */
598: alarm(0);
599: signal(SIGALRM, SIG_DFL);
600: signal(SIGHUP, SIG_DFL);
601: signal(SIGTERM, SIG_DFL);
602: signal(SIGQUIT, SIG_DFL);
603: signal(SIGCHLD, SIG_DFL);
604:
605: /* Set socket options for the connection. We want the socket to close
606: as fast as possible without waiting for anything. If the connection
607: is not a socket, these will do nothing. */
608: /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
609: linger.l_onoff = 1;
610: linger.l_linger = 5;
611: setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
612:
613: /* Register our connection. This turns encryption off because we do not
614: have a key. */
1.2 provos 615: packet_set_connection(sock_in, sock_out);
1.1 deraadt 616:
617: /* Log the connection. */
618: log("Connection from %.100s port %d",
619: get_remote_ipaddr(), get_remote_port());
620:
621: /* Check whether logins are denied from this host. */
622: if (options.num_deny_hosts > 0)
623: {
624: const char *hostname = get_canonical_hostname();
625: const char *ipaddr = get_remote_ipaddr();
626: int i;
627: for (i = 0; i < options.num_deny_hosts; i++)
628: if (match_pattern(hostname, options.deny_hosts[i]) ||
629: match_pattern(ipaddr, options.deny_hosts[i]))
630: {
631: log("Connection from %.200s denied.\n", hostname);
632: hostname = "You are not allowed to connect. Go away!\r\n";
633: write(sock_out, hostname, strlen(hostname));
634: close(sock_in);
635: close(sock_out);
636: exit(0);
637: }
638: }
639:
640: /* We don\'t want to listen forever unless the other side successfully
641: authenticates itself. So we set up an alarm which is cleared after
642: successful authentication. A limit of zero indicates no limit.
643: Note that we don\'t set the alarm in debugging mode; it is just annoying
644: to have the server exit just when you are about to discover the bug. */
645: signal(SIGALRM, grace_alarm_handler);
646: if (!debug_flag)
647: alarm(options.login_grace_time);
648:
649: /* Send our protocol version identification. */
1.6 deraadt 650: snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.1 deraadt 651: PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
652: if (write(sock_out, buf, strlen(buf)) != strlen(buf))
653: fatal("Could not write ident string.");
654:
655: /* Read other side\'s version identification. */
656: for (i = 0; i < sizeof(buf) - 1; i++)
657: {
658: if (read(sock_in, &buf[i], 1) != 1)
659: fatal("Did not receive ident string.");
660: if (buf[i] == '\r')
661: {
662: buf[i] = '\n';
663: buf[i + 1] = 0;
664: break;
665: }
666: if (buf[i] == '\n')
667: {
668: /* buf[i] == '\n' */
669: buf[i + 1] = 0;
670: break;
671: }
672: }
673: buf[sizeof(buf) - 1] = 0;
674:
675: /* Check that the versions match. In future this might accept several
676: versions and set appropriate flags to handle them. */
677: if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
678: remote_version) != 3)
679: {
680: const char *s = "Protocol mismatch.\n";
681: (void) write(sock_out, s, strlen(s));
682: close(sock_in);
683: close(sock_out);
684: fatal("Bad protocol version identification: %.100s", buf);
685: }
686: debug("Client protocol version %d.%d; client software version %.100s",
687: remote_major, remote_minor, remote_version);
688: if (remote_major != PROTOCOL_MAJOR)
689: {
690: const char *s = "Protocol major versions differ.\n";
691: (void) write(sock_out, s, strlen(s));
692: close(sock_in);
693: close(sock_out);
694: fatal("Protocol major versions differ: %d vs. %d",
695: PROTOCOL_MAJOR, remote_major);
696: }
697:
698: /* Check that the client has sufficiently high software version. */
699: if (remote_major == 1 && remote_minor == 0)
700: packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
701:
702: /* Check whether logins are permitted from this host. */
703: if (options.num_allow_hosts > 0)
704: {
705: const char *hostname = get_canonical_hostname();
706: const char *ipaddr = get_remote_ipaddr();
707: int i;
708: for (i = 0; i < options.num_allow_hosts; i++)
709: if (match_pattern(hostname, options.allow_hosts[i]) ||
710: match_pattern(ipaddr, options.allow_hosts[i]))
711: break;
712: if (i >= options.num_allow_hosts)
713: {
714: log("Connection from %.200s not allowed.\n", hostname);
715: packet_disconnect("Sorry, you are not allowed to connect.");
716: /*NOTREACHED*/
717: }
718: }
719:
720: packet_set_nonblocking();
721:
722: /* Handle the connection. We pass as argument whether the connection
723: came from a privileged port. */
1.13 deraadt 724: do_connection(get_remote_port() < IPPORT_RESERVED);
1.1 deraadt 725:
726: #ifdef KRB4
727: /* Cleanup user's ticket cache file. */
728: if (options.kerberos_ticket_cleanup)
729: (void) dest_tkt();
730: #endif /* KRB4 */
731:
732: /* Cleanup user's local Xauthority file. */
733: if (xauthfile) unlink(xauthfile);
734:
735: /* The connection has been terminated. */
736: log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
737: packet_close();
738: exit(0);
739: }
740:
741: /* Process an incoming connection. Protocol version identifiers have already
742: been exchanged. This sends server key and performs the key exchange.
743: Server and host keys will no longer be needed after this functions. */
744:
745: void do_connection(int privileged_port)
746: {
747: int i;
1.2 provos 748: BIGNUM *session_key_int;
1.1 deraadt 749: unsigned char session_key[SSH_SESSION_KEY_LENGTH];
750: unsigned char check_bytes[8];
751: char *user;
752: unsigned int cipher_type, auth_mask, protocol_flags;
753: int plen, slen;
1.5 dugsong 754: u_int32_t rand = 0;
1.1 deraadt 755:
756: /* Generate check bytes that the client must send back in the user packet
757: in order for it to be accepted; this is used to defy ip spoofing
758: attacks. Note that this only works against somebody doing IP spoofing
759: from a remote machine; any machine on the local network can still see
760: outgoing packets and catch the random cookie. This only affects
761: rhosts authentication, and this is one of the reasons why it is
762: inherently insecure. */
1.2 provos 763: for (i = 0; i < 8; i++) {
764: if (i % 4 == 0)
765: rand = arc4random();
766: check_bytes[i] = rand & 0xff;
767: rand >>= 8;
768: }
1.1 deraadt 769:
770: /* Send our public key. We include in the packet 64 bits of random
771: data that must be matched in the reply in order to prevent IP spoofing. */
772: packet_start(SSH_SMSG_PUBLIC_KEY);
773: for (i = 0; i < 8; i++)
774: packet_put_char(check_bytes[i]);
775:
776: /* Store our public server RSA key. */
1.2 provos 777: packet_put_int(BN_num_bits(public_key->n));
778: packet_put_bignum(public_key->e);
779: packet_put_bignum(public_key->n);
1.1 deraadt 780:
781: /* Store our public host RSA key. */
1.2 provos 782: packet_put_int(BN_num_bits(sensitive_data.host_key->n));
783: packet_put_bignum(sensitive_data.host_key->e);
784: packet_put_bignum(sensitive_data.host_key->n);
1.1 deraadt 785:
786: /* Put protocol flags. */
787: packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
788:
789: /* Declare which ciphers we support. */
790: packet_put_int(cipher_mask());
791:
792: /* Declare supported authentication types. */
793: auth_mask = 0;
794: if (options.rhosts_authentication)
795: auth_mask |= 1 << SSH_AUTH_RHOSTS;
796: if (options.rhosts_rsa_authentication)
797: auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
798: if (options.rsa_authentication)
799: auth_mask |= 1 << SSH_AUTH_RSA;
800: #ifdef KRB4
1.8 dugsong 801: if (options.kerberos_authentication)
1.1 deraadt 802: auth_mask |= 1 << SSH_AUTH_KERBEROS;
803: #endif
1.5 dugsong 804: #ifdef AFS
1.1 deraadt 805: if (options.kerberos_tgt_passing)
806: auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1.8 dugsong 807: if (options.afs_token_passing)
1.1 deraadt 808: auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
809: #endif
810: if (options.password_authentication)
811: auth_mask |= 1 << SSH_AUTH_PASSWORD;
812: packet_put_int(auth_mask);
813:
814: /* Send the packet and wait for it to be sent. */
815: packet_send();
816: packet_write_wait();
817:
818: debug("Sent %d bit public key and %d bit host key.",
1.2 provos 819: BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
1.1 deraadt 820:
821: /* Read clients reply (cipher type and session key). */
822: packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
823:
824: /* Get cipher type. */
825: cipher_type = packet_get_char();
826:
827: /* Get check bytes from the packet. These must match those we sent earlier
828: with the public key packet. */
829: for (i = 0; i < 8; i++)
830: if (check_bytes[i] != packet_get_char())
831: packet_disconnect("IP Spoofing check bytes do not match.");
832:
833: debug("Encryption type: %.200s", cipher_name(cipher_type));
834:
835: /* Get the encrypted integer. */
1.2 provos 836: session_key_int = BN_new();
837: packet_get_bignum(session_key_int, &slen);
1.1 deraadt 838:
839: /* Get protocol flags. */
840: protocol_flags = packet_get_int();
841: packet_set_protocol_flags(protocol_flags);
842:
843: packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
844:
845: /* Decrypt it using our private server key and private host key (key with
846: larger modulus first). */
1.2 provos 847: if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
1.1 deraadt 848: {
849: /* Private key has bigger modulus. */
1.2 provos 850: assert(BN_num_bits(sensitive_data.private_key->n) >=
851: BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED);
852: rsa_private_decrypt(session_key_int, session_key_int,
853: sensitive_data.private_key);
854: rsa_private_decrypt(session_key_int, session_key_int,
855: sensitive_data.host_key);
1.1 deraadt 856: }
857: else
858: {
859: /* Host key has bigger modulus (or they are equal). */
1.2 provos 860: assert(BN_num_bits(sensitive_data.host_key->n) >=
861: BN_num_bits(sensitive_data.private_key->n) +
862: SSH_KEY_BITS_RESERVED);
863: rsa_private_decrypt(session_key_int, session_key_int,
864: sensitive_data.host_key);
865: rsa_private_decrypt(session_key_int, session_key_int,
866: sensitive_data.private_key);
1.1 deraadt 867: }
868:
869: /* Compute session id for this session. */
1.2 provos 870: compute_session_id(session_id, check_bytes,
871: BN_num_bits(sensitive_data.host_key->n),
872: sensitive_data.host_key->n,
873: BN_num_bits(sensitive_data.private_key->n),
874: sensitive_data.private_key->n);
1.1 deraadt 875:
876: /* Extract session key from the decrypted integer. The key is in the
877: least significant 256 bits of the integer; the first byte of the
878: key is in the highest bits. */
1.2 provos 879: assert(BN_num_bytes(session_key_int) == sizeof(session_key));
880: BN_bn2bin(session_key_int, session_key);
1.1 deraadt 881:
882: /* Xor the first 16 bytes of the session key with the session id. */
883: for (i = 0; i < 16; i++)
884: session_key[i] ^= session_id[i];
885:
886: /* Destroy the decrypted integer. It is no longer needed. */
1.2 provos 887: BN_clear_free(session_key_int);
1.1 deraadt 888:
889: /* Set the session key. From this on all communications will be
890: encrypted. */
891: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
892: cipher_type, 0);
893:
894: /* Destroy our copy of the session key. It is no longer needed. */
895: memset(session_key, 0, sizeof(session_key));
896:
897: debug("Received session key; encryption turned on.");
898:
899: /* Send an acknowledgement packet. Note that this packet is sent
900: encrypted. */
901: packet_start(SSH_SMSG_SUCCESS);
902: packet_send();
903: packet_write_wait();
904:
905: /* Get the name of the user that we wish to log in as. */
906: packet_read_expect(&plen, SSH_CMSG_USER);
907:
908: /* Get the user name. */
909: {
910: int ulen;
911: user = packet_get_string(&ulen);
912: packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
913: }
914:
915: /* Destroy the private and public keys. They will no longer be needed. */
1.2 provos 916: RSA_free(public_key);
917: RSA_free(sensitive_data.private_key);
918: RSA_free(sensitive_data.host_key);
1.1 deraadt 919:
920: /* Do the authentication. */
921: do_authentication(user, privileged_port);
922: }
923:
924: /* Performs authentication of an incoming connection. Session key has already
925: been exchanged and encryption is enabled. User is the user name to log
926: in as (received from the clinet). Privileged_port is true if the
927: connection comes from a privileged port (used for .rhosts authentication).*/
928:
1.2 provos 929: void
930: do_authentication(char *user, int privileged_port)
1.1 deraadt 931: {
932: int type;
933: int authenticated = 0;
934: char *password;
935: struct passwd *pw, pwcopy;
936: char *client_user;
937: unsigned int client_host_key_bits;
1.2 provos 938: BIGNUM *client_host_key_e, *client_host_key_n;
1.1 deraadt 939:
940: #ifdef AFS
941: /* If machine has AFS, set process authentication group. */
942: if (k_hasafs()) {
943: k_setpag();
944: k_unlog();
945: }
946: #endif /* AFS */
947:
948: /* Verify that the user is a valid user. */
949: pw = getpwnam(user);
950: if (!pw)
951: {
952: /* The user does not exist. */
953: packet_start(SSH_SMSG_FAILURE);
954: packet_send();
955: packet_write_wait();
956:
957: /* Keep reading packets, and always respond with a failure. This is to
958: avoid disclosing whether such a user really exists. */
959: for (;;)
960: {
961: /* Read a packet. This will not return if the client disconnects. */
962: int plen;
963: (void) packet_read(&plen);
964:
965: /* Send failure. This should be indistinguishable from a failed
966: authentication. */
967: packet_start(SSH_SMSG_FAILURE);
968: packet_send();
969: packet_write_wait();
970: }
971: /*NOTREACHED*/
972: abort();
973: }
974:
975: /* Take a copy of the returned structure. */
976: memset(&pwcopy, 0, sizeof(pwcopy));
977: pwcopy.pw_name = xstrdup(pw->pw_name);
978: pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
979: pwcopy.pw_uid = pw->pw_uid;
980: pwcopy.pw_gid = pw->pw_gid;
981: pwcopy.pw_dir = xstrdup(pw->pw_dir);
982: pwcopy.pw_shell = xstrdup(pw->pw_shell);
983: pw = &pwcopy;
984:
985: /* If we are not running as root, the user must have the same uid as the
986: server. */
987: if (getuid() != 0 && pw->pw_uid != getuid())
988: packet_disconnect("Cannot change user when server not running as root.");
989:
990: debug("Attempting authentication for %.100s.", user);
991:
992: /* If the user has no password, accept authentication immediately. */
993: if (options.password_authentication &&
994: #ifdef KRB4
995: options.kerberos_or_local_passwd &&
996: #endif /* KRB4 */
997: auth_password(user, ""))
998: {
999: /* Authentication with empty password succeeded. */
1000: debug("Login for user %.100s accepted without authentication.", user);
1001: /* authentication_type = SSH_AUTH_PASSWORD; */
1002: authenticated = 1;
1003: /* Success packet will be sent after loop below. */
1004: }
1005: else
1006: {
1007: /* Indicate that authentication is needed. */
1008: packet_start(SSH_SMSG_FAILURE);
1009: packet_send();
1010: packet_write_wait();
1011: }
1012:
1013: /* Loop until the user has been authenticated or the connection is closed. */
1014: while (!authenticated)
1015: {
1016: int plen;
1017: /* Get a packet from the client. */
1018: type = packet_read(&plen);
1019:
1020: /* Process the packet. */
1021: switch (type)
1022: {
1023:
1.5 dugsong 1024: #ifdef AFS
1.1 deraadt 1025: case SSH_CMSG_HAVE_KERBEROS_TGT:
1026: if (!options.kerberos_tgt_passing)
1027: {
1.5 dugsong 1028: /* packet_get_all(); */
1.1 deraadt 1029: log("Kerberos tgt passing disabled.");
1030: break;
1031: }
1.5 dugsong 1032: else {
1033: /* Accept Kerberos tgt. */
1.1 deraadt 1034: int dlen;
1.5 dugsong 1035: char *tgt = packet_get_string(&dlen);
1.1 deraadt 1036: packet_integrity_check(plen, 4 + dlen, type);
1.5 dugsong 1037: if (!auth_kerberos_tgt(pw, tgt))
1038: debug("Kerberos tgt REFUSED for %s", user);
1039: xfree(tgt);
1.1 deraadt 1040: }
1041: continue;
1.5 dugsong 1042:
1.1 deraadt 1043: case SSH_CMSG_HAVE_AFS_TOKEN:
1044: if (!options.afs_token_passing || !k_hasafs()) {
1045: /* packet_get_all(); */
1046: log("AFS token passing disabled.");
1047: break;
1048: }
1049: else {
1050: /* Accept AFS token. */
1051: int dlen;
1052: char *token_string = packet_get_string(&dlen);
1053: packet_integrity_check(plen, 4 + dlen, type);
1054: if (!auth_afs_token(user, pw->pw_uid, token_string))
1.5 dugsong 1055: debug("AFS token REFUSED for %s", user);
1.1 deraadt 1056: xfree(token_string);
1057: continue;
1058: }
1059: #endif /* AFS */
1060:
1061: #ifdef KRB4
1062: case SSH_CMSG_AUTH_KERBEROS:
1063: if (!options.kerberos_authentication)
1064: {
1.5 dugsong 1065: /* packet_get_all(); */
1.1 deraadt 1066: log("Kerberos authentication disabled.");
1067: break;
1068: }
1.5 dugsong 1069: else {
1.1 deraadt 1070: /* Try Kerberos v4 authentication. */
1071: KTEXT_ST auth;
1072: char *tkt_user = NULL;
1073: char *kdata = packet_get_string((unsigned int *)&auth.length);
1074: packet_integrity_check(plen, 4 + auth.length, type);
1075:
1.5 dugsong 1076: if (auth.length < MAX_KTXT_LEN)
1077: memcpy(auth.dat, kdata, auth.length);
1.1 deraadt 1078: xfree(kdata);
1.5 dugsong 1079:
1.1 deraadt 1080: if (auth_krb4(user, &auth, &tkt_user)) {
1081: /* Client has successfully authenticated to us. */
1.5 dugsong 1082: log("Kerberos authentication accepted %s for account "
1083: "%s from %s", tkt_user, user, get_canonical_hostname());
1.1 deraadt 1084: /* authentication_type = SSH_AUTH_KERBEROS; */
1085: authenticated = 1;
1086: xfree(tkt_user);
1087: }
1.5 dugsong 1088: else {
1089: log("Kerberos authentication failed for account "
1090: "%s from %s", user, get_canonical_hostname());
1091: }
1.1 deraadt 1092: }
1093: break;
1094: #endif /* KRB4 */
1095:
1096: case SSH_CMSG_AUTH_RHOSTS:
1097: if (!options.rhosts_authentication)
1098: {
1099: log("Rhosts authentication disabled.");
1100: break;
1101: }
1102:
1103: /* Rhosts authentication (also uses /etc/hosts.equiv). */
1104: if (!privileged_port)
1105: {
1106: log("Rhosts authentication not available for connections from unprivileged port.");
1107: break;
1108: }
1109:
1110: /* Get client user name. Note that we just have to trust the client;
1111: this is one reason why rhosts authentication is insecure.
1112: (Another is IP-spoofing on a local network.) */
1113: {
1114: int dlen;
1115: client_user = packet_get_string(&dlen);
1116: packet_integrity_check(plen, 4 + dlen, type);
1117: }
1118:
1119: /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1120: if (auth_rhosts(pw, client_user, options.ignore_rhosts,
1121: options.strict_modes))
1122: {
1123: /* Authentication accepted. */
1124: log("Rhosts authentication accepted for %.100s, remote %.100s on %.700s.",
1125: user, client_user, get_canonical_hostname());
1126: authenticated = 1;
1127: xfree(client_user);
1128: break;
1129: }
1.4 deraadt 1130: log("Rhosts authentication failed for %.100s, remote %.100s.",
1.1 deraadt 1131: user, client_user);
1132: xfree(client_user);
1133: break;
1134:
1135: case SSH_CMSG_AUTH_RHOSTS_RSA:
1136: if (!options.rhosts_rsa_authentication)
1137: {
1138: log("Rhosts with RSA authentication disabled.");
1139: break;
1140: }
1141:
1142: /* Rhosts authentication (also uses /etc/hosts.equiv) with RSA
1143: host authentication. */
1144: if (!privileged_port)
1145: {
1146: log("Rhosts authentication not available for connections from unprivileged port.");
1147: break;
1148: }
1149:
1150: {
1151: int ulen, elen, nlen;
1152: /* Get client user name. Note that we just have to trust
1153: the client; root on the client machine can claim to be
1154: any user. */
1155: client_user = packet_get_string(&ulen);
1156:
1157: /* Get the client host key. */
1.2 provos 1158: client_host_key_e = BN_new();
1159: client_host_key_n = BN_new();
1.1 deraadt 1160: client_host_key_bits = packet_get_int();
1.2 provos 1161: packet_get_bignum(client_host_key_e, &elen);
1162: packet_get_bignum(client_host_key_n, &nlen);
1.1 deraadt 1163:
1164: packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1165: }
1166:
1167: /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1.2 provos 1168: if (auth_rhosts_rsa(pw, client_user,
1169: client_host_key_bits, client_host_key_e,
1170: client_host_key_n, options.ignore_rhosts,
1.1 deraadt 1171: options.strict_modes))
1172: {
1173: /* Authentication accepted. */
1174: authenticated = 1;
1175: xfree(client_user);
1.2 provos 1176: BN_clear_free(client_host_key_e);
1177: BN_clear_free(client_host_key_n);
1.1 deraadt 1178: break;
1179: }
1.4 deraadt 1180: log("Rhosts authentication failed for %.100s, remote %.100s.",
1.1 deraadt 1181: user, client_user);
1182: xfree(client_user);
1.2 provos 1183: BN_clear_free(client_host_key_e);
1184: BN_clear_free(client_host_key_n);
1.1 deraadt 1185: break;
1186:
1187: case SSH_CMSG_AUTH_RSA:
1188: if (!options.rsa_authentication)
1189: {
1190: log("RSA authentication disabled.");
1191: break;
1192: }
1193:
1194: /* RSA authentication requested. */
1195: {
1196: int nlen;
1.2 provos 1197: BIGNUM *n;
1198: n = BN_new();
1199: packet_get_bignum(n, &nlen);
1.1 deraadt 1200:
1201: packet_integrity_check(plen, nlen, type);
1202:
1.2 provos 1203: if (auth_rsa(pw, n))
1.1 deraadt 1204: {
1205: /* Successful authentication. */
1.2 provos 1206: BN_clear_free(n);
1.1 deraadt 1207: log("RSA authentication for %.100s accepted.", user);
1208: authenticated = 1;
1209: break;
1210: }
1.2 provos 1211: BN_clear_free(n);
1.4 deraadt 1212: log("RSA authentication for %.100s failed.", user);
1.1 deraadt 1213: }
1214: break;
1215:
1216: case SSH_CMSG_AUTH_PASSWORD:
1217: if (!options.password_authentication)
1218: {
1219: log("Password authentication disabled.");
1220: break;
1221: }
1222:
1223: /* Password authentication requested. */
1224: /* Read user password. It is in plain text, but was transmitted
1225: over the encrypted channel so it is not visible to an outside
1226: observer. */
1227: {
1228: int passw_len;
1229: password = packet_get_string(&passw_len);
1230: packet_integrity_check(plen, 4 + passw_len, type);
1231: }
1232:
1233: /* Try authentication with the password. */
1234: if (auth_password(user, password))
1235: {
1236: /* Successful authentication. */
1237: /* Clear the password from memory. */
1238: memset(password, 0, strlen(password));
1239: xfree(password);
1240: log("Password authentication for %.100s accepted.", user);
1241: authenticated = 1;
1242: break;
1243: }
1.4 deraadt 1244: log("Password authentication for %.100s failed.", user);
1.1 deraadt 1245: memset(password, 0, strlen(password));
1246: xfree(password);
1247: break;
1248:
1249: default:
1250: /* Any unknown messages will be ignored (and failure returned)
1251: during authentication. */
1252: log("Unknown message during authentication: type %d", type);
1253: break; /* Respond with a failure message. */
1254: }
1255: /* If successfully authenticated, break out of loop. */
1256: if (authenticated)
1257: break;
1258:
1259: /* Send a message indicating that the authentication attempt failed. */
1260: packet_start(SSH_SMSG_FAILURE);
1261: packet_send();
1262: packet_write_wait();
1263: }
1264:
1265: /* Check if the user is logging in as root and root logins are disallowed. */
1266: if (pw->pw_uid == 0 && !options.permit_root_login)
1267: {
1268: if (forced_command)
1269: log("Root login accepted for forced command.", forced_command);
1270: else
1271: packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1272: get_canonical_hostname());
1273: }
1274:
1275: /* The user has been authenticated and accepted. */
1276: packet_start(SSH_SMSG_SUCCESS);
1277: packet_send();
1278: packet_write_wait();
1279:
1280: /* Perform session preparation. */
1281: do_authenticated(pw);
1282: }
1283:
1284: /* Prepares for an interactive session. This is called after the user has
1285: been successfully authenticated. During this message exchange, pseudo
1286: terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1287: are requested, etc. */
1288:
1289: void do_authenticated(struct passwd *pw)
1290: {
1291: int type;
1292: int compression_level = 0, enable_compression_after_reply = 0;
1293: int have_pty = 0, ptyfd = -1, ttyfd = -1;
1294: int row, col, xpixel, ypixel, screen;
1295: char ttyname[64];
1296: char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1297: struct group *grp;
1298: gid_t tty_gid;
1299: mode_t tty_mode;
1300: int n_bytes;
1301:
1302: /* Cancel the alarm we set to limit the time taken for authentication. */
1303: alarm(0);
1304:
1305: /* Inform the channel mechanism that we are the server side and that
1306: the client may request to connect to any port at all. (The user could
1307: do it anyway, and we wouldn\'t know what is permitted except by the
1308: client telling us, so we can equally well trust the client not to request
1309: anything bogus.) */
1310: channel_permit_all_opens();
1311:
1312: /* We stay in this loop until the client requests to execute a shell or a
1313: command. */
1314: while (1)
1315: {
1316: int plen, dlen;
1317:
1318: /* Get a packet from the client. */
1319: type = packet_read(&plen);
1320:
1321: /* Process the packet. */
1322: switch (type)
1323: {
1324: case SSH_CMSG_REQUEST_COMPRESSION:
1325: packet_integrity_check(plen, 4, type);
1326: compression_level = packet_get_int();
1327: if (compression_level < 1 || compression_level > 9)
1328: {
1329: packet_send_debug("Received illegal compression level %d.",
1330: compression_level);
1331: goto fail;
1332: }
1333: /* Enable compression after we have responded with SUCCESS. */
1334: enable_compression_after_reply = 1;
1335: break;
1336:
1337: case SSH_CMSG_REQUEST_PTY:
1338: if (no_pty_flag)
1339: {
1340: debug("Allocating a pty not permitted for this authentication.");
1341: goto fail;
1342: }
1343: if (have_pty)
1344: packet_disconnect("Protocol error: you already have a pty.");
1345:
1346: debug("Allocating pty.");
1347:
1348: /* Allocate a pty and open it. */
1349: if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1350: {
1351: error("Failed to allocate pty.");
1352: goto fail;
1353: }
1354:
1355: /* Determine the group to make the owner of the tty. */
1356: grp = getgrnam("tty");
1357: if (grp)
1358: {
1359: tty_gid = grp->gr_gid;
1360: tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1361: }
1362: else
1363: {
1364: tty_gid = pw->pw_gid;
1365: tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1366: }
1367:
1368: /* Change ownership of the tty. */
1369: if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1370: fatal("chown(%.100s, %d, %d) failed: %.100s",
1371: ttyname, pw->pw_uid, tty_gid, strerror(errno));
1372: if (chmod(ttyname, tty_mode) < 0)
1373: fatal("chmod(%.100s, 0%o) failed: %.100s",
1374: ttyname, tty_mode, strerror(errno));
1375:
1376: /* Get TERM from the packet. Note that the value may be of arbitrary
1377: length. */
1378:
1379: term = packet_get_string(&dlen);
1380: packet_integrity_check(dlen, strlen(term), type);
1381: /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1382: /* Remaining bytes */
1383: n_bytes = plen - (4 + dlen + 4*4);
1384:
1385: if (strcmp(term, "") == 0)
1386: term = NULL;
1387:
1388: /* Get window size from the packet. */
1389: row = packet_get_int();
1390: col = packet_get_int();
1391: xpixel = packet_get_int();
1392: ypixel = packet_get_int();
1393: pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1394:
1395: /* Get tty modes from the packet. */
1396: tty_parse_modes(ttyfd, &n_bytes);
1397: packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1398:
1399: /* Indicate that we now have a pty. */
1400: have_pty = 1;
1401: break;
1402:
1403: case SSH_CMSG_X11_REQUEST_FORWARDING:
1404: if (!options.x11_forwarding)
1405: {
1406: packet_send_debug("X11 forwarding disabled in server configuration file.");
1407: goto fail;
1408: }
1409: #ifdef XAUTH_PATH
1410: if (no_x11_forwarding_flag)
1411: {
1412: packet_send_debug("X11 forwarding not permitted for this authentication.");
1413: goto fail;
1414: }
1415: debug("Received request for X11 forwarding with auth spoofing.");
1416: if (display)
1417: packet_disconnect("Protocol error: X11 display already set.");
1418: {
1419: int proto_len, data_len;
1420: proto = packet_get_string(&proto_len);
1421: data = packet_get_string(&data_len);
1422: packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1423: }
1424: if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1425: screen = packet_get_int();
1426: else
1427: screen = 0;
1428: display = x11_create_display_inet(screen);
1429: if (!display)
1430: goto fail;
1431:
1432: /* Setup to always have a local .Xauthority. */
1433: xauthfile = xmalloc(MAXPATHLEN);
1.6 deraadt 1434: snprintf(xauthfile, MAXPATHLEN, "/tmp/Xauth%d_%d",
1435: pw->pw_uid, getpid());
1.1 deraadt 1436:
1437: break;
1438: #else /* XAUTH_PATH */
1439: /* No xauth program; we won't accept forwarding with spoofing. */
1440: packet_send_debug("No xauth program; cannot forward with spoofing.");
1441: goto fail;
1442: #endif /* XAUTH_PATH */
1443:
1444: case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1445: if (no_agent_forwarding_flag)
1446: {
1447: debug("Authentication agent forwarding not permitted for this authentication.");
1448: goto fail;
1449: }
1450: debug("Received authentication agent forwarding request.");
1451: auth_input_request_forwarding(pw);
1452: break;
1453:
1454: case SSH_CMSG_PORT_FORWARD_REQUEST:
1455: if (no_port_forwarding_flag)
1456: {
1457: debug("Port forwarding not permitted for this authentication.");
1458: goto fail;
1459: }
1460: debug("Received TCP/IP port forwarding request.");
1461: channel_input_port_forward_request(pw->pw_uid == 0);
1462: break;
1463:
1464: case SSH_CMSG_EXEC_SHELL:
1465: /* Set interactive/non-interactive mode. */
1466: packet_set_interactive(have_pty || display != NULL,
1467: options.keepalives);
1468:
1469: if (forced_command != NULL)
1470: goto do_forced_command;
1471: debug("Forking shell.");
1472: packet_integrity_check(plen, 0, type);
1473: if (have_pty)
1474: do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1475: data);
1476: else
1477: do_exec_no_pty(NULL, pw, display, proto, data);
1478: return;
1479:
1480: case SSH_CMSG_EXEC_CMD:
1481: /* Set interactive/non-interactive mode. */
1482: packet_set_interactive(have_pty || display != NULL,
1483: options.keepalives);
1484:
1485: if (forced_command != NULL)
1486: goto do_forced_command;
1487: /* Get command from the packet. */
1488: {
1489: int dlen;
1490: command = packet_get_string(&dlen);
1491: debug("Executing command '%.500s'", command);
1492: packet_integrity_check(plen, 4 + dlen, type);
1493: }
1494: if (have_pty)
1495: do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1496: proto, data);
1497: else
1498: do_exec_no_pty(command, pw, display, proto, data);
1499: xfree(command);
1500: return;
1501:
1502: default:
1503: /* Any unknown messages in this phase are ignored, and a failure
1504: message is returned. */
1505: log("Unknown packet type received after authentication: %d", type);
1506: goto fail;
1507: }
1508:
1509: /* The request was successfully processed. */
1510: packet_start(SSH_SMSG_SUCCESS);
1511: packet_send();
1512: packet_write_wait();
1513:
1514: /* Enable compression now that we have replied if appropriate. */
1515: if (enable_compression_after_reply)
1516: {
1517: enable_compression_after_reply = 0;
1518: packet_start_compression(compression_level);
1519: }
1520:
1521: continue;
1522:
1523: fail:
1524: /* The request failed. */
1525: packet_start(SSH_SMSG_FAILURE);
1526: packet_send();
1527: packet_write_wait();
1528: continue;
1529:
1530: do_forced_command:
1531: /* There is a forced command specified for this login. Execute it. */
1532: debug("Executing forced command: %.900s", forced_command);
1533: if (have_pty)
1534: do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1535: proto, data);
1536: else
1537: do_exec_no_pty(forced_command, pw, display, proto, data);
1538: return;
1539: }
1540: }
1541:
1542: /* This is called to fork and execute a command when we have no tty. This
1543: will call do_child from the child, and server_loop from the parent after
1544: setting up file descriptors and such. */
1545:
1546: void do_exec_no_pty(const char *command, struct passwd *pw,
1547: const char *display, const char *auth_proto,
1548: const char *auth_data)
1549: {
1550: int pid;
1551:
1552: #ifdef USE_PIPES
1553: int pin[2], pout[2], perr[2];
1554: /* Allocate pipes for communicating with the program. */
1555: if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1556: packet_disconnect("Could not create pipes: %.100s",
1557: strerror(errno));
1558: #else /* USE_PIPES */
1559: int inout[2], err[2];
1560: /* Uses socket pairs to communicate with the program. */
1561: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1562: socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1563: packet_disconnect("Could not create socket pairs: %.100s",
1564: strerror(errno));
1565: #endif /* USE_PIPES */
1566:
1567: /* Fork the child. */
1568: if ((pid = fork()) == 0)
1569: {
1570: /* Child. Reinitialize the log since the pid has changed. */
1571: log_init(av0, debug_flag && !inetd_flag, debug_flag,
1572: options.quiet_mode, options.log_facility);
1573:
1574: #ifdef USE_PIPES
1575: /* Redirect stdin. We close the parent side of the socket pair,
1576: and make the child side the standard input. */
1577: close(pin[1]);
1578: if (dup2(pin[0], 0) < 0)
1579: perror("dup2 stdin");
1580: close(pin[0]);
1581:
1582: /* Redirect stdout. */
1583: close(pout[0]);
1584: if (dup2(pout[1], 1) < 0)
1585: perror("dup2 stdout");
1586: close(pout[1]);
1587:
1588: /* Redirect stderr. */
1589: close(perr[0]);
1590: if (dup2(perr[1], 2) < 0)
1591: perror("dup2 stderr");
1592: close(perr[1]);
1593: #else /* USE_PIPES */
1594: /* Redirect stdin, stdout, and stderr. Stdin and stdout will use the
1595: same socket, as some programs (particularly rdist) seem to depend
1596: on it. */
1597: close(inout[1]);
1598: close(err[1]);
1599: if (dup2(inout[0], 0) < 0) /* stdin */
1600: perror("dup2 stdin");
1601: if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1602: perror("dup2 stdout");
1603: if (dup2(err[0], 2) < 0) /* stderr */
1604: perror("dup2 stderr");
1605: #endif /* USE_PIPES */
1606:
1607: /* Do processing for the child (exec command etc). */
1608: do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1609: /*NOTREACHED*/
1610: }
1611: if (pid < 0)
1612: packet_disconnect("fork failed: %.100s", strerror(errno));
1613: #ifdef USE_PIPES
1614: /* We are the parent. Close the child sides of the pipes. */
1615: close(pin[0]);
1616: close(pout[1]);
1617: close(perr[1]);
1618:
1619: /* Enter the interactive session. */
1620: server_loop(pid, pin[1], pout[0], perr[0]);
1621: /* server_loop has closed pin[1], pout[1], and perr[1]. */
1622: #else /* USE_PIPES */
1623: /* We are the parent. Close the child sides of the socket pairs. */
1624: close(inout[0]);
1625: close(err[0]);
1626:
1627: /* Enter the interactive session. Note: server_loop must be able to handle
1628: the case that fdin and fdout are the same. */
1629: server_loop(pid, inout[1], inout[1], err[1]);
1630: /* server_loop has closed inout[1] and err[1]. */
1631: #endif /* USE_PIPES */
1632: }
1633:
1634: struct pty_cleanup_context
1635: {
1636: const char *ttyname;
1637: int pid;
1638: };
1639:
1640: /* Function to perform cleanup if we get aborted abnormally (e.g., due to a
1641: dropped connection). */
1642:
1643: void pty_cleanup_proc(void *context)
1644: {
1645: struct pty_cleanup_context *cu = context;
1646:
1647: debug("pty_cleanup_proc called");
1648:
1.5 dugsong 1649: #if defined(KRB4)
1.1 deraadt 1650: /* Destroy user's ticket cache file. */
1651: (void) dest_tkt();
1.5 dugsong 1652: #endif /* KRB4 */
1.1 deraadt 1653:
1654: /* Record that the user has logged out. */
1655: record_logout(cu->pid, cu->ttyname);
1656:
1657: /* Release the pseudo-tty. */
1658: pty_release(cu->ttyname);
1659: }
1660:
1661: /* This is called to fork and execute a command when we have a tty. This
1662: will call do_child from the child, and server_loop from the parent after
1663: setting up file descriptors, controlling tty, updating wtmp, utmp,
1664: lastlog, and other such operations. */
1665:
1666: void do_exec_pty(const char *command, int ptyfd, int ttyfd,
1667: const char *ttyname, struct passwd *pw, const char *term,
1668: const char *display, const char *auth_proto,
1669: const char *auth_data)
1670: {
1671: int pid, fdout;
1672: const char *hostname;
1673: time_t last_login_time;
1674: char buf[100], *time_string;
1675: FILE *f;
1676: char line[256];
1677: struct stat st;
1678: int quiet_login;
1679: struct sockaddr_in from;
1680: int fromlen;
1681: struct pty_cleanup_context cleanup_context;
1682:
1683: /* Get remote host name. */
1684: hostname = get_canonical_hostname();
1685:
1686: /* Get the time when the user last logged in. Buf will be set to contain
1687: the hostname the last login was from. */
1688: last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1689: buf, sizeof(buf));
1690:
1691: /* Fork the child. */
1692: if ((pid = fork()) == 0)
1693: {
1694: pid = getpid();
1695:
1696: /* Child. Reinitialize the log because the pid has changed. */
1697: log_init(av0, debug_flag && !inetd_flag, debug_flag, options.quiet_mode,
1698: options.log_facility);
1699:
1700: /* Close the master side of the pseudo tty. */
1701: close(ptyfd);
1702:
1703: /* Make the pseudo tty our controlling tty. */
1704: pty_make_controlling_tty(&ttyfd, ttyname);
1705:
1706: /* Redirect stdin from the pseudo tty. */
1707: if (dup2(ttyfd, fileno(stdin)) < 0)
1708: error("dup2 stdin failed: %.100s", strerror(errno));
1709:
1710: /* Redirect stdout to the pseudo tty. */
1711: if (dup2(ttyfd, fileno(stdout)) < 0)
1712: error("dup2 stdin failed: %.100s", strerror(errno));
1713:
1714: /* Redirect stderr to the pseudo tty. */
1715: if (dup2(ttyfd, fileno(stderr)) < 0)
1716: error("dup2 stdin failed: %.100s", strerror(errno));
1717:
1718: /* Close the extra descriptor for the pseudo tty. */
1719: close(ttyfd);
1720:
1721: /* Get IP address of client. This is needed because we want to record
1722: where the user logged in from. If the connection is not a socket,
1723: let the ip address be 0.0.0.0. */
1724: memset(&from, 0, sizeof(from));
1725: if (packet_get_connection_in() == packet_get_connection_out())
1726: {
1727: fromlen = sizeof(from);
1728: if (getpeername(packet_get_connection_in(),
1729: (struct sockaddr *)&from, &fromlen) < 0)
1730: fatal("getpeername: %.100s", strerror(errno));
1731: }
1732:
1733: /* Record that there was a login on that terminal. */
1734: record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
1735: &from);
1736:
1737: /* Check if .hushlogin exists. */
1.6 deraadt 1738: snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
1.1 deraadt 1739: quiet_login = stat(line, &st) >= 0;
1740:
1741: /* If the user has logged in before, display the time of last login.
1742: However, don't display anything extra if a command has been
1743: specified (so that ssh can be used to execute commands on a remote
1744: machine without users knowing they are going to another machine). */
1745: if (command == NULL && last_login_time != 0 && !quiet_login)
1746: {
1747: /* Convert the date to a string. */
1748: time_string = ctime(&last_login_time);
1749: /* Remove the trailing newline. */
1750: if (strchr(time_string, '\n'))
1751: *strchr(time_string, '\n') = 0;
1752: /* Display the last login time. Host if displayed if known. */
1753: if (strcmp(buf, "") == 0)
1754: printf("Last login: %s\r\n", time_string);
1755: else
1756: printf("Last login: %s from %s\r\n", time_string, buf);
1757: }
1758:
1759: /* Print /etc/motd unless a command was specified or printing it was
1760: disabled in server options. Note that some machines appear to
1761: print it in /etc/profile or similar. */
1762: if (command == NULL && options.print_motd && !quiet_login)
1763: {
1764: /* Print /etc/motd if it exists. */
1765: f = fopen("/etc/motd", "r");
1766: if (f)
1767: {
1768: while (fgets(line, sizeof(line), f))
1769: fputs(line, stdout);
1770: fclose(f);
1771: }
1772: }
1773:
1774: /* Do common processing for the child, such as execing the command. */
1775: do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
1776: /*NOTREACHED*/
1777: }
1778: if (pid < 0)
1779: packet_disconnect("fork failed: %.100s", strerror(errno));
1780: /* Parent. Close the slave side of the pseudo tty. */
1781: close(ttyfd);
1782:
1783: /* Create another descriptor of the pty master side for use as the standard
1784: input. We could use the original descriptor, but this simplifies code
1785: in server_loop. The descriptor is bidirectional. */
1786: fdout = dup(ptyfd);
1787: if (fdout < 0)
1788: packet_disconnect("dup failed: %.100s", strerror(errno));
1789:
1790: /* Add a cleanup function to clear the utmp entry and record logout time
1791: in case we call fatal() (e.g., the connection gets closed). */
1792: cleanup_context.pid = pid;
1793: cleanup_context.ttyname = ttyname;
1794: fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
1795:
1796: /* Enter interactive session. */
1797: server_loop(pid, ptyfd, fdout, -1);
1798: /* server_loop has not closed ptyfd and fdout. */
1799:
1800: /* Cancel the cleanup function. */
1801: fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context);
1802:
1803: /* Record that the user has logged out. */
1804: record_logout(pid, ttyname);
1805:
1806: /* Release the pseudo-tty. */
1807: pty_release(ttyname);
1808:
1809: /* Close the server side of the socket pairs. We must do this after the
1810: pty cleanup, so that another process doesn't get this pty while we're
1811: still cleaning up. */
1812: close(ptyfd);
1813: close(fdout);
1814: }
1815:
1816: /* Sets the value of the given variable in the environment. If the variable
1817: already exists, its value is overriden. */
1818:
1819: void child_set_env(char ***envp, unsigned int *envsizep, const char *name,
1820: const char *value)
1821: {
1822: unsigned int i, namelen;
1823: char **env;
1824:
1825: /* Find the slot where the value should be stored. If the variable already
1826: exists, we reuse the slot; otherwise we append a new slot at the end
1827: of the array, expanding if necessary. */
1828: env = *envp;
1829: namelen = strlen(name);
1830: for (i = 0; env[i]; i++)
1831: if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1832: break;
1833: if (env[i])
1834: {
1835: /* Name already exists. Reuse the slot. */
1836: xfree(env[i]);
1837: }
1838: else
1839: {
1840: /* New variable. Expand the array if necessary. */
1841: if (i >= (*envsizep) - 1)
1842: {
1843: (*envsizep) += 50;
1844: env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
1845: }
1846:
1847: /* Need to set the NULL pointer at end of array beyond the new
1848: slot. */
1849: env[i + 1] = NULL;
1850: }
1851:
1852: /* Allocate space and format the variable in the appropriate slot. */
1853: env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1.6 deraadt 1854: snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1.1 deraadt 1855: }
1856:
1857: /* Reads environment variables from the given file and adds/overrides them
1858: into the environment. If the file does not exist, this does nothing.
1859: Otherwise, it must consist of empty lines, comments (line starts with '#')
1860: and assignments of the form name=value. No other forms are allowed. */
1861:
1862: void read_environment_file(char ***env, unsigned int *envsize,
1863: const char *filename)
1864: {
1865: FILE *f;
1866: char buf[4096];
1867: char *cp, *value;
1868:
1869: /* Open the environment file. */
1870: f = fopen(filename, "r");
1871: if (!f)
1872: return; /* Not found. */
1873:
1874: /* Process each line. */
1875: while (fgets(buf, sizeof(buf), f))
1876: {
1877: /* Skip leading whitespace. */
1878: for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1879: ;
1880:
1881: /* Ignore empty and comment lines. */
1882: if (!*cp || *cp == '#' || *cp == '\n')
1883: continue;
1884:
1885: /* Remove newline. */
1886: if (strchr(cp, '\n'))
1887: *strchr(cp, '\n') = '\0';
1888:
1889: /* Find the equals sign. Its lack indicates badly formatted line. */
1890: value = strchr(cp, '=');
1891: if (value == NULL)
1892: {
1893: fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
1894: continue;
1895: }
1896:
1897: /* Replace the equals sign by nul, and advance value to the value
1898: string. */
1899: *value = '\0';
1900: value++;
1901:
1902: /* Set the value in environment. */
1903: child_set_env(env, envsize, cp, value);
1904: }
1905:
1906: fclose(f);
1907: }
1908:
1909: /* Performs common processing for the child, such as setting up the
1910: environment, closing extra file descriptors, setting the user and group
1911: ids, and executing the command or shell. */
1912:
1913: void do_child(const char *command, struct passwd *pw, const char *term,
1914: const char *display, const char *auth_proto,
1915: const char *auth_data, const char *ttyname)
1916: {
1917: const char *shell, *cp;
1918: char buf[256];
1919: FILE *f;
1920: unsigned int envsize, i;
1921: char **env;
1922: extern char **environ;
1923: struct stat st;
1924: char *argv[10];
1925:
1926: /* Check /etc/nologin. */
1927: f = fopen("/etc/nologin", "r");
1928: if (f)
1929: { /* /etc/nologin exists. Print its contents and exit. */
1930: while (fgets(buf, sizeof(buf), f))
1931: fputs(buf, stderr);
1932: fclose(f);
1933: if (pw->pw_uid != 0)
1934: exit(254);
1935: }
1936:
1937: /* Set login name in the kernel. */
1938: setlogin(pw->pw_name);
1939:
1940: /* Set uid, gid, and groups. */
1941: if (getuid() == 0 || geteuid() == 0)
1942: {
1943: if (setgid(pw->pw_gid) < 0)
1944: {
1945: perror("setgid");
1946: exit(1);
1947: }
1948: /* Initialize the group list. */
1949: if (initgroups(pw->pw_name, pw->pw_gid) < 0)
1950: {
1951: perror("initgroups");
1952: exit(1);
1953: }
1954: endgrent();
1955:
1956: /* Permanently switch to the desired uid. */
1957: permanently_set_uid(pw->pw_uid);
1958: }
1959:
1960: if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1961: fatal("Failed to set uids to %d.", (int)pw->pw_uid);
1962:
1963: /* Get the shell from the password data. An empty shell field is legal,
1964: and means /bin/sh. */
1.9 deraadt 1965: shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.1 deraadt 1966:
1967: #ifdef AFS
1968: /* Try to get AFS tokens for the local cell. */
1969: if (k_hasafs()) {
1970: char cell[64];
1971:
1972: if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1973: krb_afslog(cell, 0);
1974:
1975: krb_afslog(0, 0);
1976: }
1977: #endif /* AFS */
1978:
1979: /* Initialize the environment. In the first part we allocate space for
1980: all environment variables. */
1981: envsize = 100;
1982: env = xmalloc(envsize * sizeof(char *));
1983: env[0] = NULL;
1984:
1985: /* Set basic environment. */
1986: child_set_env(&env, &envsize, "USER", pw->pw_name);
1987: child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1988: child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1.9 deraadt 1989: child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1.1 deraadt 1990:
1991: /* Let it inherit timezone if we have one. */
1992: if (getenv("TZ"))
1993: child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1994:
1.6 deraadt 1995: snprintf(buf, sizeof buf, "%.200s/%.50s",
1.14 deraadt 1996: _PATH_MAILDIR, pw->pw_name);
1.1 deraadt 1997: child_set_env(&env, &envsize, "MAIL", buf);
1998:
1999: /* Normal systems set SHELL by default. */
2000: child_set_env(&env, &envsize, "SHELL", shell);
2001:
2002: /* Set custom environment options from RSA authentication. */
2003: while (custom_environment)
2004: {
2005: struct envstring *ce = custom_environment;
2006: char *s = ce->s;
2007: int i;
2008: for (i = 0; s[i] != '=' && s[i]; i++)
2009: ;
2010: if (s[i] == '=')
2011: {
2012: s[i] = 0;
2013: child_set_env(&env, &envsize, s, s + i + 1);
2014: }
2015: custom_environment = ce->next;
2016: xfree(ce->s);
2017: xfree(ce);
2018: }
2019:
2020: /* Set SSH_CLIENT. */
1.6 deraadt 2021: snprintf(buf, sizeof buf, "%.50s %d %d",
1.1 deraadt 2022: get_remote_ipaddr(), get_remote_port(), options.port);
2023: child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2024:
2025: /* Set SSH_TTY if we have a pty. */
2026: if (ttyname)
2027: child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2028:
2029: /* Set TERM if we have a pty. */
2030: if (term)
2031: child_set_env(&env, &envsize, "TERM", term);
2032:
2033: /* Set DISPLAY if we have one. */
2034: if (display)
2035: child_set_env(&env, &envsize, "DISPLAY", display);
2036:
1.5 dugsong 2037: #ifdef KRB4
1.1 deraadt 2038: if (ticket)
2039: child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2040: #endif /* KRB4 */
2041:
2042: /* Set XAUTHORITY to always be a local file. */
2043: if (xauthfile)
2044: child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2045:
2046: /* Set variable for forwarded authentication connection, if we have one. */
2047: if (get_permanent_fd(pw->pw_shell) < 0)
2048: {
2049: if (auth_get_socket_name() != NULL)
2050: child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2051: auth_get_socket_name());
2052: }
2053: else
2054: if (auth_get_fd() >= 0)
2055: {
1.6 deraadt 2056: snprintf(buf, sizeof buf, "%d", auth_get_fd());
1.1 deraadt 2057: child_set_env(&env, &envsize, SSH_AUTHFD_ENV_NAME, buf);
2058: }
2059:
2060: /* Read $HOME/.ssh/environment. */
1.6 deraadt 2061: snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
1.1 deraadt 2062: read_environment_file(&env, &envsize, buf);
2063:
2064: /* If debugging, dump the environment to stderr. */
2065: if (debug_flag)
2066: {
2067: fprintf(stderr, "Environment:\n");
2068: for (i = 0; env[i]; i++)
2069: fprintf(stderr, " %.200s\n", env[i]);
2070: }
2071:
2072: /* Close the connection descriptors; note that this is the child, and the
2073: server will still have the socket open, and it is important that we
2074: do not shutdown it. Note that the descriptors cannot be closed before
2075: building the environment, as we call get_remote_ipaddr there. */
2076: if (packet_get_connection_in() == packet_get_connection_out())
2077: close(packet_get_connection_in());
2078: else
2079: {
2080: close(packet_get_connection_in());
2081: close(packet_get_connection_out());
2082: }
2083: /* Close all descriptors related to channels. They will still remain
2084: open in the parent. */
2085: channel_close_all();
2086:
2087: /* Close any extra file descriptors. Note that there may still be
2088: descriptors left by system functions. They will be closed later. */
2089: endpwent();
2090: endhostent();
2091:
2092: /* Close any extra open file descriptors so that we don\'t have them
2093: hanging around in clients. Note that we want to do this after
2094: initgroups, because at least on Solaris 2.3 it leaves file descriptors
2095: open. */
2096: for (i = 3; i < 64; i++)
2097: {
2098: if (i == auth_get_fd())
2099: continue;
2100: close(i);
2101: }
2102:
2103: /* Change current directory to the user\'s home directory. */
2104: if (chdir(pw->pw_dir) < 0)
2105: fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2106: pw->pw_dir, strerror(errno));
2107:
2108: /* Must take new environment into use so that .ssh/rc, /etc/sshrc and
2109: xauth are run in the proper environment. */
2110: environ = env;
2111:
2112: /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2113: in this order). */
2114: if (stat(SSH_USER_RC, &st) >= 0)
2115: {
2116: if (debug_flag)
2117: fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2118:
2119: f = popen("/bin/sh " SSH_USER_RC, "w");
2120: if (f)
2121: {
2122: if (auth_proto != NULL && auth_data != NULL)
2123: fprintf(f, "%s %s\n", auth_proto, auth_data);
2124: pclose(f);
2125: }
2126: else
2127: fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2128: }
2129: else
2130: if (stat(SSH_SYSTEM_RC, &st) >= 0)
2131: {
2132: if (debug_flag)
2133: fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2134:
2135: f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2136: if (f)
2137: {
2138: if (auth_proto != NULL && auth_data != NULL)
2139: fprintf(f, "%s %s\n", auth_proto, auth_data);
2140: pclose(f);
2141: }
2142: else
2143: fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2144: }
2145: #ifdef XAUTH_PATH
2146: else
2147: {
2148: /* Add authority data to .Xauthority if appropriate. */
2149: if (auth_proto != NULL && auth_data != NULL)
2150: {
2151: if (debug_flag)
2152: fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2153: XAUTH_PATH, display, auth_proto, auth_data);
2154:
2155: f = popen(XAUTH_PATH " -q -", "w");
2156: if (f)
2157: {
2158: fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2159: fclose(f);
2160: }
2161: else
2162: fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2163: }
2164: }
2165: #endif /* XAUTH_PATH */
2166:
2167: /* Get the last component of the shell name. */
2168: cp = strrchr(shell, '/');
2169: if (cp)
2170: cp++;
2171: else
2172: cp = shell;
2173:
2174: /* If we have no command, execute the shell. In this case, the shell name
2175: to be passed in argv[0] is preceded by '-' to indicate that this is
2176: a login shell. */
2177: if (!command)
2178: {
2179: char buf[256];
2180:
2181: /* Start the shell. Set initial character to '-'. */
2182: buf[0] = '-';
2183: strncpy(buf + 1, cp, sizeof(buf) - 1);
2184: buf[sizeof(buf) - 1] = 0;
2185: /* Execute the shell. */
2186: argv[0] = buf;
2187: argv[1] = NULL;
2188: execve(shell, argv, env);
2189: /* Executing the shell failed. */
2190: perror(shell);
2191: exit(1);
2192: }
2193:
2194: /* Execute the command using the user's shell. This uses the -c option
2195: to execute the command. */
2196: argv[0] = (char *)cp;
2197: argv[1] = "-c";
2198: argv[2] = (char *)command;
2199: argv[3] = NULL;
2200: execve(shell, argv, env);
2201: perror(shell);
2202: exit(1);
2203: }