- (dtucker) [openbsd-compat/port-linux.c] Bug #1851: fix syntax error in
[openssh-git.git] / authfile.c
blobf2aec267a5a6196be1a138f6237e452040e78ff1
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.
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".
16 * Copyright (c) 2000 Markus Friedl. All rights reserved.
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.
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.
39 #include "includes.h"
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <sys/param.h>
44 #include <sys/uio.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
50 /* compatibility with old or broken OpenSSL versions */
51 #include "openbsd-compat/openssl-compat.h"
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>
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"
72 /* Version identification string for SSH v1 identity files. */
73 static const char authfile_id_string[] =
74 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
77 * Serialises the authentication (private) key to a blob, encrypting it with
78 * passphrase. The identification of the blob (lowest 64 bits of n) will
79 * precede the key to provide identification of the key without needing a
80 * passphrase.
82 static int
83 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
84 const char *comment)
86 Buffer buffer, encrypted;
87 u_char buf[100], *cp;
88 int i, cipher_num;
89 CipherContext ciphercontext;
90 Cipher *cipher;
91 u_int32_t rnd;
94 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
95 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
97 cipher_num = (strcmp(passphrase, "") == 0) ?
98 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
99 if ((cipher = cipher_by_number(cipher_num)) == NULL)
100 fatal("save_private_key_rsa: bad cipher");
102 /* This buffer is used to built the secret part of the private key. */
103 buffer_init(&buffer);
105 /* Put checkbytes for checking passphrase validity. */
106 rnd = arc4random();
107 buf[0] = rnd & 0xff;
108 buf[1] = (rnd >> 8) & 0xff;
109 buf[2] = buf[0];
110 buf[3] = buf[1];
111 buffer_append(&buffer, buf, 4);
114 * Store the private key (n and e will not be stored because they
115 * will be stored in plain text, and storing them also in encrypted
116 * format would just give known plaintext).
118 buffer_put_bignum(&buffer, key->rsa->d);
119 buffer_put_bignum(&buffer, key->rsa->iqmp);
120 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
121 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
123 /* Pad the part to be encrypted until its size is a multiple of 8. */
124 while (buffer_len(&buffer) % 8 != 0)
125 buffer_put_char(&buffer, 0);
127 /* This buffer will be used to contain the data in the file. */
128 buffer_init(&encrypted);
130 /* First store keyfile id string. */
131 for (i = 0; authfile_id_string[i]; i++)
132 buffer_put_char(&encrypted, authfile_id_string[i]);
133 buffer_put_char(&encrypted, 0);
135 /* Store cipher type. */
136 buffer_put_char(&encrypted, cipher_num);
137 buffer_put_int(&encrypted, 0); /* For future extension */
139 /* Store public key. This will be in plain text. */
140 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
141 buffer_put_bignum(&encrypted, key->rsa->n);
142 buffer_put_bignum(&encrypted, key->rsa->e);
143 buffer_put_cstring(&encrypted, comment);
145 /* Allocate space for the private part of the key in the buffer. */
146 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
148 cipher_set_key_string(&ciphercontext, cipher, passphrase,
149 CIPHER_ENCRYPT);
150 cipher_crypt(&ciphercontext, cp,
151 buffer_ptr(&buffer), buffer_len(&buffer));
152 cipher_cleanup(&ciphercontext);
153 memset(&ciphercontext, 0, sizeof(ciphercontext));
155 /* Destroy temporary data. */
156 memset(buf, 0, sizeof(buf));
157 buffer_free(&buffer);
159 buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
160 buffer_free(&encrypted);
162 return 1;
165 /* convert SSH v2 key in OpenSSL PEM format */
166 static int
167 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
168 const char *comment)
170 int success = 0;
171 int blen, len = strlen(_passphrase);
172 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
173 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
174 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
175 #else
176 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
177 #endif
178 const u_char *bptr;
179 BIO *bio;
181 if (len > 0 && len <= 4) {
182 error("passphrase too short: have %d bytes, need > 4", len);
183 return 0;
185 if ((bio = BIO_new(BIO_s_mem())) == NULL) {
186 error("%s: BIO_new failed", __func__);
187 return 0;
189 switch (key->type) {
190 case KEY_DSA:
191 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
192 cipher, passphrase, len, NULL, NULL);
193 break;
194 #ifdef OPENSSL_HAS_ECC
195 case KEY_ECDSA:
196 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
197 cipher, passphrase, len, NULL, NULL);
198 break;
199 #endif
200 case KEY_RSA:
201 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
202 cipher, passphrase, len, NULL, NULL);
203 break;
205 if (success) {
206 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
207 success = 0;
208 else
209 buffer_append(blob, bptr, blen);
211 BIO_free(bio);
212 return success;
215 /* Save a key blob to a file */
216 static int
217 key_save_private_blob(Buffer *keybuf, const char *filename)
219 int fd;
221 if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
222 error("open %s failed: %s.", filename, strerror(errno));
223 return 0;
225 if (atomicio(vwrite, fd, buffer_ptr(keybuf),
226 buffer_len(keybuf)) != buffer_len(keybuf)) {
227 error("write to key file %s failed: %s", filename,
228 strerror(errno));
229 close(fd);
230 unlink(filename);
231 return 0;
233 close(fd);
234 return 1;
237 /* Serialise "key" to buffer "blob" */
238 static int
239 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
240 const char *comment)
242 switch (key->type) {
243 case KEY_RSA1:
244 return key_private_rsa1_to_blob(key, blob, passphrase, comment);
245 case KEY_DSA:
246 case KEY_ECDSA:
247 case KEY_RSA:
248 return key_private_pem_to_blob(key, blob, passphrase, comment);
249 default:
250 error("%s: cannot save key type %d", __func__, key->type);
251 return 0;
256 key_save_private(Key *key, const char *filename, const char *passphrase,
257 const char *comment)
259 Buffer keyblob;
260 int success = 0;
262 buffer_init(&keyblob);
263 if (!key_private_to_blob(key, &keyblob, passphrase, comment))
264 goto out;
265 if (!key_save_private_blob(&keyblob, filename))
266 goto out;
267 success = 1;
268 out:
269 buffer_free(&keyblob);
270 return success;
274 * Parse the public, unencrypted portion of a RSA1 key.
276 static Key *
277 key_parse_public_rsa1(Buffer *blob, char **commentp)
279 Key *pub;
281 /* Check that it is at least big enough to contain the ID string. */
282 if (buffer_len(blob) < sizeof(authfile_id_string)) {
283 debug3("Truncated RSA1 identifier");
284 return NULL;
288 * Make sure it begins with the id string. Consume the id string
289 * from the buffer.
291 if (memcmp(buffer_ptr(blob), authfile_id_string,
292 sizeof(authfile_id_string)) != 0) {
293 debug3("Incorrect RSA1 identifier");
294 return NULL;
296 buffer_consume(blob, sizeof(authfile_id_string));
298 /* Skip cipher type and reserved data. */
299 (void) buffer_get_char(blob); /* cipher type */
300 (void) buffer_get_int(blob); /* reserved */
302 /* Read the public key from the buffer. */
303 (void) buffer_get_int(blob);
304 pub = key_new(KEY_RSA1);
305 buffer_get_bignum(blob, pub->rsa->n);
306 buffer_get_bignum(blob, pub->rsa->e);
307 if (commentp)
308 *commentp = buffer_get_string(blob, NULL);
309 /* The encrypted private part is not parsed by this function. */
310 buffer_clear(blob);
312 return pub;
315 /* Load the contents of a key file into a buffer */
316 static int
317 key_load_file(int fd, const char *filename, Buffer *blob)
319 size_t len;
320 u_char *cp;
321 struct stat st;
323 if (fstat(fd, &st) < 0) {
324 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
325 filename == NULL ? "" : filename,
326 filename == NULL ? "" : " ",
327 strerror(errno));
328 close(fd);
329 return 0;
331 if (st.st_size > 1*1024*1024) {
332 error("%s: key file %.200s%stoo large", __func__,
333 filename == NULL ? "" : filename,
334 filename == NULL ? "" : " ");
335 close(fd);
336 return 0;
338 len = (size_t)st.st_size; /* truncated */
340 buffer_init(blob);
341 cp = buffer_append_space(blob, len);
343 if (atomicio(read, fd, cp, len) != len) {
344 debug("%s: read from key file %.200s%sfailed: %.100s", __func__,
345 filename == NULL ? "" : filename,
346 filename == NULL ? "" : " ",
347 strerror(errno));
348 buffer_clear(blob);
349 close(fd);
350 return 0;
352 return 1;
356 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
357 * encountered (the file does not exist or is not readable), and the key
358 * otherwise.
360 static Key *
361 key_load_public_rsa1(int fd, const char *filename, char **commentp)
363 Buffer buffer;
364 Key *pub;
366 buffer_init(&buffer);
367 if (!key_load_file(fd, filename, &buffer)) {
368 buffer_free(&buffer);
369 return NULL;
372 pub = key_parse_public_rsa1(&buffer, commentp);
373 if (pub == NULL)
374 debug3("Could not load \"%s\" as a RSA1 public key", filename);
375 buffer_free(&buffer);
376 return pub;
379 /* load public key from private-key file, works only for SSH v1 */
380 Key *
381 key_load_public_type(int type, const char *filename, char **commentp)
383 Key *pub;
384 int fd;
386 if (type == KEY_RSA1) {
387 fd = open(filename, O_RDONLY);
388 if (fd < 0)
389 return NULL;
390 pub = key_load_public_rsa1(fd, filename, commentp);
391 close(fd);
392 return pub;
394 return NULL;
397 static Key *
398 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
400 int check1, check2, cipher_type;
401 Buffer decrypted;
402 u_char *cp;
403 CipherContext ciphercontext;
404 Cipher *cipher;
405 Key *prv = NULL;
407 /* Check that it is at least big enough to contain the ID string. */
408 if (buffer_len(blob) < sizeof(authfile_id_string)) {
409 debug3("Truncated RSA1 identifier");
410 return NULL;
414 * Make sure it begins with the id string. Consume the id string
415 * from the buffer.
417 if (memcmp(buffer_ptr(blob), authfile_id_string,
418 sizeof(authfile_id_string)) != 0) {
419 debug3("Incorrect RSA1 identifier");
420 return NULL;
422 buffer_consume(blob, sizeof(authfile_id_string));
424 /* Read cipher type. */
425 cipher_type = buffer_get_char(blob);
426 (void) buffer_get_int(blob); /* Reserved data. */
428 /* Read the public key from the buffer. */
429 (void) buffer_get_int(blob);
430 prv = key_new_private(KEY_RSA1);
432 buffer_get_bignum(blob, prv->rsa->n);
433 buffer_get_bignum(blob, prv->rsa->e);
434 if (commentp)
435 *commentp = buffer_get_string(blob, NULL);
436 else
437 (void)buffer_get_string_ptr(blob, NULL);
439 /* Check that it is a supported cipher. */
440 cipher = cipher_by_number(cipher_type);
441 if (cipher == NULL) {
442 debug("Unsupported RSA1 cipher %d", cipher_type);
443 goto fail;
445 /* Initialize space for decrypted data. */
446 buffer_init(&decrypted);
447 cp = buffer_append_space(&decrypted, buffer_len(blob));
449 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
450 cipher_set_key_string(&ciphercontext, cipher, passphrase,
451 CIPHER_DECRYPT);
452 cipher_crypt(&ciphercontext, cp,
453 buffer_ptr(blob), buffer_len(blob));
454 cipher_cleanup(&ciphercontext);
455 memset(&ciphercontext, 0, sizeof(ciphercontext));
456 buffer_clear(blob);
458 check1 = buffer_get_char(&decrypted);
459 check2 = buffer_get_char(&decrypted);
460 if (check1 != buffer_get_char(&decrypted) ||
461 check2 != buffer_get_char(&decrypted)) {
462 if (strcmp(passphrase, "") != 0)
463 debug("Bad passphrase supplied for RSA1 key");
464 /* Bad passphrase. */
465 buffer_free(&decrypted);
466 goto fail;
468 /* Read the rest of the private key. */
469 buffer_get_bignum(&decrypted, prv->rsa->d);
470 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
471 /* in SSL and SSH v1 p and q are exchanged */
472 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
473 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
475 /* calculate p-1 and q-1 */
476 rsa_generate_additional_parameters(prv->rsa);
478 buffer_free(&decrypted);
480 /* enable blinding */
481 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
482 error("%s: RSA_blinding_on failed", __func__);
483 goto fail;
485 return prv;
487 fail:
488 if (commentp)
489 xfree(*commentp);
490 key_free(prv);
491 return NULL;
494 static Key *
495 key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
496 char **commentp)
498 EVP_PKEY *pk = NULL;
499 Key *prv = NULL;
500 char *name = "<no key>";
501 BIO *bio;
503 if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
504 buffer_len(blob))) == NULL) {
505 error("%s: BIO_new_mem_buf failed", __func__);
506 return NULL;
509 pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
510 BIO_free(bio);
511 if (pk == NULL) {
512 debug("%s: PEM_read_PrivateKey failed", __func__);
513 (void)ERR_get_error();
514 } else if (pk->type == EVP_PKEY_RSA &&
515 (type == KEY_UNSPEC||type==KEY_RSA)) {
516 prv = key_new(KEY_UNSPEC);
517 prv->rsa = EVP_PKEY_get1_RSA(pk);
518 prv->type = KEY_RSA;
519 name = "rsa w/o comment";
520 #ifdef DEBUG_PK
521 RSA_print_fp(stderr, prv->rsa, 8);
522 #endif
523 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
524 error("%s: RSA_blinding_on failed", __func__);
525 key_free(prv);
526 prv = NULL;
528 } else if (pk->type == EVP_PKEY_DSA &&
529 (type == KEY_UNSPEC||type==KEY_DSA)) {
530 prv = key_new(KEY_UNSPEC);
531 prv->dsa = EVP_PKEY_get1_DSA(pk);
532 prv->type = KEY_DSA;
533 name = "dsa w/o comment";
534 #ifdef DEBUG_PK
535 DSA_print_fp(stderr, prv->dsa, 8);
536 #endif
537 #ifdef OPENSSL_HAS_ECC
538 } else if (pk->type == EVP_PKEY_EC &&
539 (type == KEY_UNSPEC||type==KEY_ECDSA)) {
540 prv = key_new(KEY_UNSPEC);
541 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
542 prv->type = KEY_ECDSA;
543 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
544 key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
545 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
546 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
547 key_ec_validate_private(prv->ecdsa) != 0) {
548 error("%s: bad ECDSA key", __func__);
549 key_free(prv);
550 prv = NULL;
552 name = "ecdsa w/o comment";
553 #ifdef DEBUG_PK
554 if (prv != NULL && prv->ecdsa != NULL)
555 key_dump_ec_key(prv->ecdsa);
556 #endif
557 #endif /* OPENSSL_HAS_ECC */
558 } else {
559 error("%s: PEM_read_PrivateKey: mismatch or "
560 "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
562 if (pk != NULL)
563 EVP_PKEY_free(pk);
564 if (prv != NULL && commentp)
565 *commentp = xstrdup(name);
566 debug("read PEM private key done: type %s",
567 prv ? key_type(prv) : "<unknown>");
568 return prv;
571 Key *
572 key_load_private_pem(int fd, int type, const char *passphrase,
573 char **commentp)
575 Buffer buffer;
576 Key *prv;
578 buffer_init(&buffer);
579 if (!key_load_file(fd, NULL, &buffer)) {
580 buffer_free(&buffer);
581 return NULL;
583 prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
584 buffer_free(&buffer);
585 return prv;
589 key_perm_ok(int fd, const char *filename)
591 struct stat st;
593 if (fstat(fd, &st) < 0)
594 return 0;
596 * if a key owned by the user is accessed, then we check the
597 * permissions of the file. if the key owned by a different user,
598 * then we don't care.
600 #ifdef HAVE_CYGWIN
601 if (check_ntsec(filename))
602 #endif
603 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
604 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
605 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
606 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
607 error("Permissions 0%3.3o for '%s' are too open.",
608 (u_int)st.st_mode & 0777, filename);
609 error("It is recommended that your private key files are NOT accessible by others.");
610 error("This private key will be ignored.");
611 return 0;
613 return 1;
616 static Key *
617 key_parse_private_type(Buffer *blob, int type, const char *passphrase,
618 char **commentp)
620 switch (type) {
621 case KEY_RSA1:
622 return key_parse_private_rsa1(blob, passphrase, commentp);
623 case KEY_DSA:
624 case KEY_ECDSA:
625 case KEY_RSA:
626 case KEY_UNSPEC:
627 return key_parse_private_pem(blob, type, passphrase, commentp);
628 default:
629 break;
631 return NULL;
634 Key *
635 key_load_private_type(int type, const char *filename, const char *passphrase,
636 char **commentp, int *perm_ok)
638 int fd;
639 Key *ret;
640 Buffer buffer;
642 fd = open(filename, O_RDONLY);
643 if (fd < 0) {
644 debug("could not open key file '%s': %s", filename,
645 strerror(errno));
646 if (perm_ok != NULL)
647 *perm_ok = 0;
648 return NULL;
650 if (!key_perm_ok(fd, filename)) {
651 if (perm_ok != NULL)
652 *perm_ok = 0;
653 error("bad permissions: ignore key: %s", filename);
654 close(fd);
655 return NULL;
657 if (perm_ok != NULL)
658 *perm_ok = 1;
660 buffer_init(&buffer);
661 if (!key_load_file(fd, filename, &buffer)) {
662 buffer_free(&buffer);
663 close(fd);
664 return NULL;
666 close(fd);
667 ret = key_parse_private_type(&buffer, type, passphrase, commentp);
668 buffer_free(&buffer);
669 return ret;
672 Key *
673 key_load_private(const char *filename, const char *passphrase,
674 char **commentp)
676 Key *pub, *prv;
677 Buffer buffer, pubcopy;
678 int fd;
680 fd = open(filename, O_RDONLY);
681 if (fd < 0) {
682 debug("could not open key file '%s': %s", filename,
683 strerror(errno));
684 return NULL;
686 if (!key_perm_ok(fd, filename)) {
687 error("bad permissions: ignore key: %s", filename);
688 close(fd);
689 return NULL;
692 buffer_init(&buffer);
693 if (!key_load_file(fd, filename, &buffer)) {
694 buffer_free(&buffer);
695 close(fd);
696 return NULL;
698 close(fd);
700 buffer_init(&pubcopy);
701 buffer_append(&pubcopy, buffer_ptr(&buffer), buffer_len(&buffer));
702 /* it's a SSH v1 key if the public key part is readable */
703 pub = key_parse_public_rsa1(&pubcopy, commentp);
704 buffer_free(&pubcopy);
705 if (pub == NULL) {
706 prv = key_parse_private_type(&buffer, KEY_UNSPEC,
707 passphrase, NULL);
708 /* use the filename as a comment for PEM */
709 if (commentp && prv)
710 *commentp = xstrdup(filename);
711 } else {
712 key_free(pub);
713 /* key_parse_public_rsa1() has already loaded the comment */
714 prv = key_parse_private_type(&buffer, KEY_RSA1, passphrase,
715 NULL);
717 buffer_free(&buffer);
718 return prv;
721 static int
722 key_try_load_public(Key *k, const char *filename, char **commentp)
724 FILE *f;
725 char line[SSH_MAX_PUBKEY_BYTES];
726 char *cp;
727 u_long linenum = 0;
729 f = fopen(filename, "r");
730 if (f != NULL) {
731 while (read_keyfile_line(f, filename, line, sizeof(line),
732 &linenum) != -1) {
733 cp = line;
734 switch (*cp) {
735 case '#':
736 case '\n':
737 case '\0':
738 continue;
740 /* Skip leading whitespace. */
741 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
743 if (*cp) {
744 if (key_read(k, &cp) == 1) {
745 if (commentp)
746 *commentp=xstrdup(filename);
747 fclose(f);
748 return 1;
752 fclose(f);
754 return 0;
757 /* load public key from ssh v1 private or any pubkey file */
758 Key *
759 key_load_public(const char *filename, char **commentp)
761 Key *pub;
762 char file[MAXPATHLEN];
764 /* try rsa1 private key */
765 pub = key_load_public_type(KEY_RSA1, filename, commentp);
766 if (pub != NULL)
767 return pub;
769 /* try rsa1 public key */
770 pub = key_new(KEY_RSA1);
771 if (key_try_load_public(pub, filename, commentp) == 1)
772 return pub;
773 key_free(pub);
775 /* try ssh2 public key */
776 pub = key_new(KEY_UNSPEC);
777 if (key_try_load_public(pub, filename, commentp) == 1)
778 return pub;
779 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
780 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
781 (key_try_load_public(pub, file, commentp) == 1))
782 return pub;
783 key_free(pub);
784 return NULL;
787 /* Load the certificate associated with the named private key */
788 Key *
789 key_load_cert(const char *filename)
791 Key *pub;
792 char *file;
794 pub = key_new(KEY_UNSPEC);
795 xasprintf(&file, "%s-cert.pub", filename);
796 if (key_try_load_public(pub, file, NULL) == 1) {
797 xfree(file);
798 return pub;
800 xfree(file);
801 key_free(pub);
802 return NULL;
805 /* Load private key and certificate */
806 Key *
807 key_load_private_cert(int type, const char *filename, const char *passphrase,
808 int *perm_ok)
810 Key *key, *pub;
812 switch (type) {
813 case KEY_RSA:
814 case KEY_DSA:
815 case KEY_ECDSA:
816 break;
817 default:
818 error("%s: unsupported key type", __func__);
819 return NULL;
822 if ((key = key_load_private_type(type, filename,
823 passphrase, NULL, perm_ok)) == NULL)
824 return NULL;
826 if ((pub = key_load_cert(filename)) == NULL) {
827 key_free(key);
828 return NULL;
831 /* Make sure the private key matches the certificate */
832 if (key_equal_public(key, pub) == 0) {
833 error("%s: certificate does not match private key %s",
834 __func__, filename);
835 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
836 error("%s: key_to_certified failed", __func__);
837 } else {
838 key_cert_copy(pub, key);
839 key_free(pub);
840 return key;
843 key_free(key);
844 key_free(pub);
845 return NULL;
849 * Returns 1 if the specified "key" is listed in the file "filename",
850 * 0 if the key is not listed or -1 on error.
851 * If strict_type is set then the key type must match exactly,
852 * otherwise a comparison that ignores certficiate data is performed.
855 key_in_file(Key *key, const char *filename, int strict_type)
857 FILE *f;
858 char line[SSH_MAX_PUBKEY_BYTES];
859 char *cp;
860 u_long linenum = 0;
861 int ret = 0;
862 Key *pub;
863 int (*key_compare)(const Key *, const Key *) = strict_type ?
864 key_equal : key_equal_public;
866 if ((f = fopen(filename, "r")) == NULL) {
867 if (errno == ENOENT) {
868 debug("%s: keyfile \"%s\" missing", __func__, filename);
869 return 0;
870 } else {
871 error("%s: could not open keyfile \"%s\": %s", __func__,
872 filename, strerror(errno));
873 return -1;
877 while (read_keyfile_line(f, filename, line, sizeof(line),
878 &linenum) != -1) {
879 cp = line;
881 /* Skip leading whitespace. */
882 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
885 /* Skip comments and empty lines */
886 switch (*cp) {
887 case '#':
888 case '\n':
889 case '\0':
890 continue;
893 pub = key_new(KEY_UNSPEC);
894 if (key_read(pub, &cp) != 1) {
895 key_free(pub);
896 continue;
898 if (key_compare(key, pub)) {
899 ret = 1;
900 key_free(pub);
901 break;
903 key_free(pub);
905 fclose(f);
906 return ret;