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