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