Merge branch 'vendor/TNFTP'
[dragonfly.git] / crypto / openssh / authfile.c
1 /* $OpenBSD: authfile.c,v 1.82 2010/08/04 05:49:22 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for reading and writing identity files, and
7  * for reading the passphrase from the user.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */
38
39 #include "includes.h"
40
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <sys/param.h>
44 #include <sys/uio.h>
45
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
49
50 /* compatibility with old or broken OpenSSL versions */
51 #include "openbsd-compat/openssl-compat.h"
52
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdarg.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60
61 #include "xmalloc.h"
62 #include "cipher.h"
63 #include "buffer.h"
64 #include "key.h"
65 #include "ssh.h"
66 #include "log.h"
67 #include "authfile.h"
68 #include "rsa.h"
69 #include "misc.h"
70 #include "atomicio.h"
71 #include "pathnames.h"
72
73 /* Version identification string for SSH v1 identity files. */
74 static const char authfile_id_string[] =
75     "SSH PRIVATE KEY FILE FORMAT 1.1\n";
76
77 /*
78  * Saves the authentication (private) key in a file, encrypting it with
79  * passphrase.  The identification of the file (lowest 64 bits of n) will
80  * precede the key to provide identification of the key without needing a
81  * passphrase.
82  */
83
84 static int
85 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
86     const char *comment)
87 {
88         Buffer buffer, encrypted;
89         u_char buf[100], *cp;
90         int fd, i, cipher_num;
91         CipherContext ciphercontext;
92         Cipher *cipher;
93         u_int32_t rnd;
94
95         /*
96          * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
97          * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
98          */
99         cipher_num = (strcmp(passphrase, "") == 0) ?
100             SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
101         if ((cipher = cipher_by_number(cipher_num)) == NULL)
102                 fatal("save_private_key_rsa: bad cipher");
103
104         /* This buffer is used to built the secret part of the private key. */
105         buffer_init(&buffer);
106
107         /* Put checkbytes for checking passphrase validity. */
108         rnd = arc4random();
109         buf[0] = rnd & 0xff;
110         buf[1] = (rnd >> 8) & 0xff;
111         buf[2] = buf[0];
112         buf[3] = buf[1];
113         buffer_append(&buffer, buf, 4);
114
115         /*
116          * Store the private key (n and e will not be stored because they
117          * will be stored in plain text, and storing them also in encrypted
118          * format would just give known plaintext).
119          */
120         buffer_put_bignum(&buffer, key->rsa->d);
121         buffer_put_bignum(&buffer, key->rsa->iqmp);
122         buffer_put_bignum(&buffer, key->rsa->q);        /* reverse from SSL p */
123         buffer_put_bignum(&buffer, key->rsa->p);        /* reverse from SSL q */
124
125         /* Pad the part to be encrypted until its size is a multiple of 8. */
126         while (buffer_len(&buffer) % 8 != 0)
127                 buffer_put_char(&buffer, 0);
128
129         /* This buffer will be used to contain the data in the file. */
130         buffer_init(&encrypted);
131
132         /* First store keyfile id string. */
133         for (i = 0; authfile_id_string[i]; i++)
134                 buffer_put_char(&encrypted, authfile_id_string[i]);
135         buffer_put_char(&encrypted, 0);
136
137         /* Store cipher type. */
138         buffer_put_char(&encrypted, cipher_num);
139         buffer_put_int(&encrypted, 0);  /* For future extension */
140
141         /* Store public key.  This will be in plain text. */
142         buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
143         buffer_put_bignum(&encrypted, key->rsa->n);
144         buffer_put_bignum(&encrypted, key->rsa->e);
145         buffer_put_cstring(&encrypted, comment);
146
147         /* Allocate space for the private part of the key in the buffer. */
148         cp = buffer_append_space(&encrypted, buffer_len(&buffer));
149
150         cipher_set_key_string(&ciphercontext, cipher, passphrase,
151             CIPHER_ENCRYPT);
152         cipher_crypt(&ciphercontext, cp,
153             buffer_ptr(&buffer), buffer_len(&buffer));
154         cipher_cleanup(&ciphercontext);
155         memset(&ciphercontext, 0, sizeof(ciphercontext));
156
157         /* Destroy temporary data. */
158         memset(buf, 0, sizeof(buf));
159         buffer_free(&buffer);
160
161         fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
162         if (fd < 0) {
163                 error("open %s failed: %s.", filename, strerror(errno));
164                 buffer_free(&encrypted);
165                 return 0;
166         }
167         if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
168             buffer_len(&encrypted)) != buffer_len(&encrypted)) {
169                 error("write to key file %s failed: %s", filename,
170                     strerror(errno));
171                 buffer_free(&encrypted);
172                 close(fd);
173                 unlink(filename);
174                 return 0;
175         }
176         close(fd);
177         buffer_free(&encrypted);
178         return 1;
179 }
180
181 /* save SSH v2 key in OpenSSL PEM format */
182 static int
183 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
184     const char *comment)
185 {
186         FILE *fp;
187         int fd;
188         int success = 0;
189         int len = strlen(_passphrase);
190         u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
191 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
192         const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
193 #else
194         const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
195 #endif
196
197         if (len > 0 && len <= 4) {
198                 error("passphrase too short: have %d bytes, need > 4", len);
199                 return 0;
200         }
201         fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
202         if (fd < 0) {
203                 error("open %s failed: %s.", filename, strerror(errno));
204                 return 0;
205         }
206         fp = fdopen(fd, "w");
207         if (fp == NULL) {
208                 error("fdopen %s failed: %s.", filename, strerror(errno));
209                 close(fd);
210                 return 0;
211         }
212         switch (key->type) {
213         case KEY_DSA:
214                 success = PEM_write_DSAPrivateKey(fp, key->dsa,
215                     cipher, passphrase, len, NULL, NULL);
216                 break;
217         case KEY_RSA:
218                 success = PEM_write_RSAPrivateKey(fp, key->rsa,
219                     cipher, passphrase, len, NULL, NULL);
220                 break;
221         }
222         fclose(fp);
223         return success;
224 }
225
226 int
227 key_save_private(Key *key, const char *filename, const char *passphrase,
228     const char *comment)
229 {
230         switch (key->type) {
231         case KEY_RSA1:
232                 return key_save_private_rsa1(key, filename, passphrase,
233                     comment);
234         case KEY_DSA:
235         case KEY_RSA:
236                 return key_save_private_pem(key, filename, passphrase,
237                     comment);
238         default:
239                 break;
240         }
241         error("key_save_private: cannot save key type %d", key->type);
242         return 0;
243 }
244
245 /*
246  * Loads the public part of the ssh v1 key file.  Returns NULL if an error was
247  * encountered (the file does not exist or is not readable), and the key
248  * otherwise.
249  */
250
251 static Key *
252 key_load_public_rsa1(int fd, const char *filename, char **commentp)
253 {
254         Buffer buffer;
255         Key *pub;
256         struct stat st;
257         char *cp;
258         u_int i;
259         size_t len;
260
261         if (fstat(fd, &st) < 0) {
262                 error("fstat for key file %.200s failed: %.100s",
263                     filename, strerror(errno));
264                 return NULL;
265         }
266         if (st.st_size > 1*1024*1024) {
267                 error("key file %.200s too large", filename);
268                 return NULL;
269         }
270         len = (size_t)st.st_size;               /* truncated */
271
272         buffer_init(&buffer);
273         cp = buffer_append_space(&buffer, len);
274
275         if (atomicio(read, fd, cp, len) != len) {
276                 debug("Read from key file %.200s failed: %.100s", filename,
277                     strerror(errno));
278                 buffer_free(&buffer);
279                 return NULL;
280         }
281
282         /* Check that it is at least big enough to contain the ID string. */
283         if (len < sizeof(authfile_id_string)) {
284                 debug3("Not a RSA1 key file %.200s.", filename);
285                 buffer_free(&buffer);
286                 return NULL;
287         }
288         /*
289          * Make sure it begins with the id string.  Consume the id string
290          * from the buffer.
291          */
292         for (i = 0; i < sizeof(authfile_id_string); i++)
293                 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
294                         debug3("Not a RSA1 key file %.200s.", filename);
295                         buffer_free(&buffer);
296                         return NULL;
297                 }
298         /* Skip cipher type and reserved data. */
299         (void) buffer_get_char(&buffer);        /* cipher type */
300         (void) buffer_get_int(&buffer);         /* reserved */
301
302         /* Read the public key from the buffer. */
303         (void) buffer_get_int(&buffer);
304         pub = key_new(KEY_RSA1);
305         buffer_get_bignum(&buffer, pub->rsa->n);
306         buffer_get_bignum(&buffer, pub->rsa->e);
307         if (commentp)
308                 *commentp = buffer_get_string(&buffer, NULL);
309         /* The encrypted private part is not parsed by this function. */
310
311         buffer_free(&buffer);
312         return pub;
313 }
314
315 /* load public key from private-key file, works only for SSH v1 */
316 Key *
317 key_load_public_type(int type, const char *filename, char **commentp)
318 {
319         Key *pub;
320         int fd;
321
322         if (type == KEY_RSA1) {
323                 fd = open(filename, O_RDONLY);
324                 if (fd < 0)
325                         return NULL;
326                 pub = key_load_public_rsa1(fd, filename, commentp);
327                 close(fd);
328                 return pub;
329         }
330         return NULL;
331 }
332
333 /*
334  * Loads the private key from the file.  Returns 0 if an error is encountered
335  * (file does not exist or is not readable, or passphrase is bad). This
336  * initializes the private key.
337  * Assumes we are called under uid of the owner of the file.
338  */
339
340 static Key *
341 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
342     char **commentp)
343 {
344         u_int i;
345         int check1, check2, cipher_type;
346         size_t len;
347         Buffer buffer, decrypted;
348         u_char *cp;
349         CipherContext ciphercontext;
350         Cipher *cipher;
351         Key *prv = NULL;
352         struct stat st;
353
354         if (fstat(fd, &st) < 0) {
355                 error("fstat for key file %.200s failed: %.100s",
356                     filename, strerror(errno));
357                 close(fd);
358                 return NULL;
359         }
360         if (st.st_size > 1*1024*1024) {
361                 error("key file %.200s too large", filename);
362                 close(fd);
363                 return (NULL);
364         }
365         len = (size_t)st.st_size;               /* truncated */
366
367         buffer_init(&buffer);
368         cp = buffer_append_space(&buffer, len);
369
370         if (atomicio(read, fd, cp, len) != len) {
371                 debug("Read from key file %.200s failed: %.100s", filename,
372                     strerror(errno));
373                 buffer_free(&buffer);
374                 close(fd);
375                 return NULL;
376         }
377
378         /* Check that it is at least big enough to contain the ID string. */
379         if (len < sizeof(authfile_id_string)) {
380                 debug3("Not a RSA1 key file %.200s.", filename);
381                 buffer_free(&buffer);
382                 close(fd);
383                 return NULL;
384         }
385         /*
386          * Make sure it begins with the id string.  Consume the id string
387          * from the buffer.
388          */
389         for (i = 0; i < sizeof(authfile_id_string); i++)
390                 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
391                         debug3("Not a RSA1 key file %.200s.", filename);
392                         buffer_free(&buffer);
393                         close(fd);
394                         return NULL;
395                 }
396
397         /* Read cipher type. */
398         cipher_type = buffer_get_char(&buffer);
399         (void) buffer_get_int(&buffer); /* Reserved data. */
400
401         /* Read the public key from the buffer. */
402         (void) buffer_get_int(&buffer);
403         prv = key_new_private(KEY_RSA1);
404
405         buffer_get_bignum(&buffer, prv->rsa->n);
406         buffer_get_bignum(&buffer, prv->rsa->e);
407         if (commentp)
408                 *commentp = buffer_get_string(&buffer, NULL);
409         else
410                 xfree(buffer_get_string(&buffer, NULL));
411
412         /* Check that it is a supported cipher. */
413         cipher = cipher_by_number(cipher_type);
414         if (cipher == NULL) {
415                 debug("Unsupported cipher %d used in key file %.200s.",
416                     cipher_type, filename);
417                 buffer_free(&buffer);
418                 goto fail;
419         }
420         /* Initialize space for decrypted data. */
421         buffer_init(&decrypted);
422         cp = buffer_append_space(&decrypted, buffer_len(&buffer));
423
424         /* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
425         cipher_set_key_string(&ciphercontext, cipher, passphrase,
426             CIPHER_DECRYPT);
427         cipher_crypt(&ciphercontext, cp,
428             buffer_ptr(&buffer), buffer_len(&buffer));
429         cipher_cleanup(&ciphercontext);
430         memset(&ciphercontext, 0, sizeof(ciphercontext));
431         buffer_free(&buffer);
432
433         check1 = buffer_get_char(&decrypted);
434         check2 = buffer_get_char(&decrypted);
435         if (check1 != buffer_get_char(&decrypted) ||
436             check2 != buffer_get_char(&decrypted)) {
437                 if (strcmp(passphrase, "") != 0)
438                         debug("Bad passphrase supplied for key file %.200s.",
439                             filename);
440                 /* Bad passphrase. */
441                 buffer_free(&decrypted);
442                 goto fail;
443         }
444         /* Read the rest of the private key. */
445         buffer_get_bignum(&decrypted, prv->rsa->d);
446         buffer_get_bignum(&decrypted, prv->rsa->iqmp);          /* u */
447         /* in SSL and SSH v1 p and q are exchanged */
448         buffer_get_bignum(&decrypted, prv->rsa->q);             /* p */
449         buffer_get_bignum(&decrypted, prv->rsa->p);             /* q */
450
451         /* calculate p-1 and q-1 */
452         rsa_generate_additional_parameters(prv->rsa);
453
454         buffer_free(&decrypted);
455
456         /* enable blinding */
457         if (RSA_blinding_on(prv->rsa, NULL) != 1) {
458                 error("key_load_private_rsa1: RSA_blinding_on failed");
459                 goto fail;
460         }
461         close(fd);
462         return prv;
463
464 fail:
465         if (commentp)
466                 xfree(*commentp);
467         close(fd);
468         key_free(prv);
469         return NULL;
470 }
471
472 Key *
473 key_load_private_pem(int fd, int type, const char *passphrase,
474     char **commentp)
475 {
476         FILE *fp;
477         EVP_PKEY *pk = NULL;
478         Key *prv = NULL;
479         char *name = "<no key>";
480
481         fp = fdopen(fd, "r");
482         if (fp == NULL) {
483                 error("fdopen failed: %s", strerror(errno));
484                 close(fd);
485                 return NULL;
486         }
487         pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
488         if (pk == NULL) {
489                 debug("PEM_read_PrivateKey failed");
490                 (void)ERR_get_error();
491         } else if (pk->type == EVP_PKEY_RSA &&
492             (type == KEY_UNSPEC||type==KEY_RSA)) {
493                 prv = key_new(KEY_UNSPEC);
494                 prv->rsa = EVP_PKEY_get1_RSA(pk);
495                 prv->type = KEY_RSA;
496                 name = "rsa w/o comment";
497 #ifdef DEBUG_PK
498                 RSA_print_fp(stderr, prv->rsa, 8);
499 #endif
500                 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
501                         error("key_load_private_pem: RSA_blinding_on failed");
502                         key_free(prv);
503                         prv = NULL;
504                 }
505         } else if (pk->type == EVP_PKEY_DSA &&
506             (type == KEY_UNSPEC||type==KEY_DSA)) {
507                 prv = key_new(KEY_UNSPEC);
508                 prv->dsa = EVP_PKEY_get1_DSA(pk);
509                 prv->type = KEY_DSA;
510                 name = "dsa w/o comment";
511 #ifdef DEBUG_PK
512                 DSA_print_fp(stderr, prv->dsa, 8);
513 #endif
514         } else {
515                 error("PEM_read_PrivateKey: mismatch or "
516                     "unknown EVP_PKEY save_type %d", pk->save_type);
517         }
518         fclose(fp);
519         if (pk != NULL)
520                 EVP_PKEY_free(pk);
521         if (prv != NULL && commentp)
522                 *commentp = xstrdup(name);
523         debug("read PEM private key done: type %s",
524             prv ? key_type(prv) : "<unknown>");
525         return prv;
526 }
527
528 int
529 key_perm_ok(int fd, const char *filename)
530 {
531         struct stat st;
532
533         if (fstat(fd, &st) < 0)
534                 return 0;
535         /*
536          * if a key owned by the user is accessed, then we check the
537          * permissions of the file. if the key owned by a different user,
538          * then we don't care.
539          */
540 #ifdef HAVE_CYGWIN
541         if (check_ntsec(filename))
542 #endif
543         if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
544                 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
545                 error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
546                 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
547                 error("Permissions 0%3.3o for '%s' are too open.",
548                     (u_int)st.st_mode & 0777, filename);
549                 error("It is recommended that your private key files are NOT accessible by others.");
550                 error("This private key will be ignored.");
551                 return 0;
552         }
553         return 1;
554 }
555
556 Key *
557 key_load_private_type(int type, const char *filename, const char *passphrase,
558     char **commentp, int *perm_ok)
559 {
560         int fd;
561
562         fd = open(filename, O_RDONLY);
563         if (fd < 0) {
564                 debug("could not open key file '%s': %s", filename,
565                     strerror(errno));
566                 if (perm_ok != NULL)
567                         *perm_ok = 0;
568                 return NULL;
569         }
570         if (!key_perm_ok(fd, filename)) {
571                 if (perm_ok != NULL)
572                         *perm_ok = 0;
573                 error("bad permissions: ignore key: %s", filename);
574                 close(fd);
575                 return NULL;
576         }
577         if (perm_ok != NULL)
578                 *perm_ok = 1;
579         switch (type) {
580         case KEY_RSA1:
581                 return key_load_private_rsa1(fd, filename, passphrase,
582                     commentp);
583                 /* closes fd */
584         case KEY_DSA:
585         case KEY_RSA:
586         case KEY_UNSPEC:
587                 return key_load_private_pem(fd, type, passphrase, commentp);
588                 /* closes fd */
589         default:
590                 close(fd);
591                 break;
592         }
593         return NULL;
594 }
595
596 Key *
597 key_load_private(const char *filename, const char *passphrase,
598     char **commentp)
599 {
600         Key *pub, *prv;
601         int fd;
602
603         fd = open(filename, O_RDONLY);
604         if (fd < 0) {
605                 debug("could not open key file '%s': %s", filename,
606                     strerror(errno));
607                 return NULL;
608         }
609         if (!key_perm_ok(fd, filename)) {
610                 error("bad permissions: ignore key: %s", filename);
611                 close(fd);
612                 return NULL;
613         }
614         pub = key_load_public_rsa1(fd, filename, commentp);
615         lseek(fd, (off_t) 0, SEEK_SET);         /* rewind */
616         if (pub == NULL) {
617                 /* closes fd */
618                 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
619                 /* use the filename as a comment for PEM */
620                 if (commentp && prv)
621                         *commentp = xstrdup(filename);
622         } else {
623                 /* it's a SSH v1 key if the public key part is readable */
624                 key_free(pub);
625                 /* closes fd */
626                 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
627         }
628         return prv;
629 }
630
631 static int
632 key_try_load_public(Key *k, const char *filename, char **commentp)
633 {
634         FILE *f;
635         char line[SSH_MAX_PUBKEY_BYTES];
636         char *cp;
637         u_long linenum = 0;
638
639         f = fopen(filename, "r");
640         if (f != NULL) {
641                 while (read_keyfile_line(f, filename, line, sizeof(line),
642                             &linenum) != -1) {
643                         cp = line;
644                         switch (*cp) {
645                         case '#':
646                         case '\n':
647                         case '\0':
648                                 continue;
649                         }
650                         /* Skip leading whitespace. */
651                         for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
652                                 ;
653                         if (*cp) {
654                                 if (key_read(k, &cp) == 1) {
655                                         if (commentp)
656                                                 *commentp=xstrdup(filename);
657                                         fclose(f);
658                                         return 1;
659                                 }
660                         }
661                 }
662                 fclose(f);
663         }
664         return 0;
665 }
666
667 /* load public key from ssh v1 private or any pubkey file */
668 Key *
669 key_load_public(const char *filename, char **commentp)
670 {
671         Key *pub;
672         char file[MAXPATHLEN];
673
674         /* try rsa1 private key */
675         pub = key_load_public_type(KEY_RSA1, filename, commentp);
676         if (pub != NULL)
677                 return pub;
678
679         /* try rsa1 public key */
680         pub = key_new(KEY_RSA1);
681         if (key_try_load_public(pub, filename, commentp) == 1)
682                 return pub;
683         key_free(pub);
684
685         /* try ssh2 public key */
686         pub = key_new(KEY_UNSPEC);
687         if (key_try_load_public(pub, filename, commentp) == 1)
688                 return pub;
689         if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
690             (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
691             (key_try_load_public(pub, file, commentp) == 1))
692                 return pub;
693         key_free(pub);
694         return NULL;
695 }
696
697 char *
698 blacklist_filename(const Key *key)
699 {
700         char *name;
701
702         xasprintf(&name, "%s.%s-%u",
703             _PATH_BLACKLIST, key_type(key), key_size(key));
704         return name;
705 }
706
707 /* Scan a blacklist of known-vulnerable keys. */
708 int
709 blacklisted_key(Key *key)
710 {
711         char *blacklist_file;
712         int fd = -1;
713         char *dgst_hex = NULL;
714         char *dgst_packed = NULL, *p;
715         int i;
716         size_t line_len;
717         struct stat st;
718         char buf[256];
719         off_t start, lower, upper;
720         int ret = 0;
721
722         blacklist_file = blacklist_filename(key);
723         debug("Checking blacklist file %s", blacklist_file);
724         fd = open(blacklist_file, O_RDONLY);
725         if (fd < 0)
726                 goto out;
727
728         dgst_hex = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
729         /* Remove all colons */
730         dgst_packed = xcalloc(1, strlen(dgst_hex) + 1);
731         for (i = 0, p = dgst_packed; dgst_hex[i]; i++)
732                 if (dgst_hex[i] != ':')
733                         *p++ = dgst_hex[i];
734         /* Only compare least-significant 80 bits (to keep the blacklist
735          * size down)
736          */
737         line_len = strlen(dgst_packed + 12);
738         if (line_len > 32)
739                 goto out;
740
741         /* Skip leading comments */
742         start = 0;
743         for (;;) {
744                 ssize_t r;
745                 char *newline;
746
747                 r = atomicio(read, fd, buf, 256);
748                 if (r <= 0)
749                         goto out;
750                 if (buf[0] != '#')
751                         break;
752
753                 newline = memchr(buf, '\n', 256);
754                 if (!newline)
755                         goto out;
756                 start += newline + 1 - buf;
757                 if (lseek(fd, start, SEEK_SET) < 0)
758                         goto out;
759         }
760
761         /* Initialise binary search record numbers */
762         if (fstat(fd, &st) < 0)
763                 goto out;
764         lower = 0;
765         upper = (st.st_size - start) / (line_len + 1);
766
767         while (lower != upper) {
768                 off_t cur;
769                 char buf[32];
770                 int cmp;
771
772                 cur = lower + (upper - lower) / 2;
773
774                 /* Read this line and compare to digest; this is
775                  * overflow-safe since cur < max(off_t) / (line_len + 1) */
776                 if (lseek(fd, start + cur * (line_len + 1), SEEK_SET) < 0)
777                         break;
778                 if (atomicio(read, fd, buf, line_len) != line_len)
779                         break;
780                 cmp = memcmp(buf, dgst_packed + 12, line_len);
781                 if (cmp < 0) {
782                         if (cur == lower)
783                                 break;
784                         lower = cur;
785                 } else if (cmp > 0) {
786                         if (cur == upper)
787                                 break;
788                         upper = cur;
789                 } else {
790                         debug("Found %s in blacklist", dgst_hex);
791                         ret = 1;
792                         break;
793                 }
794         }
795
796 out:
797         if (dgst_packed)
798                 xfree(dgst_packed);
799         if (dgst_hex)
800                 xfree(dgst_hex);
801         if (fd >= 0)
802                 close(fd);
803         xfree(blacklist_file);
804         return ret;
805 }
806
807 /* Load the certificate associated with the named private key */
808 Key *
809 key_load_cert(const char *filename)
810 {
811         Key *pub;
812         char *file;
813
814         pub = key_new(KEY_UNSPEC);
815         xasprintf(&file, "%s-cert.pub", filename);
816         if (key_try_load_public(pub, file, NULL) == 1) {
817                 xfree(file);
818                 return pub;
819         }
820         xfree(file);
821         key_free(pub);
822         return NULL;
823 }
824
825 /* Load private key and certificate */
826 Key *
827 key_load_private_cert(int type, const char *filename, const char *passphrase,
828     int *perm_ok)
829 {
830         Key *key, *pub;
831
832         switch (type) {
833         case KEY_RSA:
834         case KEY_DSA:
835                 break;
836         default:
837                 error("%s: unsupported key type", __func__);
838                 return NULL;
839         }
840
841         if ((key = key_load_private_type(type, filename, 
842             passphrase, NULL, perm_ok)) == NULL)
843                 return NULL;
844
845         if ((pub = key_load_cert(filename)) == NULL) {
846                 key_free(key);
847                 return NULL;
848         }
849
850         /* Make sure the private key matches the certificate */
851         if (key_equal_public(key, pub) == 0) {
852                 error("%s: certificate does not match private key %s",
853                     __func__, filename);
854         } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
855                 error("%s: key_to_certified failed", __func__);
856         } else {
857                 key_cert_copy(pub, key);
858                 key_free(pub);
859                 return key;
860         }
861
862         key_free(key);
863         key_free(pub);
864         return NULL;
865 }
866
867 /*
868  * Returns 1 if the specified "key" is listed in the file "filename",
869  * 0 if the key is not listed or -1 on error.
870  * If strict_type is set then the key type must match exactly,
871  * otherwise a comparison that ignores certficiate data is performed.
872  */
873 int
874 key_in_file(Key *key, const char *filename, int strict_type)
875 {
876         FILE *f;
877         char line[SSH_MAX_PUBKEY_BYTES];
878         char *cp;
879         u_long linenum = 0;
880         int ret = 0;
881         Key *pub;
882         int (*key_compare)(const Key *, const Key *) = strict_type ?
883             key_equal : key_equal_public;
884
885         if ((f = fopen(filename, "r")) == NULL) {
886                 if (errno == ENOENT) {
887                         debug("%s: keyfile \"%s\" missing", __func__, filename);
888                         return 0;
889                 } else {
890                         error("%s: could not open keyfile \"%s\": %s", __func__,
891                             filename, strerror(errno));
892                         return -1;
893                 }
894         }
895
896         while (read_keyfile_line(f, filename, line, sizeof(line),
897                     &linenum) != -1) {
898                 cp = line;
899
900                 /* Skip leading whitespace. */
901                 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
902                         ;
903
904                 /* Skip comments and empty lines */
905                 switch (*cp) {
906                 case '#':
907                 case '\n':
908                 case '\0':
909                         continue;
910                 }
911
912                 pub = key_new(KEY_UNSPEC);
913                 if (key_read(pub, &cp) != 1) {
914                         key_free(pub);
915                         continue;
916                 }
917                 if (key_compare(key, pub)) {
918                         ret = 1;
919                         key_free(pub);
920                         break;
921                 }
922                 key_free(pub);
923         }
924         fclose(f);
925         return ret;
926 }
927