kernel - ACPI - Fix missing unlocks in error path in acpi_ec
[dragonfly.git] / crypto / openssh / authfile.c
blob5348a014d9143da1e7e7d1876edb6d4e9abd2b01
1 /* $OpenBSD: authfile.c,v 1.76 2006/08/03 03:34:41 deraadt 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 #include <errno.h>
51 #include <fcntl.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
58 #include "xmalloc.h"
59 #include "cipher.h"
60 #include "buffer.h"
61 #include "key.h"
62 #include "ssh.h"
63 #include "log.h"
64 #include "authfile.h"
65 #include "rsa.h"
66 #include "misc.h"
67 #include "atomicio.h"
68 #include "pathnames.h"
70 /* Version identification string for SSH v1 identity files. */
71 static const char authfile_id_string[] =
72 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
75 * Saves the authentication (private) key in a file, encrypting it with
76 * passphrase. The identification of the file (lowest 64 bits of n) will
77 * precede the key to provide identification of the key without needing a
78 * passphrase.
81 static int
82 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
83 const char *comment)
85 Buffer buffer, encrypted;
86 u_char buf[100], *cp;
87 int fd, i, cipher_num;
88 CipherContext ciphercontext;
89 Cipher *cipher;
90 u_int32_t rnd;
93 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
94 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
96 cipher_num = (strcmp(passphrase, "") == 0) ?
97 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
98 if ((cipher = cipher_by_number(cipher_num)) == NULL)
99 fatal("save_private_key_rsa: bad cipher");
101 /* This buffer is used to built the secret part of the private key. */
102 buffer_init(&buffer);
104 /* Put checkbytes for checking passphrase validity. */
105 rnd = arc4random();
106 buf[0] = rnd & 0xff;
107 buf[1] = (rnd >> 8) & 0xff;
108 buf[2] = buf[0];
109 buf[3] = buf[1];
110 buffer_append(&buffer, buf, 4);
113 * Store the private key (n and e will not be stored because they
114 * will be stored in plain text, and storing them also in encrypted
115 * format would just give known plaintext).
117 buffer_put_bignum(&buffer, key->rsa->d);
118 buffer_put_bignum(&buffer, key->rsa->iqmp);
119 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
120 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
122 /* Pad the part to be encrypted until its size is a multiple of 8. */
123 while (buffer_len(&buffer) % 8 != 0)
124 buffer_put_char(&buffer, 0);
126 /* This buffer will be used to contain the data in the file. */
127 buffer_init(&encrypted);
129 /* First store keyfile id string. */
130 for (i = 0; authfile_id_string[i]; i++)
131 buffer_put_char(&encrypted, authfile_id_string[i]);
132 buffer_put_char(&encrypted, 0);
134 /* Store cipher type. */
135 buffer_put_char(&encrypted, cipher_num);
136 buffer_put_int(&encrypted, 0); /* For future extension */
138 /* Store public key. This will be in plain text. */
139 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
140 buffer_put_bignum(&encrypted, key->rsa->n);
141 buffer_put_bignum(&encrypted, key->rsa->e);
142 buffer_put_cstring(&encrypted, comment);
144 /* Allocate space for the private part of the key in the buffer. */
145 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
147 cipher_set_key_string(&ciphercontext, cipher, passphrase,
148 CIPHER_ENCRYPT);
149 cipher_crypt(&ciphercontext, cp,
150 buffer_ptr(&buffer), buffer_len(&buffer));
151 cipher_cleanup(&ciphercontext);
152 memset(&ciphercontext, 0, sizeof(ciphercontext));
154 /* Destroy temporary data. */
155 memset(buf, 0, sizeof(buf));
156 buffer_free(&buffer);
158 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
159 if (fd < 0) {
160 error("open %s failed: %s.", filename, strerror(errno));
161 buffer_free(&encrypted);
162 return 0;
164 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
165 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
166 error("write to key file %s failed: %s", filename,
167 strerror(errno));
168 buffer_free(&encrypted);
169 close(fd);
170 unlink(filename);
171 return 0;
173 close(fd);
174 buffer_free(&encrypted);
175 return 1;
178 /* save SSH v2 key in OpenSSL PEM format */
179 static int
180 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
181 const char *comment)
183 FILE *fp;
184 int fd;
185 int success = 0;
186 int len = strlen(_passphrase);
187 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
188 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
190 if (len > 0 && len <= 4) {
191 error("passphrase too short: have %d bytes, need > 4", len);
192 return 0;
194 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
195 if (fd < 0) {
196 error("open %s failed: %s.", filename, strerror(errno));
197 return 0;
199 fp = fdopen(fd, "w");
200 if (fp == NULL) {
201 error("fdopen %s failed: %s.", filename, strerror(errno));
202 close(fd);
203 return 0;
205 switch (key->type) {
206 case KEY_DSA:
207 success = PEM_write_DSAPrivateKey(fp, key->dsa,
208 cipher, passphrase, len, NULL, NULL);
209 break;
210 case KEY_RSA:
211 success = PEM_write_RSAPrivateKey(fp, key->rsa,
212 cipher, passphrase, len, NULL, NULL);
213 break;
215 fclose(fp);
216 return success;
220 key_save_private(Key *key, const char *filename, const char *passphrase,
221 const char *comment)
223 switch (key->type) {
224 case KEY_RSA1:
225 return key_save_private_rsa1(key, filename, passphrase,
226 comment);
227 case KEY_DSA:
228 case KEY_RSA:
229 return key_save_private_pem(key, filename, passphrase,
230 comment);
231 default:
232 break;
234 error("key_save_private: cannot save key type %d", key->type);
235 return 0;
239 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
240 * encountered (the file does not exist or is not readable), and the key
241 * otherwise.
244 static Key *
245 key_load_public_rsa1(int fd, const char *filename, char **commentp)
247 Buffer buffer;
248 Key *pub;
249 struct stat st;
250 char *cp;
251 u_int i;
252 size_t len;
254 if (fstat(fd, &st) < 0) {
255 error("fstat for key file %.200s failed: %.100s",
256 filename, strerror(errno));
257 return NULL;
259 if (st.st_size > 1*1024*1024) {
260 error("key file %.200s too large", filename);
261 return NULL;
263 len = (size_t)st.st_size; /* truncated */
265 buffer_init(&buffer);
266 cp = buffer_append_space(&buffer, len);
268 if (atomicio(read, fd, cp, len) != len) {
269 debug("Read from key file %.200s failed: %.100s", filename,
270 strerror(errno));
271 buffer_free(&buffer);
272 return NULL;
275 /* Check that it is at least big enough to contain the ID string. */
276 if (len < sizeof(authfile_id_string)) {
277 debug3("Not a RSA1 key file %.200s.", filename);
278 buffer_free(&buffer);
279 return NULL;
282 * Make sure it begins with the id string. Consume the id string
283 * from the buffer.
285 for (i = 0; i < sizeof(authfile_id_string); i++)
286 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
287 debug3("Not a RSA1 key file %.200s.", filename);
288 buffer_free(&buffer);
289 return NULL;
291 /* Skip cipher type and reserved data. */
292 (void) buffer_get_char(&buffer); /* cipher type */
293 (void) buffer_get_int(&buffer); /* reserved */
295 /* Read the public key from the buffer. */
296 (void) buffer_get_int(&buffer);
297 pub = key_new(KEY_RSA1);
298 buffer_get_bignum(&buffer, pub->rsa->n);
299 buffer_get_bignum(&buffer, pub->rsa->e);
300 if (commentp)
301 *commentp = buffer_get_string(&buffer, NULL);
302 /* The encrypted private part is not parsed by this function. */
304 buffer_free(&buffer);
305 return pub;
308 /* load public key from private-key file, works only for SSH v1 */
309 Key *
310 key_load_public_type(int type, const char *filename, char **commentp)
312 Key *pub;
313 int fd;
315 if (type == KEY_RSA1) {
316 fd = open(filename, O_RDONLY);
317 if (fd < 0)
318 return NULL;
319 pub = key_load_public_rsa1(fd, filename, commentp);
320 close(fd);
321 return pub;
323 return NULL;
327 * Loads the private key from the file. Returns 0 if an error is encountered
328 * (file does not exist or is not readable, or passphrase is bad). This
329 * initializes the private key.
330 * Assumes we are called under uid of the owner of the file.
333 static Key *
334 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
335 char **commentp)
337 u_int i;
338 int check1, check2, cipher_type;
339 size_t len;
340 Buffer buffer, decrypted;
341 u_char *cp;
342 CipherContext ciphercontext;
343 Cipher *cipher;
344 Key *prv = NULL;
345 struct stat st;
347 if (fstat(fd, &st) < 0) {
348 error("fstat for key file %.200s failed: %.100s",
349 filename, strerror(errno));
350 close(fd);
351 return NULL;
353 if (st.st_size > 1*1024*1024) {
354 error("key file %.200s too large", filename);
355 close(fd);
356 return (NULL);
358 len = (size_t)st.st_size; /* truncated */
360 buffer_init(&buffer);
361 cp = buffer_append_space(&buffer, len);
363 if (atomicio(read, fd, cp, len) != len) {
364 debug("Read from key file %.200s failed: %.100s", filename,
365 strerror(errno));
366 buffer_free(&buffer);
367 close(fd);
368 return NULL;
371 /* Check that it is at least big enough to contain the ID string. */
372 if (len < sizeof(authfile_id_string)) {
373 debug3("Not a RSA1 key file %.200s.", filename);
374 buffer_free(&buffer);
375 close(fd);
376 return NULL;
379 * Make sure it begins with the id string. Consume the id string
380 * from the buffer.
382 for (i = 0; i < sizeof(authfile_id_string); i++)
383 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
384 debug3("Not a RSA1 key file %.200s.", filename);
385 buffer_free(&buffer);
386 close(fd);
387 return NULL;
390 /* Read cipher type. */
391 cipher_type = buffer_get_char(&buffer);
392 (void) buffer_get_int(&buffer); /* Reserved data. */
394 /* Read the public key from the buffer. */
395 (void) buffer_get_int(&buffer);
396 prv = key_new_private(KEY_RSA1);
398 buffer_get_bignum(&buffer, prv->rsa->n);
399 buffer_get_bignum(&buffer, prv->rsa->e);
400 if (commentp)
401 *commentp = buffer_get_string(&buffer, NULL);
402 else
403 xfree(buffer_get_string(&buffer, NULL));
405 /* Check that it is a supported cipher. */
406 cipher = cipher_by_number(cipher_type);
407 if (cipher == NULL) {
408 debug("Unsupported cipher %d used in key file %.200s.",
409 cipher_type, filename);
410 buffer_free(&buffer);
411 goto fail;
413 /* Initialize space for decrypted data. */
414 buffer_init(&decrypted);
415 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
417 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
418 cipher_set_key_string(&ciphercontext, cipher, passphrase,
419 CIPHER_DECRYPT);
420 cipher_crypt(&ciphercontext, cp,
421 buffer_ptr(&buffer), buffer_len(&buffer));
422 cipher_cleanup(&ciphercontext);
423 memset(&ciphercontext, 0, sizeof(ciphercontext));
424 buffer_free(&buffer);
426 check1 = buffer_get_char(&decrypted);
427 check2 = buffer_get_char(&decrypted);
428 if (check1 != buffer_get_char(&decrypted) ||
429 check2 != buffer_get_char(&decrypted)) {
430 if (strcmp(passphrase, "") != 0)
431 debug("Bad passphrase supplied for key file %.200s.",
432 filename);
433 /* Bad passphrase. */
434 buffer_free(&decrypted);
435 goto fail;
437 /* Read the rest of the private key. */
438 buffer_get_bignum(&decrypted, prv->rsa->d);
439 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
440 /* in SSL and SSH v1 p and q are exchanged */
441 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
442 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
444 /* calculate p-1 and q-1 */
445 rsa_generate_additional_parameters(prv->rsa);
447 buffer_free(&decrypted);
449 /* enable blinding */
450 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
451 error("key_load_private_rsa1: RSA_blinding_on failed");
452 goto fail;
454 close(fd);
455 return prv;
457 fail:
458 if (commentp)
459 xfree(*commentp);
460 close(fd);
461 key_free(prv);
462 return NULL;
465 Key *
466 key_load_private_pem(int fd, int type, const char *passphrase,
467 char **commentp)
469 FILE *fp;
470 EVP_PKEY *pk = NULL;
471 Key *prv = NULL;
472 char *name = "<no key>";
474 fp = fdopen(fd, "r");
475 if (fp == NULL) {
476 error("fdopen failed: %s", strerror(errno));
477 close(fd);
478 return NULL;
480 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
481 if (pk == NULL) {
482 debug("PEM_read_PrivateKey failed");
483 (void)ERR_get_error();
484 } else if (pk->type == EVP_PKEY_RSA &&
485 (type == KEY_UNSPEC||type==KEY_RSA)) {
486 prv = key_new(KEY_UNSPEC);
487 prv->rsa = EVP_PKEY_get1_RSA(pk);
488 prv->type = KEY_RSA;
489 name = "rsa w/o comment";
490 #ifdef DEBUG_PK
491 RSA_print_fp(stderr, prv->rsa, 8);
492 #endif
493 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
494 error("key_load_private_pem: RSA_blinding_on failed");
495 key_free(prv);
496 prv = NULL;
498 } else if (pk->type == EVP_PKEY_DSA &&
499 (type == KEY_UNSPEC||type==KEY_DSA)) {
500 prv = key_new(KEY_UNSPEC);
501 prv->dsa = EVP_PKEY_get1_DSA(pk);
502 prv->type = KEY_DSA;
503 name = "dsa w/o comment";
504 #ifdef DEBUG_PK
505 DSA_print_fp(stderr, prv->dsa, 8);
506 #endif
507 } else {
508 error("PEM_read_PrivateKey: mismatch or "
509 "unknown EVP_PKEY save_type %d", pk->save_type);
511 fclose(fp);
512 if (pk != NULL)
513 EVP_PKEY_free(pk);
514 if (prv != NULL && commentp)
515 *commentp = xstrdup(name);
516 debug("read PEM private key done: type %s",
517 prv ? key_type(prv) : "<unknown>");
518 return prv;
522 key_perm_ok(int fd, const char *filename)
524 struct stat st;
526 if (fstat(fd, &st) < 0)
527 return 0;
529 * if a key owned by the user is accessed, then we check the
530 * permissions of the file. if the key owned by a different user,
531 * then we don't care.
533 #ifdef HAVE_CYGWIN
534 if (check_ntsec(filename))
535 #endif
536 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
537 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
538 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
539 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
540 error("Permissions 0%3.3o for '%s' are too open.",
541 (u_int)st.st_mode & 0777, filename);
542 error("It is recommended that your private key files are NOT accessible by others.");
543 error("This private key will be ignored.");
544 return 0;
546 return 1;
549 Key *
550 key_load_private_type(int type, const char *filename, const char *passphrase,
551 char **commentp, int *perm_ok)
553 int fd;
555 fd = open(filename, O_RDONLY);
556 if (fd < 0)
557 return NULL;
558 if (!key_perm_ok(fd, filename)) {
559 if (perm_ok != NULL)
560 *perm_ok = 0;
561 error("bad permissions: ignore key: %s", filename);
562 close(fd);
563 return NULL;
565 if (perm_ok != NULL)
566 *perm_ok = 1;
567 switch (type) {
568 case KEY_RSA1:
569 return key_load_private_rsa1(fd, filename, passphrase,
570 commentp);
571 /* closes fd */
572 case KEY_DSA:
573 case KEY_RSA:
574 case KEY_UNSPEC:
575 return key_load_private_pem(fd, type, passphrase, commentp);
576 /* closes fd */
577 default:
578 close(fd);
579 break;
581 return NULL;
584 Key *
585 key_load_private(const char *filename, const char *passphrase,
586 char **commentp)
588 Key *pub, *prv;
589 int fd;
591 fd = open(filename, O_RDONLY);
592 if (fd < 0)
593 return NULL;
594 if (!key_perm_ok(fd, filename)) {
595 error("bad permissions: ignore key: %s", filename);
596 close(fd);
597 return NULL;
599 pub = key_load_public_rsa1(fd, filename, commentp);
600 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
601 if (pub == NULL) {
602 /* closes fd */
603 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
604 /* use the filename as a comment for PEM */
605 if (commentp && prv)
606 *commentp = xstrdup(filename);
607 } else {
608 /* it's a SSH v1 key if the public key part is readable */
609 key_free(pub);
610 /* closes fd */
611 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
613 return prv;
616 static int
617 key_try_load_public(Key *k, const char *filename, char **commentp)
619 FILE *f;
620 char line[SSH_MAX_PUBKEY_BYTES];
621 char *cp;
622 u_long linenum = 0;
624 f = fopen(filename, "r");
625 if (f != NULL) {
626 while (read_keyfile_line(f, filename, line, sizeof(line),
627 &linenum) != -1) {
628 cp = line;
629 switch (*cp) {
630 case '#':
631 case '\n':
632 case '\0':
633 continue;
635 /* Skip leading whitespace. */
636 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
638 if (*cp) {
639 if (key_read(k, &cp) == 1) {
640 if (commentp)
641 *commentp=xstrdup(filename);
642 fclose(f);
643 return 1;
647 fclose(f);
649 return 0;
652 /* load public key from ssh v1 private or any pubkey file */
653 Key *
654 key_load_public(const char *filename, char **commentp)
656 Key *pub;
657 char file[MAXPATHLEN];
659 /* try rsa1 private key */
660 pub = key_load_public_type(KEY_RSA1, filename, commentp);
661 if (pub != NULL)
662 return pub;
664 /* try rsa1 public key */
665 pub = key_new(KEY_RSA1);
666 if (key_try_load_public(pub, filename, commentp) == 1)
667 return pub;
668 key_free(pub);
670 /* try ssh2 public key */
671 pub = key_new(KEY_UNSPEC);
672 if (key_try_load_public(pub, filename, commentp) == 1)
673 return pub;
674 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
675 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
676 (key_try_load_public(pub, file, commentp) == 1))
677 return pub;
678 key_free(pub);
679 return NULL;
682 char *
683 blacklist_filename(const Key *key)
685 char *name;
687 xasprintf(&name, "%s.%s-%u",
688 _PATH_BLACKLIST, key_type(key), key_size(key));
689 return name;
692 /* Scan a blacklist of known-vulnerable keys. */
694 blacklisted_key(const Key *key)
696 char *blacklist_file;
697 int fd = -1;
698 char *dgst_hex = NULL;
699 char *dgst_packed = NULL, *p;
700 int i;
701 size_t line_len;
702 struct stat st;
703 char buf[256];
704 off_t start, lower, upper;
705 int ret = 0;
707 blacklist_file = blacklist_filename(key);
708 debug("Checking blacklist file %s", blacklist_file);
709 fd = open(blacklist_file, O_RDONLY);
710 if (fd < 0)
711 goto out;
713 dgst_hex = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
714 /* Remove all colons */
715 dgst_packed = xcalloc(1, strlen(dgst_hex) + 1);
716 for (i = 0, p = dgst_packed; dgst_hex[i]; i++)
717 if (dgst_hex[i] != ':')
718 *p++ = dgst_hex[i];
719 /* Only compare least-significant 80 bits (to keep the blacklist
720 * size down)
722 line_len = strlen(dgst_packed + 12);
723 if (line_len > 32)
724 goto out;
726 /* Skip leading comments */
727 start = 0;
728 for (;;) {
729 ssize_t r;
730 char *newline;
732 r = atomicio(read, fd, buf, 256);
733 if (r <= 0)
734 goto out;
735 if (buf[0] != '#')
736 break;
738 newline = memchr(buf, '\n', 256);
739 if (!newline)
740 goto out;
741 start += newline + 1 - buf;
742 if (lseek(fd, start, SEEK_SET) < 0)
743 goto out;
746 /* Initialise binary search record numbers */
747 if (fstat(fd, &st) < 0)
748 goto out;
749 lower = 0;
750 upper = (st.st_size - start) / (line_len + 1);
752 while (lower != upper) {
753 off_t cur;
754 char buf[32];
755 int cmp;
757 cur = lower + (upper - lower) / 2;
759 /* Read this line and compare to digest; this is
760 * overflow-safe since cur < max(off_t) / (line_len + 1) */
761 if (lseek(fd, start + cur * (line_len + 1), SEEK_SET) < 0)
762 break;
763 if (atomicio(read, fd, buf, line_len) != line_len)
764 break;
765 cmp = memcmp(buf, dgst_packed + 12, line_len);
766 if (cmp < 0) {
767 if (cur == lower)
768 break;
769 lower = cur;
770 } else if (cmp > 0) {
771 if (cur == upper)
772 break;
773 upper = cur;
774 } else {
775 debug("Found %s in blacklist", dgst_hex);
776 ret = 1;
777 break;
781 out:
782 if (dgst_packed)
783 xfree(dgst_packed);
784 if (dgst_hex)
785 xfree(dgst_hex);
786 if (fd >= 0)
787 close(fd);
788 xfree(blacklist_file);
789 return ret;