Note appropriate krb5 build dependency
[openssh.git] / authfile.c
1 /* $OpenBSD: authfile.c,v 1.87 2010/11/29 18:57:04 markus 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  * Serialises the authentication (private) key to a blob, encrypting it with
79  * passphrase.  The identification of the blob (lowest 64 bits of n) will
80  * precede the key to provide identification of the key without needing a
81  * passphrase.
82  */
83 static int
84 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
85     const char *comment)
86 {
87         Buffer buffer, encrypted;
88         u_char buf[100], *cp;
89         int i, cipher_num;
90         CipherContext ciphercontext;
91         Cipher *cipher;
92         u_int32_t rnd;
93
94         /*
95          * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
96          * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
97          */
98         cipher_num = (strcmp(passphrase, "") == 0) ?
99             SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
100         if ((cipher = cipher_by_number(cipher_num)) == NULL)
101                 fatal("save_private_key_rsa: bad cipher");
102
103         /* This buffer is used to built the secret part of the private key. */
104         buffer_init(&buffer);
105
106         /* Put checkbytes for checking passphrase validity. */
107         rnd = arc4random();
108         buf[0] = rnd & 0xff;
109         buf[1] = (rnd >> 8) & 0xff;
110         buf[2] = buf[0];
111         buf[3] = buf[1];
112         buffer_append(&buffer, buf, 4);
113
114         /*
115          * Store the private key (n and e will not be stored because they
116          * will be stored in plain text, and storing them also in encrypted
117          * format would just give known plaintext).
118          */
119         buffer_put_bignum(&buffer, key->rsa->d);
120         buffer_put_bignum(&buffer, key->rsa->iqmp);
121         buffer_put_bignum(&buffer, key->rsa->q);        /* reverse from SSL p */
122         buffer_put_bignum(&buffer, key->rsa->p);        /* reverse from SSL q */
123
124         /* Pad the part to be encrypted until its size is a multiple of 8. */
125         while (buffer_len(&buffer) % 8 != 0)
126                 buffer_put_char(&buffer, 0);
127
128         /* This buffer will be used to contain the data in the file. */
129         buffer_init(&encrypted);
130
131         /* First store keyfile id string. */
132         for (i = 0; authfile_id_string[i]; i++)
133                 buffer_put_char(&encrypted, authfile_id_string[i]);
134         buffer_put_char(&encrypted, 0);
135
136         /* Store cipher type. */
137         buffer_put_char(&encrypted, cipher_num);
138         buffer_put_int(&encrypted, 0);  /* For future extension */
139
140         /* Store public key.  This will be in plain text. */
141         buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
142         buffer_put_bignum(&encrypted, key->rsa->n);
143         buffer_put_bignum(&encrypted, key->rsa->e);
144         buffer_put_cstring(&encrypted, comment);
145
146         /* Allocate space for the private part of the key in the buffer. */
147         cp = buffer_append_space(&encrypted, buffer_len(&buffer));
148
149         cipher_set_key_string(&ciphercontext, cipher, passphrase,
150             CIPHER_ENCRYPT);
151         cipher_crypt(&ciphercontext, cp,
152             buffer_ptr(&buffer), buffer_len(&buffer));
153         cipher_cleanup(&ciphercontext);
154         memset(&ciphercontext, 0, sizeof(ciphercontext));
155
156         /* Destroy temporary data. */
157         memset(buf, 0, sizeof(buf));
158         buffer_free(&buffer);
159
160         buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
161         buffer_free(&encrypted);
162
163         return 1;
164 }
165
166 /* convert SSH v2 key in OpenSSL PEM format */
167 static int
168 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
169     const char *comment)
170 {
171         int success = 0;
172         int blen, len = strlen(_passphrase);
173         u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
174 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
175         const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
176 #else
177         const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
178 #endif
179         const u_char *bptr;
180         BIO *bio;
181
182         if (len > 0 && len <= 4) {
183                 error("passphrase too short: have %d bytes, need > 4", len);
184                 return 0;
185         }
186         if ((bio = BIO_new(BIO_s_mem())) == NULL) {
187                 error("%s: BIO_new failed", __func__);
188                 return 0;
189         }
190         switch (key->type) {
191         case KEY_DSA:
192                 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
193                     cipher, passphrase, len, NULL, NULL);
194                 break;
195 #ifdef OPENSSL_HAS_ECC
196         case KEY_ECDSA:
197                 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
198                     cipher, passphrase, len, NULL, NULL);
199                 break;
200 #endif
201         case KEY_RSA:
202                 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
203                     cipher, passphrase, len, NULL, NULL);
204                 break;
205         }
206         if (success) {
207                 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
208                         success = 0;
209                 else
210                         buffer_append(blob, bptr, blen);
211         }
212         BIO_free(bio);
213         return success;
214 }
215
216 /* Save a key blob to a file */
217 static int
218 key_save_private_blob(Buffer *keybuf, const char *filename)
219 {
220         int fd;
221
222         if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
223                 error("open %s failed: %s.", filename, strerror(errno));
224                 return 0;
225         }
226         if (atomicio(vwrite, fd, buffer_ptr(keybuf),
227             buffer_len(keybuf)) != buffer_len(keybuf)) {
228                 error("write to key file %s failed: %s", filename,
229                     strerror(errno));
230                 close(fd);
231                 unlink(filename);
232                 return 0;
233         }
234         close(fd);
235         return 1;
236 }
237
238 /* Serialise "key" to buffer "blob" */
239 static int
240 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
241     const char *comment)
242 {
243         switch (key->type) {
244         case KEY_RSA1:
245                 return key_private_rsa1_to_blob(key, blob, passphrase, comment);
246         case KEY_DSA:
247         case KEY_ECDSA:
248         case KEY_RSA:
249                 return key_private_pem_to_blob(key, blob, passphrase, comment);
250         default:
251                 error("%s: cannot save key type %d", __func__, key->type);
252                 return 0;
253         }
254 }
255
256 int
257 key_save_private(Key *key, const char *filename, const char *passphrase,
258     const char *comment)
259 {
260         Buffer keyblob;
261         int success = 0;
262
263         buffer_init(&keyblob);
264         if (!key_private_to_blob(key, &keyblob, passphrase, comment))
265                 goto out;
266         if (!key_save_private_blob(&keyblob, filename))
267                 goto out;
268         success = 1;
269  out:
270         buffer_free(&keyblob);
271         return success;
272 }
273
274 /*
275  * Parse the public, unencrypted portion of a RSA1 key.
276  */
277 static Key *
278 key_parse_public_rsa1(Buffer *blob, char **commentp)
279 {
280         Key *pub;
281
282         /* Check that it is at least big enough to contain the ID string. */
283         if (buffer_len(blob) < sizeof(authfile_id_string)) {
284                 debug3("Truncated RSA1 identifier");
285                 return NULL;
286         }
287
288         /*
289          * Make sure it begins with the id string.  Consume the id string
290          * from the buffer.
291          */
292         if (memcmp(buffer_ptr(blob), authfile_id_string,
293             sizeof(authfile_id_string)) != 0) {
294                 debug3("Incorrect RSA1 identifier");
295                 return NULL;
296         }
297         buffer_consume(blob, sizeof(authfile_id_string));
298
299         /* Skip cipher type and reserved data. */
300         (void) buffer_get_char(blob);   /* cipher type */
301         (void) buffer_get_int(blob);            /* reserved */
302
303         /* Read the public key from the buffer. */
304         (void) buffer_get_int(blob);
305         pub = key_new(KEY_RSA1);
306         buffer_get_bignum(blob, pub->rsa->n);
307         buffer_get_bignum(blob, pub->rsa->e);
308         if (commentp)
309                 *commentp = buffer_get_string(blob, NULL);
310         /* The encrypted private part is not parsed by this function. */
311         buffer_clear(blob);
312
313         return pub;
314 }
315
316 /* Load the contents of a key file into a buffer */
317 static int
318 key_load_file(int fd, const char *filename, Buffer *blob)
319 {
320         size_t len, readcount;
321         u_char *cp;
322         struct stat st;
323
324         if (fstat(fd, &st) < 0) {
325                 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
326                     filename == NULL ? "" : filename,
327                     filename == NULL ? "" : " ",
328                     strerror(errno));
329                 close(fd);
330                 return 0;
331         }
332         if (st.st_size > 1*1024*1024) {
333                 error("%s: key file %.200s%stoo large", __func__,
334                     filename == NULL ? "" : filename,
335                     filename == NULL ? "" : " ");
336                 close(fd);
337                 return 0;
338         }
339         len = (size_t)st.st_size;               /* truncated */
340         if (0 == len && S_ISFIFO(st.st_mode))
341                 len = 8192; /* we will try reading up to 8KiB from a FIFO */
342
343         buffer_init(blob);
344         cp = buffer_append_space(blob, len);
345
346         readcount = atomicio(read, fd, cp, len);
347         if (readcount != len && !(readcount > 0 && S_ISFIFO(st.st_mode))) {
348                 debug("%s: read from key file %.200s%sfailed: %.100s", __func__,
349                     filename == NULL ? "" : filename,
350                     filename == NULL ? "" : " ",
351                     strerror(errno));
352                 buffer_clear(blob);
353                 close(fd);
354                 return 0;
355         }
356         return 1;
357 }
358
359 /*
360  * Loads the public part of the ssh v1 key file.  Returns NULL if an error was
361  * encountered (the file does not exist or is not readable), and the key
362  * otherwise.
363  */
364 static Key *
365 key_load_public_rsa1(int fd, const char *filename, char **commentp)
366 {
367         Buffer buffer;
368         Key *pub;
369
370         buffer_init(&buffer);
371         if (!key_load_file(fd, filename, &buffer)) {
372                 buffer_free(&buffer);
373                 return NULL;
374         }
375
376         pub = key_parse_public_rsa1(&buffer, commentp);
377         if (pub == NULL)
378                 debug3("Could not load \"%s\" as a RSA1 public key", filename);
379         buffer_free(&buffer);
380         return pub;
381 }
382
383 /* load public key from private-key file, works only for SSH v1 */
384 Key *
385 key_load_public_type(int type, const char *filename, char **commentp)
386 {
387         Key *pub;
388         int fd;
389
390         if (type == KEY_RSA1) {
391                 fd = open(filename, O_RDONLY);
392                 if (fd < 0)
393                         return NULL;
394                 pub = key_load_public_rsa1(fd, filename, commentp);
395                 close(fd);
396                 return pub;
397         }
398         return NULL;
399 }
400
401 static Key *
402 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
403 {
404         int check1, check2, cipher_type;
405         Buffer decrypted;
406         u_char *cp;
407         CipherContext ciphercontext;
408         Cipher *cipher;
409         Key *prv = NULL;
410
411         /* Check that it is at least big enough to contain the ID string. */
412         if (buffer_len(blob) < sizeof(authfile_id_string)) {
413                 debug3("Truncated RSA1 identifier");
414                 return NULL;
415         }
416
417         /*
418          * Make sure it begins with the id string.  Consume the id string
419          * from the buffer.
420          */
421         if (memcmp(buffer_ptr(blob), authfile_id_string,
422             sizeof(authfile_id_string)) != 0) {
423                 debug3("Incorrect RSA1 identifier");
424                 return NULL;
425         }
426         buffer_consume(blob, sizeof(authfile_id_string));
427
428         /* Read cipher type. */
429         cipher_type = buffer_get_char(blob);
430         (void) buffer_get_int(blob);    /* Reserved data. */
431
432         /* Read the public key from the buffer. */
433         (void) buffer_get_int(blob);
434         prv = key_new_private(KEY_RSA1);
435
436         buffer_get_bignum(blob, prv->rsa->n);
437         buffer_get_bignum(blob, prv->rsa->e);
438         if (commentp)
439                 *commentp = buffer_get_string(blob, NULL);
440         else
441                 (void)buffer_get_string_ptr(blob, NULL);
442
443         /* Check that it is a supported cipher. */
444         cipher = cipher_by_number(cipher_type);
445         if (cipher == NULL) {
446                 debug("Unsupported RSA1 cipher %d", cipher_type);
447                 goto fail;
448         }
449         /* Initialize space for decrypted data. */
450         buffer_init(&decrypted);
451         cp = buffer_append_space(&decrypted, buffer_len(blob));
452
453         /* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
454         cipher_set_key_string(&ciphercontext, cipher, passphrase,
455             CIPHER_DECRYPT);
456         cipher_crypt(&ciphercontext, cp,
457             buffer_ptr(blob), buffer_len(blob));
458         cipher_cleanup(&ciphercontext);
459         memset(&ciphercontext, 0, sizeof(ciphercontext));
460         buffer_clear(blob);
461
462         check1 = buffer_get_char(&decrypted);
463         check2 = buffer_get_char(&decrypted);
464         if (check1 != buffer_get_char(&decrypted) ||
465             check2 != buffer_get_char(&decrypted)) {
466                 if (strcmp(passphrase, "") != 0)
467                         debug("Bad passphrase supplied for RSA1 key");
468                 /* Bad passphrase. */
469                 buffer_free(&decrypted);
470                 goto fail;
471         }
472         /* Read the rest of the private key. */
473         buffer_get_bignum(&decrypted, prv->rsa->d);
474         buffer_get_bignum(&decrypted, prv->rsa->iqmp);          /* u */
475         /* in SSL and SSH v1 p and q are exchanged */
476         buffer_get_bignum(&decrypted, prv->rsa->q);             /* p */
477         buffer_get_bignum(&decrypted, prv->rsa->p);             /* q */
478
479         /* calculate p-1 and q-1 */
480         rsa_generate_additional_parameters(prv->rsa);
481
482         buffer_free(&decrypted);
483
484         /* enable blinding */
485         if (RSA_blinding_on(prv->rsa, NULL) != 1) {
486                 error("%s: RSA_blinding_on failed", __func__);
487                 goto fail;
488         }
489         return prv;
490
491 fail:
492         if (commentp)
493                 xfree(*commentp);
494         key_free(prv);
495         return NULL;
496 }
497
498 static Key *
499 key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
500     char **commentp)
501 {
502         EVP_PKEY *pk = NULL;
503         Key *prv = NULL;
504         char *name = "<no key>";
505         BIO *bio;
506
507         if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
508             buffer_len(blob))) == NULL) {
509                 error("%s: BIO_new_mem_buf failed", __func__);
510                 return NULL;
511         }
512         
513         pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
514         BIO_free(bio);
515         if (pk == NULL) {
516                 debug("%s: PEM_read_PrivateKey failed", __func__);
517                 (void)ERR_get_error();
518         } else if (pk->type == EVP_PKEY_RSA &&
519             (type == KEY_UNSPEC||type==KEY_RSA)) {
520                 prv = key_new(KEY_UNSPEC);
521                 prv->rsa = EVP_PKEY_get1_RSA(pk);
522                 prv->type = KEY_RSA;
523                 name = "rsa w/o comment";
524 #ifdef DEBUG_PK
525                 RSA_print_fp(stderr, prv->rsa, 8);
526 #endif
527                 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
528                         error("%s: RSA_blinding_on failed", __func__);
529                         key_free(prv);
530                         prv = NULL;
531                 }
532         } else if (pk->type == EVP_PKEY_DSA &&
533             (type == KEY_UNSPEC||type==KEY_DSA)) {
534                 prv = key_new(KEY_UNSPEC);
535                 prv->dsa = EVP_PKEY_get1_DSA(pk);
536                 prv->type = KEY_DSA;
537                 name = "dsa w/o comment";
538 #ifdef DEBUG_PK
539                 DSA_print_fp(stderr, prv->dsa, 8);
540 #endif
541 #ifdef OPENSSL_HAS_ECC
542         } else if (pk->type == EVP_PKEY_EC &&
543             (type == KEY_UNSPEC||type==KEY_ECDSA)) {
544                 prv = key_new(KEY_UNSPEC);
545                 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
546                 prv->type = KEY_ECDSA;
547                 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
548                     key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
549                     key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
550                     EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
551                     key_ec_validate_private(prv->ecdsa) != 0) {
552                         error("%s: bad ECDSA key", __func__);
553                         key_free(prv);
554                         prv = NULL;
555                 }
556                 name = "ecdsa w/o comment";
557 #ifdef DEBUG_PK
558                 if (prv != NULL && prv->ecdsa != NULL)
559                         key_dump_ec_key(prv->ecdsa);
560 #endif
561 #endif /* OPENSSL_HAS_ECC */
562         } else {
563                 error("%s: PEM_read_PrivateKey: mismatch or "
564                     "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
565         }
566         if (pk != NULL)
567                 EVP_PKEY_free(pk);
568         if (prv != NULL && commentp)
569                 *commentp = xstrdup(name);
570         debug("read PEM private key done: type %s",
571             prv ? key_type(prv) : "<unknown>");
572         return prv;
573 }
574
575 Key *
576 key_load_private_pem(int fd, int type, const char *passphrase,
577     char **commentp)
578 {
579         Buffer buffer;
580         Key *prv;
581
582         buffer_init(&buffer);
583         if (!key_load_file(fd, NULL, &buffer)) {
584                 buffer_free(&buffer);
585                 return NULL;
586         }
587         prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
588         buffer_free(&buffer);
589         return prv;
590 }
591
592 int
593 key_perm_ok(int fd, const char *filename)
594 {
595         struct stat st;
596
597         if (fstat(fd, &st) < 0)
598                 return 0;
599         /*
600          * if a key owned by the user is accessed, then we check the
601          * permissions of the file. if the key owned by a different user,
602          * then we don't care.
603          */
604 #ifdef HAVE_CYGWIN
605         if (check_ntsec(filename))
606 #endif
607         if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
608                 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
609                 error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
610                 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
611                 error("Permissions 0%3.3o for '%s' are too open.",
612                     (u_int)st.st_mode & 0777, filename);
613                 error("It is recommended that your private key files are NOT accessible by others.");
614                 error("This private key will be ignored.");
615                 return 0;
616         }
617         return 1;
618 }
619
620 static Key *
621 key_parse_private_type(Buffer *blob, int type, const char *passphrase,
622     char **commentp)
623 {
624         switch (type) {
625         case KEY_RSA1:
626                 return key_parse_private_rsa1(blob, passphrase, commentp);
627         case KEY_DSA:
628         case KEY_ECDSA:
629         case KEY_RSA:
630         case KEY_UNSPEC:
631                 return key_parse_private_pem(blob, type, passphrase, commentp);
632         default:
633                 break;
634         }
635         return NULL;
636 }
637
638 Key *
639 key_load_private_type(int type, const char *filename, const char *passphrase,
640     char **commentp, int *perm_ok)
641 {
642         int fd;
643         Key *ret;
644         Buffer buffer;
645
646         fd = open(filename, O_RDONLY);
647         if (fd < 0) {
648                 debug("could not open key file '%s': %s", filename,
649                     strerror(errno));
650                 if (perm_ok != NULL)
651                         *perm_ok = 0;
652                 return NULL;
653         }
654         if (!key_perm_ok(fd, filename)) {
655                 if (perm_ok != NULL)
656                         *perm_ok = 0;
657                 error("bad permissions: ignore key: %s", filename);
658                 close(fd);
659                 return NULL;
660         }
661         if (perm_ok != NULL)
662                 *perm_ok = 1;
663
664         buffer_init(&buffer);
665         if (!key_load_file(fd, filename, &buffer)) {
666                 buffer_free(&buffer);
667                 close(fd);
668                 return NULL;
669         }
670         close(fd);
671         ret = key_parse_private_type(&buffer, type, passphrase, commentp);
672         buffer_free(&buffer);
673         return ret;
674 }
675
676 Key *
677 key_load_private(const char *filename, const char *passphrase,
678     char **commentp)
679 {
680         Key *pub, *prv;
681         Buffer buffer, pubcopy;
682         int fd;
683
684         fd = open(filename, O_RDONLY);
685         if (fd < 0) {
686                 debug("could not open key file '%s': %s", filename,
687                     strerror(errno));
688                 return NULL;
689         }
690         if (!key_perm_ok(fd, filename)) {
691                 error("bad permissions: ignore key: %s", filename);
692                 close(fd);
693                 return NULL;
694         }
695
696         buffer_init(&buffer);
697         if (!key_load_file(fd, filename, &buffer)) {
698                 buffer_free(&buffer);
699                 close(fd);
700                 return NULL;
701         }
702         close(fd);
703
704         buffer_init(&pubcopy);
705         buffer_append(&pubcopy, buffer_ptr(&buffer), buffer_len(&buffer));
706         /* it's a SSH v1 key if the public key part is readable */
707         pub = key_parse_public_rsa1(&pubcopy, commentp);
708         buffer_free(&pubcopy);
709         if (pub == NULL) {
710                 prv = key_parse_private_type(&buffer, KEY_UNSPEC,
711                     passphrase, NULL);
712                 /* use the filename as a comment for PEM */
713                 if (commentp && prv)
714                         *commentp = xstrdup(filename);
715         } else {
716                 key_free(pub);
717                 /* key_parse_public_rsa1() has already loaded the comment */
718                 prv = key_parse_private_type(&buffer, KEY_RSA1, passphrase,
719                     NULL);
720         }
721         buffer_free(&buffer);
722         return prv;
723 }
724
725 static int
726 key_try_load_public(Key *k, const char *filename, char **commentp)
727 {
728         FILE *f;
729         char line[SSH_MAX_PUBKEY_BYTES];
730         char *cp;
731         u_long linenum = 0;
732
733         f = fopen(filename, "r");
734         if (f != NULL) {
735                 while (read_keyfile_line(f, filename, line, sizeof(line),
736                             &linenum) != -1) {
737                         cp = line;
738                         switch (*cp) {
739                         case '#':
740                         case '\n':
741                         case '\0':
742                                 continue;
743                         }
744                         /* Skip leading whitespace. */
745                         for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
746                                 ;
747                         if (*cp) {
748                                 if (key_read(k, &cp) == 1) {
749                                         if (commentp)
750                                                 *commentp=xstrdup(filename);
751                                         fclose(f);
752                                         return 1;
753                                 }
754                         }
755                 }
756                 fclose(f);
757         }
758         return 0;
759 }
760
761 /* load public key from ssh v1 private or any pubkey file */
762 Key *
763 key_load_public(const char *filename, char **commentp)
764 {
765         Key *pub;
766         char file[MAXPATHLEN];
767
768         /* try rsa1 private key */
769         pub = key_load_public_type(KEY_RSA1, filename, commentp);
770         if (pub != NULL)
771                 return pub;
772
773         /* try rsa1 public key */
774         pub = key_new(KEY_RSA1);
775         if (key_try_load_public(pub, filename, commentp) == 1)
776                 return pub;
777         key_free(pub);
778
779         /* try ssh2 public key */
780         pub = key_new(KEY_UNSPEC);
781         if (key_try_load_public(pub, filename, commentp) == 1)
782                 return pub;
783         if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
784             (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
785             (key_try_load_public(pub, file, commentp) == 1))
786                 return pub;
787         key_free(pub);
788         return NULL;
789 }
790
791 /* Load the certificate associated with the named private key */
792 Key *
793 key_load_cert(const char *filename)
794 {
795         Key *pub;
796         char *file;
797
798         pub = key_new(KEY_UNSPEC);
799         xasprintf(&file, "%s-cert.pub", filename);
800         if (key_try_load_public(pub, file, NULL) == 1) {
801                 xfree(file);
802                 return pub;
803         }
804         xfree(file);
805         key_free(pub);
806         return NULL;
807 }
808
809 /* Load private key and certificate */
810 Key *
811 key_load_private_cert(int type, const char *filename, const char *passphrase,
812     int *perm_ok)
813 {
814         Key *key, *pub;
815
816         switch (type) {
817         case KEY_RSA:
818         case KEY_DSA:
819         case KEY_ECDSA:
820                 break;
821         default:
822                 error("%s: unsupported key type", __func__);
823                 return NULL;
824         }
825
826         if ((key = key_load_private_type(type, filename, 
827             passphrase, NULL, perm_ok)) == NULL)
828                 return NULL;
829
830         if ((pub = key_load_cert(filename)) == NULL) {
831                 key_free(key);
832                 return NULL;
833         }
834
835         /* Make sure the private key matches the certificate */
836         if (key_equal_public(key, pub) == 0) {
837                 error("%s: certificate does not match private key %s",
838                     __func__, filename);
839         } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
840                 error("%s: key_to_certified failed", __func__);
841         } else {
842                 key_cert_copy(pub, key);
843                 key_free(pub);
844                 return key;
845         }
846
847         key_free(key);
848         key_free(pub);
849         return NULL;
850 }
851
852 /*
853  * Returns 1 if the specified "key" is listed in the file "filename",
854  * 0 if the key is not listed or -1 on error.
855  * If strict_type is set then the key type must match exactly,
856  * otherwise a comparison that ignores certficiate data is performed.
857  */
858 int
859 key_in_file(Key *key, const char *filename, int strict_type)
860 {
861         FILE *f;
862         char line[SSH_MAX_PUBKEY_BYTES];
863         char *cp;
864         u_long linenum = 0;
865         int ret = 0;
866         Key *pub;
867         int (*key_compare)(const Key *, const Key *) = strict_type ?
868             key_equal : key_equal_public;
869
870         if ((f = fopen(filename, "r")) == NULL) {
871                 if (errno == ENOENT) {
872                         debug("%s: keyfile \"%s\" missing", __func__, filename);
873                         return 0;
874                 } else {
875                         error("%s: could not open keyfile \"%s\": %s", __func__,
876                             filename, strerror(errno));
877                         return -1;
878                 }
879         }
880
881         while (read_keyfile_line(f, filename, line, sizeof(line),
882                     &linenum) != -1) {
883                 cp = line;
884
885                 /* Skip leading whitespace. */
886                 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
887                         ;
888
889                 /* Skip comments and empty lines */
890                 switch (*cp) {
891                 case '#':
892                 case '\n':
893                 case '\0':
894                         continue;
895                 }
896
897                 pub = key_new(KEY_UNSPEC);
898                 if (key_read(pub, &cp) != 1) {
899                         key_free(pub);
900                         continue;
901                 }
902                 if (key_compare(key, pub)) {
903                         ret = 1;
904                         key_free(pub);
905                         break;
906                 }
907                 key_free(pub);
908         }
909         fclose(f);
910         return ret;
911 }
912
913 /* Scan a blacklist of known-vulnerable keys in blacklist_file. */
914 static int
915 blacklisted_key_in_file(Key *key, const char *blacklist_file, char **fp)
916 {
917         int fd = -1;
918         char *dgst_hex = NULL;
919         char *dgst_packed = NULL, *p;
920         int i;
921         size_t line_len;
922         struct stat st;
923         char buf[256];
924         off_t start, lower, upper;
925         int ret = 0;
926
927         debug("Checking blacklist file %s", blacklist_file);
928         fd = open(blacklist_file, O_RDONLY);
929         if (fd < 0) {
930                 ret = -1;
931                 goto out;
932         }
933
934         dgst_hex = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
935         /* Remove all colons */
936         dgst_packed = xcalloc(1, strlen(dgst_hex) + 1);
937         for (i = 0, p = dgst_packed; dgst_hex[i]; i++)
938                 if (dgst_hex[i] != ':')
939                         *p++ = dgst_hex[i];
940         /* Only compare least-significant 80 bits (to keep the blacklist
941          * size down)
942          */
943         line_len = strlen(dgst_packed + 12);
944         if (line_len > 32)
945                 goto out;
946
947         /* Skip leading comments */
948         start = 0;
949         for (;;) {
950                 ssize_t r;
951                 char *newline;
952
953                 r = atomicio(read, fd, buf, sizeof(buf));
954                 if (r <= 0)
955                         goto out;
956                 if (buf[0] != '#')
957                         break;
958
959                 newline = memchr(buf, '\n', sizeof(buf));
960                 if (!newline)
961                         goto out;
962                 start += newline + 1 - buf;
963                 if (lseek(fd, start, SEEK_SET) < 0)
964                         goto out;
965         }
966
967         /* Initialise binary search record numbers */
968         if (fstat(fd, &st) < 0)
969                 goto out;
970         lower = 0;
971         upper = (st.st_size - start) / (line_len + 1);
972
973         while (lower != upper) {
974                 off_t cur;
975                 int cmp;
976
977                 cur = lower + (upper - lower) / 2;
978
979                 /* Read this line and compare to digest; this is
980                  * overflow-safe since cur < max(off_t) / (line_len + 1) */
981                 if (lseek(fd, start + cur * (line_len + 1), SEEK_SET) < 0)
982                         break;
983                 if (atomicio(read, fd, buf, line_len) != line_len)
984                         break;
985                 cmp = memcmp(buf, dgst_packed + 12, line_len);
986                 if (cmp < 0) {
987                         if (cur == lower)
988                                 break;
989                         lower = cur;
990                 } else if (cmp > 0) {
991                         if (cur == upper)
992                                 break;
993                         upper = cur;
994                 } else {
995                         debug("Found %s in blacklist", dgst_hex);
996                         ret = 1;
997                         break;
998                 }
999         }
1000
1001 out:
1002         if (dgst_packed)
1003                 xfree(dgst_packed);
1004         if (ret != 1 && dgst_hex) {
1005                 xfree(dgst_hex);
1006                 dgst_hex = NULL;
1007         }
1008         if (fp)
1009                 *fp = dgst_hex;
1010         if (fd >= 0)
1011                 close(fd);
1012         return ret;
1013 }
1014
1015 /*
1016  * Scan blacklists of known-vulnerable keys. If a vulnerable key is found,
1017  * its fingerprint is returned in *fp, unless fp is NULL.
1018  */
1019 int
1020 blacklisted_key(Key *key, char **fp)
1021 {
1022         Key *public;
1023         char *blacklist_file;
1024         int ret, ret2;
1025
1026         public = key_demote(key);
1027         if (public->type == KEY_RSA1)
1028                 public->type = KEY_RSA;
1029
1030         xasprintf(&blacklist_file, "%s.%s-%u",
1031             _PATH_BLACKLIST, key_type(public), key_size(public));
1032         ret = blacklisted_key_in_file(public, blacklist_file, fp);
1033         xfree(blacklist_file);
1034         if (ret > 0) {
1035                 key_free(public);
1036                 return ret;
1037         }
1038
1039         xasprintf(&blacklist_file, "%s.%s-%u",
1040             _PATH_BLACKLIST_CONFIG, key_type(public), key_size(public));
1041         ret2 = blacklisted_key_in_file(public, blacklist_file, fp);
1042         xfree(blacklist_file);
1043         if (ret2 > ret)
1044                 ret = ret2;
1045
1046         key_free(public);
1047         return ret;
1048 }
1049