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