]> andersk Git - openssh.git/blame - sshconnect.c
- Generate manpages before make install not at the end of make all
[openssh.git] / sshconnect.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: Sat Mar 18 22:15:47 1995 ylo
6 * Code to connect to a remote host, and to perform the client side of the
7 * login (authentication) dialog.
8 */
8efc0c15 9
10#include "includes.h"
4fe2af09 11RCSID("$OpenBSD: sshconnect.c,v 1.58 2000/03/23 22:15:33 markus Exp $");
8efc0c15 12
5881cd60 13#ifdef HAVE_OPENSSL
4fe2af09 14#include <openssl/rsa.h>
15#include <openssl/dsa.h>
5881cd60 16#include <openssl/md5.h>
4fe2af09 17#include <openssl/bn.h>
5881cd60 18#endif
19#ifdef HAVE_SSL
4fe2af09 20#include <ssl/rsa.h>
21#include <ssl/dsa.h>
5881cd60 22#include <ssl/md5.h>
4fe2af09 23#include <ssl/bn.h>
5881cd60 24#endif
25
8efc0c15 26#include "xmalloc.h"
27#include "rsa.h"
28#include "ssh.h"
29#include "packet.h"
30#include "authfd.h"
31#include "cipher.h"
32#include "mpaux.h"
33#include "uidswap.h"
34#include "compat.h"
6fa724bc 35#include "readconf.h"
4fe2af09 36#include "key.h"
37#include "hostfile.h"
8efc0c15 38
39/* Session id for the current session. */
40unsigned char session_id[16];
41
7b2ea3a1 42/* authentications supported by server */
43unsigned int supported_authentications;
44
57112b5a 45extern Options options;
48e671d5 46extern char *__progname;
57112b5a 47
5260325f 48/*
49 * Connect to the given ssh server using a proxy command.
50 */
8efc0c15 51int
57112b5a 52ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
8efc0c15 53 const char *proxy_command)
54{
5260325f 55 Buffer command;
56 const char *cp;
57 char *command_string;
58 int pin[2], pout[2];
59 int pid;
48e671d5 60 char strport[NI_MAXSERV];
5260325f 61
62 /* Convert the port number into a string. */
48e671d5 63 snprintf(strport, sizeof strport, "%hu", port);
5260325f 64
65 /* Build the final command string in the buffer by making the
66 appropriate substitutions to the given proxy command. */
67 buffer_init(&command);
68 for (cp = proxy_command; *cp; cp++) {
69 if (cp[0] == '%' && cp[1] == '%') {
70 buffer_append(&command, "%", 1);
71 cp++;
72 continue;
73 }
74 if (cp[0] == '%' && cp[1] == 'h') {
75 buffer_append(&command, host, strlen(host));
76 cp++;
77 continue;
78 }
79 if (cp[0] == '%' && cp[1] == 'p') {
48e671d5 80 buffer_append(&command, strport, strlen(strport));
5260325f 81 cp++;
82 continue;
83 }
84 buffer_append(&command, cp, 1);
8efc0c15 85 }
5260325f 86 buffer_append(&command, "\0", 1);
87
88 /* Get the final command string. */
89 command_string = buffer_ptr(&command);
90
91 /* Create pipes for communicating with the proxy. */
92 if (pipe(pin) < 0 || pipe(pout) < 0)
93 fatal("Could not create pipes to communicate with the proxy: %.100s",
94 strerror(errno));
95
96 debug("Executing proxy command: %.500s", command_string);
97
98 /* Fork and execute the proxy command. */
99 if ((pid = fork()) == 0) {
100 char *argv[10];
101
102 /* Child. Permanently give up superuser privileges. */
103 permanently_set_uid(original_real_uid);
104
105 /* Redirect stdin and stdout. */
106 close(pin[1]);
107 if (pin[0] != 0) {
108 if (dup2(pin[0], 0) < 0)
109 perror("dup2 stdin");
110 close(pin[0]);
111 }
112 close(pout[0]);
113 if (dup2(pout[1], 1) < 0)
114 perror("dup2 stdout");
115 /* Cannot be 1 because pin allocated two descriptors. */
116 close(pout[1]);
117
118 /* Stderr is left as it is so that error messages get
119 printed on the user's terminal. */
120 argv[0] = "/bin/sh";
121 argv[1] = "-c";
122 argv[2] = command_string;
123 argv[3] = NULL;
124
125 /* Execute the proxy command. Note that we gave up any
126 extra privileges above. */
127 execv("/bin/sh", argv);
128 perror("/bin/sh");
129 exit(1);
8efc0c15 130 }
5260325f 131 /* Parent. */
132 if (pid < 0)
133 fatal("fork failed: %.100s", strerror(errno));
134
135 /* Close child side of the descriptors. */
136 close(pin[0]);
137 close(pout[1]);
138
139 /* Free the command name. */
140 buffer_free(&command);
141
142 /* Set the connection file descriptors. */
143 packet_set_connection(pout[0], pin[1]);
8efc0c15 144
5260325f 145 return 1;
146}
8efc0c15 147
5260325f 148/*
149 * Creates a (possibly privileged) socket for use as the ssh connection.
150 */
151int
48e671d5 152ssh_create_socket(uid_t original_real_uid, int privileged, int family)
8efc0c15 153{
5260325f 154 int sock;
155
aa3378df 156 /*
157 * If we are running as root and want to connect to a privileged
158 * port, bind our own socket to a privileged port.
159 */
5260325f 160 if (privileged) {
161 int p = IPPORT_RESERVED - 1;
48e671d5 162 sock = rresvport_af(&p, family);
5260325f 163 if (sock < 0)
c8d54615 164 error("rresvport: af=%d %.100s", family, strerror(errno));
165 else
166 debug("Allocated local port %d.", p);
5260325f 167 } else {
95f1eccc 168 /*
169 * Just create an ordinary socket on arbitrary port. We use
170 * the user's uid to create the socket.
171 */
5260325f 172 temporarily_use_uid(original_real_uid);
48e671d5 173 sock = socket(family, SOCK_STREAM, 0);
5260325f 174 if (sock < 0)
48e671d5 175 error("socket: %.100s", strerror(errno));
5260325f 176 restore_uid();
177 }
178 return sock;
8efc0c15 179}
180
5260325f 181/*
48e671d5 182 * Opens a TCP/IP connection to the remote server on the given host.
183 * The address of the remote host will be returned in hostaddr.
184 * If port is 0, the default port will be used. If anonymous is zero,
5260325f 185 * a privileged port will be allocated to make the connection.
186 * This requires super-user privileges if anonymous is false.
187 * Connection_attempts specifies the maximum number of tries (one per
188 * second). If proxy_command is non-NULL, it specifies the command (with %h
189 * and %p substituted for host and port, respectively) to use to contact
190 * the daemon.
191 */
192int
48e671d5 193ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
57112b5a 194 u_short port, int connection_attempts,
5260325f 195 int anonymous, uid_t original_real_uid,
196 const char *proxy_command)
8efc0c15 197{
48e671d5 198 int sock = -1, attempt;
5260325f 199 struct servent *sp;
48e671d5 200 struct addrinfo hints, *ai, *aitop;
201 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
202 int gaierr;
5260325f 203 struct linger linger;
204
205 debug("ssh_connect: getuid %d geteuid %d anon %d",
206 (int) getuid(), (int) geteuid(), anonymous);
207
208 /* Get default port if port has not been set. */
209 if (port == 0) {
210 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
211 if (sp)
212 port = ntohs(sp->s_port);
213 else
214 port = SSH_DEFAULT_PORT;
8efc0c15 215 }
5260325f 216 /* If a proxy command is given, connect using it. */
217 if (proxy_command != NULL)
218 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
219
220 /* No proxy command. */
221
48e671d5 222 memset(&hints, 0, sizeof(hints));
223 hints.ai_family = IPv4or6;
224 hints.ai_socktype = SOCK_STREAM;
225 snprintf(strport, sizeof strport, "%d", port);
226 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
227 fatal("%s: %.100s: %s", __progname, host,
228 gai_strerror(gaierr));
5260325f 229
95f1eccc 230 /*
231 * Try to connect several times. On some machines, the first time
232 * will sometimes fail. In general socket code appears to behave
233 * quite magically on many machines.
234 */
5260325f 235 for (attempt = 0; attempt < connection_attempts; attempt++) {
236 if (attempt > 0)
237 debug("Trying again...");
238
48e671d5 239 /* Loop through addresses for this host, and try each one in
240 sequence until the connection succeeds. */
241 for (ai = aitop; ai; ai = ai->ai_next) {
242 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
243 continue;
244 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
245 ntop, sizeof(ntop), strport, sizeof(strport),
246 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
247 error("ssh_connect: getnameinfo failed");
248 continue;
249 }
250 debug("Connecting to %.200s [%.100s] port %s.",
251 host, ntop, strport);
252
253 /* Create a socket for connecting. */
254 sock = ssh_create_socket(original_real_uid,
255 !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
256 ai->ai_family);
257 if (sock < 0)
258 continue;
259
260 /* Connect to the host. We use the user's uid in the
261 * hope that it will help with tcp_wrappers showing
262 * the remote uid as root.
aa3378df 263 */
5260325f 264 temporarily_use_uid(original_real_uid);
48e671d5 265 if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
266 /* Successful connection. */
267 memcpy(hostaddr, ai->ai_addr, sizeof(*(ai->ai_addr)));
5260325f 268 restore_uid();
269 break;
48e671d5 270 } else {
5260325f 271 debug("connect: %.100s", strerror(errno));
272 restore_uid();
aa3378df 273 /*
274 * Close the failed socket; there appear to
275 * be some problems when reusing a socket for
276 * which connect() has already returned an
277 * error.
278 */
5260325f 279 shutdown(sock, SHUT_RDWR);
280 close(sock);
281 }
8efc0c15 282 }
48e671d5 283 if (ai)
284 break; /* Successful connection. */
8efc0c15 285
5260325f 286 /* Sleep a moment before retrying. */
287 sleep(1);
288 }
48e671d5 289
290 freeaddrinfo(aitop);
291
5260325f 292 /* Return failure if we didn't get a successful connection. */
293 if (attempt >= connection_attempts)
294 return 0;
8efc0c15 295
5260325f 296 debug("Connection established.");
8efc0c15 297
aa3378df 298 /*
299 * Set socket options. We would like the socket to disappear as soon
300 * as it has been closed for whatever reason.
301 */
302 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
5260325f 303 linger.l_onoff = 1;
304 linger.l_linger = 5;
305 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
8efc0c15 306
5260325f 307 /* Set the connection. */
308 packet_set_connection(sock, sock);
8efc0c15 309
5260325f 310 return 1;
8efc0c15 311}
312
5260325f 313/*
314 * Checks if the user has an authentication agent, and if so, tries to
315 * authenticate using the agent.
316 */
8efc0c15 317int
318try_agent_authentication()
319{
5260325f 320 int status, type;
321 char *comment;
322 AuthenticationConnection *auth;
323 unsigned char response[16];
324 unsigned int i;
325 BIGNUM *e, *n, *challenge;
326
327 /* Get connection to the agent. */
328 auth = ssh_get_authentication_connection();
329 if (!auth)
330 return 0;
331
332 e = BN_new();
333 n = BN_new();
334 challenge = BN_new();
335
336 /* Loop through identities served by the agent. */
337 for (status = ssh_get_first_identity(auth, e, n, &comment);
338 status;
339 status = ssh_get_next_identity(auth, e, n, &comment)) {
340 int plen, clen;
341
342 /* Try this identity. */
343 debug("Trying RSA authentication via agent with '%.100s'", comment);
344 xfree(comment);
345
346 /* Tell the server that we are willing to authenticate using this key. */
347 packet_start(SSH_CMSG_AUTH_RSA);
348 packet_put_bignum(n);
349 packet_send();
350 packet_write_wait();
351
352 /* Wait for server's response. */
353 type = packet_read(&plen);
354
355 /* The server sends failure if it doesn\'t like our key or
356 does not support RSA authentication. */
357 if (type == SSH_SMSG_FAILURE) {
358 debug("Server refused our key.");
359 continue;
360 }
361 /* Otherwise it should have sent a challenge. */
362 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
363 packet_disconnect("Protocol error during RSA authentication: %d",
364 type);
8efc0c15 365
5260325f 366 packet_get_bignum(challenge, &clen);
8efc0c15 367
5260325f 368 packet_integrity_check(plen, clen, type);
8efc0c15 369
5260325f 370 debug("Received RSA challenge from server.");
371
372 /* Ask the agent to decrypt the challenge. */
373 if (!ssh_decrypt_challenge(auth, e, n, challenge,
374 session_id, 1, response)) {
375 /* The agent failed to authenticate this identifier although it
376 advertised it supports this. Just return a wrong value. */
377 log("Authentication agent failed to decrypt challenge.");
378 memset(response, 0, sizeof(response));
379 }
380 debug("Sending response to RSA challenge.");
381
382 /* Send the decrypted challenge back to the server. */
383 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
384 for (i = 0; i < 16; i++)
385 packet_put_char(response[i]);
386 packet_send();
387 packet_write_wait();
388
389 /* Wait for response from the server. */
390 type = packet_read(&plen);
391
392 /* The server returns success if it accepted the authentication. */
393 if (type == SSH_SMSG_SUCCESS) {
394 debug("RSA authentication accepted by server.");
395 BN_clear_free(e);
396 BN_clear_free(n);
397 BN_clear_free(challenge);
398 return 1;
399 }
400 /* Otherwise it should return failure. */
401 if (type != SSH_SMSG_FAILURE)
402 packet_disconnect("Protocol error waiting RSA auth response: %d",
403 type);
404 }
405
406 BN_clear_free(e);
407 BN_clear_free(n);
408 BN_clear_free(challenge);
8efc0c15 409
5260325f 410 debug("RSA authentication using agent refused.");
411 return 0;
412}
8efc0c15 413
5260325f 414/*
415 * Computes the proper response to a RSA challenge, and sends the response to
416 * the server.
417 */
8efc0c15 418void
5260325f 419respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
8efc0c15 420{
5260325f 421 unsigned char buf[32], response[16];
422 MD5_CTX md;
423 int i, len;
424
425 /* Decrypt the challenge using the private key. */
426 rsa_private_decrypt(challenge, challenge, prv);
427
428 /* Compute the response. */
429 /* The response is MD5 of decrypted challenge plus session id. */
430 len = BN_num_bytes(challenge);
431 if (len <= 0 || len > sizeof(buf))
432 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
433 len);
434
435 memset(buf, 0, sizeof(buf));
436 BN_bn2bin(challenge, buf + sizeof(buf) - len);
437 MD5_Init(&md);
438 MD5_Update(&md, buf, 32);
439 MD5_Update(&md, session_id, 16);
440 MD5_Final(response, &md);
441
442 debug("Sending response to host key RSA challenge.");
443
444 /* Send the response back to the server. */
445 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
446 for (i = 0; i < 16; i++)
447 packet_put_char(response[i]);
448 packet_send();
449 packet_write_wait();
8efc0c15 450
5260325f 451 memset(buf, 0, sizeof(buf));
452 memset(response, 0, sizeof(response));
453 memset(&md, 0, sizeof(md));
454}
8efc0c15 455
5260325f 456/*
457 * Checks if the user has authentication file, and if so, tries to authenticate
458 * the user using it.
459 */
8efc0c15 460int
57112b5a 461try_rsa_authentication(const char *authfile)
8efc0c15 462{
5260325f 463 BIGNUM *challenge;
464 RSA *private_key;
465 RSA *public_key;
466 char *passphrase, *comment;
467 int type, i;
468 int plen, clen;
469
470 /* Try to load identification for the authentication key. */
471 public_key = RSA_new();
472 if (!load_public_key(authfile, public_key, &comment)) {
473 RSA_free(public_key);
57112b5a 474 /* Could not load it. Fail. */
475 return 0;
8efc0c15 476 }
5260325f 477 debug("Trying RSA authentication with key '%.100s'", comment);
478
479 /* Tell the server that we are willing to authenticate using this key. */
480 packet_start(SSH_CMSG_AUTH_RSA);
481 packet_put_bignum(public_key->n);
482 packet_send();
483 packet_write_wait();
484
485 /* We no longer need the public key. */
486 RSA_free(public_key);
487
488 /* Wait for server's response. */
489 type = packet_read(&plen);
490
aa3378df 491 /*
492 * The server responds with failure if it doesn\'t like our key or
493 * doesn\'t support RSA authentication.
494 */
5260325f 495 if (type == SSH_SMSG_FAILURE) {
496 debug("Server refused our key.");
497 xfree(comment);
57112b5a 498 return 0;
8efc0c15 499 }
5260325f 500 /* Otherwise, the server should respond with a challenge. */
501 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
502 packet_disconnect("Protocol error during RSA authentication: %d", type);
503
504 /* Get the challenge from the packet. */
505 challenge = BN_new();
506 packet_get_bignum(challenge, &clen);
507
508 packet_integrity_check(plen, clen, type);
509
510 debug("Received RSA challenge from server.");
511
512 private_key = RSA_new();
aa3378df 513 /*
514 * Load the private key. Try first with empty passphrase; if it
515 * fails, ask for a passphrase.
516 */
5260325f 517 if (!load_private_key(authfile, "", private_key, NULL)) {
518 char buf[300];
519 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
a408af76 520 comment);
5260325f 521 if (!options.batch_mode)
522 passphrase = read_passphrase(buf, 0);
523 else {
524 debug("Will not query passphrase for %.100s in batch mode.",
525 comment);
526 passphrase = xstrdup("");
527 }
8efc0c15 528
5260325f 529 /* Load the authentication file using the pasphrase. */
530 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
531 memset(passphrase, 0, strlen(passphrase));
532 xfree(passphrase);
533 error("Bad passphrase.");
534
535 /* Send a dummy response packet to avoid protocol error. */
536 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
537 for (i = 0; i < 16; i++)
538 packet_put_char(0);
539 packet_send();
540 packet_write_wait();
541
542 /* Expect the server to reject it... */
543 packet_read_expect(&plen, SSH_SMSG_FAILURE);
544 xfree(comment);
545 return 0;
546 }
547 /* Destroy the passphrase. */
548 memset(passphrase, 0, strlen(passphrase));
549 xfree(passphrase);
550 }
551 /* We no longer need the comment. */
552 xfree(comment);
553
554 /* Compute and send a response to the challenge. */
555 respond_to_rsa_challenge(challenge, private_key);
556
557 /* Destroy the private key. */
558 RSA_free(private_key);
8efc0c15 559
5260325f 560 /* We no longer need the challenge. */
561 BN_clear_free(challenge);
562
563 /* Wait for response from the server. */
564 type = packet_read(&plen);
565 if (type == SSH_SMSG_SUCCESS) {
566 debug("RSA authentication accepted by server.");
567 return 1;
568 }
569 if (type != SSH_SMSG_FAILURE)
570 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
571 debug("RSA authentication refused.");
572 return 0;
573}
8efc0c15 574
5260325f 575/*
576 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
577 * authentication and RSA host authentication.
578 */
8efc0c15 579int
5260325f 580try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
8efc0c15 581{
5260325f 582 int type;
583 BIGNUM *challenge;
584 int plen, clen;
585
586 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
587
588 /* Tell the server that we are willing to authenticate using this key. */
589 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
590 packet_put_string(local_user, strlen(local_user));
591 packet_put_int(BN_num_bits(host_key->n));
592 packet_put_bignum(host_key->e);
593 packet_put_bignum(host_key->n);
594 packet_send();
595 packet_write_wait();
596
597 /* Wait for server's response. */
598 type = packet_read(&plen);
599
600 /* The server responds with failure if it doesn't admit our
601 .rhosts authentication or doesn't know our host key. */
602 if (type == SSH_SMSG_FAILURE) {
603 debug("Server refused our rhosts authentication or host key.");
604 return 0;
605 }
606 /* Otherwise, the server should respond with a challenge. */
607 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
608 packet_disconnect("Protocol error during RSA authentication: %d", type);
609
610 /* Get the challenge from the packet. */
611 challenge = BN_new();
612 packet_get_bignum(challenge, &clen);
613
614 packet_integrity_check(plen, clen, type);
615
616 debug("Received RSA challenge for host key from server.");
617
618 /* Compute a response to the challenge. */
619 respond_to_rsa_challenge(challenge, host_key);
620
621 /* We no longer need the challenge. */
622 BN_clear_free(challenge);
623
624 /* Wait for response from the server. */
625 type = packet_read(&plen);
626 if (type == SSH_SMSG_SUCCESS) {
627 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
628 return 1;
629 }
630 if (type != SSH_SMSG_FAILURE)
631 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
632 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
633 return 0;
8efc0c15 634}
635
636#ifdef KRB4
5260325f 637int
638try_kerberos_authentication()
8efc0c15 639{
5260325f 640 KTEXT_ST auth; /* Kerberos data */
641 char *reply;
642 char inst[INST_SZ];
643 char *realm;
644 CREDENTIALS cred;
645 int r, type, plen;
610cd5c6 646 socklen_t slen;
5260325f 647 Key_schedule schedule;
648 u_long checksum, cksum;
649 MSG_DAT msg_data;
650 struct sockaddr_in local, foreign;
651 struct stat st;
652
653 /* Don't do anything if we don't have any tickets. */
654 if (stat(tkt_string(), &st) < 0)
655 return 0;
656
657 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
658
659 realm = (char *) krb_realmofhost(get_canonical_hostname());
660 if (!realm) {
661 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
662 return 0;
663 }
664 /* This can really be anything. */
665 checksum = (u_long) getpid();
666
667 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
668 if (r != KSUCCESS) {
669 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
670 return 0;
671 }
672 /* Get session key to decrypt the server's reply with. */
673 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
674 if (r != KSUCCESS) {
675 debug("get_cred failed: %s", krb_err_txt[r]);
676 return 0;
677 }
678 des_key_sched((des_cblock *) cred.session, schedule);
679
680 /* Send authentication info to server. */
681 packet_start(SSH_CMSG_AUTH_KERBEROS);
682 packet_put_string((char *) auth.dat, auth.length);
683 packet_send();
684 packet_write_wait();
685
686 /* Zero the buffer. */
687 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
688
610cd5c6 689 slen = sizeof(local);
5260325f 690 memset(&local, 0, sizeof(local));
691 if (getsockname(packet_get_connection_in(),
610cd5c6 692 (struct sockaddr *) & local, &slen) < 0)
5260325f 693 debug("getsockname failed: %s", strerror(errno));
694
610cd5c6 695 slen = sizeof(foreign);
5260325f 696 memset(&foreign, 0, sizeof(foreign));
697 if (getpeername(packet_get_connection_in(),
610cd5c6 698 (struct sockaddr *) & foreign, &slen) < 0) {
5260325f 699 debug("getpeername failed: %s", strerror(errno));
700 fatal_cleanup();
701 }
702 /* Get server reply. */
703 type = packet_read(&plen);
704 switch (type) {
705 case SSH_SMSG_FAILURE:
706 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
707 debug("Kerberos V4 authentication failed.");
708 return 0;
709 break;
710
711 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
712 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
713 debug("Kerberos V4 authentication accepted.");
714
715 /* Get server's response. */
716 reply = packet_get_string((unsigned int *) &auth.length);
717 memcpy(auth.dat, reply, auth.length);
718 xfree(reply);
719
720 packet_integrity_check(plen, 4 + auth.length, type);
721
aa3378df 722 /*
723 * If his response isn't properly encrypted with the session
724 * key, and the decrypted checksum fails to match, he's
725 * bogus. Bail out.
726 */
5260325f 727 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
728 &foreign, &local, &msg_data);
729 if (r != KSUCCESS) {
730 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
731 packet_disconnect("Kerberos V4 challenge failed!");
732 }
733 /* Fetch the (incremented) checksum that we supplied in the request. */
734 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
735 cksum = ntohl(cksum);
736
737 /* If it matches, we're golden. */
738 if (cksum == checksum + 1) {
739 debug("Kerberos V4 challenge successful.");
740 return 1;
741 } else
742 packet_disconnect("Kerberos V4 challenge failed!");
743 break;
744
745 default:
746 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
747 }
748 return 0;
8efc0c15 749}
5260325f 750
8efc0c15 751#endif /* KRB4 */
752
753#ifdef AFS
5260325f 754int
755send_kerberos_tgt()
8efc0c15 756{
5260325f 757 CREDENTIALS *creds;
758 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
759 int r, type, plen;
610cd5c6 760 char buffer[8192];
5260325f 761 struct stat st;
762
763 /* Don't do anything if we don't have any tickets. */
764 if (stat(tkt_string(), &st) < 0)
765 return 0;
766
767 creds = xmalloc(sizeof(*creds));
768
769 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
770 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
771 return 0;
772 }
773 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
774 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
775 return 0;
776 }
777 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
778 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
779 return 0;
780 }
610cd5c6 781 creds_to_radix(creds, (unsigned char *)buffer);
5260325f 782 xfree(creds);
783
784 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
610cd5c6 785 packet_put_string(buffer, strlen(buffer));
5260325f 786 packet_send();
787 packet_write_wait();
788
789 type = packet_read(&plen);
790
791 if (type == SSH_SMSG_FAILURE)
792 debug("Kerberos TGT for realm %s rejected.", prealm);
793 else if (type != SSH_SMSG_SUCCESS)
794 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
795
796 return 1;
8efc0c15 797}
798
5260325f 799void
800send_afs_tokens(void)
8efc0c15 801{
5260325f 802 CREDENTIALS creds;
803 struct ViceIoctl parms;
804 struct ClearToken ct;
805 int i, type, len, plen;
806 char buf[2048], *p, *server_cell;
610cd5c6 807 char buffer[8192];
5260325f 808
809 /* Move over ktc_GetToken, here's something leaner. */
810 for (i = 0; i < 100; i++) { /* just in case */
811 parms.in = (char *) &i;
812 parms.in_size = sizeof(i);
813 parms.out = buf;
814 parms.out_size = sizeof(buf);
815 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
816 break;
817 p = buf;
818
819 /* Get secret token. */
820 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
821 if (creds.ticket_st.length > MAX_KTXT_LEN)
822 break;
823 p += sizeof(unsigned int);
824 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
825 p += creds.ticket_st.length;
826
827 /* Get clear token. */
828 memcpy(&len, p, sizeof(len));
829 if (len != sizeof(struct ClearToken))
830 break;
831 p += sizeof(len);
832 memcpy(&ct, p, len);
833 p += len;
834 p += sizeof(len); /* primary flag */
835 server_cell = p;
836
837 /* Flesh out our credentials. */
838 strlcpy(creds.service, "afs", sizeof creds.service);
839 creds.instance[0] = '\0';
840 strlcpy(creds.realm, server_cell, REALM_SZ);
841 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
842 creds.issue_date = ct.BeginTimestamp;
843 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
844 creds.kvno = ct.AuthHandle;
845 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
846 creds.pinst[0] = '\0';
847
848 /* Encode token, ship it off. */
610cd5c6 849 if (!creds_to_radix(&creds, (unsigned char*) buffer))
5260325f 850 break;
851 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
610cd5c6 852 packet_put_string(buffer, strlen(buffer));
5260325f 853 packet_send();
854 packet_write_wait();
855
856 /* Roger, Roger. Clearance, Clarence. What's your vector,
857 Victor? */
858 type = packet_read(&plen);
859
860 if (type == SSH_SMSG_FAILURE)
861 debug("AFS token for cell %s rejected.", server_cell);
862 else if (type != SSH_SMSG_SUCCESS)
863 packet_disconnect("Protocol error on AFS token response: %d", type);
864 }
8efc0c15 865}
8efc0c15 866
5260325f 867#endif /* AFS */
8efc0c15 868
57112b5a 869/*
870 * Tries to authenticate with any string-based challenge/response system.
871 * Note that the client code is not tied to s/key or TIS.
872 */
873int
874try_skey_authentication()
875{
610cd5c6 876 int type, i;
877 int payload_len;
878 unsigned int clen;
57112b5a 879 char *challenge, *response;
880
881 debug("Doing skey authentication.");
882
883 /* request a challenge */
884 packet_start(SSH_CMSG_AUTH_TIS);
885 packet_send();
886 packet_write_wait();
887
888 type = packet_read(&payload_len);
889 if (type != SSH_SMSG_FAILURE &&
890 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
891 packet_disconnect("Protocol error: got %d in response "
892 "to skey-auth", type);
893 }
894 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
895 debug("No challenge for skey authentication.");
896 return 0;
897 }
610cd5c6 898 challenge = packet_get_string(&clen);
899 packet_integrity_check(payload_len, (4 + clen), type);
57112b5a 900 if (options.cipher == SSH_CIPHER_NONE)
901 log("WARNING: Encryption is disabled! "
902 "Reponse will be transmitted in clear text.");
903 fprintf(stderr, "%s\n", challenge);
c8d54615 904 xfree(challenge);
57112b5a 905 fflush(stderr);
906 for (i = 0; i < options.number_of_password_prompts; i++) {
907 if (i != 0)
908 error("Permission denied, please try again.");
909 response = read_passphrase("Response: ", 0);
910 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
911 packet_put_string(response, strlen(response));
912 memset(response, 0, strlen(response));
913 xfree(response);
914 packet_send();
915 packet_write_wait();
916 type = packet_read(&payload_len);
917 if (type == SSH_SMSG_SUCCESS)
918 return 1;
919 if (type != SSH_SMSG_FAILURE)
920 packet_disconnect("Protocol error: got %d in response "
921 "to skey-auth-reponse", type);
922 }
923 /* failure */
924 return 0;
925}
926
927/*
928 * Tries to authenticate with plain passwd authentication.
929 */
930int
931try_password_authentication(char *prompt)
932{
933 int type, i, payload_len;
934 char *password;
935
936 debug("Doing password authentication.");
937 if (options.cipher == SSH_CIPHER_NONE)
938 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
939 for (i = 0; i < options.number_of_password_prompts; i++) {
940 if (i != 0)
941 error("Permission denied, please try again.");
942 password = read_passphrase(prompt, 0);
943 packet_start(SSH_CMSG_AUTH_PASSWORD);
944 packet_put_string(password, strlen(password));
945 memset(password, 0, strlen(password));
946 xfree(password);
947 packet_send();
948 packet_write_wait();
949
950 type = packet_read(&payload_len);
951 if (type == SSH_SMSG_SUCCESS)
952 return 1;
953 if (type != SSH_SMSG_FAILURE)
954 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
955 }
956 /* failure */
957 return 0;
958}
959
5260325f 960/*
961 * Waits for the server identification string, and sends our own
962 * identification string.
963 */
964void
965ssh_exchange_identification()
8efc0c15 966{
5260325f 967 char buf[256], remote_version[256]; /* must be same size! */
968 int remote_major, remote_minor, i;
969 int connection_in = packet_get_connection_in();
970 int connection_out = packet_get_connection_out();
5260325f 971
972 /* Read other side\'s version identification. */
973 for (i = 0; i < sizeof(buf) - 1; i++) {
c8d54615 974 int len = read(connection_in, &buf[i], 1);
975 if (len < 0)
5260325f 976 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
c8d54615 977 if (len != 1)
978 fatal("ssh_exchange_identification: Connection closed by remote host");
5260325f 979 if (buf[i] == '\r') {
980 buf[i] = '\n';
981 buf[i + 1] = 0;
982 break;
983 }
984 if (buf[i] == '\n') {
985 buf[i + 1] = 0;
986 break;
987 }
8efc0c15 988 }
5260325f 989 buf[sizeof(buf) - 1] = 0;
990
aa3378df 991 /*
992 * Check that the versions match. In future this might accept
993 * several versions and set appropriate flags to handle them.
994 */
5260325f 995 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
996 remote_version) != 3)
997 fatal("Bad remote protocol version identification: '%.100s'", buf);
998 debug("Remote protocol version %d.%d, remote software version %.100s",
999 remote_major, remote_minor, remote_version);
1000
1001 /* Check if the remote protocol version is too old. */
1002 if (remote_major == 1 && remote_minor < 3)
1003 fatal("Remote machine has too old SSH software version.");
1004
1005 /* We speak 1.3, too. */
1006 if (remote_major == 1 && remote_minor == 3) {
1007 enable_compat13();
7b2ea3a1 1008 if (options.forward_agent) {
1009 log("Agent forwarding disabled for protocol 1.3");
5260325f 1010 options.forward_agent = 0;
1011 }
8efc0c15 1012 }
8efc0c15 1013#if 0
aa3378df 1014 /*
1015 * Removed for now, to permit compatibility with latter versions. The
1016 * server will reject our version and disconnect if it doesn't
1017 * support it.
1018 */
5260325f 1019 if (remote_major != PROTOCOL_MAJOR)
1020 fatal("Protocol major versions differ: %d vs. %d",
1021 PROTOCOL_MAJOR, remote_major);
8efc0c15 1022#endif
1023
5260325f 1024 /* Send our own protocol version identification. */
1025 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
a408af76 1026 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1027 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
5260325f 1028 fatal("write: %.100s", strerror(errno));
8efc0c15 1029}
1030
1031int ssh_cipher_default = SSH_CIPHER_3DES;
1032
5260325f 1033int
1034read_yes_or_no(const char *prompt, int defval)
8efc0c15 1035{
5260325f 1036 char buf[1024];
1037 FILE *f;
1038 int retval = -1;
1039
1040 if (isatty(0))
1041 f = stdin;
1042 else
1043 f = fopen("/dev/tty", "rw");
1044
1045 if (f == NULL)
1046 return 0;
1047
1048 fflush(stdout);
1049
1050 while (1) {
1051 fprintf(stderr, "%s", prompt);
1052 if (fgets(buf, sizeof(buf), f) == NULL) {
1053 /* Print a newline (the prompt probably didn\'t have one). */
1054 fprintf(stderr, "\n");
1055 strlcpy(buf, "no", sizeof buf);
1056 }
1057 /* Remove newline from response. */
1058 if (strchr(buf, '\n'))
1059 *strchr(buf, '\n') = 0;
1060
1061 if (buf[0] == 0)
1062 retval = defval;
1063 if (strcmp(buf, "yes") == 0)
1064 retval = 1;
1065 if (strcmp(buf, "no") == 0)
1066 retval = 0;
1067
1068 if (retval != -1) {
1069 if (f != stdin)
1070 fclose(f);
1071 return retval;
1072 }
8efc0c15 1073 }
8efc0c15 1074}
1075
5260325f 1076/*
95f1eccc 1077 * check whether the supplied host key is valid, return only if ok.
5260325f 1078 */
95f1eccc 1079
5260325f 1080void
4fe2af09 1081check_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
8efc0c15 1082{
4fe2af09 1083 Key *file_key;
95f1eccc 1084 char *ip = NULL;
5260325f 1085 char hostline[1000], *hostp;
5260325f 1086 HostStatus host_status;
1087 HostStatus ip_status;
48e671d5 1088 int local = 0, host_ip_differ = 0;
20af321f 1089 int salen;
48e671d5 1090 char ntop[NI_MAXHOST];
1091
1092 /*
1093 * Force accepting of the host key for loopback/localhost. The
1094 * problem is that if the home directory is NFS-mounted to multiple
1095 * machines, localhost will refer to a different machine in each of
1096 * them, and the user will get bogus HOST_CHANGED warnings. This
1097 * essentially disables host authentication for localhost; however,
1098 * this is probably not a real problem.
1099 */
1100 switch (hostaddr->sa_family) {
1101 case AF_INET:
1102 local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
20af321f 1103 salen = sizeof(struct sockaddr_in);
48e671d5 1104 break;
1105 case AF_INET6:
1106 local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
20af321f 1107 salen = sizeof(struct sockaddr_in6);
48e671d5 1108 break;
1109 default:
1110 local = 0;
20af321f 1111 salen = sizeof(struct sockaddr_storage);
48e671d5 1112 break;
1113 }
1114 if (local) {
1115 debug("Forcing accepting of host key for loopback/localhost.");
1116 return;
1117 }
5260325f 1118
57112b5a 1119 /*
1120 * Turn off check_host_ip for proxy connects, since
1121 * we don't have the remote ip-address
1122 */
1123 if (options.proxy_command != NULL && options.check_host_ip)
1124 options.check_host_ip = 0;
1125
48e671d5 1126 if (options.check_host_ip) {
20af321f 1127 if (getnameinfo(hostaddr, salen, ntop, sizeof(ntop),
48e671d5 1128 NULL, 0, NI_NUMERICHOST) != 0)
1129 fatal("check_host_key: getnameinfo failed");
1130 ip = xstrdup(ntop);
1131 }
5260325f 1132
95f1eccc 1133 /*
1134 * Store the host key from the known host file in here so that we can
1135 * compare it with the key for the IP address.
1136 */
4fe2af09 1137 file_key = key_new(host_key->type);
5260325f 1138
aa3378df 1139 /*
1140 * Check if the host key is present in the user\'s list of known
1141 * hosts or in the systemwide list.
1142 */
4fe2af09 1143 host_status = check_host_in_hostfile(options.user_hostfile, host, host_key, file_key);
5260325f 1144 if (host_status == HOST_NEW)
4fe2af09 1145 host_status = check_host_in_hostfile(options.system_hostfile, host, host_key, file_key);
aa3378df 1146 /*
1147 * Also perform check for the ip address, skip the check if we are
1148 * localhost or the hostname was an ip address to begin with
1149 */
5260325f 1150 if (options.check_host_ip && !local && strcmp(host, ip)) {
4fe2af09 1151 Key *ip_key = key_new(host_key->type);
1152 ip_status = check_host_in_hostfile(options.user_hostfile, ip, host_key, ip_key);
5260325f 1153
1154 if (ip_status == HOST_NEW)
4fe2af09 1155 ip_status = check_host_in_hostfile(options.system_hostfile, ip, host_key, ip_key);
5260325f 1156 if (host_status == HOST_CHANGED &&
4fe2af09 1157 (ip_status != HOST_CHANGED || !key_equal(ip_key, file_key)))
5260325f 1158 host_ip_differ = 1;
1159
4fe2af09 1160 key_free(ip_key);
5260325f 1161 } else
1162 ip_status = host_status;
1163
4fe2af09 1164 key_free(file_key);
5260325f 1165
1166 switch (host_status) {
1167 case HOST_OK:
1168 /* The host is known and the key matches. */
1169 debug("Host '%.200s' is known and matches the host key.", host);
1170 if (options.check_host_ip) {
1171 if (ip_status == HOST_NEW) {
4fe2af09 1172 if (!add_host_to_hostfile(options.user_hostfile, ip, host_key))
5260325f 1173 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1174 ip, options.user_hostfile);
1175 else
1176 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1177 ip);
1178 } else if (ip_status != HOST_OK)
1179 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1180 host, ip);
1181 }
1182 break;
1183 case HOST_NEW:
1184 /* The host is new. */
1185 if (options.strict_host_key_checking == 1) {
1186 /* User has requested strict host key checking. We will not add the host key
1187 automatically. The only alternative left is to abort. */
1188 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1189 } else if (options.strict_host_key_checking == 2) {
1190 /* The default */
1191 char prompt[1024];
4fe2af09 1192 char *fp = key_fingerprint(host_key);
5260325f 1193 snprintf(prompt, sizeof(prompt),
a408af76 1194 "The authenticity of host '%.200s' can't be established.\n"
4fe2af09 1195 "Key fingerprint is %s.\n"
a408af76 1196 "Are you sure you want to continue connecting (yes/no)? ",
4fe2af09 1197 host, fp);
5260325f 1198 if (!read_yes_or_no(prompt, -1))
1199 fatal("Aborted by user!\n");
1200 }
1201 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1202 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1203 hostp = hostline;
1204 } else
1205 hostp = host;
1206
1207 /* If not in strict mode, add the key automatically to the local known_hosts file. */
4fe2af09 1208 if (!add_host_to_hostfile(options.user_hostfile, hostp, host_key))
5260325f 1209 log("Failed to add the host to the list of known hosts (%.500s).",
1210 options.user_hostfile);
1211 else
1212 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1213 hostp);
1214 break;
1215 case HOST_CHANGED:
1216 if (options.check_host_ip && host_ip_differ) {
1217 char *msg;
1218 if (ip_status == HOST_NEW)
1219 msg = "is unknown";
1220 else if (ip_status == HOST_OK)
1221 msg = "is unchanged";
1222 else
1223 msg = "has a different value";
1224 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1225 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1226 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1227 error("The host key for %s has changed,", host);
1228 error("and the key for the according IP address %s", ip);
1229 error("%s. This could either mean that", msg);
1230 error("DNS SPOOFING is happening or the IP address for the host");
1231 error("and its host key have changed at the same time");
1232 }
1233 /* The host key has changed. */
1234 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
ae2f7af7 1235 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
5260325f 1236 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1237 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1238 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1239 error("It is also possible that the host key has just been changed.");
1240 error("Please contact your system administrator.");
1241 error("Add correct host key in %.100s to get rid of this message.",
1242 options.user_hostfile);
1243
aa3378df 1244 /*
1245 * If strict host key checking is in use, the user will have
1246 * to edit the key manually and we can only abort.
1247 */
5260325f 1248 if (options.strict_host_key_checking)
1249 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1250
aa3378df 1251 /*
1252 * If strict host key checking has not been requested, allow
1253 * the connection but without password authentication or
1254 * agent forwarding.
1255 */
5260325f 1256 if (options.password_authentication) {
1257 error("Password authentication is disabled to avoid trojan horses.");
1258 options.password_authentication = 0;
1259 }
1260 if (options.forward_agent) {
1261 error("Agent forwarding is disabled to avoid trojan horses.");
1262 options.forward_agent = 0;
1263 }
aa3378df 1264 /*
1265 * XXX Should permit the user to change to use the new id.
1266 * This could be done by converting the host key to an
1267 * identifying sentence, tell that the host identifies itself
1268 * by that sentence, and ask the user if he/she whishes to
1269 * accept the authentication.
1270 */
5260325f 1271 break;
1272 }
5260325f 1273 if (options.check_host_ip)
1274 xfree(ip);
95f1eccc 1275}
4fe2af09 1276void
1277check_rsa_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1278{
1279 Key k;
1280 k.type = KEY_RSA;
1281 k.rsa = host_key;
1282 check_host_key(host, hostaddr, &k);
1283}
95f1eccc 1284
1285/*
7b2ea3a1 1286 * SSH1 key exchange
95f1eccc 1287 */
1288void
7b2ea3a1 1289ssh_kex(char *host, struct sockaddr *hostaddr)
95f1eccc 1290{
7b2ea3a1 1291 int i;
95f1eccc 1292 BIGNUM *key;
1293 RSA *host_key;
1294 RSA *public_key;
1295 int bits, rbits;
1296 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
7b2ea3a1 1297 unsigned char cookie[8];
1298 unsigned int supported_ciphers;
95f1eccc 1299 unsigned int server_flags, client_flags;
1300 int payload_len, clen, sum_len = 0;
1301 u_int32_t rand = 0;
1302
95f1eccc 1303 debug("Waiting for server public key.");
1304
1305 /* Wait for a public key packet from the server. */
1306 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1307
7b2ea3a1 1308 /* Get cookie from the packet. */
95f1eccc 1309 for (i = 0; i < 8; i++)
7b2ea3a1 1310 cookie[i] = packet_get_char();
95f1eccc 1311
1312 /* Get the public key. */
1313 public_key = RSA_new();
1314 bits = packet_get_int();/* bits */
1315 public_key->e = BN_new();
1316 packet_get_bignum(public_key->e, &clen);
1317 sum_len += clen;
1318 public_key->n = BN_new();
1319 packet_get_bignum(public_key->n, &clen);
1320 sum_len += clen;
1321
1322 rbits = BN_num_bits(public_key->n);
1323 if (bits != rbits) {
1324 log("Warning: Server lies about size of server public key: "
1325 "actual size is %d bits vs. announced %d.", rbits, bits);
1326 log("Warning: This may be due to an old implementation of ssh.");
1327 }
1328 /* Get the host key. */
1329 host_key = RSA_new();
1330 bits = packet_get_int();/* bits */
1331 host_key->e = BN_new();
1332 packet_get_bignum(host_key->e, &clen);
1333 sum_len += clen;
1334 host_key->n = BN_new();
1335 packet_get_bignum(host_key->n, &clen);
1336 sum_len += clen;
1337
1338 rbits = BN_num_bits(host_key->n);
1339 if (bits != rbits) {
1340 log("Warning: Server lies about size of server host key: "
1341 "actual size is %d bits vs. announced %d.", rbits, bits);
1342 log("Warning: This may be due to an old implementation of ssh.");
1343 }
1344
1345 /* Get protocol flags. */
1346 server_flags = packet_get_int();
1347 packet_set_protocol_flags(server_flags);
1348
1349 supported_ciphers = packet_get_int();
1350 supported_authentications = packet_get_int();
1351
1352 debug("Received server public key (%d bits) and host key (%d bits).",
1353 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1354
1355 packet_integrity_check(payload_len,
1356 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1357 SSH_SMSG_PUBLIC_KEY);
1358
4fe2af09 1359 check_rsa_host_key(host, hostaddr, host_key);
95f1eccc 1360
1361 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1362
7b2ea3a1 1363 compute_session_id(session_id, cookie, host_key->n, public_key->n);
5260325f 1364
1365 /* Generate a session key. */
1366 arc4random_stir();
1367
aa3378df 1368 /*
1369 * Generate an encryption key for the session. The key is a 256 bit
1370 * random number, interpreted as a 32-byte key, with the least
1371 * significant 8 bits being the first byte of the key.
1372 */
5260325f 1373 for (i = 0; i < 32; i++) {
1374 if (i % 4 == 0)
1375 rand = arc4random();
1376 session_key[i] = rand & 0xff;
1377 rand >>= 8;
1378 }
1379
aa3378df 1380 /*
1381 * According to the protocol spec, the first byte of the session key
1382 * is the highest byte of the integer. The session key is xored with
1383 * the first 16 bytes of the session id.
1384 */
5260325f 1385 key = BN_new();
1386 BN_set_word(key, 0);
1387 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1388 BN_lshift(key, key, 8);
1389 if (i < 16)
1390 BN_add_word(key, session_key[i] ^ session_id[i]);
1391 else
1392 BN_add_word(key, session_key[i]);
1393 }
1394
aa3378df 1395 /*
1396 * Encrypt the integer using the public key and host key of the
1397 * server (key with smaller modulus first).
1398 */
5260325f 1399 if (BN_cmp(public_key->n, host_key->n) < 0) {
1400 /* Public key has smaller modulus. */
1401 if (BN_num_bits(host_key->n) <
1402 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1403 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1404 "SSH_KEY_BITS_RESERVED %d",
1405 BN_num_bits(host_key->n),
1406 BN_num_bits(public_key->n),
1407 SSH_KEY_BITS_RESERVED);
1408 }
1409 rsa_public_encrypt(key, key, public_key);
1410 rsa_public_encrypt(key, key, host_key);
1411 } else {
1412 /* Host key has smaller modulus (or they are equal). */
1413 if (BN_num_bits(public_key->n) <
1414 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1415 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1416 "SSH_KEY_BITS_RESERVED %d",
1417 BN_num_bits(public_key->n),
1418 BN_num_bits(host_key->n),
1419 SSH_KEY_BITS_RESERVED);
1420 }
1421 rsa_public_encrypt(key, key, host_key);
1422 rsa_public_encrypt(key, key, public_key);
1423 }
1424
7b2ea3a1 1425 /* Destroy the public keys since we no longer need them. */
1426 RSA_free(public_key);
1427 RSA_free(host_key);
1428
5260325f 1429 if (options.cipher == SSH_CIPHER_NOT_SET) {
1430 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1431 options.cipher = ssh_cipher_default;
1432 else {
1433 debug("Cipher %s not supported, using %.100s instead.",
1434 cipher_name(ssh_cipher_default),
1435 cipher_name(SSH_FALLBACK_CIPHER));
1436 options.cipher = SSH_FALLBACK_CIPHER;
1437 }
1438 }
1439 /* Check that the selected cipher is supported. */
1440 if (!(supported_ciphers & (1 << options.cipher)))
1441 fatal("Selected cipher type %.100s not supported by server.",
1442 cipher_name(options.cipher));
1443
1444 debug("Encryption type: %.100s", cipher_name(options.cipher));
1445
1446 /* Send the encrypted session key to the server. */
1447 packet_start(SSH_CMSG_SESSION_KEY);
1448 packet_put_char(options.cipher);
1449
7b2ea3a1 1450 /* Send the cookie back to the server. */
5260325f 1451 for (i = 0; i < 8; i++)
7b2ea3a1 1452 packet_put_char(cookie[i]);
5260325f 1453
7b2ea3a1 1454 /* Send and destroy the encrypted encryption key integer. */
5260325f 1455 packet_put_bignum(key);
7b2ea3a1 1456 BN_clear_free(key);
5260325f 1457
1458 /* Send protocol flags. */
95f1eccc 1459 packet_put_int(client_flags);
5260325f 1460
1461 /* Send the packet now. */
8efc0c15 1462 packet_send();
1463 packet_write_wait();
5260325f 1464
5260325f 1465 debug("Sent encrypted session key.");
1466
1467 /* Set the encryption key. */
1468 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1469
1470 /* We will no longer need the session key here. Destroy any extra copies. */
1471 memset(session_key, 0, sizeof(session_key));
1472
aa3378df 1473 /*
1474 * Expect a success message from the server. Note that this message
1475 * will be received in encrypted form.
1476 */
5260325f 1477 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1478
1479 debug("Received encrypted confirmation.");
7b2ea3a1 1480}
1481
1482/*
1483 * Authenticate user
1484 */
1485void
1486ssh_userauth(int host_key_valid, RSA *own_host_key,
1487 uid_t original_real_uid, char *host)
1488{
1489 int i, type;
1490 int payload_len;
1491 struct passwd *pw;
1492 const char *server_user, *local_user;
1493
1494 /* Get local user name. Use it as server user if no user name was given. */
1495 pw = getpwuid(original_real_uid);
1496 if (!pw)
1497 fatal("User id %d not found from user database.", original_real_uid);
1498 local_user = xstrdup(pw->pw_name);
1499 server_user = options.user ? options.user : local_user;
5260325f 1500
1501 /* Send the name of the user to log in as on the server. */
1502 packet_start(SSH_CMSG_USER);
1503 packet_put_string(server_user, strlen(server_user));
1504 packet_send();
1505 packet_write_wait();
1506
aa3378df 1507 /*
1508 * The server should respond with success if no authentication is
1509 * needed (the user has no password). Otherwise the server responds
1510 * with failure.
1511 */
8efc0c15 1512 type = packet_read(&payload_len);
5260325f 1513
1514 /* check whether the connection was accepted without authentication. */
8efc0c15 1515 if (type == SSH_SMSG_SUCCESS)
5260325f 1516 return;
8efc0c15 1517 if (type != SSH_SMSG_FAILURE)
5260325f 1518 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1519 type);
1520
1521#ifdef AFS
1522 /* Try Kerberos tgt passing if the server supports it. */
1523 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1524 options.kerberos_tgt_passing) {
1525 if (options.cipher == SSH_CIPHER_NONE)
1526 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1527 (void) send_kerberos_tgt();
1528 }
1529 /* Try AFS token passing if the server supports it. */
1530 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1531 options.afs_token_passing && k_hasafs()) {
1532 if (options.cipher == SSH_CIPHER_NONE)
1533 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1534 send_afs_tokens();
1535 }
1536#endif /* AFS */
8efc0c15 1537
5260325f 1538#ifdef KRB4
1539 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1540 options.kerberos_authentication) {
1541 debug("Trying Kerberos authentication.");
1542 if (try_kerberos_authentication()) {
1543 /* The server should respond with success or failure. */
1544 type = packet_read(&payload_len);
1545 if (type == SSH_SMSG_SUCCESS)
1546 return;
1547 if (type != SSH_SMSG_FAILURE)
1548 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1549 }
1550 }
1551#endif /* KRB4 */
1552
aa3378df 1553 /*
1554 * Use rhosts authentication if running in privileged socket and we
1555 * do not wish to remain anonymous.
1556 */
5260325f 1557 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1558 options.rhosts_authentication) {
1559 debug("Trying rhosts authentication.");
1560 packet_start(SSH_CMSG_AUTH_RHOSTS);
1561 packet_put_string(local_user, strlen(local_user));
1562 packet_send();
1563 packet_write_wait();
1564
1565 /* The server should respond with success or failure. */
1566 type = packet_read(&payload_len);
1567 if (type == SSH_SMSG_SUCCESS)
1568 return;
1569 if (type != SSH_SMSG_FAILURE)
1570 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1571 type);
1572 }
aa3378df 1573 /*
1574 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1575 * authentication.
1576 */
5260325f 1577 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1578 options.rhosts_rsa_authentication && host_key_valid) {
1579 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1580 return;
1581 }
1582 /* Try RSA authentication if the server supports it. */
1583 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1584 options.rsa_authentication) {
aa3378df 1585 /*
1586 * Try RSA authentication using the authentication agent. The
1587 * agent is tried first because no passphrase is needed for
1588 * it, whereas identity files may require passphrases.
1589 */
5260325f 1590 if (try_agent_authentication())
1591 return;
1592
1593 /* Try RSA authentication for each identity. */
1594 for (i = 0; i < options.num_identity_files; i++)
57112b5a 1595 if (try_rsa_authentication(options.identity_files[i]))
5260325f 1596 return;
1597 }
1598 /* Try skey authentication if the server supports it. */
1599 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1600 options.skey_authentication && !options.batch_mode) {
57112b5a 1601 if (try_skey_authentication())
1602 return;
5260325f 1603 }
1604 /* Try password authentication if the server supports it. */
1605 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1606 options.password_authentication && !options.batch_mode) {
1607 char prompt[80];
a408af76 1608
57112b5a 1609 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
a408af76 1610 server_user, host);
57112b5a 1611 if (try_password_authentication(prompt))
1612 return;
5260325f 1613 }
1614 /* All authentication methods have failed. Exit with an error message. */
1615 fatal("Permission denied.");
1616 /* NOTREACHED */
8efc0c15 1617}
7b2ea3a1 1618/*
1619 * Starts a dialog with the server, and authenticates the current user on the
1620 * server. This does not need any extra privileges. The basic connection
1621 * to the server must already have been established before this is called.
1622 * If login fails, this function prints an error and never returns.
1623 * This function does not require super-user privileges.
1624 */
1625void
1626ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
1627 struct sockaddr *hostaddr, uid_t original_real_uid)
1628{
1629 char *host, *cp;
1630
1631 /* Convert the user-supplied hostname into all lowercase. */
1632 host = xstrdup(orighost);
1633 for (cp = host; *cp; cp++)
1634 if (isupper(*cp))
1635 *cp = tolower(*cp);
1636
1637 /* Exchange protocol version identification strings with the server. */
1638 ssh_exchange_identification();
1639
1640 /* Put the connection into non-blocking mode. */
1641 packet_set_nonblocking();
1642
1643 supported_authentications = 0;
1644 /* key exchange */
1645 ssh_kex(host, hostaddr);
1646 if (supported_authentications == 0)
1647 fatal("supported_authentications == 0.");
4fe2af09 1648
7b2ea3a1 1649 /* authenticate user */
1650 ssh_userauth(host_key_valid, own_host_key, original_real_uid, host);
1651}
This page took 0.323092 seconds and 5 git commands to generate.