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