]> andersk Git - openssh.git/blob - sshconnect1.c
- (bal) OpenBSD CVS update
[openssh.git] / sshconnect1.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  * Code to connect to a remote host, and to perform the client side of the
6  * login (authentication) dialog.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14
15 #include "includes.h"
16 RCSID("$OpenBSD: sshconnect1.c,v 1.12 2000/12/10 17:01:53 markus Exp $");
17
18 #include <openssl/bn.h>
19 #include <openssl/dsa.h>
20 #include <openssl/rsa.h>
21 #include <openssl/evp.h>
22
23 #include "xmalloc.h"
24 #include "rsa.h"
25 #include "ssh.h"
26 #include "buffer.h"
27 #include "packet.h"
28 #include "mpaux.h"
29 #include "uidswap.h"
30 #include "readconf.h"
31 #include "key.h"
32 #include "authfd.h"
33 #include "sshconnect.h"
34 #include "authfile.h"
35
36 /* Session id for the current session. */
37 unsigned char session_id[16];
38 unsigned int supported_authentications = 0;
39
40 extern Options options;
41 extern char *__progname;
42
43 /*
44  * Checks if the user has an authentication agent, and if so, tries to
45  * authenticate using the agent.
46  */
47 int
48 try_agent_authentication()
49 {
50         int type;
51         char *comment;
52         AuthenticationConnection *auth;
53         unsigned char response[16];
54         unsigned int i;
55         int plen, clen;
56         Key *key;
57         BIGNUM *challenge;
58
59         /* Get connection to the agent. */
60         auth = ssh_get_authentication_connection();
61         if (!auth)
62                 return 0;
63
64         challenge = BN_new();
65         key = key_new(KEY_RSA1);
66
67         /* Loop through identities served by the agent. */
68         for (key = ssh_get_first_identity(auth, &comment, 1);
69              key != NULL;
70              key = ssh_get_next_identity(auth, &comment, 1)) {
71
72                 /* Try this identity. */
73                 debug("Trying RSA authentication via agent with '%.100s'", comment);
74                 xfree(comment);
75
76                 /* Tell the server that we are willing to authenticate using this key. */
77                 packet_start(SSH_CMSG_AUTH_RSA);
78                 packet_put_bignum(key->rsa->n);
79                 packet_send();
80                 packet_write_wait();
81
82                 /* Wait for server's response. */
83                 type = packet_read(&plen);
84
85                 /* The server sends failure if it doesn\'t like our key or
86                    does not support RSA authentication. */
87                 if (type == SSH_SMSG_FAILURE) {
88                         debug("Server refused our key.");
89                         key_free(key);
90                         continue;
91                 }
92                 /* Otherwise it should have sent a challenge. */
93                 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
94                         packet_disconnect("Protocol error during RSA authentication: %d",
95                                           type);
96
97                 packet_get_bignum(challenge, &clen);
98
99                 packet_integrity_check(plen, clen, type);
100
101                 debug("Received RSA challenge from server.");
102
103                 /* Ask the agent to decrypt the challenge. */
104                 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
105                         /*
106                          * The agent failed to authenticate this identifier
107                          * although it advertised it supports this.  Just
108                          * return a wrong value.
109                          */
110                         log("Authentication agent failed to decrypt challenge.");
111                         memset(response, 0, sizeof(response));
112                 }
113                 key_free(key);
114                 debug("Sending response to RSA challenge.");
115
116                 /* Send the decrypted challenge back to the server. */
117                 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
118                 for (i = 0; i < 16; i++)
119                         packet_put_char(response[i]);
120                 packet_send();
121                 packet_write_wait();
122
123                 /* Wait for response from the server. */
124                 type = packet_read(&plen);
125
126                 /* The server returns success if it accepted the authentication. */
127                 if (type == SSH_SMSG_SUCCESS) {
128                         BN_clear_free(challenge);
129                         debug("RSA authentication accepted by server.");
130                         return 1;
131                 }
132                 /* Otherwise it should return failure. */
133                 if (type != SSH_SMSG_FAILURE)
134                         packet_disconnect("Protocol error waiting RSA auth response: %d",
135                                           type);
136         }
137         BN_clear_free(challenge);
138         debug("RSA authentication using agent refused.");
139         return 0;
140 }
141
142 /*
143  * Computes the proper response to a RSA challenge, and sends the response to
144  * the server.
145  */
146 void
147 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
148 {
149         unsigned char buf[32], response[16];
150         MD5_CTX md;
151         int i, len;
152
153         /* Decrypt the challenge using the private key. */
154         rsa_private_decrypt(challenge, challenge, prv);
155
156         /* Compute the response. */
157         /* The response is MD5 of decrypted challenge plus session id. */
158         len = BN_num_bytes(challenge);
159         if (len <= 0 || len > sizeof(buf))
160                 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
161                                   len);
162
163         memset(buf, 0, sizeof(buf));
164         BN_bn2bin(challenge, buf + sizeof(buf) - len);
165         MD5_Init(&md);
166         MD5_Update(&md, buf, 32);
167         MD5_Update(&md, session_id, 16);
168         MD5_Final(response, &md);
169
170         debug("Sending response to host key RSA challenge.");
171
172         /* Send the response back to the server. */
173         packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
174         for (i = 0; i < 16; i++)
175                 packet_put_char(response[i]);
176         packet_send();
177         packet_write_wait();
178
179         memset(buf, 0, sizeof(buf));
180         memset(response, 0, sizeof(response));
181         memset(&md, 0, sizeof(md));
182 }
183
184 /*
185  * Checks if the user has authentication file, and if so, tries to authenticate
186  * the user using it.
187  */
188 int
189 try_rsa_authentication(const char *authfile)
190 {
191         BIGNUM *challenge;
192         Key *public;
193         Key *private;
194         char *passphrase, *comment;
195         int type, i;
196         int plen, clen;
197
198         /* Try to load identification for the authentication key. */
199         public = key_new(KEY_RSA1);
200         if (!load_public_key(authfile, public, &comment)) {
201                 key_free(public);
202                 /* Could not load it.  Fail. */
203                 return 0;
204         }
205         debug("Trying RSA authentication with key '%.100s'", comment);
206
207         /* Tell the server that we are willing to authenticate using this key. */
208         packet_start(SSH_CMSG_AUTH_RSA);
209         packet_put_bignum(public->rsa->n);
210         packet_send();
211         packet_write_wait();
212
213         /* We no longer need the public key. */
214         key_free(public);
215
216         /* Wait for server's response. */
217         type = packet_read(&plen);
218
219         /*
220          * The server responds with failure if it doesn\'t like our key or
221          * doesn\'t support RSA authentication.
222          */
223         if (type == SSH_SMSG_FAILURE) {
224                 debug("Server refused our key.");
225                 xfree(comment);
226                 return 0;
227         }
228         /* Otherwise, the server should respond with a challenge. */
229         if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
230                 packet_disconnect("Protocol error during RSA authentication: %d", type);
231
232         /* Get the challenge from the packet. */
233         challenge = BN_new();
234         packet_get_bignum(challenge, &clen);
235
236         packet_integrity_check(plen, clen, type);
237
238         debug("Received RSA challenge from server.");
239
240         private = key_new(KEY_RSA1);
241         /*
242          * Load the private key.  Try first with empty passphrase; if it
243          * fails, ask for a passphrase.
244          */
245         if (!load_private_key(authfile, "", private, NULL)) {
246                 char buf[300];
247                 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
248                     comment);
249                 if (!options.batch_mode)
250                         passphrase = read_passphrase(buf, 0);
251                 else {
252                         debug("Will not query passphrase for %.100s in batch mode.",
253                               comment);
254                         passphrase = xstrdup("");
255                 }
256
257                 /* Load the authentication file using the pasphrase. */
258                 if (!load_private_key(authfile, passphrase, private, NULL)) {
259                         memset(passphrase, 0, strlen(passphrase));
260                         xfree(passphrase);
261                         error("Bad passphrase.");
262
263                         /* Send a dummy response packet to avoid protocol error. */
264                         packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
265                         for (i = 0; i < 16; i++)
266                                 packet_put_char(0);
267                         packet_send();
268                         packet_write_wait();
269
270                         /* Expect the server to reject it... */
271                         packet_read_expect(&plen, SSH_SMSG_FAILURE);
272                         xfree(comment);
273                         return 0;
274                 }
275                 /* Destroy the passphrase. */
276                 memset(passphrase, 0, strlen(passphrase));
277                 xfree(passphrase);
278         }
279         /* We no longer need the comment. */
280         xfree(comment);
281
282         /* Compute and send a response to the challenge. */
283         respond_to_rsa_challenge(challenge, private->rsa);
284
285         /* Destroy the private key. */
286         key_free(private);
287
288         /* We no longer need the challenge. */
289         BN_clear_free(challenge);
290
291         /* Wait for response from the server. */
292         type = packet_read(&plen);
293         if (type == SSH_SMSG_SUCCESS) {
294                 debug("RSA authentication accepted by server.");
295                 return 1;
296         }
297         if (type != SSH_SMSG_FAILURE)
298                 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
299         debug("RSA authentication refused.");
300         return 0;
301 }
302
303 /*
304  * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
305  * authentication and RSA host authentication.
306  */
307 int
308 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
309 {
310         int type;
311         BIGNUM *challenge;
312         int plen, clen;
313
314         debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
315
316         /* Tell the server that we are willing to authenticate using this key. */
317         packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
318         packet_put_string(local_user, strlen(local_user));
319         packet_put_int(BN_num_bits(host_key->n));
320         packet_put_bignum(host_key->e);
321         packet_put_bignum(host_key->n);
322         packet_send();
323         packet_write_wait();
324
325         /* Wait for server's response. */
326         type = packet_read(&plen);
327
328         /* The server responds with failure if it doesn't admit our
329            .rhosts authentication or doesn't know our host key. */
330         if (type == SSH_SMSG_FAILURE) {
331                 debug("Server refused our rhosts authentication or host key.");
332                 return 0;
333         }
334         /* Otherwise, the server should respond with a challenge. */
335         if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
336                 packet_disconnect("Protocol error during RSA authentication: %d", type);
337
338         /* Get the challenge from the packet. */
339         challenge = BN_new();
340         packet_get_bignum(challenge, &clen);
341
342         packet_integrity_check(plen, clen, type);
343
344         debug("Received RSA challenge for host key from server.");
345
346         /* Compute a response to the challenge. */
347         respond_to_rsa_challenge(challenge, host_key);
348
349         /* We no longer need the challenge. */
350         BN_clear_free(challenge);
351
352         /* Wait for response from the server. */
353         type = packet_read(&plen);
354         if (type == SSH_SMSG_SUCCESS) {
355                 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
356                 return 1;
357         }
358         if (type != SSH_SMSG_FAILURE)
359                 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
360         debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
361         return 0;
362 }
363
364 #ifdef KRB4
365 int
366 try_kerberos_authentication()
367 {
368         KTEXT_ST auth;          /* Kerberos data */
369         char *reply;
370         char inst[INST_SZ];
371         char *realm;
372         CREDENTIALS cred;
373         int r, type, plen;
374         socklen_t slen;
375         Key_schedule schedule;
376         u_long checksum, cksum;
377         MSG_DAT msg_data;
378         struct sockaddr_in local, foreign;
379         struct stat st;
380
381         /* Don't do anything if we don't have any tickets. */
382         if (stat(tkt_string(), &st) < 0)
383                 return 0;
384
385         strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
386
387         realm = (char *) krb_realmofhost(get_canonical_hostname());
388         if (!realm) {
389                 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
390                 return 0;
391         }
392         /* This can really be anything. */
393         checksum = (u_long) getpid();
394
395         r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
396         if (r != KSUCCESS) {
397                 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
398                 return 0;
399         }
400         /* Get session key to decrypt the server's reply with. */
401         r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
402         if (r != KSUCCESS) {
403                 debug("get_cred failed: %s", krb_err_txt[r]);
404                 return 0;
405         }
406         des_key_sched((des_cblock *) cred.session, schedule);
407
408         /* Send authentication info to server. */
409         packet_start(SSH_CMSG_AUTH_KERBEROS);
410         packet_put_string((char *) auth.dat, auth.length);
411         packet_send();
412         packet_write_wait();
413
414         /* Zero the buffer. */
415         (void) memset(auth.dat, 0, MAX_KTXT_LEN);
416
417         slen = sizeof(local);
418         memset(&local, 0, sizeof(local));
419         if (getsockname(packet_get_connection_in(),
420                         (struct sockaddr *) & local, &slen) < 0)
421                 debug("getsockname failed: %s", strerror(errno));
422
423         slen = sizeof(foreign);
424         memset(&foreign, 0, sizeof(foreign));
425         if (getpeername(packet_get_connection_in(),
426                         (struct sockaddr *) & foreign, &slen) < 0) {
427                 debug("getpeername failed: %s", strerror(errno));
428                 fatal_cleanup();
429         }
430         /* Get server reply. */
431         type = packet_read(&plen);
432         switch (type) {
433         case SSH_SMSG_FAILURE:
434                 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
435                 debug("Kerberos V4 authentication failed.");
436                 return 0;
437                 break;
438
439         case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
440                 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
441                 debug("Kerberos V4 authentication accepted.");
442
443                 /* Get server's response. */
444                 reply = packet_get_string((unsigned int *) &auth.length);
445                 memcpy(auth.dat, reply, auth.length);
446                 xfree(reply);
447
448                 packet_integrity_check(plen, 4 + auth.length, type);
449
450                 /*
451                  * If his response isn't properly encrypted with the session
452                  * key, and the decrypted checksum fails to match, he's
453                  * bogus. Bail out.
454                  */
455                 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
456                                 &foreign, &local, &msg_data);
457                 if (r != KSUCCESS) {
458                         debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
459                         packet_disconnect("Kerberos V4 challenge failed!");
460                 }
461                 /* Fetch the (incremented) checksum that we supplied in the request. */
462                 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
463                 cksum = ntohl(cksum);
464
465                 /* If it matches, we're golden. */
466                 if (cksum == checksum + 1) {
467                         debug("Kerberos V4 challenge successful.");
468                         return 1;
469                 } else
470                         packet_disconnect("Kerberos V4 challenge failed!");
471                 break;
472
473         default:
474                 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
475         }
476         return 0;
477 }
478
479 #endif /* KRB4 */
480
481 #ifdef AFS
482 int
483 send_kerberos_tgt()
484 {
485         CREDENTIALS *creds;
486         char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
487         int r, type, plen;
488         char buffer[8192];
489         struct stat st;
490
491         /* Don't do anything if we don't have any tickets. */
492         if (stat(tkt_string(), &st) < 0)
493                 return 0;
494
495         creds = xmalloc(sizeof(*creds));
496
497         if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
498                 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
499                 return 0;
500         }
501         if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
502                 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
503                 return 0;
504         }
505         if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
506                 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
507                 return 0;
508         }
509         creds_to_radix(creds, (unsigned char *)buffer, sizeof buffer);
510         xfree(creds);
511
512         packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
513         packet_put_string(buffer, strlen(buffer));
514         packet_send();
515         packet_write_wait();
516
517         type = packet_read(&plen);
518
519         if (type == SSH_SMSG_FAILURE)
520                 debug("Kerberos TGT for realm %s rejected.", prealm);
521         else if (type != SSH_SMSG_SUCCESS)
522                 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
523
524         return 1;
525 }
526
527 void
528 send_afs_tokens(void)
529 {
530         CREDENTIALS creds;
531         struct ViceIoctl parms;
532         struct ClearToken ct;
533         int i, type, len, plen;
534         char buf[2048], *p, *server_cell;
535         char buffer[8192];
536
537         /* Move over ktc_GetToken, here's something leaner. */
538         for (i = 0; i < 100; i++) {     /* just in case */
539                 parms.in = (char *) &i;
540                 parms.in_size = sizeof(i);
541                 parms.out = buf;
542                 parms.out_size = sizeof(buf);
543                 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
544                         break;
545                 p = buf;
546
547                 /* Get secret token. */
548                 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
549                 if (creds.ticket_st.length > MAX_KTXT_LEN)
550                         break;
551                 p += sizeof(unsigned int);
552                 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
553                 p += creds.ticket_st.length;
554
555                 /* Get clear token. */
556                 memcpy(&len, p, sizeof(len));
557                 if (len != sizeof(struct ClearToken))
558                         break;
559                 p += sizeof(len);
560                 memcpy(&ct, p, len);
561                 p += len;
562                 p += sizeof(len);       /* primary flag */
563                 server_cell = p;
564
565                 /* Flesh out our credentials. */
566                 strlcpy(creds.service, "afs", sizeof creds.service);
567                 creds.instance[0] = '\0';
568                 strlcpy(creds.realm, server_cell, REALM_SZ);
569                 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
570                 creds.issue_date = ct.BeginTimestamp;
571                 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
572                 creds.kvno = ct.AuthHandle;
573                 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
574                 creds.pinst[0] = '\0';
575
576                 /* Encode token, ship it off. */
577                 if (creds_to_radix(&creds, (unsigned char*) buffer, sizeof buffer) <= 0)
578                         break;
579                 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
580                 packet_put_string(buffer, strlen(buffer));
581                 packet_send();
582                 packet_write_wait();
583
584                 /* Roger, Roger. Clearance, Clarence. What's your vector,
585                    Victor? */
586                 type = packet_read(&plen);
587
588                 if (type == SSH_SMSG_FAILURE)
589                         debug("AFS token for cell %s rejected.", server_cell);
590                 else if (type != SSH_SMSG_SUCCESS)
591                         packet_disconnect("Protocol error on AFS token response: %d", type);
592         }
593 }
594
595 #endif /* AFS */
596
597 /*
598  * Tries to authenticate with any string-based challenge/response system.
599  * Note that the client code is not tied to s/key or TIS.
600  */
601 int
602 try_skey_authentication()
603 {
604         int type, i;
605         int payload_len;
606         unsigned int clen;
607         char prompt[1024];
608         char *challenge, *response;
609
610         debug("Doing skey authentication.");
611
612         for (i = 0; i < options.number_of_password_prompts; i++) {
613                 /* request a challenge */
614                 packet_start(SSH_CMSG_AUTH_TIS);
615                 packet_send();
616                 packet_write_wait();
617
618                 type = packet_read(&payload_len);
619                 if (type != SSH_SMSG_FAILURE &&
620                     type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
621                         packet_disconnect("Protocol error: got %d in response "
622                             "to skey-auth", type);
623                 }
624                 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
625                         debug("No challenge for skey authentication.");
626                         return 0;
627                 }
628                 challenge = packet_get_string(&clen);
629                 packet_integrity_check(payload_len, (4 + clen), type);
630                 snprintf(prompt, sizeof prompt, "%s\nResponse: ", challenge);
631                 xfree(challenge);
632                 if (i != 0)
633                         error("Permission denied, please try again.");
634                 if (options.cipher == SSH_CIPHER_NONE)
635                         log("WARNING: Encryption is disabled! "
636                             "Reponse will be transmitted in clear text.");
637                 response = read_passphrase(prompt, 0);
638                 if (strcmp(response, "") == 0) {
639                         xfree(response);
640                         break;
641                 }
642                 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
643                 packet_put_string(response, strlen(response));
644                 memset(response, 0, strlen(response));
645                 xfree(response);
646                 packet_send();
647                 packet_write_wait();
648                 type = packet_read(&payload_len);
649                 if (type == SSH_SMSG_SUCCESS)
650                         return 1;
651                 if (type != SSH_SMSG_FAILURE)
652                         packet_disconnect("Protocol error: got %d in response "
653                             "to skey-auth-reponse", type);
654         }
655         /* failure */
656         return 0;
657 }
658
659 /*
660  * Tries to authenticate with plain passwd authentication.
661  */
662 int
663 try_password_authentication(char *prompt)
664 {
665         int type, i, payload_len;
666         char *password;
667
668         debug("Doing password authentication.");
669         if (options.cipher == SSH_CIPHER_NONE)
670                 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
671         for (i = 0; i < options.number_of_password_prompts; i++) {
672                 if (i != 0)
673                         error("Permission denied, please try again.");
674                 password = read_passphrase(prompt, 0);
675                 packet_start(SSH_CMSG_AUTH_PASSWORD);
676                 packet_put_string(password, strlen(password));
677                 memset(password, 0, strlen(password));
678                 xfree(password);
679                 packet_send();
680                 packet_write_wait();
681
682                 type = packet_read(&payload_len);
683                 if (type == SSH_SMSG_SUCCESS)
684                         return 1;
685                 if (type != SSH_SMSG_FAILURE)
686                         packet_disconnect("Protocol error: got %d in response to passwd auth", type);
687         }
688         /* failure */
689         return 0;
690 }
691
692 /*
693  * SSH1 key exchange
694  */
695 void
696 ssh_kex(char *host, struct sockaddr *hostaddr)
697 {
698         int i;
699         BIGNUM *key;
700         RSA *host_key;
701         RSA *public_key;
702         Key k;
703         int bits, rbits;
704         int ssh_cipher_default = SSH_CIPHER_3DES;
705         unsigned char session_key[SSH_SESSION_KEY_LENGTH];
706         unsigned char cookie[8];
707         unsigned int supported_ciphers;
708         unsigned int server_flags, client_flags;
709         int payload_len, clen, sum_len = 0;
710         u_int32_t rand = 0;
711
712         debug("Waiting for server public key.");
713
714         /* Wait for a public key packet from the server. */
715         packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
716
717         /* Get cookie from the packet. */
718         for (i = 0; i < 8; i++)
719                 cookie[i] = packet_get_char();
720
721         /* Get the public key. */
722         public_key = RSA_new();
723         bits = packet_get_int();/* bits */
724         public_key->e = BN_new();
725         packet_get_bignum(public_key->e, &clen);
726         sum_len += clen;
727         public_key->n = BN_new();
728         packet_get_bignum(public_key->n, &clen);
729         sum_len += clen;
730
731         rbits = BN_num_bits(public_key->n);
732         if (bits != rbits) {
733                 log("Warning: Server lies about size of server public key: "
734                     "actual size is %d bits vs. announced %d.", rbits, bits);
735                 log("Warning: This may be due to an old implementation of ssh.");
736         }
737         /* Get the host key. */
738         host_key = RSA_new();
739         bits = packet_get_int();/* bits */
740         host_key->e = BN_new();
741         packet_get_bignum(host_key->e, &clen);
742         sum_len += clen;
743         host_key->n = BN_new();
744         packet_get_bignum(host_key->n, &clen);
745         sum_len += clen;
746
747         rbits = BN_num_bits(host_key->n);
748         if (bits != rbits) {
749                 log("Warning: Server lies about size of server host key: "
750                     "actual size is %d bits vs. announced %d.", rbits, bits);
751                 log("Warning: This may be due to an old implementation of ssh.");
752         }
753
754         /* Get protocol flags. */
755         server_flags = packet_get_int();
756         packet_set_protocol_flags(server_flags);
757
758         supported_ciphers = packet_get_int();
759         supported_authentications = packet_get_int();
760
761         debug("Received server public key (%d bits) and host key (%d bits).",
762               BN_num_bits(public_key->n), BN_num_bits(host_key->n));
763
764         packet_integrity_check(payload_len,
765                                8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
766                                SSH_SMSG_PUBLIC_KEY);
767         k.type = KEY_RSA1;
768         k.rsa = host_key;
769         check_host_key(host, hostaddr, &k,
770             options.user_hostfile, options.system_hostfile);
771
772         client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
773
774         compute_session_id(session_id, cookie, host_key->n, public_key->n);
775
776         /* Generate a session key. */
777         arc4random_stir();
778
779         /*
780          * Generate an encryption key for the session.   The key is a 256 bit
781          * random number, interpreted as a 32-byte key, with the least
782          * significant 8 bits being the first byte of the key.
783          */
784         for (i = 0; i < 32; i++) {
785                 if (i % 4 == 0)
786                         rand = arc4random();
787                 session_key[i] = rand & 0xff;
788                 rand >>= 8;
789         }
790
791         /*
792          * According to the protocol spec, the first byte of the session key
793          * is the highest byte of the integer.  The session key is xored with
794          * the first 16 bytes of the session id.
795          */
796         key = BN_new();
797         BN_set_word(key, 0);
798         for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
799                 BN_lshift(key, key, 8);
800                 if (i < 16)
801                         BN_add_word(key, session_key[i] ^ session_id[i]);
802                 else
803                         BN_add_word(key, session_key[i]);
804         }
805
806         /*
807          * Encrypt the integer using the public key and host key of the
808          * server (key with smaller modulus first).
809          */
810         if (BN_cmp(public_key->n, host_key->n) < 0) {
811                 /* Public key has smaller modulus. */
812                 if (BN_num_bits(host_key->n) <
813                     BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
814                         fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
815                               "SSH_KEY_BITS_RESERVED %d",
816                               BN_num_bits(host_key->n),
817                               BN_num_bits(public_key->n),
818                               SSH_KEY_BITS_RESERVED);
819                 }
820                 rsa_public_encrypt(key, key, public_key);
821                 rsa_public_encrypt(key, key, host_key);
822         } else {
823                 /* Host key has smaller modulus (or they are equal). */
824                 if (BN_num_bits(public_key->n) <
825                     BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
826                         fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
827                               "SSH_KEY_BITS_RESERVED %d",
828                               BN_num_bits(public_key->n),
829                               BN_num_bits(host_key->n),
830                               SSH_KEY_BITS_RESERVED);
831                 }
832                 rsa_public_encrypt(key, key, host_key);
833                 rsa_public_encrypt(key, key, public_key);
834         }
835
836         /* Destroy the public keys since we no longer need them. */
837         RSA_free(public_key);
838         RSA_free(host_key);
839
840         if (options.cipher == SSH_CIPHER_NOT_SET) {
841                 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
842                         options.cipher = ssh_cipher_default;
843         } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
844             !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
845                 log("No valid SSH1 cipher, using %.100s instead.",
846                     cipher_name(ssh_cipher_default));
847                 options.cipher = ssh_cipher_default;
848         }
849         /* Check that the selected cipher is supported. */
850         if (!(supported_ciphers & (1 << options.cipher)))
851                 fatal("Selected cipher type %.100s not supported by server.",
852                       cipher_name(options.cipher));
853
854         debug("Encryption type: %.100s", cipher_name(options.cipher));
855
856         /* Send the encrypted session key to the server. */
857         packet_start(SSH_CMSG_SESSION_KEY);
858         packet_put_char(options.cipher);
859
860         /* Send the cookie back to the server. */
861         for (i = 0; i < 8; i++)
862                 packet_put_char(cookie[i]);
863
864         /* Send and destroy the encrypted encryption key integer. */
865         packet_put_bignum(key);
866         BN_clear_free(key);
867
868         /* Send protocol flags. */
869         packet_put_int(client_flags);
870
871         /* Send the packet now. */
872         packet_send();
873         packet_write_wait();
874
875         debug("Sent encrypted session key.");
876
877         /* Set the encryption key. */
878         packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
879
880         /* We will no longer need the session key here.  Destroy any extra copies. */
881         memset(session_key, 0, sizeof(session_key));
882
883         /*
884          * Expect a success message from the server.  Note that this message
885          * will be received in encrypted form.
886          */
887         packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
888
889         debug("Received encrypted confirmation.");
890 }
891
892 /*
893  * Authenticate user
894  */
895 void
896 ssh_userauth(
897     const char* local_user,
898     const char* server_user,
899     char *host,
900     int host_key_valid, RSA *own_host_key)
901 {
902         int i, type;
903         int payload_len;
904
905         if (supported_authentications == 0)
906                 fatal("ssh_userauth: server supports no auth methods");
907
908         /* Send the name of the user to log in as on the server. */
909         packet_start(SSH_CMSG_USER);
910         packet_put_string(server_user, strlen(server_user));
911         packet_send();
912         packet_write_wait();
913
914         /*
915          * The server should respond with success if no authentication is
916          * needed (the user has no password).  Otherwise the server responds
917          * with failure.
918          */
919         type = packet_read(&payload_len);
920
921         /* check whether the connection was accepted without authentication. */
922         if (type == SSH_SMSG_SUCCESS)
923                 return;
924         if (type != SSH_SMSG_FAILURE)
925                 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
926                                   type);
927
928 #ifdef AFS
929         /* Try Kerberos tgt passing if the server supports it. */
930         if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
931             options.kerberos_tgt_passing) {
932                 if (options.cipher == SSH_CIPHER_NONE)
933                         log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
934                 (void) send_kerberos_tgt();
935         }
936         /* Try AFS token passing if the server supports it. */
937         if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
938             options.afs_token_passing && k_hasafs()) {
939                 if (options.cipher == SSH_CIPHER_NONE)
940                         log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
941                 send_afs_tokens();
942         }
943 #endif /* AFS */
944
945 #ifdef KRB4
946         if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
947             options.kerberos_authentication) {
948                 debug("Trying Kerberos authentication.");
949                 if (try_kerberos_authentication()) {
950                         /* The server should respond with success or failure. */
951                         type = packet_read(&payload_len);
952                         if (type == SSH_SMSG_SUCCESS)
953                                 return;
954                         if (type != SSH_SMSG_FAILURE)
955                                 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
956                 }
957         }
958 #endif /* KRB4 */
959
960         /*
961          * Use rhosts authentication if running in privileged socket and we
962          * do not wish to remain anonymous.
963          */
964         if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
965             options.rhosts_authentication) {
966                 debug("Trying rhosts authentication.");
967                 packet_start(SSH_CMSG_AUTH_RHOSTS);
968                 packet_put_string(local_user, strlen(local_user));
969                 packet_send();
970                 packet_write_wait();
971
972                 /* The server should respond with success or failure. */
973                 type = packet_read(&payload_len);
974                 if (type == SSH_SMSG_SUCCESS)
975                         return;
976                 if (type != SSH_SMSG_FAILURE)
977                         packet_disconnect("Protocol error: got %d in response to rhosts auth",
978                                           type);
979         }
980         /*
981          * Try .rhosts or /etc/hosts.equiv authentication with RSA host
982          * authentication.
983          */
984         if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
985             options.rhosts_rsa_authentication && host_key_valid) {
986                 if (try_rhosts_rsa_authentication(local_user, own_host_key))
987                         return;
988         }
989         /* Try RSA authentication if the server supports it. */
990         if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
991             options.rsa_authentication) {
992                 /*
993                  * Try RSA authentication using the authentication agent. The
994                  * agent is tried first because no passphrase is needed for
995                  * it, whereas identity files may require passphrases.
996                  */
997                 if (try_agent_authentication())
998                         return;
999
1000                 /* Try RSA authentication for each identity. */
1001                 for (i = 0; i < options.num_identity_files; i++)
1002                         if (options.identity_files_type[i] == KEY_RSA1 &&
1003                             try_rsa_authentication(options.identity_files[i]))
1004                                 return;
1005         }
1006         /* Try skey authentication if the server supports it. */
1007         if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1008             options.skey_authentication && !options.batch_mode) {
1009                 if (try_skey_authentication())
1010                         return;
1011         }
1012         /* Try password authentication if the server supports it. */
1013         if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1014             options.password_authentication && !options.batch_mode) {
1015                 char prompt[80];
1016
1017                 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1018                     server_user, host);
1019                 if (try_password_authentication(prompt))
1020                         return;
1021         }
1022         /* All authentication methods have failed.  Exit with an error message. */
1023         fatal("Permission denied.");
1024         /* NOTREACHED */
1025 }
This page took 1.152658 seconds and 5 git commands to generate.