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