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