]> andersk Git - openssh.git/blame - sshd.c
- Add recommendation to use GNU make to INSTALL document
[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
8efc0c15 46/* Local Xauthority file. */
6a17f9c2 47static char *xauthfile = NULL;
8efc0c15 48
49/* Server configuration options. */
50ServerOptions options;
51
52/* Name of the server configuration file. */
53char *config_file_name = SERVER_CONFIG_FILE;
54
55/* Debug mode flag. This can be set on the command line. If debug
56 mode is enabled, extra debugging output will be sent to the system
57 log, the daemon will not go to background, and will exit after processing
58 the first connection. */
59int debug_flag = 0;
60
61/* Flag indicating that the daemon is being started from inetd. */
62int inetd_flag = 0;
63
6a17f9c2 64/* debug goes to stderr unless inetd_flag is set */
65int log_stderr = 0;
66
8efc0c15 67/* argv[0] without path. */
68char *av0;
69
70/* Saved arguments to main(). */
71char **saved_argv;
72
73/* This is set to the socket that the server is listening; this is used in
74 the SIGHUP signal handler. */
75int listen_sock;
76
77/* Flags set in auth-rsa from authorized_keys flags. These are set in
78 auth-rsa.c. */
79int no_port_forwarding_flag = 0;
80int no_agent_forwarding_flag = 0;
81int no_x11_forwarding_flag = 0;
82int no_pty_flag = 0;
83char *forced_command = NULL; /* RSA authentication "command=" option. */
84struct envstring *custom_environment = NULL;
85 /* RSA authentication "environment=" options. */
86
87/* Session id for the current session. */
88unsigned char session_id[16];
89
90/* Any really sensitive data in the application is contained in this structure.
91 The idea is that this structure could be locked into memory so that the
92 pages do not get written into swap. However, there are some problems.
93 The private key contains BIGNUMs, and we do not (in principle) have
94 access to the internals of them, and locking just the structure is not
95 very useful. Currently, memory locking is not implemented. */
96struct
97{
98 /* Private part of server key. */
99 RSA *private_key;
100
101 /* Private part of host key. */
102 RSA *host_key;
103} sensitive_data;
104
105/* Flag indicating whether the current session key has been used. This flag
106 is set whenever the key is used, and cleared when the key is regenerated. */
107int key_used = 0;
108
109/* This is set to true when SIGHUP is received. */
110int received_sighup = 0;
111
112/* Public side of the server key. This value is regenerated regularly with
113 the private key. */
114RSA *public_key;
115
116/* Prototypes for various functions defined later in this file. */
e7c0f9d5 117void do_connection();
118void do_authentication(char *user);
119void do_authloop(struct passwd *pw);
120void do_fake_authloop(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);
e7c0f9d5 132
5aecb327 133#ifdef HAVE_LIBPAM
8efc0c15 134static int pamconv(int num_msg, const struct pam_message **msg,
e7c0f9d5 135 struct pam_response **resp, void *appdata_ptr);
c75a1a66 136void do_pam_account_and_session(char *username, char *remote_user,
137 const char *remote_host);
d813bc69 138void pam_cleanup_proc(void *context);
8efc0c15 139
140static struct pam_conv conv = {
141 pamconv,
142 NULL
143};
d813bc69 144struct pam_handle_t *pamh = NULL;
145const char *pampasswd = NULL;
e1a9c08d 146char *pamconv_msg = NULL;
8efc0c15 147
148static int pamconv(int num_msg, const struct pam_message **msg,
149 struct pam_response **resp, void *appdata_ptr)
150{
06479889 151 struct pam_response *reply;
152 int count;
153 size_t msg_len;
154 char *p;
8efc0c15 155
d813bc69 156 /* PAM will free this later */
157 reply = malloc(num_msg * sizeof(*reply));
158 if (reply == NULL)
159 return PAM_CONV_ERR;
160
8efc0c15 161 for(count = 0; count < num_msg; count++)
162 {
163 switch (msg[count]->msg_style)
164 {
8efc0c15 165 case PAM_PROMPT_ECHO_OFF:
0183ea1c 166 if (pampasswd == NULL)
d813bc69 167 {
8efc0c15 168 free(reply);
d813bc69 169 return PAM_CONV_ERR;
170 }
171 reply[count].resp_retcode = PAM_SUCCESS;
172 reply[count].resp = xstrdup(pampasswd);
173 break;
174
175 case PAM_TEXT_INFO:
176 reply[count].resp_retcode = PAM_SUCCESS;
177 reply[count].resp = xstrdup("");
e1a9c08d 178
06479889 179 if (msg[count]->msg == NULL)
180 break;
e1a9c08d 181 debug("Adding PAM message: %s", msg[count]->msg);
06479889 182
183 msg_len = strlen(msg[count]->msg);
184 if (pamconv_msg)
e1a9c08d 185 {
06479889 186 size_t n = strlen(pamconv_msg);
187 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
188 p = pamconv_msg + n;
e1a9c08d 189 }
06479889 190 else
191 pamconv_msg = p = xmalloc(msg_len + 2);
192 memcpy(p, msg[count]->msg, msg_len);
193 p[msg_len] = '\n';
194 p[msg_len + 1] = '\0';
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",
96ad4350 220 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
549b3eed 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",
96ad4350 227 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
549b3eed 228 }
d813bc69 229 }
230}
231
c75a1a66 232void do_pam_account_and_session(char *username, char *remote_user,
233 const char *remote_host)
d813bc69 234{
549b3eed 235 int pam_retval;
236
237 if (remote_host != NULL)
d813bc69 238 {
549b3eed 239 debug("PAM setting rhost to \"%.200s\"", remote_host);
240 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host);
241 if (pam_retval != PAM_SUCCESS)
242 {
96ad4350 243 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 244 do_fake_authloop(username);
549b3eed 245 }
0183ea1c 246 }
549b3eed 247
248 if (remote_user != NULL)
0183ea1c 249 {
549b3eed 250 debug("PAM setting ruser to \"%.200s\"", remote_user);
251 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
252 if (pam_retval != PAM_SUCCESS)
253 {
96ad4350 254 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 255 do_fake_authloop(username);
549b3eed 256 }
0183ea1c 257 }
549b3eed 258
259 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
260 if (pam_retval != PAM_SUCCESS)
0183ea1c 261 {
96ad4350 262 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 263 do_fake_authloop(username);
0183ea1c 264 }
d813bc69 265
549b3eed 266 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
267 if (pam_retval != PAM_SUCCESS)
d813bc69 268 {
96ad4350 269 log("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 270 do_fake_authloop(username);
d813bc69 271 }
8efc0c15 272}
5aecb327 273#endif /* HAVE_LIBPAM */
8efc0c15 274
275/* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
276 the effect is to reread the configuration file (and to regenerate
277 the server key). */
278
279void sighup_handler(int sig)
280{
281 received_sighup = 1;
282 signal(SIGHUP, sighup_handler);
283}
284
285/* Called from the main program after receiving SIGHUP. Restarts the
286 server. */
287
288void sighup_restart()
289{
290 log("Received SIGHUP; restarting.");
291 close(listen_sock);
292 execv(saved_argv[0], saved_argv);
293 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
294 exit(1);
295}
296
297/* Generic signal handler for terminating signals in the master daemon.
298 These close the listen socket; not closing it seems to cause "Address
299 already in use" problems on some machines, which is inconvenient. */
300
301void sigterm_handler(int sig)
302{
303 log("Received signal %d; terminating.", sig);
304 close(listen_sock);
305 exit(255);
306}
307
308/* SIGCHLD handler. This is called whenever a child dies. This will then
309 reap any zombies left by exited c. */
310
311void main_sigchld_handler(int sig)
312{
313 int save_errno = errno;
314 int status;
5ad13cd7 315
316 while (waitpid(-1, &status, WNOHANG) > 0)
317 ;
318
8efc0c15 319 signal(SIGCHLD, main_sigchld_handler);
320 errno = save_errno;
321}
322
323/* Signal handler for the alarm after the login grace period has expired. */
324
325void grace_alarm_handler(int sig)
326{
327 /* Close the connection. */
328 packet_close();
329
330 /* Log error and exit. */
331 fatal("Timeout before authentication.");
332}
333
334/* Signal handler for the key regeneration alarm. Note that this
335 alarm only occurs in the daemon waiting for connections, and it does not
336 do anything with the private key or random state before forking. Thus there
337 should be no concurrency control/asynchronous execution problems. */
338
339void key_regeneration_alarm(int sig)
340{
341 int save_errno = errno;
342
343 /* Check if we should generate a new key. */
344 if (key_used)
345 {
346 /* This should really be done in the background. */
347 log("Generating new %d bit RSA key.", options.server_key_bits);
348
349 if (sensitive_data.private_key != NULL)
350 RSA_free(sensitive_data.private_key);
351 sensitive_data.private_key = RSA_new();
352
353 if (public_key != NULL)
354 RSA_free(public_key);
355 public_key = RSA_new();
356
357 rsa_generate_key(sensitive_data.private_key, public_key,
358 options.server_key_bits);
359 arc4random_stir();
360 key_used = 0;
361 log("RSA key generation complete.");
362 }
363
364 /* Reschedule the alarm. */
365 signal(SIGALRM, key_regeneration_alarm);
366 alarm(options.key_regeneration_time);
367 errno = save_errno;
368}
369
370/* Main program for the daemon. */
371
372int
373main(int ac, char **av)
374{
375 extern char *optarg;
376 extern int optind;
377 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
378 int remote_major, remote_minor;
379 int silentrsa = 0;
380 struct sockaddr_in sin;
381 char buf[100]; /* Must not be larger than remote_version. */
382 char remote_version[100]; /* Must be at least as big as buf. */
e7c0f9d5 383 int remote_port;
8efc0c15 384 char *comment;
385 FILE *f;
386 struct linger linger;
387
388 /* Save argv[0]. */
389 saved_argv = av;
390 if (strchr(av[0], '/'))
391 av0 = strrchr(av[0], '/') + 1;
392 else
393 av0 = av[0];
394
395 /* Initialize configuration options to their default values. */
396 initialize_server_options(&options);
397
398 /* Parse command-line arguments. */
399 while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF)
400 {
401 switch (opt)
402 {
403 case 'f':
404 config_file_name = optarg;
405 break;
406 case 'd':
407 debug_flag = 1;
6a17f9c2 408 options.log_level = SYSLOG_LEVEL_DEBUG;
8efc0c15 409 break;
410 case 'i':
411 inetd_flag = 1;
412 break;
413 case 'Q':
414 silentrsa = 1;
415 break;
416 case 'q':
6a17f9c2 417 options.log_level = SYSLOG_LEVEL_QUIET;
8efc0c15 418 break;
419 case 'b':
420 options.server_key_bits = atoi(optarg);
421 break;
422 case 'p':
423 options.port = atoi(optarg);
424 break;
425 case 'g':
426 options.login_grace_time = atoi(optarg);
427 break;
428 case 'k':
429 options.key_regeneration_time = atoi(optarg);
430 break;
431 case 'h':
432 options.host_key_file = optarg;
433 break;
434 case '?':
435 default:
436 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
437 fprintf(stderr, "Usage: %s [options]\n", av0);
438 fprintf(stderr, "Options:\n");
439 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
440 fprintf(stderr, " -d Debugging mode\n");
441 fprintf(stderr, " -i Started from inetd\n");
442 fprintf(stderr, " -q Quiet (no logging)\n");
443 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
444 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
445 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
446 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
447 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
448 HOST_KEY_FILE);
449 exit(1);
450 }
451 }
452
453 /* check if RSA support exists */
454 if (rsa_alive() == 0) {
455 if (silentrsa == 0)
456 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
457 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
458 exit(1);
459 }
460
461 /* Read server configuration options from the configuration file. */
462 read_server_config(&options, config_file_name);
463
464 /* Fill in default values for those options not explicitly set. */
465 fill_default_server_options(&options);
466
467 /* Check certain values for sanity. */
468 if (options.server_key_bits < 512 ||
469 options.server_key_bits > 32768)
470 {
471 fprintf(stderr, "Bad server key size.\n");
472 exit(1);
473 }
474 if (options.port < 1 || options.port > 65535)
475 {
476 fprintf(stderr, "Bad port number.\n");
477 exit(1);
478 }
479
480 /* Check that there are no remaining arguments. */
481 if (optind < ac)
482 {
483 fprintf(stderr, "Extra argument %s.\n", av[optind]);
484 exit(1);
485 }
486
f095fcc7 487 /* Force logging to stderr while loading the private host key
488 unless started from inetd */
489 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
8efc0c15 490
491 debug("sshd version %.100s", SSH_VERSION);
492
493 sensitive_data.host_key = RSA_new();
f095fcc7 494 errno = 0;
8efc0c15 495 /* Load the host key. It must have empty passphrase. */
496 if (!load_private_key(options.host_key_file, "",
497 sensitive_data.host_key, &comment))
498 {
f095fcc7 499 error("Could not load host key: %.200s: %.100s",
500 options.host_key_file, strerror(errno));
8efc0c15 501 exit(1);
502 }
503 xfree(comment);
504
f095fcc7 505 /* Initialize the log (it is reinitialized below in case we forked). */
506 if (debug_flag && !inetd_flag)
507 log_stderr = 1;
508 log_init(av0, options.log_level, options.log_facility, log_stderr);
509
8efc0c15 510 /* If not in debugging mode, and not started from inetd, disconnect from
511 the controlling terminal, and fork. The original process exits. */
512 if (!debug_flag && !inetd_flag)
513 {
514#ifdef TIOCNOTTY
515 int fd;
516#endif /* TIOCNOTTY */
517 if (daemon(0, 0) < 0)
518 fatal("daemon() failed: %.200s", strerror(errno));
519
520 /* Disconnect from the controlling tty. */
521#ifdef TIOCNOTTY
522 fd = open("/dev/tty", O_RDWR|O_NOCTTY);
523 if (fd >= 0)
524 {
525 (void)ioctl(fd, TIOCNOTTY, NULL);
526 close(fd);
527 }
528#endif /* TIOCNOTTY */
529 }
530
531 /* Reinitialize the log (because of the fork above). */
6a17f9c2 532 log_init(av0, options.log_level, options.log_facility, log_stderr);
8efc0c15 533
534 /* Check that server and host key lengths differ sufficiently. This is
535 necessary to make double encryption work with rsaref. Oh, I hate
536 software patents. I dont know if this can go? Niels */
537 if (options.server_key_bits >
538 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
539 options.server_key_bits <
540 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
541 {
542 options.server_key_bits =
543 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
544 debug("Forcing server key to %d bits to make it differ from host key.",
545 options.server_key_bits);
546 }
547
548 /* Do not display messages to stdout in RSA code. */
549 rsa_set_verbose(0);
550
551 /* Initialize the random number generator. */
552 arc4random_stir();
553
554 /* Chdir to the root directory so that the current disk can be unmounted
555 if desired. */
556 chdir("/");
557
558 /* Close connection cleanly after attack. */
559 cipher_attack_detected = packet_disconnect;
560
561 /* Start listening for a socket, unless started from inetd. */
562 if (inetd_flag)
563 {
564 int s1, s2;
565 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
566 s2 = dup(s1);
567 sock_in = dup(0);
568 sock_out = dup(1);
569 /* We intentionally do not close the descriptors 0, 1, and 2 as our
570 code for setting the descriptors won\'t work if ttyfd happens to
571 be one of those. */
572 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
573
574 public_key = RSA_new();
575 sensitive_data.private_key = RSA_new();
576 /* Generate an rsa key. */
577 log("Generating %d bit RSA key.", options.server_key_bits);
578 rsa_generate_key(sensitive_data.private_key, public_key,
579 options.server_key_bits);
580 arc4random_stir();
581 log("RSA key generation complete.");
582 }
583 else
584 {
585 /* Create socket for listening. */
586 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
587 if (listen_sock < 0)
588 fatal("socket: %.100s", strerror(errno));
589
590 /* Set socket options. We try to make the port reusable and have it
591 close as fast as possible without waiting in unnecessary wait states
592 on close. */
593 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
594 sizeof(on));
595 linger.l_onoff = 1;
596 linger.l_linger = 5;
597 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
598 sizeof(linger));
599
600 /* Initialize the socket address. */
601 memset(&sin, 0, sizeof(sin));
602 sin.sin_family = AF_INET;
603 sin.sin_addr = options.listen_addr;
604 sin.sin_port = htons(options.port);
605
606 /* Bind the socket to the desired port. */
607 if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
608 {
609 error("bind: %.100s", strerror(errno));
610 shutdown(listen_sock, SHUT_RDWR);
611 close(listen_sock);
612 fatal("Bind to port %d failed.", options.port);
613 }
614
615 if (!debug_flag)
616 {
617 /* Record our pid in /etc/sshd_pid to make it easier to kill the
618 correct sshd. We don\'t want to do this before the bind above
619 because the bind will fail if there already is a daemon, and this
620 will overwrite any old pid in the file. */
621 f = fopen(SSH_DAEMON_PID_FILE, "w");
622 if (f)
623 {
624 fprintf(f, "%u\n", (unsigned int)getpid());
625 fclose(f);
626 }
627 }
628
629 /* Start listening on the port. */
630 log("Server listening on port %d.", options.port);
631 if (listen(listen_sock, 5) < 0)
632 fatal("listen: %.100s", strerror(errno));
633
634 public_key = RSA_new();
635 sensitive_data.private_key = RSA_new();
636 /* Generate an rsa key. */
637 log("Generating %d bit RSA key.", options.server_key_bits);
638 rsa_generate_key(sensitive_data.private_key, public_key,
639 options.server_key_bits);
640 arc4random_stir();
641 log("RSA key generation complete.");
642
643 /* Schedule server key regeneration alarm. */
644 signal(SIGALRM, key_regeneration_alarm);
645 alarm(options.key_regeneration_time);
646
647 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
648 signal(SIGHUP, sighup_handler);
649 signal(SIGTERM, sigterm_handler);
650 signal(SIGQUIT, sigterm_handler);
651
652 /* Arrange SIGCHLD to be caught. */
653 signal(SIGCHLD, main_sigchld_handler);
654
655 /* Stay listening for connections until the system crashes or the
656 daemon is killed with a signal. */
657 for (;;)
658 {
659 if (received_sighup)
660 sighup_restart();
661 /* Wait in accept until there is a connection. */
662 aux = sizeof(sin);
663 newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux);
664 if (received_sighup)
665 sighup_restart();
666 if (newsock < 0)
667 {
668 if (errno == EINTR)
669 continue;
670 error("accept: %.100s", strerror(errno));
671 continue;
672 }
673
674 /* Got connection. Fork a child to handle it, unless we are in
675 debugging mode. */
676 if (debug_flag)
677 {
678 /* In debugging mode. Close the listening socket, and start
679 processing the connection without forking. */
680 debug("Server will not fork when running in debugging mode.");
681 close(listen_sock);
682 sock_in = newsock;
683 sock_out = newsock;
684 pid = getpid();
685 break;
686 }
687 else
688 {
689 /* Normal production daemon. Fork, and have the child process
690 the connection. The parent continues listening. */
691 if ((pid = fork()) == 0)
692 {
693 /* Child. Close the listening socket, and start using
694 the accepted socket. Reinitialize logging (since our
695 pid has changed). We break out of the loop to handle
696 the connection. */
697 close(listen_sock);
698 sock_in = newsock;
699 sock_out = newsock;
6a17f9c2 700 log_init(av0, options.log_level, options.log_facility, log_stderr);
8efc0c15 701 break;
702 }
703 }
704
705 /* Parent. Stay in the loop. */
706 if (pid < 0)
707 error("fork: %.100s", strerror(errno));
708 else
709 debug("Forked child %d.", pid);
710
711 /* Mark that the key has been used (it was "given" to the child). */
712 key_used = 1;
713
714 arc4random_stir();
715
716 /* Close the new socket (the child is now taking care of it). */
717 close(newsock);
718 }
719 }
720
721 /* This is the child processing a new connection. */
722
723 /* Disable the key regeneration alarm. We will not regenerate the key
724 since we are no longer in a position to give it to anyone. We will
725 not restart on SIGHUP since it no longer makes sense. */
726 alarm(0);
727 signal(SIGALRM, SIG_DFL);
728 signal(SIGHUP, SIG_DFL);
729 signal(SIGTERM, SIG_DFL);
730 signal(SIGQUIT, SIG_DFL);
731 signal(SIGCHLD, SIG_DFL);
732
733 /* Set socket options for the connection. We want the socket to close
734 as fast as possible without waiting for anything. If the connection
735 is not a socket, these will do nothing. */
736 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
737 linger.l_onoff = 1;
738 linger.l_linger = 5;
739 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
740
741 /* Register our connection. This turns encryption off because we do not
742 have a key. */
743 packet_set_connection(sock_in, sock_out);
744
e7c0f9d5 745 remote_port = get_remote_port();
746
8efc0c15 747 /* Check whether logins are denied from this host. */
748#ifdef LIBWRAP
749 {
750 struct request_info req;
751
752 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
753 fromhost(&req);
754
755 if (!hosts_access(&req)) {
756 close(sock_in);
757 close(sock_out);
758 refuse(&req);
759 }
e7c0f9d5 760 log("Connection from %.500s port %d", eval_client(&req), remote_port);
8efc0c15 761 }
762#else
763 /* Log the connection. */
e7c0f9d5 764 log("Connection from %.100s port %d", get_remote_ipaddr(), remote_port);
8efc0c15 765#endif /* LIBWRAP */
766
767 /* We don\'t want to listen forever unless the other side successfully
768 authenticates itself. So we set up an alarm which is cleared after
769 successful authentication. A limit of zero indicates no limit.
770 Note that we don\'t set the alarm in debugging mode; it is just annoying
771 to have the server exit just when you are about to discover the bug. */
772 signal(SIGALRM, grace_alarm_handler);
773 if (!debug_flag)
774 alarm(options.login_grace_time);
775
776 /* Send our protocol version identification. */
777 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
778 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
779 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
780 fatal("Could not write ident string.");
781
782 /* Read other side\'s version identification. */
783 for (i = 0; i < sizeof(buf) - 1; i++)
784 {
785 if (read(sock_in, &buf[i], 1) != 1)
786 fatal("Did not receive ident string.");
787 if (buf[i] == '\r')
788 {
789 buf[i] = '\n';
790 buf[i + 1] = 0;
791 break;
792 }
793 if (buf[i] == '\n')
794 {
795 /* buf[i] == '\n' */
796 buf[i + 1] = 0;
797 break;
798 }
799 }
800 buf[sizeof(buf) - 1] = 0;
801
802 /* Check that the versions match. In future this might accept several
803 versions and set appropriate flags to handle them. */
804 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
805 remote_version) != 3)
806 {
807 const char *s = "Protocol mismatch.\n";
808 (void) write(sock_out, s, strlen(s));
809 close(sock_in);
810 close(sock_out);
811 fatal("Bad protocol version identification: %.100s", buf);
812 }
813 debug("Client protocol version %d.%d; client software version %.100s",
814 remote_major, remote_minor, remote_version);
815 if (remote_major != PROTOCOL_MAJOR)
816 {
817 const char *s = "Protocol major versions differ.\n";
818 (void) write(sock_out, s, strlen(s));
819 close(sock_in);
820 close(sock_out);
821 fatal("Protocol major versions differ: %d vs. %d",
822 PROTOCOL_MAJOR, remote_major);
823 }
824
825 /* Check that the client has sufficiently high software version. */
826 if (remote_major == 1 && remote_minor < 3)
827 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
828
829 if (remote_major == 1 && remote_minor == 3) {
830 enable_compat13();
831 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
832 debug("Agent forwarding disabled, remote version is not compatible.");
833 no_agent_forwarding_flag = 1;
834 }
835 }
836
e7c0f9d5 837 /* Check that the connection comes from a privileged port.
838 Rhosts- and Rhosts-RSA-Authentication only make sense
839 from priviledged programs.
840 Of course, if the intruder has root access on his local machine,
841 he can connect from any port. So do not use these authentication
842 methods from machines that you do not trust. */
843 if (remote_port >= IPPORT_RESERVED ||
844 remote_port < IPPORT_RESERVED / 2)
845 {
846 options.rhosts_authentication = 0;
847 options.rhosts_rsa_authentication = 0;
848 }
849
8efc0c15 850 packet_set_nonblocking();
851
e7c0f9d5 852 /* Handle the connection. */
853 do_connection();
8efc0c15 854
855#ifdef KRB4
856 /* Cleanup user's ticket cache file. */
857 if (options.kerberos_ticket_cleanup)
858 (void) dest_tkt();
859#endif /* KRB4 */
860
861 /* Cleanup user's local Xauthority file. */
862 if (xauthfile) unlink(xauthfile);
863
864 /* The connection has been terminated. */
865 log("Closing connection to %.100s", inet_ntoa(sin.sin_addr));
866
5aecb327 867#ifdef HAVE_LIBPAM
d813bc69 868 {
869 int retval;
870
871 if (pamh != NULL)
872 {
549b3eed 873 debug("Closing PAM session.");
d813bc69 874 retval = pam_close_session((pam_handle_t *)pamh, 0);
8efc0c15 875
549b3eed 876 debug("Terminating PAM library.");
d813bc69 877 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
878 log("Cannot release PAM authentication.");
8efc0c15 879
d813bc69 880 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
881 }
882 }
5aecb327 883#endif /* HAVE_LIBPAM */
8efc0c15 884
885 packet_close();
886
887 exit(0);
888}
889
890/* Process an incoming connection. Protocol version identifiers have already
891 been exchanged. This sends server key and performs the key exchange.
892 Server and host keys will no longer be needed after this functions. */
893
e7c0f9d5 894void
895do_connection()
8efc0c15 896{
a61d322f 897 int i, len;
8efc0c15 898 BIGNUM *session_key_int;
899 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
900 unsigned char check_bytes[8];
901 char *user;
902 unsigned int cipher_type, auth_mask, protocol_flags;
903 int plen, slen;
904 u_int32_t rand = 0;
905
906 /* Generate check bytes that the client must send back in the user packet
907 in order for it to be accepted; this is used to defy ip spoofing
908 attacks. Note that this only works against somebody doing IP spoofing
909 from a remote machine; any machine on the local network can still see
910 outgoing packets and catch the random cookie. This only affects
911 rhosts authentication, and this is one of the reasons why it is
912 inherently insecure. */
913 for (i = 0; i < 8; i++) {
914 if (i % 4 == 0)
915 rand = arc4random();
916 check_bytes[i] = rand & 0xff;
917 rand >>= 8;
918 }
919
920 /* Send our public key. We include in the packet 64 bits of random
921 data that must be matched in the reply in order to prevent IP spoofing. */
922 packet_start(SSH_SMSG_PUBLIC_KEY);
923 for (i = 0; i < 8; i++)
924 packet_put_char(check_bytes[i]);
925
926 /* Store our public server RSA key. */
927 packet_put_int(BN_num_bits(public_key->n));
928 packet_put_bignum(public_key->e);
929 packet_put_bignum(public_key->n);
930
931 /* Store our public host RSA key. */
932 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
933 packet_put_bignum(sensitive_data.host_key->e);
934 packet_put_bignum(sensitive_data.host_key->n);
935
936 /* Put protocol flags. */
937 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
938
939 /* Declare which ciphers we support. */
940 packet_put_int(cipher_mask());
941
942 /* Declare supported authentication types. */
943 auth_mask = 0;
944 if (options.rhosts_authentication)
945 auth_mask |= 1 << SSH_AUTH_RHOSTS;
946 if (options.rhosts_rsa_authentication)
947 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
948 if (options.rsa_authentication)
949 auth_mask |= 1 << SSH_AUTH_RSA;
950#ifdef KRB4
951 if (options.kerberos_authentication)
952 auth_mask |= 1 << SSH_AUTH_KERBEROS;
953#endif
954#ifdef AFS
955 if (options.kerberos_tgt_passing)
956 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
957 if (options.afs_token_passing)
958 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
959#endif
960 if (options.password_authentication)
961 auth_mask |= 1 << SSH_AUTH_PASSWORD;
962 packet_put_int(auth_mask);
963
964 /* Send the packet and wait for it to be sent. */
965 packet_send();
966 packet_write_wait();
967
968 debug("Sent %d bit public key and %d bit host key.",
969 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
970
971 /* Read clients reply (cipher type and session key). */
972 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
973
974 /* Get cipher type. */
975 cipher_type = packet_get_char();
976
977 /* Get check bytes from the packet. These must match those we sent earlier
978 with the public key packet. */
979 for (i = 0; i < 8; i++)
980 if (check_bytes[i] != packet_get_char())
981 packet_disconnect("IP Spoofing check bytes do not match.");
982
983 debug("Encryption type: %.200s", cipher_name(cipher_type));
984
985 /* Get the encrypted integer. */
986 session_key_int = BN_new();
987 packet_get_bignum(session_key_int, &slen);
988
989 /* Get protocol flags. */
990 protocol_flags = packet_get_int();
991 packet_set_protocol_flags(protocol_flags);
992
993 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
994
995 /* Decrypt it using our private server key and private host key (key with
996 larger modulus first). */
997 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0)
998 {
999 /* Private key has bigger modulus. */
e1a9c08d 1000 if (BN_num_bits(sensitive_data.private_key->n) <
1001 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1002 fatal("do_connection: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1003 BN_num_bits(sensitive_data.private_key->n),
1004 BN_num_bits(sensitive_data.host_key->n),
1005 SSH_KEY_BITS_RESERVED);
1006 }
1007
8efc0c15 1008 rsa_private_decrypt(session_key_int, session_key_int,
1009 sensitive_data.private_key);
1010 rsa_private_decrypt(session_key_int, session_key_int,
1011 sensitive_data.host_key);
1012 }
1013 else
1014 {
1015 /* Host key has bigger modulus (or they are equal). */
e1a9c08d 1016 if (BN_num_bits(sensitive_data.host_key->n) <
1017 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1018 fatal("do_connection: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1019 BN_num_bits(sensitive_data.host_key->n),
1020 BN_num_bits(sensitive_data.private_key->n),
1021 SSH_KEY_BITS_RESERVED);
1022 }
8efc0c15 1023 rsa_private_decrypt(session_key_int, session_key_int,
1024 sensitive_data.host_key);
1025 rsa_private_decrypt(session_key_int, session_key_int,
1026 sensitive_data.private_key);
1027 }
1028
1029 /* Compute session id for this session. */
1030 compute_session_id(session_id, check_bytes,
8efc0c15 1031 sensitive_data.host_key->n,
8efc0c15 1032 sensitive_data.private_key->n);
1033
1034 /* Extract session key from the decrypted integer. The key is in the
1035 least significant 256 bits of the integer; the first byte of the
1036 key is in the highest bits. */
1037 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
a61d322f 1038 len = BN_num_bytes(session_key_int);
e35c1dc2 1039 if (len < 0 || len > sizeof(session_key))
a61d322f 1040 fatal("do_connection: bad len: session_key_int %d > sizeof(session_key) %d",
1041 len, sizeof(session_key));
1042 memset(session_key, 0, sizeof(session_key));
1043 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
8efc0c15 1044
1045 /* Xor the first 16 bytes of the session key with the session id. */
1046 for (i = 0; i < 16; i++)
1047 session_key[i] ^= session_id[i];
1048
1049 /* Destroy the decrypted integer. It is no longer needed. */
1050 BN_clear_free(session_key_int);
1051
1052 /* Set the session key. From this on all communications will be
1053 encrypted. */
4d195447 1054 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
8efc0c15 1055
1056 /* Destroy our copy of the session key. It is no longer needed. */
1057 memset(session_key, 0, sizeof(session_key));
1058
1059 debug("Received session key; encryption turned on.");
1060
1061 /* Send an acknowledgement packet. Note that this packet is sent
1062 encrypted. */
1063 packet_start(SSH_SMSG_SUCCESS);
1064 packet_send();
1065 packet_write_wait();
1066
1067 /* Get the name of the user that we wish to log in as. */
1068 packet_read_expect(&plen, SSH_CMSG_USER);
1069
1070 /* Get the user name. */
1071 {
1072 int ulen;
1073 user = packet_get_string(&ulen);
1074 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1075 }
1076
1077 /* Destroy the private and public keys. They will no longer be needed. */
1078 RSA_free(public_key);
1079 RSA_free(sensitive_data.private_key);
1080 RSA_free(sensitive_data.host_key);
1081
1082 setproctitle("%s", user);
1083 /* Do the authentication. */
e7c0f9d5 1084 do_authentication(user);
8efc0c15 1085}
1086
1087/* Check if the user is allowed to log in via ssh. If user is listed in
1088 DenyUsers or user's primary group is listed in DenyGroups, false will
1089 be returned. If AllowUsers isn't empty and user isn't listed there, or
1090 if AllowGroups isn't empty and user isn't listed there, false will be
1091 returned. Otherwise true is returned.
1092 XXX This function should also check if user has a valid shell */
1093
1094static int
1095allowed_user(struct passwd *pw)
1096{
1097 struct group *grp;
1098 int i;
1099
1100 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1101 if (!pw)
1102 return 0;
1103
1104 /* XXX Should check for valid login shell */
1105
1106 /* Return false if user is listed in DenyUsers */
1107 if (options.num_deny_users > 0)
1108 {
1109 if (!pw->pw_name)
1110 return 0;
1111 for (i = 0; i < options.num_deny_users; i++)
1112 if (match_pattern(pw->pw_name, options.deny_users[i]))
1113 return 0;
1114 }
1115
1116 /* Return false if AllowUsers isn't empty and user isn't listed there */
1117 if (options.num_allow_users > 0)
1118 {
1119 if (!pw->pw_name)
1120 return 0;
1121 for (i = 0; i < options.num_allow_users; i++)
1122 if (match_pattern(pw->pw_name, options.allow_users[i]))
1123 break;
1124 /* i < options.num_allow_users iff we break for loop */
1125 if (i >= options.num_allow_users)
1126 return 0;
1127 }
1128
1129 /* Get the primary group name if we need it. Return false if it fails */
1130 if (options.num_deny_groups > 0 || options.num_allow_groups > 0 )
1131 {
1132 grp = getgrgid(pw->pw_gid);
1133 if (!grp)
1134 return 0;
1135
1136 /* Return false if user's group is listed in DenyGroups */
1137 if (options.num_deny_groups > 0)
1138 {
1139 if (!grp->gr_name)
1140 return 0;
1141 for (i = 0; i < options.num_deny_groups; i++)
1142 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1143 return 0;
1144 }
1145
1146 /* Return false if AllowGroups isn't empty and user's group isn't
1147 listed there */
1148 if (options.num_allow_groups > 0)
1149 {
1150 if (!grp->gr_name)
1151 return 0;
1152 for (i = 0; i < options.num_allow_groups; i++)
1153 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1154 break;
1155 /* i < options.num_allow_groups iff we break for loop */
1156 if (i >= options.num_allow_groups)
1157 return 0;
1158 }
1159 }
1160
1161 /* We found no reason not to let this user try to log on... */
1162 return 1;
1163}
1164
1165/* Performs authentication of an incoming connection. Session key has already
1166 been exchanged and encryption is enabled. User is the user name to log
e7c0f9d5 1167 in as (received from the client). */
8efc0c15 1168
1169void
e7c0f9d5 1170do_authentication(char *user)
8efc0c15 1171{
8efc0c15 1172 struct passwd *pw, pwcopy;
e7c0f9d5 1173
8efc0c15 1174#ifdef AFS
1175 /* If machine has AFS, set process authentication group. */
1176 if (k_hasafs()) {
1177 k_setpag();
1178 k_unlog();
1179 }
1180#endif /* AFS */
1181
1182 /* Verify that the user is a valid user. */
1183 pw = getpwnam(user);
8efc0c15 1184 if (!pw || !allowed_user(pw))
e7c0f9d5 1185 do_fake_authloop(user);
1186
8efc0c15 1187 /* Take a copy of the returned structure. */
1188 memset(&pwcopy, 0, sizeof(pwcopy));
1189 pwcopy.pw_name = xstrdup(pw->pw_name);
1190 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1191 pwcopy.pw_uid = pw->pw_uid;
1192 pwcopy.pw_gid = pw->pw_gid;
1193 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1194 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1195 pw = &pwcopy;
1196
5aecb327 1197#ifdef HAVE_LIBPAM
c75a1a66 1198 {
1199 int pam_retval;
1200
1201 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
e7c0f9d5 1202
c75a1a66 1203 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1204 if (pam_retval != PAM_SUCCESS)
96ad4350 1205 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 1206
c75a1a66 1207 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1208 }
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);
e7c0f9d5 1227 } else {
1228 /* Loop until the user has been authenticated or the connection is closed,
1229 do_authloop() returns only if authentication is successfull */
1230 do_authloop(pw);
8efc0c15 1231 }
e7c0f9d5 1232
1233 /* XXX log unified auth message */
1234
1235 /* Check if the user is logging in as root and root logins are disallowed. */
1236 if (pw->pw_uid == 0 && !options.permit_root_login)
8efc0c15 1237 {
e7c0f9d5 1238 if (forced_command)
1239 log("Root login accepted for forced command.");
1240 else
1241 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1242 get_canonical_hostname());
8efc0c15 1243 }
1244
e7c0f9d5 1245 /* The user has been authenticated and accepted. */
1246 packet_start(SSH_SMSG_SUCCESS);
1247 packet_send();
1248 packet_write_wait();
8efc0c15 1249
e7c0f9d5 1250 /* Perform session preparation. */
1251 do_authenticated(pw);
1252}
8efc0c15 1253
e7c0f9d5 1254#define MAX_AUTH_FAILURES 5
1255
1256/* read packets and try to authenticate local user *pw.
1257 return if authentication is successfull */
1258void
1259do_authloop(struct passwd *pw)
1260{
1261 int authentication_failures = 0;
4d195447 1262 unsigned int bits;
e7c0f9d5 1263 BIGNUM *client_host_key_e, *client_host_key_n;
1264 BIGNUM *n;
c75a1a66 1265 char *client_user = NULL, *password = NULL;
e7c0f9d5 1266 int plen, dlen, nlen, ulen, elen;
c75a1a66 1267#ifdef HAVE_LIBPAM
1268 int pam_retval;
1269#endif /* HAVE_LIBPAM */
e7c0f9d5 1270
1271 /* Indicate that authentication is needed. */
1272 packet_start(SSH_SMSG_FAILURE);
1273 packet_send();
1274 packet_write_wait();
1275
1276 for (;;) {
1277 int authenticated = 0;
1278
1279 /* Get a packet from the client. */
1280 int type = packet_read(&plen);
1281
1282 /* Process the packet. */
1283 switch (type)
1284 {
1285#ifdef AFS
1286 case SSH_CMSG_HAVE_KERBEROS_TGT:
1287 if (!options.kerberos_tgt_passing)
1288 {
8efc0c15 1289 /* packet_get_all(); */
e7c0f9d5 1290 log("Kerberos tgt passing disabled.");
8efc0c15 1291 break;
1292 }
e7c0f9d5 1293 else {
1294 /* Accept Kerberos tgt. */
1295 char *tgt = packet_get_string(&dlen);
1296 packet_integrity_check(plen, 4 + dlen, type);
1297 if (!auth_kerberos_tgt(pw, tgt))
1298 debug("Kerberos tgt REFUSED for %s", pw->pw_name);
1299 xfree(tgt);
1300 }
1301 continue;
1302
1303 case SSH_CMSG_HAVE_AFS_TOKEN:
1304 if (!options.afs_token_passing || !k_hasafs()) {
1305 /* packet_get_all(); */
1306 log("AFS token passing disabled.");
1307 break;
1308 }
1309 else {
1310 /* Accept AFS token. */
1311 char *token_string = packet_get_string(&dlen);
1312 packet_integrity_check(plen, 4 + dlen, type);
1313 if (!auth_afs_token(pw, token_string))
1314 debug("AFS token REFUSED for %s", pw->pw_name);
1315 xfree(token_string);
1316 }
1317 continue;
8efc0c15 1318#endif /* AFS */
8efc0c15 1319
e7c0f9d5 1320#ifdef KRB4
1321 case SSH_CMSG_AUTH_KERBEROS:
1322 if (!options.kerberos_authentication)
1323 {
1324 /* packet_get_all(); */
1325 log("Kerberos authentication disabled.");
1326 break;
8efc0c15 1327 }
e7c0f9d5 1328 else {
1329 /* Try Kerberos v4 authentication. */
1330 KTEXT_ST auth;
1331 char *tkt_user = NULL;
1332 char *kdata = packet_get_string((unsigned int *)&auth.length);
1333 packet_integrity_check(plen, 4 + auth.length, type);
1334
1335 if (auth.length < MAX_KTXT_LEN)
1336 memcpy(auth.dat, kdata, auth.length);
1337 xfree(kdata);
8efc0c15 1338
e7c0f9d5 1339 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1340
1341 log("Kerberos authentication %s%s for account %s from %s",
1342 authenticated ? "accepted " : "failed",
1343 tkt_user != NULL ? tkt_user : "",
1344 pw->pw_name, get_canonical_hostname());
1345 if (authenticated)
1346 xfree(tkt_user);
1347 }
1348 break;
1349#endif /* KRB4 */
1350
1351 case SSH_CMSG_AUTH_RHOSTS:
1352 if (!options.rhosts_authentication)
8efc0c15 1353 {
e7c0f9d5 1354 log("Rhosts authentication disabled.");
1355 break;
8efc0c15 1356 }
e7c0f9d5 1357
1358 /* Get client user name. Note that we just have to trust the client;
1359 this is one reason why rhosts authentication is insecure.
1360 (Another is IP-spoofing on a local network.) */
1361 client_user = packet_get_string(&dlen);
1362 packet_integrity_check(plen, 4 + dlen, type);
1363
1364 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */
1365 authenticated = auth_rhosts(pw, client_user);
8efc0c15 1366
e7c0f9d5 1367 log("Rhosts authentication %s for %.100s, remote %.100s on %.700s.",
1368 authenticated ? "accepted" : "failed",
1369 pw->pw_name, client_user, get_canonical_hostname());
5aecb327 1370#ifndef HAVE_LIBPAM
e7c0f9d5 1371 xfree(client_user);
5aecb327 1372#endif /* HAVE_LIBPAM */
e7c0f9d5 1373 break;
1374
1375 case SSH_CMSG_AUTH_RHOSTS_RSA:
1376 if (!options.rhosts_rsa_authentication)
8efc0c15 1377 {
e7c0f9d5 1378 log("Rhosts with RSA authentication disabled.");
1379 break;
8efc0c15 1380 }
e7c0f9d5 1381
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();
4d195447 1390 bits = packet_get_int();
e7c0f9d5 1391 packet_get_bignum(client_host_key_e, &elen);
1392 packet_get_bignum(client_host_key_n, &nlen);
4d195447 1393
1394 if (bits != BN_num_bits(client_host_key_n))
1395 error("Warning: keysize mismatch for client_host_key: "
2ad77510 1396 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
e7c0f9d5 1397 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1398
4d195447 1399 authenticated = auth_rhosts_rsa(pw, client_user,
e7c0f9d5 1400 client_host_key_e, client_host_key_n);
1401 log("Rhosts authentication %s for %.100s, remote %.100s.",
1402 authenticated ? "accepted" : "failed",
1403 pw->pw_name, client_user);
5aecb327 1404#ifndef HAVE_LIBPAM
e7c0f9d5 1405 xfree(client_user);
5aecb327 1406#endif /* HAVE_LIBPAM */
e7c0f9d5 1407 BN_clear_free(client_host_key_e);
1408 BN_clear_free(client_host_key_n);
1409 break;
1410
1411 case SSH_CMSG_AUTH_RSA:
1412 if (!options.rsa_authentication)
8efc0c15 1413 {
e7c0f9d5 1414 log("RSA authentication disabled.");
1415 break;
8efc0c15 1416 }
e7c0f9d5 1417
1418 /* RSA authentication requested. */
1419 n = BN_new();
1420 packet_get_bignum(n, &nlen);
1421 packet_integrity_check(plen, nlen, type);
2bd61362 1422
e7c0f9d5 1423 authenticated = auth_rsa(pw, n);
e7c0f9d5 1424 log("RSA authentication %s for %.100s.",
1425 authenticated ? "accepted" : "failed",
1426 pw->pw_name);
2bd61362 1427 BN_clear_free(n);
e7c0f9d5 1428 break;
1429
1430 case SSH_CMSG_AUTH_PASSWORD:
1431 if (!options.password_authentication)
8efc0c15 1432 {
e7c0f9d5 1433 log("Password authentication disabled.");
1434 break;
8efc0c15 1435 }
e7c0f9d5 1436
1437 /* Read user password. It is in plain text, but was transmitted
1438 over the encrypted channel so it is not visible to an outside
1439 observer. */
1440 password = packet_get_string(&dlen);
1441 packet_integrity_check(plen, 4 + dlen, type);
1442
5aecb327 1443#ifdef HAVE_LIBPAM
c75a1a66 1444 /* Do PAM auth with password */
e7c0f9d5 1445 pampasswd = password;
c75a1a66 1446 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
e7c0f9d5 1447 if (pam_retval == PAM_SUCCESS)
1448 {
c75a1a66 1449 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name);
e7c0f9d5 1450 authenticated = 1;
1451 break;
1452 }
c75a1a66 1453
1454 log("PAM Password authentication for \"%.100s\" failed: %s",
96ad4350 1455 pw->pw_name, PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
e7c0f9d5 1456 break;
5aecb327 1457#else /* HAVE_LIBPAM */
e7c0f9d5 1458 /* Try authentication with the password. */
1459 authenticated = auth_password(pw, password);
2bd61362 1460 log("Password authentication %s for %.100s.",
1461 authenticated ? "accepted" : "failed",
1462 pw->pw_name);
8efc0c15 1463
e7c0f9d5 1464 memset(password, 0, strlen(password));
1465 xfree(password);
8efc0c15 1466 break;
e7c0f9d5 1467#endif /* HAVE_LIBPAM */
1468
1469 case SSH_CMSG_AUTH_TIS:
1470 /* TIS Authentication is unsupported */
1471 log("TIS authentication disabled.");
1472 break;
1473
1474 default:
1475 /* Any unknown messages will be ignored (and failure returned)
1476 during authentication. */
1477 log("Unknown message during authentication: type %d", type);
1478 break; /* Respond with a failure message. */
8efc0c15 1479 }
e35c1dc2 1480
e7c0f9d5 1481 if (authenticated)
1482 break;
1483 if (++authentication_failures >= MAX_AUTH_FAILURES)
1484 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1485 pw->pw_name, get_canonical_hostname());
1486 /* Send a message indicating that the authentication attempt failed. */
1487 packet_start(SSH_SMSG_FAILURE);
1488 packet_send();
1489 packet_write_wait();
1490 }
8efc0c15 1491
5aecb327 1492#ifdef HAVE_LIBPAM
e7c0f9d5 1493 do_pam_account_and_session(pw->pw_name, client_user, get_canonical_hostname());
d813bc69 1494
1495 /* Clean up */
1496 if (client_user != NULL)
1497 xfree(client_user);
1498
1499 if (password != NULL)
1500 {
1501 memset(password, 0, strlen(password));
1502 xfree(password);
1503 }
5aecb327 1504#endif /* HAVE_LIBPAM */
8efc0c15 1505}
1506
e7c0f9d5 1507/* The user does not exist or access is denied,
1508 but fake indication that authentication is needed. */
1509void
1510do_fake_authloop(char *user)
0183ea1c 1511{
1512 int authentication_failures = 0;
e7c0f9d5 1513
1514 /* Indicate that authentication is needed. */
0183ea1c 1515 packet_start(SSH_SMSG_FAILURE);
1516 packet_send();
1517 packet_write_wait();
1518
1519 /* Keep reading packets, and always respond with a failure. This is to
1520 avoid disclosing whether such a user really exists. */
e7c0f9d5 1521 for (;;)
0183ea1c 1522 {
e7c0f9d5 1523 /* Read a packet. This will not return if the client disconnects. */
1524 int plen;
1525 int type = packet_read(&plen);
1526#ifdef SKEY
1527 int passw_len;
1528 char *password, *skeyinfo;
1529 if (options.password_authentication &&
1530 options.skey_authentication == 1 &&
1531 type == SSH_CMSG_AUTH_PASSWORD &&
1532 (password = packet_get_string(&passw_len)) != NULL &&
1533 passw_len == 5 &&
1534 strncasecmp(password, "s/key", 5) == 0 &&
1535 (skeyinfo = skey_fake_keyinfo(user)) != NULL ){
1536 /* Send a fake s/key challenge. */
1537 packet_send_debug(skeyinfo);
1538 }
1539#endif
1540 if (++authentication_failures >= MAX_AUTH_FAILURES)
1541 packet_disconnect("Too many authentication failures for %.100s from %.200s",
1542 user, get_canonical_hostname());
1543 /* Send failure. This should be indistinguishable from a failed
1544 authentication. */
1545 packet_start(SSH_SMSG_FAILURE);
1546 packet_send();
1547 packet_write_wait();
0183ea1c 1548 }
0183ea1c 1549 /*NOTREACHED*/
1550 abort();
1551}
1552
e7c0f9d5 1553
6a17f9c2 1554/* Remove local Xauthority file. */
1555static void
1556xauthfile_cleanup_proc(void *ignore)
1557{
1558 debug("xauthfile_cleanup_proc called");
1559
1560 if (xauthfile != NULL) {
1561 unlink(xauthfile);
1562 xfree(xauthfile);
1563 xauthfile = NULL;
1564 }
1565}
1566
8efc0c15 1567/* Prepares for an interactive session. This is called after the user has
1568 been successfully authenticated. During this message exchange, pseudo
1569 terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1570 are requested, etc. */
1571
1572void do_authenticated(struct passwd *pw)
1573{
1574 int type;
1575 int compression_level = 0, enable_compression_after_reply = 0;
1576 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1577 int row, col, xpixel, ypixel, screen;
1578 char ttyname[64];
1579 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL;
1580 struct group *grp;
1581 gid_t tty_gid;
1582 mode_t tty_mode;
1583 int n_bytes;
1584
1585 /* Cancel the alarm we set to limit the time taken for authentication. */
1586 alarm(0);
1587
1588 /* Inform the channel mechanism that we are the server side and that
1589 the client may request to connect to any port at all. (The user could
1590 do it anyway, and we wouldn\'t know what is permitted except by the
1591 client telling us, so we can equally well trust the client not to request
1592 anything bogus.) */
1593 channel_permit_all_opens();
1594
1595 /* We stay in this loop until the client requests to execute a shell or a
1596 command. */
1597 while (1)
1598 {
1599 int plen, dlen;
1600
1601 /* Get a packet from the client. */
1602 type = packet_read(&plen);
1603
1604 /* Process the packet. */
1605 switch (type)
1606 {
1607 case SSH_CMSG_REQUEST_COMPRESSION:
1608 packet_integrity_check(plen, 4, type);
1609 compression_level = packet_get_int();
1610 if (compression_level < 1 || compression_level > 9)
1611 {
1612 packet_send_debug("Received illegal compression level %d.",
1613 compression_level);
1614 goto fail;
1615 }
1616 /* Enable compression after we have responded with SUCCESS. */
1617 enable_compression_after_reply = 1;
1618 break;
1619
1620 case SSH_CMSG_REQUEST_PTY:
1621 if (no_pty_flag)
1622 {
1623 debug("Allocating a pty not permitted for this authentication.");
1624 goto fail;
1625 }
1626 if (have_pty)
1627 packet_disconnect("Protocol error: you already have a pty.");
1628
1629 debug("Allocating pty.");
1630
1631 /* Allocate a pty and open it. */
1632 if (!pty_allocate(&ptyfd, &ttyfd, ttyname))
1633 {
1634 error("Failed to allocate pty.");
1635 goto fail;
1636 }
1637
1638 /* Determine the group to make the owner of the tty. */
1639 grp = getgrnam("tty");
1640 if (grp)
1641 {
1642 tty_gid = grp->gr_gid;
1643 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP;
1644 }
1645 else
1646 {
1647 tty_gid = pw->pw_gid;
1648 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH;
1649 }
1650
1651 /* Change ownership of the tty. */
1652 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1653 fatal("chown(%.100s, %d, %d) failed: %.100s",
1654 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1655 if (chmod(ttyname, tty_mode) < 0)
1656 fatal("chmod(%.100s, 0%o) failed: %.100s",
1657 ttyname, tty_mode, strerror(errno));
1658
1659 /* Get TERM from the packet. Note that the value may be of arbitrary
1660 length. */
1661
1662 term = packet_get_string(&dlen);
1663 packet_integrity_check(dlen, strlen(term), type);
1664 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1665 /* Remaining bytes */
1666 n_bytes = plen - (4 + dlen + 4*4);
1667
1668 if (strcmp(term, "") == 0)
1669 term = NULL;
1670
1671 /* Get window size from the packet. */
1672 row = packet_get_int();
1673 col = packet_get_int();
1674 xpixel = packet_get_int();
1675 ypixel = packet_get_int();
1676 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1677
1678 /* Get tty modes from the packet. */
1679 tty_parse_modes(ttyfd, &n_bytes);
1680 packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type);
1681
1682 /* Indicate that we now have a pty. */
1683 have_pty = 1;
1684 break;
1685
1686 case SSH_CMSG_X11_REQUEST_FORWARDING:
1687 if (!options.x11_forwarding)
1688 {
1689 packet_send_debug("X11 forwarding disabled in server configuration file.");
1690 goto fail;
1691 }
1692#ifdef XAUTH_PATH
1693 if (no_x11_forwarding_flag)
1694 {
1695 packet_send_debug("X11 forwarding not permitted for this authentication.");
1696 goto fail;
1697 }
1698 debug("Received request for X11 forwarding with auth spoofing.");
1699 if (display)
1700 packet_disconnect("Protocol error: X11 display already set.");
1701 {
1702 int proto_len, data_len;
1703 proto = packet_get_string(&proto_len);
1704 data = packet_get_string(&data_len);
1705 packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type);
1706 }
1707 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1708 screen = packet_get_int();
1709 else
1710 screen = 0;
1711 display = x11_create_display_inet(screen);
1712 if (!display)
1713 goto fail;
1714
1715 /* Setup to always have a local .Xauthority. */
1716 xauthfile = xmalloc(MAXPATHLEN);
1717 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1718
1719 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1720 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1721 close(xauthfd);
6a17f9c2 1722 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
8efc0c15 1723 }
1724 else {
1725 xfree(xauthfile);
1726 xauthfile = NULL;
1727 }
1728 break;
1729#else /* XAUTH_PATH */
1730 /* No xauth program; we won't accept forwarding with spoofing. */
1731 packet_send_debug("No xauth program; cannot forward with spoofing.");
1732 goto fail;
1733#endif /* XAUTH_PATH */
1734
1735 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1736 if (no_agent_forwarding_flag)
1737 {
1738 debug("Authentication agent forwarding not permitted for this authentication.");
1739 goto fail;
1740 }
1741 debug("Received authentication agent forwarding request.");
1742 auth_input_request_forwarding(pw);
1743 break;
1744
1745 case SSH_CMSG_PORT_FORWARD_REQUEST:
1746 if (no_port_forwarding_flag)
1747 {
1748 debug("Port forwarding not permitted for this authentication.");
1749 goto fail;
1750 }
1751 debug("Received TCP/IP port forwarding request.");
1752 channel_input_port_forward_request(pw->pw_uid == 0);
1753 break;
1754
9d6b7add 1755 case SSH_CMSG_MAX_PACKET_SIZE:
1756 if (packet_set_maxsize(packet_get_int()) < 0)
1757 goto fail;
1758 break;
1759
8efc0c15 1760 case SSH_CMSG_EXEC_SHELL:
1761 /* Set interactive/non-interactive mode. */
1762 packet_set_interactive(have_pty || display != NULL,
1763 options.keepalives);
1764
1765 if (forced_command != NULL)
1766 goto do_forced_command;
1767 debug("Forking shell.");
1768 packet_integrity_check(plen, 0, type);
1769 if (have_pty)
1770 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto,
1771 data);
1772 else
1773 do_exec_no_pty(NULL, pw, display, proto, data);
1774 return;
1775
1776 case SSH_CMSG_EXEC_CMD:
1777 /* Set interactive/non-interactive mode. */
1778 packet_set_interactive(have_pty || display != NULL,
1779 options.keepalives);
1780
1781 if (forced_command != NULL)
1782 goto do_forced_command;
1783 /* Get command from the packet. */
1784 {
1785 int dlen;
1786 command = packet_get_string(&dlen);
1787 debug("Executing command '%.500s'", command);
1788 packet_integrity_check(plen, 4 + dlen, type);
1789 }
1790 if (have_pty)
1791 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display,
1792 proto, data);
1793 else
1794 do_exec_no_pty(command, pw, display, proto, data);
1795 xfree(command);
1796 return;
1797
8efc0c15 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 2.189475 seconds and 5 git commands to generate.