Annotation of src/usr.bin/ssh/sshd.c, Revision 1.92
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.92 ! markus 14: RCSID("$OpenBSD: sshd.c,v 1.91 2000/03/09 19:31:47 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.92 ! markus 1186: int plen;
! 1187: unsigned int ulen;
1.77 markus 1188: char *user;
1189:
1190: /* Get the name of the user that we wish to log in as. */
1191: packet_read_expect(&plen, SSH_CMSG_USER);
1192:
1193: /* Get the user name. */
1194: user = packet_get_string(&ulen);
1195: packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1196:
1197: setproctitle("%s", user);
1.52 markus 1198:
1.1 deraadt 1199: #ifdef AFS
1.64 markus 1200: /* If machine has AFS, set process authentication group. */
1201: if (k_hasafs()) {
1202: k_setpag();
1203: k_unlog();
1204: }
1.1 deraadt 1205: #endif /* AFS */
1206:
1.64 markus 1207: /* Verify that the user is a valid user. */
1208: pw = getpwnam(user);
1209: if (!pw || !allowed_user(pw))
1210: do_fake_authloop(user);
1.85 markus 1211: xfree(user);
1.64 markus 1212:
1213: /* Take a copy of the returned structure. */
1214: memset(&pwcopy, 0, sizeof(pwcopy));
1215: pwcopy.pw_name = xstrdup(pw->pw_name);
1216: pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1217: pwcopy.pw_uid = pw->pw_uid;
1218: pwcopy.pw_gid = pw->pw_gid;
1219: pwcopy.pw_dir = xstrdup(pw->pw_dir);
1220: pwcopy.pw_shell = xstrdup(pw->pw_shell);
1221: pw = &pwcopy;
1222:
1.66 markus 1223: /*
1224: * If we are not running as root, the user must have the same uid as
1225: * the server.
1226: */
1.64 markus 1227: if (getuid() != 0 && pw->pw_uid != getuid())
1228: packet_disconnect("Cannot change user when server not running as root.");
1229:
1.85 markus 1230: debug("Attempting authentication for %.100s.", pw->pw_name);
1.1 deraadt 1231:
1.64 markus 1232: /* If the user has no password, accept authentication immediately. */
1233: if (options.password_authentication &&
1.1 deraadt 1234: #ifdef KRB4
1.64 markus 1235: (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1.1 deraadt 1236: #endif /* KRB4 */
1.64 markus 1237: auth_password(pw, "")) {
1238: /* Authentication with empty password succeeded. */
1239: log("Login for user %s from %.100s, accepted without authentication.",
1240: pw->pw_name, get_remote_ipaddr());
1241: } else {
1242: /* Loop until the user has been authenticated or the
1243: connection is closed, do_authloop() returns only if
1244: authentication is successfull */
1245: do_authloop(pw);
1246: }
1.52 markus 1247:
1.64 markus 1248: /* The user has been authenticated and accepted. */
1249: packet_start(SSH_SMSG_SUCCESS);
1250: packet_send();
1251: packet_write_wait();
1252:
1253: /* Perform session preparation. */
1254: do_authenticated(pw);
1.52 markus 1255: }
1256:
1.62 markus 1257: #define AUTH_FAIL_MAX 6
1258: #define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1259: #define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
1.52 markus 1260:
1.65 deraadt 1261: /*
1262: * read packets and try to authenticate local user *pw.
1263: * return if authentication is successfull
1264: */
1.52 markus 1265: void
1.64 markus 1266: do_authloop(struct passwd * pw)
1.52 markus 1267: {
1.64 markus 1268: int attempt = 0;
1269: unsigned int bits;
1270: BIGNUM *client_host_key_e, *client_host_key_n;
1271: BIGNUM *n;
1272: char *client_user, *password;
1273: char user[1024];
1.92 ! markus 1274: unsigned int dlen;
! 1275: int plen, nlen, elen;
! 1276: unsigned int ulen;
1.64 markus 1277: int type = 0;
1278: void (*authlog) (const char *fmt,...) = verbose;
1279:
1280: /* Indicate that authentication is needed. */
1281: packet_start(SSH_SMSG_FAILURE);
1282: packet_send();
1283: packet_write_wait();
1284:
1285: for (attempt = 1;; attempt++) {
1286: int authenticated = 0;
1287: strlcpy(user, "", sizeof user);
1288:
1289: /* Get a packet from the client. */
1290: type = packet_read(&plen);
1291:
1292: /* Process the packet. */
1293: switch (type) {
1.5 dugsong 1294: #ifdef AFS
1.64 markus 1295: case SSH_CMSG_HAVE_KERBEROS_TGT:
1296: if (!options.kerberos_tgt_passing) {
1297: /* packet_get_all(); */
1298: verbose("Kerberos tgt passing disabled.");
1299: break;
1300: } else {
1301: /* Accept Kerberos tgt. */
1302: char *tgt = packet_get_string(&dlen);
1303: packet_integrity_check(plen, 4 + dlen, type);
1304: if (!auth_kerberos_tgt(pw, tgt))
1305: verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1306: xfree(tgt);
1307: }
1308: continue;
1309:
1310: case SSH_CMSG_HAVE_AFS_TOKEN:
1311: if (!options.afs_token_passing || !k_hasafs()) {
1312: /* packet_get_all(); */
1313: verbose("AFS token passing disabled.");
1314: break;
1315: } else {
1316: /* Accept AFS token. */
1317: char *token_string = packet_get_string(&dlen);
1318: packet_integrity_check(plen, 4 + dlen, type);
1319: if (!auth_afs_token(pw, token_string))
1320: verbose("AFS token REFUSED for %s", pw->pw_name);
1321: xfree(token_string);
1322: }
1323: continue;
1.1 deraadt 1324: #endif /* AFS */
1325: #ifdef KRB4
1.64 markus 1326: case SSH_CMSG_AUTH_KERBEROS:
1327: if (!options.kerberos_authentication) {
1328: /* packet_get_all(); */
1329: verbose("Kerberos authentication disabled.");
1330: break;
1331: } else {
1332: /* Try Kerberos v4 authentication. */
1333: KTEXT_ST auth;
1334: char *tkt_user = NULL;
1335: char *kdata = packet_get_string((unsigned int *) &auth.length);
1336: packet_integrity_check(plen, 4 + auth.length, type);
1337:
1338: if (auth.length < MAX_KTXT_LEN)
1339: memcpy(auth.dat, kdata, auth.length);
1340: xfree(kdata);
1341:
1342: authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1343:
1344: if (authenticated) {
1345: snprintf(user, sizeof user, " tktuser %s", tkt_user);
1346: xfree(tkt_user);
1347: }
1348: }
1349: break;
1.52 markus 1350: #endif /* KRB4 */
1.64 markus 1351:
1352: case SSH_CMSG_AUTH_RHOSTS:
1353: if (!options.rhosts_authentication) {
1354: verbose("Rhosts authentication disabled.");
1355: break;
1356: }
1.66 markus 1357: /*
1358: * Get client user name. Note that we just have to
1359: * trust the client; this is one reason why rhosts
1360: * authentication is insecure. (Another is
1361: * IP-spoofing on a local network.)
1362: */
1.64 markus 1363: client_user = packet_get_string(&ulen);
1364: packet_integrity_check(plen, 4 + ulen, type);
1365:
1366: /* Try to authenticate using /etc/hosts.equiv and
1367: .rhosts. */
1368: authenticated = auth_rhosts(pw, client_user);
1369:
1370: snprintf(user, sizeof user, " ruser %s", client_user);
1371: xfree(client_user);
1372: break;
1373:
1374: case SSH_CMSG_AUTH_RHOSTS_RSA:
1375: if (!options.rhosts_rsa_authentication) {
1376: verbose("Rhosts with RSA authentication disabled.");
1377: break;
1378: }
1.66 markus 1379: /*
1380: * Get client user name. Note that we just have to
1381: * trust the client; root on the client machine can
1382: * claim to be any user.
1383: */
1.64 markus 1384: client_user = packet_get_string(&ulen);
1385:
1386: /* Get the client host key. */
1387: client_host_key_e = BN_new();
1388: client_host_key_n = BN_new();
1389: bits = packet_get_int();
1390: packet_get_bignum(client_host_key_e, &elen);
1391: packet_get_bignum(client_host_key_n, &nlen);
1392:
1393: if (bits != BN_num_bits(client_host_key_n))
1394: error("Warning: keysize mismatch for client_host_key: "
1395: "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1396: packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1397:
1398: authenticated = auth_rhosts_rsa(pw, client_user,
1399: client_host_key_e, client_host_key_n);
1400: BN_clear_free(client_host_key_e);
1401: BN_clear_free(client_host_key_n);
1402:
1403: snprintf(user, sizeof user, " ruser %s", client_user);
1404: xfree(client_user);
1405: break;
1406:
1407: case SSH_CMSG_AUTH_RSA:
1408: if (!options.rsa_authentication) {
1409: verbose("RSA authentication disabled.");
1410: break;
1411: }
1412: /* RSA authentication requested. */
1413: n = BN_new();
1414: packet_get_bignum(n, &nlen);
1415: packet_integrity_check(plen, nlen, type);
1416: authenticated = auth_rsa(pw, n);
1417: BN_clear_free(n);
1418: break;
1419:
1420: case SSH_CMSG_AUTH_PASSWORD:
1421: if (!options.password_authentication) {
1422: verbose("Password authentication disabled.");
1423: break;
1424: }
1.66 markus 1425: /*
1426: * Read user password. It is in plain text, but was
1427: * transmitted over the encrypted channel so it is
1428: * not visible to an outside observer.
1429: */
1.64 markus 1430: password = packet_get_string(&dlen);
1431: packet_integrity_check(plen, 4 + dlen, type);
1432:
1433: /* Try authentication with the password. */
1434: authenticated = auth_password(pw, password);
1435:
1436: memset(password, 0, strlen(password));
1437: xfree(password);
1438: break;
1439:
1.63 markus 1440: #ifdef SKEY
1.64 markus 1441: case SSH_CMSG_AUTH_TIS:
1442: debug("rcvd SSH_CMSG_AUTH_TIS");
1443: if (options.skey_authentication == 1) {
1444: char *skeyinfo = skey_keyinfo(pw->pw_name);
1445: if (skeyinfo == NULL) {
1446: debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1447: skeyinfo = skey_fake_keyinfo(pw->pw_name);
1448: }
1449: if (skeyinfo != NULL) {
1.66 markus 1450: /* we send our s/key- in tis-challenge messages */
1.64 markus 1451: debug("sending challenge '%s'", skeyinfo);
1452: packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1453: packet_put_string(skeyinfo, strlen(skeyinfo));
1454: packet_send();
1455: packet_write_wait();
1456: continue;
1457: }
1458: }
1459: break;
1460: case SSH_CMSG_AUTH_TIS_RESPONSE:
1461: debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1462: if (options.skey_authentication == 1) {
1463: char *response = packet_get_string(&dlen);
1464: debug("skey response == '%s'", response);
1465: packet_integrity_check(plen, 4 + dlen, type);
1466: authenticated = (skey_haskey(pw->pw_name) == 0 &&
1467: skey_passcheck(pw->pw_name, response) != -1);
1468: xfree(response);
1469: }
1470: break;
1.63 markus 1471: #else
1.64 markus 1472: case SSH_CMSG_AUTH_TIS:
1473: /* TIS Authentication is unsupported */
1474: log("TIS authentication unsupported.");
1475: break;
1.63 markus 1476: #endif
1.64 markus 1477:
1478: default:
1.66 markus 1479: /*
1480: * Any unknown messages will be ignored (and failure
1481: * returned) during authentication.
1482: */
1.64 markus 1483: log("Unknown message during authentication: type %d", type);
1484: break;
1.91 markus 1485: }
1486:
1487: /*
1488: * Check if the user is logging in as root and root logins
1489: * are disallowed.
1490: * Note that root login is allowed for forced commands.
1491: */
1492: if (authenticated && pw->pw_uid == 0 && !options.permit_root_login) {
1493: if (forced_command) {
1494: log("Root login accepted for forced command.");
1495: } else {
1496: authenticated = 0;
1497: log("ROOT LOGIN REFUSED FROM %.200s",
1498: get_canonical_hostname());
1499: }
1.64 markus 1500: }
1501:
1502: /* Raise logging level */
1503: if (authenticated ||
1504: attempt == AUTH_FAIL_LOG ||
1505: type == SSH_CMSG_AUTH_PASSWORD)
1506: authlog = log;
1507:
1508: authlog("%s %s for %.200s from %.200s port %d%s",
1509: authenticated ? "Accepted" : "Failed",
1510: get_authname(type),
1511: pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1512: get_remote_ipaddr(),
1513: get_remote_port(),
1514: user);
1515:
1516: if (authenticated)
1517: return;
1518:
1519: if (attempt > AUTH_FAIL_MAX)
1520: packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1521:
1522: /* Send a message indicating that the authentication attempt failed. */
1523: packet_start(SSH_SMSG_FAILURE);
1524: packet_send();
1525: packet_write_wait();
1526: }
1.52 markus 1527: }
1.1 deraadt 1528:
1.65 deraadt 1529: /*
1530: * The user does not exist or access is denied,
1531: * but fake indication that authentication is needed.
1532: */
1.52 markus 1533: void
1534: do_fake_authloop(char *user)
1535: {
1.64 markus 1536: int attempt = 0;
1537:
1538: log("Faking authloop for illegal user %.200s from %.200s port %d",
1539: user,
1540: get_remote_ipaddr(),
1541: get_remote_port());
1.62 markus 1542:
1.64 markus 1543: /* Indicate that authentication is needed. */
1544: packet_start(SSH_SMSG_FAILURE);
1545: packet_send();
1546: packet_write_wait();
1547:
1.66 markus 1548: /*
1549: * Keep reading packets, and always respond with a failure. This is
1550: * to avoid disclosing whether such a user really exists.
1551: */
1.64 markus 1552: for (attempt = 1;; attempt++) {
1.66 markus 1553: /* Read a packet. This will not return if the client disconnects. */
1.64 markus 1554: int plen;
1555: int type = packet_read(&plen);
1.52 markus 1556: #ifdef SKEY
1.92 ! markus 1557: unsigned int dlen;
1.64 markus 1558: char *password, *skeyinfo;
1.73 markus 1559: /* Try to send a fake s/key challenge. */
1560: if (options.skey_authentication == 1 &&
1.64 markus 1561: (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1.85 markus 1562: password = NULL;
1.73 markus 1563: if (type == SSH_CMSG_AUTH_TIS) {
1564: packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1565: packet_put_string(skeyinfo, strlen(skeyinfo));
1566: packet_send();
1567: packet_write_wait();
1568: continue;
1569: } else if (type == SSH_CMSG_AUTH_PASSWORD &&
1570: options.password_authentication &&
1571: (password = packet_get_string(&dlen)) != NULL &&
1572: dlen == 5 &&
1573: strncasecmp(password, "s/key", 5) == 0 ) {
1574: packet_send_debug(skeyinfo);
1575: }
1.85 markus 1576: if (password != NULL)
1577: xfree(password);
1.64 markus 1578: }
1.52 markus 1579: #endif
1.64 markus 1580: if (attempt > AUTH_FAIL_MAX)
1581: packet_disconnect(AUTH_FAIL_MSG, user);
1.62 markus 1582:
1.66 markus 1583: /*
1584: * Send failure. This should be indistinguishable from a
1585: * failed authentication.
1586: */
1.64 markus 1587: packet_start(SSH_SMSG_FAILURE);
1588: packet_send();
1589: packet_write_wait();
1590: }
1591: /* NOTREACHED */
1592: abort();
1.52 markus 1593: }
1.1 deraadt 1594:
1.88 markus 1595: struct pty_cleanup_context {
1596: const char *ttyname;
1597: int pid;
1598: };
1599:
1600: /*
1601: * Function to perform cleanup if we get aborted abnormally (e.g., due to a
1602: * dropped connection).
1603: */
1604: void
1605: pty_cleanup_proc(void *context)
1606: {
1607: struct pty_cleanup_context *cu = context;
1608:
1609: debug("pty_cleanup_proc called");
1610:
1611: /* Record that the user has logged out. */
1612: record_logout(cu->pid, cu->ttyname);
1613:
1614: /* Release the pseudo-tty. */
1615: pty_release(cu->ttyname);
1616: }
1617:
1618: /* simple cleanup: chown tty slave back to root */
1619: static void
1620: pty_release_proc(void *tty)
1621: {
1622: char *ttyname = tty;
1623: pty_release(ttyname);
1624: }
1625:
1.65 deraadt 1626: /*
1627: * Prepares for an interactive session. This is called after the user has
1628: * been successfully authenticated. During this message exchange, pseudo
1629: * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1630: * are requested, etc.
1631: */
1.64 markus 1632: void
1633: do_authenticated(struct passwd * pw)
1.1 deraadt 1634: {
1.64 markus 1635: int type;
1636: int compression_level = 0, enable_compression_after_reply = 0;
1.87 markus 1637: int have_pty = 0, ptyfd = -1, ttyfd = -1;
1.64 markus 1638: int row, col, xpixel, ypixel, screen;
1639: char ttyname[64];
1.88 markus 1640: char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1.92 ! markus 1641: int plen;
! 1642: unsigned int dlen;
1.64 markus 1643: int n_bytes;
1644:
1.66 markus 1645: /*
1646: * Cancel the alarm we set to limit the time taken for
1647: * authentication.
1648: */
1.64 markus 1649: alarm(0);
1650:
1.66 markus 1651: /*
1652: * Inform the channel mechanism that we are the server side and that
1653: * the client may request to connect to any port at all. (The user
1654: * could do it anyway, and we wouldn\'t know what is permitted except
1655: * by the client telling us, so we can equally well trust the client
1656: * not to request anything bogus.)
1657: */
1.82 markus 1658: if (!no_port_forwarding_flag)
1659: channel_permit_all_opens();
1.64 markus 1660:
1.66 markus 1661: /*
1662: * We stay in this loop until the client requests to execute a shell
1663: * or a command.
1664: */
1.64 markus 1665: while (1) {
1666:
1667: /* Get a packet from the client. */
1668: type = packet_read(&plen);
1669:
1670: /* Process the packet. */
1671: switch (type) {
1672: case SSH_CMSG_REQUEST_COMPRESSION:
1673: packet_integrity_check(plen, 4, type);
1674: compression_level = packet_get_int();
1675: if (compression_level < 1 || compression_level > 9) {
1676: packet_send_debug("Received illegal compression level %d.",
1677: compression_level);
1678: goto fail;
1679: }
1680: /* Enable compression after we have responded with SUCCESS. */
1681: enable_compression_after_reply = 1;
1682: break;
1683:
1684: case SSH_CMSG_REQUEST_PTY:
1685: if (no_pty_flag) {
1686: debug("Allocating a pty not permitted for this authentication.");
1687: goto fail;
1688: }
1689: if (have_pty)
1690: packet_disconnect("Protocol error: you already have a pty.");
1691:
1692: debug("Allocating pty.");
1693:
1694: /* Allocate a pty and open it. */
1.67 deraadt 1695: if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1696: sizeof(ttyname))) {
1.64 markus 1697: error("Failed to allocate pty.");
1698: goto fail;
1699: }
1.88 markus 1700: fatal_add_cleanup(pty_release_proc, (void *)ttyname);
1701: pty_setowner(pw, ttyname);
1.64 markus 1702:
1703: /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1704: term = packet_get_string(&dlen);
1705: packet_integrity_check(dlen, strlen(term), type);
1.88 markus 1706:
1.64 markus 1707: /* Remaining bytes */
1708: n_bytes = plen - (4 + dlen + 4 * 4);
1709:
1.88 markus 1710: if (strcmp(term, "") == 0) {
1711: xfree(term);
1.64 markus 1712: term = NULL;
1.88 markus 1713: }
1.64 markus 1714:
1715: /* Get window size from the packet. */
1716: row = packet_get_int();
1717: col = packet_get_int();
1718: xpixel = packet_get_int();
1719: ypixel = packet_get_int();
1720: pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1721:
1722: /* Get tty modes from the packet. */
1723: tty_parse_modes(ttyfd, &n_bytes);
1724: packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
1725:
1726: /* Indicate that we now have a pty. */
1727: have_pty = 1;
1728: break;
1729:
1730: case SSH_CMSG_X11_REQUEST_FORWARDING:
1731: if (!options.x11_forwarding) {
1732: packet_send_debug("X11 forwarding disabled in server configuration file.");
1733: goto fail;
1734: }
1.1 deraadt 1735: #ifdef XAUTH_PATH
1.64 markus 1736: if (no_x11_forwarding_flag) {
1737: packet_send_debug("X11 forwarding not permitted for this authentication.");
1738: goto fail;
1739: }
1740: debug("Received request for X11 forwarding with auth spoofing.");
1741: if (display)
1742: packet_disconnect("Protocol error: X11 display already set.");
1743: {
1.92 ! markus 1744: unsigned int proto_len, data_len;
1.64 markus 1745: proto = packet_get_string(&proto_len);
1746: data = packet_get_string(&data_len);
1747: packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1748: }
1749: if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1750: screen = packet_get_int();
1751: else
1752: screen = 0;
1.74 markus 1753: display = x11_create_display_inet(screen, options.x11_display_offset);
1.64 markus 1754: if (!display)
1755: goto fail;
1756:
1757: /* Setup to always have a local .Xauthority. */
1758: xauthfile = xmalloc(MAXPATHLEN);
1.87 markus 1759: strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1760: temporarily_use_uid(pw->pw_uid);
1761: if (mkdtemp(xauthfile) == NULL) {
1762: restore_uid();
1763: error("private X11 dir: mkdtemp %s failed: %s",
1764: xauthfile, strerror(errno));
1.64 markus 1765: xfree(xauthfile);
1766: xauthfile = NULL;
1.87 markus 1767: goto fail;
1.64 markus 1768: }
1.89 markus 1769: strlcat(xauthfile, "/cookies", MAXPATHLEN);
1770: open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1.87 markus 1771: restore_uid();
1772: fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1.64 markus 1773: break;
1.1 deraadt 1774: #else /* XAUTH_PATH */
1.64 markus 1775: packet_send_debug("No xauth program; cannot forward with spoofing.");
1776: goto fail;
1.1 deraadt 1777: #endif /* XAUTH_PATH */
1778:
1.64 markus 1779: case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1.78 markus 1780: if (no_agent_forwarding_flag || compat13) {
1.64 markus 1781: debug("Authentication agent forwarding not permitted for this authentication.");
1782: goto fail;
1783: }
1784: debug("Received authentication agent forwarding request.");
1785: auth_input_request_forwarding(pw);
1786: break;
1787:
1788: case SSH_CMSG_PORT_FORWARD_REQUEST:
1789: if (no_port_forwarding_flag) {
1790: debug("Port forwarding not permitted for this authentication.");
1791: goto fail;
1792: }
1793: debug("Received TCP/IP port forwarding request.");
1794: channel_input_port_forward_request(pw->pw_uid == 0);
1795: break;
1796:
1797: case SSH_CMSG_MAX_PACKET_SIZE:
1798: if (packet_set_maxsize(packet_get_int()) < 0)
1799: goto fail;
1800: break;
1801:
1802: case SSH_CMSG_EXEC_SHELL:
1803: /* Set interactive/non-interactive mode. */
1804: packet_set_interactive(have_pty || display != NULL,
1805: options.keepalives);
1806:
1807: if (forced_command != NULL)
1808: goto do_forced_command;
1809: debug("Forking shell.");
1810: packet_integrity_check(plen, 0, type);
1811: if (have_pty)
1812: do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1813: else
1814: do_exec_no_pty(NULL, pw, display, proto, data);
1815: return;
1816:
1817: case SSH_CMSG_EXEC_CMD:
1818: /* Set interactive/non-interactive mode. */
1819: packet_set_interactive(have_pty || display != NULL,
1820: options.keepalives);
1821:
1822: if (forced_command != NULL)
1823: goto do_forced_command;
1824: /* Get command from the packet. */
1825: {
1.92 ! markus 1826: unsigned int dlen;
1.64 markus 1827: command = packet_get_string(&dlen);
1828: debug("Executing command '%.500s'", command);
1829: packet_integrity_check(plen, 4 + dlen, type);
1830: }
1831: if (have_pty)
1832: do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1833: else
1834: do_exec_no_pty(command, pw, display, proto, data);
1835: xfree(command);
1836: return;
1837:
1838: default:
1.66 markus 1839: /*
1840: * Any unknown messages in this phase are ignored,
1841: * and a failure message is returned.
1842: */
1.64 markus 1843: log("Unknown packet type received after authentication: %d", type);
1844: goto fail;
1845: }
1.1 deraadt 1846:
1.64 markus 1847: /* The request was successfully processed. */
1848: packet_start(SSH_SMSG_SUCCESS);
1849: packet_send();
1850: packet_write_wait();
1851:
1852: /* Enable compression now that we have replied if appropriate. */
1853: if (enable_compression_after_reply) {
1854: enable_compression_after_reply = 0;
1855: packet_start_compression(compression_level);
1856: }
1857: continue;
1.1 deraadt 1858:
1.64 markus 1859: fail:
1860: /* The request failed. */
1861: packet_start(SSH_SMSG_FAILURE);
1862: packet_send();
1863: packet_write_wait();
1864: continue;
1.1 deraadt 1865:
1.64 markus 1866: do_forced_command:
1.66 markus 1867: /*
1868: * There is a forced command specified for this login.
1869: * Execute it.
1870: */
1.64 markus 1871: debug("Executing forced command: %.900s", forced_command);
1872: if (have_pty)
1873: do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1874: else
1875: do_exec_no_pty(forced_command, pw, display, proto, data);
1876: return;
1877: }
1.1 deraadt 1878: }
1879:
1.65 deraadt 1880: /*
1881: * This is called to fork and execute a command when we have no tty. This
1882: * will call do_child from the child, and server_loop from the parent after
1883: * setting up file descriptors and such.
1884: */
1.64 markus 1885: void
1886: do_exec_no_pty(const char *command, struct passwd * pw,
1887: const char *display, const char *auth_proto,
1888: const char *auth_data)
1889: {
1890: int pid;
1.1 deraadt 1891:
1892: #ifdef USE_PIPES
1.64 markus 1893: int pin[2], pout[2], perr[2];
1894: /* Allocate pipes for communicating with the program. */
1895: if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1896: packet_disconnect("Could not create pipes: %.100s",
1897: strerror(errno));
1.1 deraadt 1898: #else /* USE_PIPES */
1.64 markus 1899: int inout[2], err[2];
1900: /* Uses socket pairs to communicate with the program. */
1901: if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1902: socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1903: packet_disconnect("Could not create socket pairs: %.100s",
1904: strerror(errno));
1.1 deraadt 1905: #endif /* USE_PIPES */
1.16 deraadt 1906:
1.64 markus 1907: setproctitle("%s@notty", pw->pw_name);
1908:
1909: /* Fork the child. */
1910: if ((pid = fork()) == 0) {
1911: /* Child. Reinitialize the log since the pid has changed. */
1912: log_init(av0, options.log_level, options.log_facility, log_stderr);
1913:
1.66 markus 1914: /*
1915: * Create a new session and process group since the 4.4BSD
1916: * setlogin() affects the entire process group.
1917: */
1.64 markus 1918: if (setsid() < 0)
1919: error("setsid failed: %.100s", strerror(errno));
1.29 deraadt 1920:
1.1 deraadt 1921: #ifdef USE_PIPES
1.66 markus 1922: /*
1923: * Redirect stdin. We close the parent side of the socket
1924: * pair, and make the child side the standard input.
1925: */
1.64 markus 1926: close(pin[1]);
1927: if (dup2(pin[0], 0) < 0)
1928: perror("dup2 stdin");
1929: close(pin[0]);
1930:
1931: /* Redirect stdout. */
1932: close(pout[0]);
1933: if (dup2(pout[1], 1) < 0)
1934: perror("dup2 stdout");
1935: close(pout[1]);
1936:
1937: /* Redirect stderr. */
1938: close(perr[0]);
1939: if (dup2(perr[1], 2) < 0)
1940: perror("dup2 stderr");
1941: close(perr[1]);
1.1 deraadt 1942: #else /* USE_PIPES */
1.66 markus 1943: /*
1944: * Redirect stdin, stdout, and stderr. Stdin and stdout will
1945: * use the same socket, as some programs (particularly rdist)
1946: * seem to depend on it.
1947: */
1.64 markus 1948: close(inout[1]);
1949: close(err[1]);
1950: if (dup2(inout[0], 0) < 0) /* stdin */
1951: perror("dup2 stdin");
1952: if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1953: perror("dup2 stdout");
1954: if (dup2(err[0], 2) < 0) /* stderr */
1955: perror("dup2 stderr");
1.1 deraadt 1956: #endif /* USE_PIPES */
1957:
1.64 markus 1958: /* Do processing for the child (exec command etc). */
1959: do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1960: /* NOTREACHED */
1961: }
1962: if (pid < 0)
1963: packet_disconnect("fork failed: %.100s", strerror(errno));
1.1 deraadt 1964: #ifdef USE_PIPES
1.64 markus 1965: /* We are the parent. Close the child sides of the pipes. */
1966: close(pin[0]);
1967: close(pout[1]);
1968: close(perr[1]);
1969:
1970: /* Enter the interactive session. */
1971: server_loop(pid, pin[1], pout[0], perr[0]);
1972: /* server_loop has closed pin[1], pout[1], and perr[1]. */
1.1 deraadt 1973: #else /* USE_PIPES */
1.64 markus 1974: /* We are the parent. Close the child sides of the socket pairs. */
1975: close(inout[0]);
1976: close(err[0]);
1977:
1.66 markus 1978: /*
1979: * Enter the interactive session. Note: server_loop must be able to
1980: * handle the case that fdin and fdout are the same.
1981: */
1.64 markus 1982: server_loop(pid, inout[1], inout[1], err[1]);
1983: /* server_loop has closed inout[1] and err[1]. */
1.1 deraadt 1984: #endif /* USE_PIPES */
1985: }
1986:
1.65 deraadt 1987: /*
1988: * This is called to fork and execute a command when we have a tty. This
1989: * will call do_child from the child, and server_loop from the parent after
1990: * setting up file descriptors, controlling tty, updating wtmp, utmp,
1991: * lastlog, and other such operations.
1992: */
1.64 markus 1993: void
1994: do_exec_pty(const char *command, int ptyfd, int ttyfd,
1995: const char *ttyname, struct passwd * pw, const char *term,
1996: const char *display, const char *auth_proto,
1997: const char *auth_data)
1998: {
1999: int pid, fdout;
1.83 markus 2000: int ptymaster;
1.64 markus 2001: const char *hostname;
2002: time_t last_login_time;
2003: char buf[100], *time_string;
2004: FILE *f;
2005: char line[256];
2006: struct stat st;
2007: int quiet_login;
1.75 markus 2008: struct sockaddr_storage from;
2009: socklen_t fromlen;
1.64 markus 2010: struct pty_cleanup_context cleanup_context;
2011:
2012: /* Get remote host name. */
2013: hostname = get_canonical_hostname();
2014:
1.66 markus 2015: /*
2016: * Get the time when the user last logged in. Buf will be set to
2017: * contain the hostname the last login was from.
2018: */
1.64 markus 2019: if (!options.use_login) {
2020: last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2021: buf, sizeof(buf));
2022: }
2023: setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
2024:
2025: /* Fork the child. */
2026: if ((pid = fork()) == 0) {
2027: pid = getpid();
2028:
2029: /* Child. Reinitialize the log because the pid has
2030: changed. */
2031: log_init(av0, options.log_level, options.log_facility, log_stderr);
2032:
2033: /* Close the master side of the pseudo tty. */
2034: close(ptyfd);
2035:
2036: /* Make the pseudo tty our controlling tty. */
2037: pty_make_controlling_tty(&ttyfd, ttyname);
2038:
2039: /* Redirect stdin from the pseudo tty. */
2040: if (dup2(ttyfd, fileno(stdin)) < 0)
2041: error("dup2 stdin failed: %.100s", strerror(errno));
2042:
2043: /* Redirect stdout to the pseudo tty. */
2044: if (dup2(ttyfd, fileno(stdout)) < 0)
2045: error("dup2 stdin failed: %.100s", strerror(errno));
2046:
2047: /* Redirect stderr to the pseudo tty. */
2048: if (dup2(ttyfd, fileno(stderr)) < 0)
2049: error("dup2 stdin failed: %.100s", strerror(errno));
2050:
2051: /* Close the extra descriptor for the pseudo tty. */
2052: close(ttyfd);
2053:
1.66 markus 2054: /*
2055: * Get IP address of client. This is needed because we want
2056: * to record where the user logged in from. If the
2057: * connection is not a socket, let the ip address be 0.0.0.0.
2058: */
1.64 markus 2059: memset(&from, 0, sizeof(from));
2060: if (packet_get_connection_in() == packet_get_connection_out()) {
2061: fromlen = sizeof(from);
2062: if (getpeername(packet_get_connection_in(),
2063: (struct sockaddr *) & from, &fromlen) < 0) {
2064: debug("getpeername: %.100s", strerror(errno));
2065: fatal_cleanup();
2066: }
2067: }
2068: /* Record that there was a login on that terminal. */
2069: record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
1.75 markus 2070: (struct sockaddr *)&from);
1.64 markus 2071:
2072: /* Check if .hushlogin exists. */
2073: snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2074: quiet_login = stat(line, &st) >= 0;
2075:
1.66 markus 2076: /*
2077: * If the user has logged in before, display the time of last
2078: * login. However, don't display anything extra if a command
2079: * has been specified (so that ssh can be used to execute
2080: * commands on a remote machine without users knowing they
2081: * are going to another machine). Login(1) will do this for
2082: * us as well, so check if login(1) is used
2083: */
1.64 markus 2084: if (command == NULL && last_login_time != 0 && !quiet_login &&
2085: !options.use_login) {
2086: /* Convert the date to a string. */
2087: time_string = ctime(&last_login_time);
2088: /* Remove the trailing newline. */
2089: if (strchr(time_string, '\n'))
2090: *strchr(time_string, '\n') = 0;
2091: /* Display the last login time. Host if displayed
2092: if known. */
2093: if (strcmp(buf, "") == 0)
2094: printf("Last login: %s\r\n", time_string);
2095: else
2096: printf("Last login: %s from %s\r\n", time_string, buf);
2097: }
1.66 markus 2098: /*
2099: * Print /etc/motd unless a command was specified or printing
2100: * it was disabled in server options or login(1) will be
2101: * used. Note that some machines appear to print it in
2102: * /etc/profile or similar.
2103: */
1.64 markus 2104: if (command == NULL && options.print_motd && !quiet_login &&
2105: !options.use_login) {
2106: /* Print /etc/motd if it exists. */
2107: f = fopen("/etc/motd", "r");
2108: if (f) {
2109: while (fgets(line, sizeof(line), f))
2110: fputs(line, stdout);
2111: fclose(f);
2112: }
2113: }
2114: /* Do common processing for the child, such as execing the command. */
2115: do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2116: /* NOTREACHED */
2117: }
2118: if (pid < 0)
2119: packet_disconnect("fork failed: %.100s", strerror(errno));
2120: /* Parent. Close the slave side of the pseudo tty. */
2121: close(ttyfd);
2122:
1.66 markus 2123: /*
1.88 markus 2124: * Add a cleanup function to clear the utmp entry and record logout
2125: * time in case we call fatal() (e.g., the connection gets closed).
2126: */
2127: cleanup_context.pid = pid;
2128: cleanup_context.ttyname = ttyname;
2129: fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2130: fatal_remove_cleanup(pty_release_proc, (void *) ttyname);
2131:
2132: /*
1.66 markus 2133: * Create another descriptor of the pty master side for use as the
2134: * standard input. We could use the original descriptor, but this
2135: * simplifies code in server_loop. The descriptor is bidirectional.
2136: */
1.64 markus 2137: fdout = dup(ptyfd);
2138: if (fdout < 0)
1.83 markus 2139: packet_disconnect("dup #1 failed: %.100s", strerror(errno));
2140:
2141: /* we keep a reference to the pty master */
2142: ptymaster = dup(ptyfd);
2143: if (ptymaster < 0)
2144: packet_disconnect("dup #2 failed: %.100s", strerror(errno));
1.64 markus 2145:
2146: /* Enter interactive session. */
2147: server_loop(pid, ptyfd, fdout, -1);
1.84 markus 2148: /* server_loop _has_ closed ptyfd and fdout. */
1.64 markus 2149:
2150: /* Cancel the cleanup function. */
2151: fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2152:
2153: /* Record that the user has logged out. */
2154: record_logout(pid, ttyname);
2155:
2156: /* Release the pseudo-tty. */
2157: pty_release(ttyname);
2158:
1.66 markus 2159: /*
2160: * Close the server side of the socket pairs. We must do this after
2161: * the pty cleanup, so that another process doesn't get this pty
2162: * while we're still cleaning up.
2163: */
1.83 markus 2164: if (close(ptymaster) < 0)
2165: error("close(ptymaster): %s", strerror(errno));
1.1 deraadt 2166: }
2167:
1.65 deraadt 2168: /*
2169: * Sets the value of the given variable in the environment. If the variable
2170: * already exists, its value is overriden.
2171: */
1.64 markus 2172: void
2173: child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2174: const char *value)
2175: {
2176: unsigned int i, namelen;
2177: char **env;
2178:
1.66 markus 2179: /*
2180: * Find the slot where the value should be stored. If the variable
2181: * already exists, we reuse the slot; otherwise we append a new slot
2182: * at the end of the array, expanding if necessary.
2183: */
1.64 markus 2184: env = *envp;
2185: namelen = strlen(name);
2186: for (i = 0; env[i]; i++)
2187: if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2188: break;
2189: if (env[i]) {
1.66 markus 2190: /* Reuse the slot. */
1.64 markus 2191: xfree(env[i]);
2192: } else {
1.66 markus 2193: /* New variable. Expand if necessary. */
1.64 markus 2194: if (i >= (*envsizep) - 1) {
2195: (*envsizep) += 50;
2196: env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2197: }
2198: /* Need to set the NULL pointer at end of array beyond the new slot. */
2199: env[i + 1] = NULL;
1.1 deraadt 2200: }
2201:
1.64 markus 2202: /* Allocate space and format the variable in the appropriate slot. */
2203: env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2204: snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1.1 deraadt 2205: }
2206:
1.65 deraadt 2207: /*
2208: * Reads environment variables from the given file and adds/overrides them
2209: * into the environment. If the file does not exist, this does nothing.
2210: * Otherwise, it must consist of empty lines, comments (line starts with '#')
2211: * and assignments of the form name=value. No other forms are allowed.
2212: */
1.64 markus 2213: void
2214: read_environment_file(char ***env, unsigned int *envsize,
2215: const char *filename)
2216: {
2217: FILE *f;
2218: char buf[4096];
2219: char *cp, *value;
2220:
2221: f = fopen(filename, "r");
2222: if (!f)
2223: return;
2224:
2225: while (fgets(buf, sizeof(buf), f)) {
1.66 markus 2226: for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2227: ;
1.64 markus 2228: if (!*cp || *cp == '#' || *cp == '\n')
2229: continue;
2230: if (strchr(cp, '\n'))
2231: *strchr(cp, '\n') = '\0';
2232: value = strchr(cp, '=');
2233: if (value == NULL) {
2234: fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2235: continue;
2236: }
1.66 markus 2237: /* Replace the equals sign by nul, and advance value to the value string. */
1.64 markus 2238: *value = '\0';
2239: value++;
2240: child_set_env(env, envsize, cp, value);
1.1 deraadt 2241: }
1.64 markus 2242: fclose(f);
1.1 deraadt 2243: }
2244:
1.65 deraadt 2245: /*
2246: * Performs common processing for the child, such as setting up the
2247: * environment, closing extra file descriptors, setting the user and group
2248: * ids, and executing the command or shell.
2249: */
1.64 markus 2250: void
2251: do_child(const char *command, struct passwd * pw, const char *term,
2252: const char *display, const char *auth_proto,
2253: const char *auth_data, const char *ttyname)
2254: {
2255: const char *shell, *cp = NULL;
2256: char buf[256];
2257: FILE *f;
2258: unsigned int envsize, i;
2259: char **env;
2260: extern char **environ;
2261: struct stat st;
2262: char *argv[10];
2263:
2264: f = fopen("/etc/nologin", "r");
2265: if (f) {
2266: /* /etc/nologin exists. Print its contents and exit. */
2267: while (fgets(buf, sizeof(buf), f))
2268: fputs(buf, stderr);
2269: fclose(f);
2270: if (pw->pw_uid != 0)
2271: exit(254);
2272: }
2273: /* Set login name in the kernel. */
2274: if (setlogin(pw->pw_name) < 0)
2275: error("setlogin failed: %s", strerror(errno));
2276:
2277: /* Set uid, gid, and groups. */
2278: /* Login(1) does this as well, and it needs uid 0 for the "-h"
2279: switch, so we let login(1) to this for us. */
2280: if (!options.use_login) {
2281: if (getuid() == 0 || geteuid() == 0) {
2282: if (setgid(pw->pw_gid) < 0) {
2283: perror("setgid");
2284: exit(1);
2285: }
2286: /* Initialize the group list. */
2287: if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2288: perror("initgroups");
2289: exit(1);
2290: }
2291: endgrent();
2292:
2293: /* Permanently switch to the desired uid. */
2294: permanently_set_uid(pw->pw_uid);
2295: }
2296: if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2297: fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2298: }
1.66 markus 2299: /*
2300: * Get the shell from the password data. An empty shell field is
2301: * legal, and means /bin/sh.
2302: */
1.64 markus 2303: shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.1 deraadt 2304:
2305: #ifdef AFS
1.64 markus 2306: /* Try to get AFS tokens for the local cell. */
2307: if (k_hasafs()) {
2308: char cell[64];
1.1 deraadt 2309:
1.64 markus 2310: if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2311: krb_afslog(cell, 0);
2312:
2313: krb_afslog(0, 0);
2314: }
1.1 deraadt 2315: #endif /* AFS */
1.64 markus 2316:
1.66 markus 2317: /* Initialize the environment. */
1.64 markus 2318: envsize = 100;
2319: env = xmalloc(envsize * sizeof(char *));
2320: env[0] = NULL;
2321:
2322: if (!options.use_login) {
2323: /* Set basic environment. */
2324: child_set_env(&env, &envsize, "USER", pw->pw_name);
2325: child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2326: child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2327: child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2328:
2329: snprintf(buf, sizeof buf, "%.200s/%.50s",
2330: _PATH_MAILDIR, pw->pw_name);
2331: child_set_env(&env, &envsize, "MAIL", buf);
2332:
2333: /* Normal systems set SHELL by default. */
2334: child_set_env(&env, &envsize, "SHELL", shell);
2335: }
2336: if (getenv("TZ"))
2337: child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2338:
2339: /* Set custom environment options from RSA authentication. */
2340: while (custom_environment) {
2341: struct envstring *ce = custom_environment;
2342: char *s = ce->s;
2343: int i;
2344: for (i = 0; s[i] != '=' && s[i]; i++);
2345: if (s[i] == '=') {
2346: s[i] = 0;
2347: child_set_env(&env, &envsize, s, s + i + 1);
2348: }
2349: custom_environment = ce->next;
2350: xfree(ce->s);
2351: xfree(ce);
1.1 deraadt 2352: }
1.64 markus 2353:
2354: snprintf(buf, sizeof buf, "%.50s %d %d",
1.75 markus 2355: get_remote_ipaddr(), get_remote_port(), get_local_port());
1.64 markus 2356: child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2357:
2358: if (ttyname)
2359: child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2360: if (term)
2361: child_set_env(&env, &envsize, "TERM", term);
2362: if (display)
2363: child_set_env(&env, &envsize, "DISPLAY", display);
1.1 deraadt 2364:
1.5 dugsong 2365: #ifdef KRB4
1.64 markus 2366: {
2367: extern char *ticket;
2368:
2369: if (ticket)
2370: child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2371: }
1.1 deraadt 2372: #endif /* KRB4 */
1.64 markus 2373:
2374: if (xauthfile)
2375: child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2376: if (auth_get_socket_name() != NULL)
2377: child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2378: auth_get_socket_name());
2379:
1.66 markus 2380: /* read $HOME/.ssh/environment. */
1.64 markus 2381: if (!options.use_login) {
2382: snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2383: read_environment_file(&env, &envsize, buf);
2384: }
2385: if (debug_flag) {
1.66 markus 2386: /* dump the environment */
1.64 markus 2387: fprintf(stderr, "Environment:\n");
2388: for (i = 0; env[i]; i++)
2389: fprintf(stderr, " %.200s\n", env[i]);
2390: }
1.66 markus 2391: /*
2392: * Close the connection descriptors; note that this is the child, and
2393: * the server will still have the socket open, and it is important
2394: * that we do not shutdown it. Note that the descriptors cannot be
2395: * closed before building the environment, as we call
2396: * get_remote_ipaddr there.
2397: */
1.64 markus 2398: if (packet_get_connection_in() == packet_get_connection_out())
2399: close(packet_get_connection_in());
2400: else {
2401: close(packet_get_connection_in());
2402: close(packet_get_connection_out());
2403: }
1.66 markus 2404: /*
2405: * Close all descriptors related to channels. They will still remain
2406: * open in the parent.
2407: */
2408: /* XXX better use close-on-exec? -markus */
1.64 markus 2409: channel_close_all();
2410:
1.66 markus 2411: /*
2412: * Close any extra file descriptors. Note that there may still be
2413: * descriptors left by system functions. They will be closed later.
2414: */
1.64 markus 2415: endpwent();
2416:
1.66 markus 2417: /*
2418: * Close any extra open file descriptors so that we don\'t have them
2419: * hanging around in clients. Note that we want to do this after
2420: * initgroups, because at least on Solaris 2.3 it leaves file
2421: * descriptors open.
2422: */
1.64 markus 2423: for (i = 3; i < 64; i++)
2424: close(i);
2425:
2426: /* Change current directory to the user\'s home directory. */
2427: if (chdir(pw->pw_dir) < 0)
2428: fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2429: pw->pw_dir, strerror(errno));
2430:
1.66 markus 2431: /*
2432: * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2433: * xauth are run in the proper environment.
2434: */
1.64 markus 2435: environ = env;
2436:
1.66 markus 2437: /*
2438: * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2439: * in this order).
2440: */
1.64 markus 2441: if (!options.use_login) {
2442: if (stat(SSH_USER_RC, &st) >= 0) {
2443: if (debug_flag)
2444: fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2445:
2446: f = popen("/bin/sh " SSH_USER_RC, "w");
2447: if (f) {
2448: if (auth_proto != NULL && auth_data != NULL)
2449: fprintf(f, "%s %s\n", auth_proto, auth_data);
2450: pclose(f);
2451: } else
2452: fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2453: } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2454: if (debug_flag)
2455: fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2456:
2457: f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2458: if (f) {
2459: if (auth_proto != NULL && auth_data != NULL)
2460: fprintf(f, "%s %s\n", auth_proto, auth_data);
2461: pclose(f);
2462: } else
2463: fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2464: }
1.1 deraadt 2465: #ifdef XAUTH_PATH
1.64 markus 2466: else {
1.66 markus 2467: /* Add authority data to .Xauthority if appropriate. */
1.64 markus 2468: if (auth_proto != NULL && auth_data != NULL) {
2469: if (debug_flag)
2470: fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2471: XAUTH_PATH, display, auth_proto, auth_data);
2472:
2473: f = popen(XAUTH_PATH " -q -", "w");
2474: if (f) {
2475: fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
1.90 markus 2476: pclose(f);
1.64 markus 2477: } else
2478: fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2479: }
2480: }
1.1 deraadt 2481: #endif /* XAUTH_PATH */
2482:
1.64 markus 2483: /* Get the last component of the shell name. */
2484: cp = strrchr(shell, '/');
2485: if (cp)
2486: cp++;
2487: else
2488: cp = shell;
2489: }
1.66 markus 2490: /*
2491: * If we have no command, execute the shell. In this case, the shell
2492: * name to be passed in argv[0] is preceded by '-' to indicate that
2493: * this is a login shell.
2494: */
1.64 markus 2495: if (!command) {
2496: if (!options.use_login) {
2497: char buf[256];
2498:
1.66 markus 2499: /*
2500: * Check for mail if we have a tty and it was enabled
2501: * in server options.
2502: */
1.64 markus 2503: if (ttyname && options.check_mail) {
2504: char *mailbox;
2505: struct stat mailstat;
2506: mailbox = getenv("MAIL");
2507: if (mailbox != NULL) {
2508: if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2509: printf("No mail.\n");
2510: else if (mailstat.st_mtime < mailstat.st_atime)
2511: printf("You have mail.\n");
2512: else
2513: printf("You have new mail.\n");
2514: }
2515: }
2516: /* Start the shell. Set initial character to '-'. */
2517: buf[0] = '-';
2518: strncpy(buf + 1, cp, sizeof(buf) - 1);
2519: buf[sizeof(buf) - 1] = 0;
2520:
2521: /* Execute the shell. */
2522: argv[0] = buf;
2523: argv[1] = NULL;
2524: execve(shell, argv, env);
2525:
2526: /* Executing the shell failed. */
2527: perror(shell);
2528: exit(1);
2529:
2530: } else {
2531: /* Launch login(1). */
2532:
2533: execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
2534: "-p", "-f", "--", pw->pw_name, NULL);
2535:
2536: /* Login couldn't be executed, die. */
2537:
2538: perror("login");
2539: exit(1);
2540: }
2541: }
1.66 markus 2542: /*
2543: * Execute the command using the user's shell. This uses the -c
2544: * option to execute the command.
2545: */
1.64 markus 2546: argv[0] = (char *) cp;
2547: argv[1] = "-c";
2548: argv[2] = (char *) command;
2549: argv[3] = NULL;
2550: execve(shell, argv, env);
2551: perror(shell);
2552: exit(1);
1.1 deraadt 2553: }