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