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