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