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