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