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