- (dtucker) [platform.c] includes.h instead of defines.h so that we get
[openssh-git.git] / authfile.c
blob7f98ab5474c2cd343b0bec2cd34979f3be813527
1 /* $OpenBSD: authfile.c,v 1.85 2010/10/28 11:22:09 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.
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 * Saves the authentication (private) key in a file, encrypting it with
78 * passphrase. The identification of the file (lowest 64 bits of n) will
79 * precede the key to provide identification of the key without needing a
80 * passphrase.
83 static int
84 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
85 const char *comment)
87 Buffer buffer, encrypted;
88 u_char buf[100], *cp;
89 int fd, i, cipher_num;
90 CipherContext ciphercontext;
91 Cipher *cipher;
92 u_int32_t rnd;
95 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
96 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
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");
103 /* This buffer is used to built the secret part of the private key. */
104 buffer_init(&buffer);
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);
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).
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 */
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);
128 /* This buffer will be used to contain the data in the file. */
129 buffer_init(&encrypted);
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);
136 /* Store cipher type. */
137 buffer_put_char(&encrypted, cipher_num);
138 buffer_put_int(&encrypted, 0); /* For future extension */
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);
146 /* Allocate space for the private part of the key in the buffer. */
147 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
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));
156 /* Destroy temporary data. */
157 memset(buf, 0, sizeof(buf));
158 buffer_free(&buffer);
160 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
161 if (fd < 0) {
162 error("open %s failed: %s.", filename, strerror(errno));
163 buffer_free(&encrypted);
164 return 0;
166 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
167 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
168 error("write to key file %s failed: %s", filename,
169 strerror(errno));
170 buffer_free(&encrypted);
171 close(fd);
172 unlink(filename);
173 return 0;
175 close(fd);
176 buffer_free(&encrypted);
177 return 1;
180 /* save SSH v2 key in OpenSSL PEM format */
181 static int
182 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
183 const char *comment)
185 FILE *fp;
186 int fd;
187 int success = 0;
188 int len = strlen(_passphrase);
189 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
190 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
191 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
192 #else
193 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
194 #endif
196 if (len > 0 && len <= 4) {
197 error("passphrase too short: have %d bytes, need > 4", len);
198 return 0;
200 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
201 if (fd < 0) {
202 error("open %s failed: %s.", filename, strerror(errno));
203 return 0;
205 fp = fdopen(fd, "w");
206 if (fp == NULL) {
207 error("fdopen %s failed: %s.", filename, strerror(errno));
208 close(fd);
209 return 0;
211 switch (key->type) {
212 case KEY_DSA:
213 success = PEM_write_DSAPrivateKey(fp, key->dsa,
214 cipher, passphrase, len, NULL, NULL);
215 break;
216 #ifdef OPENSSL_HAS_ECC
217 case KEY_ECDSA:
218 success = PEM_write_ECPrivateKey(fp, key->ecdsa,
219 cipher, passphrase, len, NULL, NULL);
220 break;
221 #endif
222 case KEY_RSA:
223 success = PEM_write_RSAPrivateKey(fp, key->rsa,
224 cipher, passphrase, len, NULL, NULL);
225 break;
227 fclose(fp);
228 return success;
232 key_save_private(Key *key, const char *filename, const char *passphrase,
233 const char *comment)
235 switch (key->type) {
236 case KEY_RSA1:
237 return key_save_private_rsa1(key, filename, passphrase,
238 comment);
239 case KEY_DSA:
240 case KEY_ECDSA:
241 case KEY_RSA:
242 return key_save_private_pem(key, filename, passphrase,
243 comment);
244 default:
245 break;
247 error("key_save_private: cannot save key type %d", key->type);
248 return 0;
252 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
253 * encountered (the file does not exist or is not readable), and the key
254 * otherwise.
257 static Key *
258 key_load_public_rsa1(int fd, const char *filename, char **commentp)
260 Buffer buffer;
261 Key *pub;
262 struct stat st;
263 char *cp;
264 u_int i;
265 size_t len;
267 if (fstat(fd, &st) < 0) {
268 error("fstat for key file %.200s failed: %.100s",
269 filename, strerror(errno));
270 return NULL;
272 if (st.st_size > 1*1024*1024) {
273 error("key file %.200s too large", filename);
274 return NULL;
276 len = (size_t)st.st_size; /* truncated */
278 buffer_init(&buffer);
279 cp = buffer_append_space(&buffer, len);
281 if (atomicio(read, fd, cp, len) != len) {
282 debug("Read from key file %.200s failed: %.100s", filename,
283 strerror(errno));
284 buffer_free(&buffer);
285 return NULL;
288 /* Check that it is at least big enough to contain the ID string. */
289 if (len < sizeof(authfile_id_string)) {
290 debug3("Not a RSA1 key file %.200s.", filename);
291 buffer_free(&buffer);
292 return NULL;
295 * Make sure it begins with the id string. Consume the id string
296 * from the buffer.
298 for (i = 0; i < sizeof(authfile_id_string); i++)
299 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
300 debug3("Not a RSA1 key file %.200s.", filename);
301 buffer_free(&buffer);
302 return NULL;
304 /* Skip cipher type and reserved data. */
305 (void) buffer_get_char(&buffer); /* cipher type */
306 (void) buffer_get_int(&buffer); /* reserved */
308 /* Read the public key from the buffer. */
309 (void) buffer_get_int(&buffer);
310 pub = key_new(KEY_RSA1);
311 buffer_get_bignum(&buffer, pub->rsa->n);
312 buffer_get_bignum(&buffer, pub->rsa->e);
313 if (commentp)
314 *commentp = buffer_get_string(&buffer, NULL);
315 /* The encrypted private part is not parsed by this function. */
317 buffer_free(&buffer);
318 return pub;
321 /* load public key from private-key file, works only for SSH v1 */
322 Key *
323 key_load_public_type(int type, const char *filename, char **commentp)
325 Key *pub;
326 int fd;
328 if (type == KEY_RSA1) {
329 fd = open(filename, O_RDONLY);
330 if (fd < 0)
331 return NULL;
332 pub = key_load_public_rsa1(fd, filename, commentp);
333 close(fd);
334 return pub;
336 return NULL;
340 * Loads the private key from the file. Returns 0 if an error is encountered
341 * (file does not exist or is not readable, or passphrase is bad). This
342 * initializes the private key.
343 * Assumes we are called under uid of the owner of the file.
346 static Key *
347 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
348 char **commentp)
350 u_int i;
351 int check1, check2, cipher_type;
352 size_t len;
353 Buffer buffer, decrypted;
354 u_char *cp;
355 CipherContext ciphercontext;
356 Cipher *cipher;
357 Key *prv = NULL;
358 struct stat st;
360 if (fstat(fd, &st) < 0) {
361 error("fstat for key file %.200s failed: %.100s",
362 filename, strerror(errno));
363 close(fd);
364 return NULL;
366 if (st.st_size > 1*1024*1024) {
367 error("key file %.200s too large", filename);
368 close(fd);
369 return (NULL);
371 len = (size_t)st.st_size; /* truncated */
373 buffer_init(&buffer);
374 cp = buffer_append_space(&buffer, len);
376 if (atomicio(read, fd, cp, len) != len) {
377 debug("Read from key file %.200s failed: %.100s", filename,
378 strerror(errno));
379 buffer_free(&buffer);
380 close(fd);
381 return NULL;
384 /* Check that it is at least big enough to contain the ID string. */
385 if (len < sizeof(authfile_id_string)) {
386 debug3("Not a RSA1 key file %.200s.", filename);
387 buffer_free(&buffer);
388 close(fd);
389 return NULL;
392 * Make sure it begins with the id string. Consume the id string
393 * from the buffer.
395 for (i = 0; i < sizeof(authfile_id_string); i++)
396 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
397 debug3("Not a RSA1 key file %.200s.", filename);
398 buffer_free(&buffer);
399 close(fd);
400 return NULL;
403 /* Read cipher type. */
404 cipher_type = buffer_get_char(&buffer);
405 (void) buffer_get_int(&buffer); /* Reserved data. */
407 /* Read the public key from the buffer. */
408 (void) buffer_get_int(&buffer);
409 prv = key_new_private(KEY_RSA1);
411 buffer_get_bignum(&buffer, prv->rsa->n);
412 buffer_get_bignum(&buffer, prv->rsa->e);
413 if (commentp)
414 *commentp = buffer_get_string(&buffer, NULL);
415 else
416 xfree(buffer_get_string(&buffer, NULL));
418 /* Check that it is a supported cipher. */
419 cipher = cipher_by_number(cipher_type);
420 if (cipher == NULL) {
421 debug("Unsupported cipher %d used in key file %.200s.",
422 cipher_type, filename);
423 buffer_free(&buffer);
424 goto fail;
426 /* Initialize space for decrypted data. */
427 buffer_init(&decrypted);
428 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
430 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
431 cipher_set_key_string(&ciphercontext, cipher, passphrase,
432 CIPHER_DECRYPT);
433 cipher_crypt(&ciphercontext, cp,
434 buffer_ptr(&buffer), buffer_len(&buffer));
435 cipher_cleanup(&ciphercontext);
436 memset(&ciphercontext, 0, sizeof(ciphercontext));
437 buffer_free(&buffer);
439 check1 = buffer_get_char(&decrypted);
440 check2 = buffer_get_char(&decrypted);
441 if (check1 != buffer_get_char(&decrypted) ||
442 check2 != buffer_get_char(&decrypted)) {
443 if (strcmp(passphrase, "") != 0)
444 debug("Bad passphrase supplied for key file %.200s.",
445 filename);
446 /* Bad passphrase. */
447 buffer_free(&decrypted);
448 goto fail;
450 /* Read the rest of the private key. */
451 buffer_get_bignum(&decrypted, prv->rsa->d);
452 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
453 /* in SSL and SSH v1 p and q are exchanged */
454 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
455 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
457 /* calculate p-1 and q-1 */
458 rsa_generate_additional_parameters(prv->rsa);
460 buffer_free(&decrypted);
462 /* enable blinding */
463 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
464 error("key_load_private_rsa1: RSA_blinding_on failed");
465 goto fail;
467 close(fd);
468 return prv;
470 fail:
471 if (commentp)
472 xfree(*commentp);
473 close(fd);
474 key_free(prv);
475 return NULL;
478 Key *
479 key_load_private_pem(int fd, int type, const char *passphrase,
480 char **commentp)
482 FILE *fp;
483 EVP_PKEY *pk = NULL;
484 Key *prv = NULL;
485 char *name = "<no key>";
487 fp = fdopen(fd, "r");
488 if (fp == NULL) {
489 error("fdopen failed: %s", strerror(errno));
490 close(fd);
491 return NULL;
493 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
494 if (pk == NULL) {
495 debug("PEM_read_PrivateKey failed");
496 (void)ERR_get_error();
497 } else if (pk->type == EVP_PKEY_RSA &&
498 (type == KEY_UNSPEC||type==KEY_RSA)) {
499 prv = key_new(KEY_UNSPEC);
500 prv->rsa = EVP_PKEY_get1_RSA(pk);
501 prv->type = KEY_RSA;
502 name = "rsa w/o comment";
503 #ifdef DEBUG_PK
504 RSA_print_fp(stderr, prv->rsa, 8);
505 #endif
506 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
507 error("key_load_private_pem: RSA_blinding_on failed");
508 key_free(prv);
509 prv = NULL;
511 } else if (pk->type == EVP_PKEY_DSA &&
512 (type == KEY_UNSPEC||type==KEY_DSA)) {
513 prv = key_new(KEY_UNSPEC);
514 prv->dsa = EVP_PKEY_get1_DSA(pk);
515 prv->type = KEY_DSA;
516 name = "dsa w/o comment";
517 #ifdef DEBUG_PK
518 DSA_print_fp(stderr, prv->dsa, 8);
519 #endif
520 #ifdef OPENSSL_HAS_ECC
521 } else if (pk->type == EVP_PKEY_EC &&
522 (type == KEY_UNSPEC||type==KEY_ECDSA)) {
523 prv = key_new(KEY_UNSPEC);
524 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
525 prv->type = KEY_ECDSA;
526 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
527 key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
528 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
529 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
530 key_ec_validate_private(prv->ecdsa) != 0) {
531 error("%s: bad ECDSA key", __func__);
532 key_free(prv);
533 prv = NULL;
535 name = "ecdsa w/o comment";
536 #ifdef DEBUG_PK
537 if (prv != NULL && prv->ecdsa != NULL)
538 key_dump_ec_key(prv->ecdsa);
539 #endif
540 #endif /* OPENSSL_HAS_ECC */
541 } else {
542 error("PEM_read_PrivateKey: mismatch or "
543 "unknown EVP_PKEY save_type %d", pk->save_type);
545 fclose(fp);
546 if (pk != NULL)
547 EVP_PKEY_free(pk);
548 if (prv != NULL && commentp)
549 *commentp = xstrdup(name);
550 debug("read PEM private key done: type %s",
551 prv ? key_type(prv) : "<unknown>");
552 return prv;
556 key_perm_ok(int fd, const char *filename)
558 struct stat st;
560 if (fstat(fd, &st) < 0)
561 return 0;
563 * if a key owned by the user is accessed, then we check the
564 * permissions of the file. if the key owned by a different user,
565 * then we don't care.
567 #ifdef HAVE_CYGWIN
568 if (check_ntsec(filename))
569 #endif
570 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
571 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
572 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
573 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
574 error("Permissions 0%3.3o for '%s' are too open.",
575 (u_int)st.st_mode & 0777, filename);
576 error("It is recommended that your private key files are NOT accessible by others.");
577 error("This private key will be ignored.");
578 return 0;
580 return 1;
583 Key *
584 key_load_private_type(int type, const char *filename, const char *passphrase,
585 char **commentp, int *perm_ok)
587 int fd;
589 fd = open(filename, O_RDONLY);
590 if (fd < 0) {
591 debug("could not open key file '%s': %s", filename,
592 strerror(errno));
593 if (perm_ok != NULL)
594 *perm_ok = 0;
595 return NULL;
597 if (!key_perm_ok(fd, filename)) {
598 if (perm_ok != NULL)
599 *perm_ok = 0;
600 error("bad permissions: ignore key: %s", filename);
601 close(fd);
602 return NULL;
604 if (perm_ok != NULL)
605 *perm_ok = 1;
606 switch (type) {
607 case KEY_RSA1:
608 return key_load_private_rsa1(fd, filename, passphrase,
609 commentp);
610 /* closes fd */
611 case KEY_DSA:
612 case KEY_ECDSA:
613 case KEY_RSA:
614 case KEY_UNSPEC:
615 return key_load_private_pem(fd, type, passphrase, commentp);
616 /* closes fd */
617 default:
618 close(fd);
619 break;
621 return NULL;
624 Key *
625 key_load_private(const char *filename, const char *passphrase,
626 char **commentp)
628 Key *pub, *prv;
629 int fd;
631 fd = open(filename, O_RDONLY);
632 if (fd < 0) {
633 debug("could not open key file '%s': %s", filename,
634 strerror(errno));
635 return NULL;
637 if (!key_perm_ok(fd, filename)) {
638 error("bad permissions: ignore key: %s", filename);
639 close(fd);
640 return NULL;
642 pub = key_load_public_rsa1(fd, filename, commentp);
643 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
644 if (pub == NULL) {
645 /* closes fd */
646 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
647 /* use the filename as a comment for PEM */
648 if (commentp && prv)
649 *commentp = xstrdup(filename);
650 } else {
651 /* it's a SSH v1 key if the public key part is readable */
652 key_free(pub);
653 /* closes fd */
654 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
656 return prv;
659 static int
660 key_try_load_public(Key *k, const char *filename, char **commentp)
662 FILE *f;
663 char line[SSH_MAX_PUBKEY_BYTES];
664 char *cp;
665 u_long linenum = 0;
667 f = fopen(filename, "r");
668 if (f != NULL) {
669 while (read_keyfile_line(f, filename, line, sizeof(line),
670 &linenum) != -1) {
671 cp = line;
672 switch (*cp) {
673 case '#':
674 case '\n':
675 case '\0':
676 continue;
678 /* Skip leading whitespace. */
679 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
681 if (*cp) {
682 if (key_read(k, &cp) == 1) {
683 if (commentp)
684 *commentp=xstrdup(filename);
685 fclose(f);
686 return 1;
690 fclose(f);
692 return 0;
695 /* load public key from ssh v1 private or any pubkey file */
696 Key *
697 key_load_public(const char *filename, char **commentp)
699 Key *pub;
700 char file[MAXPATHLEN];
702 /* try rsa1 private key */
703 pub = key_load_public_type(KEY_RSA1, filename, commentp);
704 if (pub != NULL)
705 return pub;
707 /* try rsa1 public key */
708 pub = key_new(KEY_RSA1);
709 if (key_try_load_public(pub, filename, commentp) == 1)
710 return pub;
711 key_free(pub);
713 /* try ssh2 public key */
714 pub = key_new(KEY_UNSPEC);
715 if (key_try_load_public(pub, filename, commentp) == 1)
716 return pub;
717 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
718 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
719 (key_try_load_public(pub, file, commentp) == 1))
720 return pub;
721 key_free(pub);
722 return NULL;
725 /* Load the certificate associated with the named private key */
726 Key *
727 key_load_cert(const char *filename)
729 Key *pub;
730 char *file;
732 pub = key_new(KEY_UNSPEC);
733 xasprintf(&file, "%s-cert.pub", filename);
734 if (key_try_load_public(pub, file, NULL) == 1) {
735 xfree(file);
736 return pub;
738 xfree(file);
739 key_free(pub);
740 return NULL;
743 /* Load private key and certificate */
744 Key *
745 key_load_private_cert(int type, const char *filename, const char *passphrase,
746 int *perm_ok)
748 Key *key, *pub;
750 switch (type) {
751 case KEY_RSA:
752 case KEY_DSA:
753 case KEY_ECDSA:
754 break;
755 default:
756 error("%s: unsupported key type", __func__);
757 return NULL;
760 if ((key = key_load_private_type(type, filename,
761 passphrase, NULL, perm_ok)) == NULL)
762 return NULL;
764 if ((pub = key_load_cert(filename)) == NULL) {
765 key_free(key);
766 return NULL;
769 /* Make sure the private key matches the certificate */
770 if (key_equal_public(key, pub) == 0) {
771 error("%s: certificate does not match private key %s",
772 __func__, filename);
773 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
774 error("%s: key_to_certified failed", __func__);
775 } else {
776 key_cert_copy(pub, key);
777 key_free(pub);
778 return key;
781 key_free(key);
782 key_free(pub);
783 return NULL;
787 * Returns 1 if the specified "key" is listed in the file "filename",
788 * 0 if the key is not listed or -1 on error.
789 * If strict_type is set then the key type must match exactly,
790 * otherwise a comparison that ignores certficiate data is performed.
793 key_in_file(Key *key, const char *filename, int strict_type)
795 FILE *f;
796 char line[SSH_MAX_PUBKEY_BYTES];
797 char *cp;
798 u_long linenum = 0;
799 int ret = 0;
800 Key *pub;
801 int (*key_compare)(const Key *, const Key *) = strict_type ?
802 key_equal : key_equal_public;
804 if ((f = fopen(filename, "r")) == NULL) {
805 if (errno == ENOENT) {
806 debug("%s: keyfile \"%s\" missing", __func__, filename);
807 return 0;
808 } else {
809 error("%s: could not open keyfile \"%s\": %s", __func__,
810 filename, strerror(errno));
811 return -1;
815 while (read_keyfile_line(f, filename, line, sizeof(line),
816 &linenum) != -1) {
817 cp = line;
819 /* Skip leading whitespace. */
820 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
823 /* Skip comments and empty lines */
824 switch (*cp) {
825 case '#':
826 case '\n':
827 case '\0':
828 continue;
831 pub = key_new(KEY_UNSPEC);
832 if (key_read(pub, &cp) != 1) {
833 key_free(pub);
834 continue;
836 if (key_compare(key, pub)) {
837 ret = 1;
838 key_free(pub);
839 break;
841 key_free(pub);
843 fclose(f);
844 return ret;