xref: /netbsd-src/crypto/external/bsd/openssh/dist/krl.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: krl.c,v 1.17 2020/05/28 17:05:49 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2012 Damien Miller <djm@mindrot.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /* $OpenBSD: krl.c,v 1.50 2020/04/03 05:48:57 djm Exp $ */
20 
21 #include "includes.h"
22 __RCSID("$NetBSD: krl.c,v 1.17 2020/05/28 17:05:49 christos Exp $");
23 #include <sys/param.h>	/* MIN */
24 #include <sys/types.h>
25 #include <sys/tree.h>
26 #include <sys/queue.h>
27 
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <time.h>
33 #include <unistd.h>
34 #include <stdlib.h>
35 
36 #include "sshbuf.h"
37 #include "ssherr.h"
38 #include "sshkey.h"
39 #include "authfile.h"
40 #include "misc.h"
41 #include "log.h"
42 #include "digest.h"
43 #include "bitmap.h"
44 #include "utf8.h"
45 
46 #include "krl.h"
47 
48 /* #define DEBUG_KRL */
49 #ifdef DEBUG_KRL
50 # define KRL_DBG(x) debug3 x
51 #else
52 # define KRL_DBG(x)
53 #endif
54 
55 /*
56  * Trees of revoked serial numbers, key IDs and keys. This allows
57  * quick searching, querying and producing lists in canonical order.
58  */
59 
60 /* Tree of serial numbers. XXX make smarter: really need a real sparse bitmap */
61 struct revoked_serial {
62 	u_int64_t lo, hi;
63 	RB_ENTRY(revoked_serial) tree_entry;
64 };
65 static int serial_cmp(struct revoked_serial *a, struct revoked_serial *b);
66 RB_HEAD(revoked_serial_tree, revoked_serial);
67 RB_GENERATE_STATIC(revoked_serial_tree, revoked_serial, tree_entry, serial_cmp);
68 
69 /* Tree of key IDs */
70 struct revoked_key_id {
71 	char *key_id;
72 	RB_ENTRY(revoked_key_id) tree_entry;
73 };
74 static int key_id_cmp(struct revoked_key_id *a, struct revoked_key_id *b);
75 RB_HEAD(revoked_key_id_tree, revoked_key_id);
76 RB_GENERATE_STATIC(revoked_key_id_tree, revoked_key_id, tree_entry, key_id_cmp);
77 
78 /* Tree of blobs (used for keys and fingerprints) */
79 struct revoked_blob {
80 	u_char *blob;
81 	size_t len;
82 	RB_ENTRY(revoked_blob) tree_entry;
83 };
84 static int blob_cmp(struct revoked_blob *a, struct revoked_blob *b);
85 RB_HEAD(revoked_blob_tree, revoked_blob);
86 RB_GENERATE_STATIC(revoked_blob_tree, revoked_blob, tree_entry, blob_cmp);
87 
88 /* Tracks revoked certs for a single CA */
89 struct revoked_certs {
90 	struct sshkey *ca_key;
91 	struct revoked_serial_tree revoked_serials;
92 	struct revoked_key_id_tree revoked_key_ids;
93 	TAILQ_ENTRY(revoked_certs) entry;
94 };
95 TAILQ_HEAD(revoked_certs_list, revoked_certs);
96 
97 struct ssh_krl {
98 	u_int64_t krl_version;
99 	u_int64_t generated_date;
100 	u_int64_t flags;
101 	char *comment;
102 	struct revoked_blob_tree revoked_keys;
103 	struct revoked_blob_tree revoked_sha1s;
104 	struct revoked_blob_tree revoked_sha256s;
105 	struct revoked_certs_list revoked_certs;
106 };
107 
108 /* Return equal if a and b overlap */
109 static int
110 serial_cmp(struct revoked_serial *a, struct revoked_serial *b)
111 {
112 	if (a->hi >= b->lo && a->lo <= b->hi)
113 		return 0;
114 	return a->lo < b->lo ? -1 : 1;
115 }
116 
117 static int
118 key_id_cmp(struct revoked_key_id *a, struct revoked_key_id *b)
119 {
120 	return strcmp(a->key_id, b->key_id);
121 }
122 
123 static int
124 blob_cmp(struct revoked_blob *a, struct revoked_blob *b)
125 {
126 	int r;
127 
128 	if (a->len != b->len) {
129 		if ((r = memcmp(a->blob, b->blob, MINIMUM(a->len, b->len))) != 0)
130 			return r;
131 		return a->len > b->len ? 1 : -1;
132 	} else
133 		return memcmp(a->blob, b->blob, a->len);
134 }
135 
136 struct ssh_krl *
137 ssh_krl_init(void)
138 {
139 	struct ssh_krl *krl;
140 
141 	if ((krl = calloc(1, sizeof(*krl))) == NULL)
142 		return NULL;
143 	RB_INIT(&krl->revoked_keys);
144 	RB_INIT(&krl->revoked_sha1s);
145 	RB_INIT(&krl->revoked_sha256s);
146 	TAILQ_INIT(&krl->revoked_certs);
147 	return krl;
148 }
149 
150 static void
151 revoked_certs_free(struct revoked_certs *rc)
152 {
153 	struct revoked_serial *rs, *trs;
154 	struct revoked_key_id *rki, *trki;
155 
156 	RB_FOREACH_SAFE(rs, revoked_serial_tree, &rc->revoked_serials, trs) {
157 		RB_REMOVE(revoked_serial_tree, &rc->revoked_serials, rs);
158 		free(rs);
159 	}
160 	RB_FOREACH_SAFE(rki, revoked_key_id_tree, &rc->revoked_key_ids, trki) {
161 		RB_REMOVE(revoked_key_id_tree, &rc->revoked_key_ids, rki);
162 		free(rki->key_id);
163 		free(rki);
164 	}
165 	sshkey_free(rc->ca_key);
166 }
167 
168 void
169 ssh_krl_free(struct ssh_krl *krl)
170 {
171 	struct revoked_blob *rb, *trb;
172 	struct revoked_certs *rc, *trc;
173 
174 	if (krl == NULL)
175 		return;
176 
177 	free(krl->comment);
178 	RB_FOREACH_SAFE(rb, revoked_blob_tree, &krl->revoked_keys, trb) {
179 		RB_REMOVE(revoked_blob_tree, &krl->revoked_keys, rb);
180 		free(rb->blob);
181 		free(rb);
182 	}
183 	RB_FOREACH_SAFE(rb, revoked_blob_tree, &krl->revoked_sha1s, trb) {
184 		RB_REMOVE(revoked_blob_tree, &krl->revoked_sha1s, rb);
185 		free(rb->blob);
186 		free(rb);
187 	}
188 	RB_FOREACH_SAFE(rb, revoked_blob_tree, &krl->revoked_sha256s, trb) {
189 		RB_REMOVE(revoked_blob_tree, &krl->revoked_sha256s, rb);
190 		free(rb->blob);
191 		free(rb);
192 	}
193 	TAILQ_FOREACH_SAFE(rc, &krl->revoked_certs, entry, trc) {
194 		TAILQ_REMOVE(&krl->revoked_certs, rc, entry);
195 		revoked_certs_free(rc);
196 	}
197 }
198 
199 void
200 ssh_krl_set_version(struct ssh_krl *krl, u_int64_t version)
201 {
202 	krl->krl_version = version;
203 }
204 
205 int
206 ssh_krl_set_comment(struct ssh_krl *krl, const char *comment)
207 {
208 	free(krl->comment);
209 	if ((krl->comment = strdup(comment)) == NULL)
210 		return SSH_ERR_ALLOC_FAIL;
211 	return 0;
212 }
213 
214 /*
215  * Find the revoked_certs struct for a CA key. If allow_create is set then
216  * create a new one in the tree if one did not exist already.
217  */
218 static int
219 revoked_certs_for_ca_key(struct ssh_krl *krl, const struct sshkey *ca_key,
220     struct revoked_certs **rcp, int allow_create)
221 {
222 	struct revoked_certs *rc;
223 	int r;
224 
225 	*rcp = NULL;
226 	TAILQ_FOREACH(rc, &krl->revoked_certs, entry) {
227 		if ((ca_key == NULL && rc->ca_key == NULL) ||
228 		    sshkey_equal(rc->ca_key, ca_key)) {
229 			*rcp = rc;
230 			return 0;
231 		}
232 	}
233 	if (!allow_create)
234 		return 0;
235 	/* If this CA doesn't exist in the list then add it now */
236 	if ((rc = calloc(1, sizeof(*rc))) == NULL)
237 		return SSH_ERR_ALLOC_FAIL;
238 	if (ca_key == NULL)
239 		rc->ca_key = NULL;
240 	else if ((r = sshkey_from_private(ca_key, &rc->ca_key)) != 0) {
241 		free(rc);
242 		return r;
243 	}
244 	RB_INIT(&rc->revoked_serials);
245 	RB_INIT(&rc->revoked_key_ids);
246 	TAILQ_INSERT_TAIL(&krl->revoked_certs, rc, entry);
247 	KRL_DBG(("%s: new CA %s", __func__,
248 	    ca_key == NULL ? "*" : sshkey_type(ca_key)));
249 	*rcp = rc;
250 	return 0;
251 }
252 
253 static int
254 insert_serial_range(struct revoked_serial_tree *rt, u_int64_t lo, u_int64_t hi)
255 {
256 	struct revoked_serial rs, *ers, *crs, *irs;
257 
258 	KRL_DBG(("%s: insert %"PRIu64":%"PRIu64, __func__, lo, hi));
259 	memset(&rs, 0, sizeof(rs));
260 	rs.lo = lo;
261 	rs.hi = hi;
262 	ers = RB_NFIND(revoked_serial_tree, rt, &rs);
263 	if (ers == NULL || serial_cmp(ers, &rs) != 0) {
264 		/* No entry matches. Just insert */
265 		if ((irs = malloc(sizeof(rs))) == NULL)
266 			return SSH_ERR_ALLOC_FAIL;
267 		memcpy(irs, &rs, sizeof(*irs));
268 		ers = RB_INSERT(revoked_serial_tree, rt, irs);
269 		if (ers != NULL) {
270 			KRL_DBG(("%s: bad: ers != NULL", __func__));
271 			/* Shouldn't happen */
272 			free(irs);
273 			return SSH_ERR_INTERNAL_ERROR;
274 		}
275 		ers = irs;
276 	} else {
277 		KRL_DBG(("%s: overlap found %"PRIu64":%"PRIu64, __func__,
278 		    ers->lo, ers->hi));
279 		/*
280 		 * The inserted entry overlaps an existing one. Grow the
281 		 * existing entry.
282 		 */
283 		if (ers->lo > lo)
284 			ers->lo = lo;
285 		if (ers->hi < hi)
286 			ers->hi = hi;
287 	}
288 
289 	/*
290 	 * The inserted or revised range might overlap or abut adjacent ones;
291 	 * coalesce as necessary.
292 	 */
293 
294 	/* Check predecessors */
295 	while ((crs = RB_PREV(revoked_serial_tree, rt, ers)) != NULL) {
296 		KRL_DBG(("%s: pred %"PRIu64":%"PRIu64, __func__,
297 		    crs->lo, crs->hi));
298 		if (ers->lo != 0 && crs->hi < ers->lo - 1)
299 			break;
300 		/* This entry overlaps. */
301 		if (crs->lo < ers->lo) {
302 			ers->lo = crs->lo;
303 			KRL_DBG(("%s: pred extend %"PRIu64":%"PRIu64, __func__,
304 			    ers->lo, ers->hi));
305 		}
306 		RB_REMOVE(revoked_serial_tree, rt, crs);
307 		free(crs);
308 	}
309 	/* Check successors */
310 	while ((crs = RB_NEXT(revoked_serial_tree, rt, ers)) != NULL) {
311 		KRL_DBG(("%s: succ %"PRIu64":%"PRIu64, __func__, crs->lo,
312 		    crs->hi));
313 		if (ers->hi != (u_int64_t)-1 && crs->lo > ers->hi + 1)
314 			break;
315 		/* This entry overlaps. */
316 		if (crs->hi > ers->hi) {
317 			ers->hi = crs->hi;
318 			KRL_DBG(("%s: succ extend %"PRIu64":%"PRIu64, __func__,
319 			    ers->lo, ers->hi));
320 		}
321 		RB_REMOVE(revoked_serial_tree, rt, crs);
322 		free(crs);
323 	}
324 	KRL_DBG(("%s: done, final %"PRIu64":%"PRIu64, __func__, ers->lo,
325 	    ers->hi));
326 	return 0;
327 }
328 
329 int
330 ssh_krl_revoke_cert_by_serial(struct ssh_krl *krl, const struct sshkey *ca_key,
331     u_int64_t serial)
332 {
333 	return ssh_krl_revoke_cert_by_serial_range(krl, ca_key, serial, serial);
334 }
335 
336 int
337 ssh_krl_revoke_cert_by_serial_range(struct ssh_krl *krl,
338     const struct sshkey *ca_key, u_int64_t lo, u_int64_t hi)
339 {
340 	struct revoked_certs *rc;
341 	int r;
342 
343 	if (lo > hi || lo == 0)
344 		return SSH_ERR_INVALID_ARGUMENT;
345 	if ((r = revoked_certs_for_ca_key(krl, ca_key, &rc, 1)) != 0)
346 		return r;
347 	return insert_serial_range(&rc->revoked_serials, lo, hi);
348 }
349 
350 int
351 ssh_krl_revoke_cert_by_key_id(struct ssh_krl *krl, const struct sshkey *ca_key,
352     const char *key_id)
353 {
354 	struct revoked_key_id *rki, *erki;
355 	struct revoked_certs *rc;
356 	int r;
357 
358 	if ((r = revoked_certs_for_ca_key(krl, ca_key, &rc, 1)) != 0)
359 		return r;
360 
361 	KRL_DBG(("%s: revoke %s", __func__, key_id));
362 	if ((rki = calloc(1, sizeof(*rki))) == NULL ||
363 	    (rki->key_id = strdup(key_id)) == NULL) {
364 		free(rki);
365 		return SSH_ERR_ALLOC_FAIL;
366 	}
367 	erki = RB_INSERT(revoked_key_id_tree, &rc->revoked_key_ids, rki);
368 	if (erki != NULL) {
369 		free(rki->key_id);
370 		free(rki);
371 	}
372 	return 0;
373 }
374 
375 /* Convert "key" to a public key blob without any certificate information */
376 static int
377 plain_key_blob(const struct sshkey *key, u_char **blob, size_t *blen)
378 {
379 	struct sshkey *kcopy;
380 	int r;
381 
382 	if ((r = sshkey_from_private(key, &kcopy)) != 0)
383 		return r;
384 	if (sshkey_is_cert(kcopy)) {
385 		if ((r = sshkey_drop_cert(kcopy)) != 0) {
386 			sshkey_free(kcopy);
387 			return r;
388 		}
389 	}
390 	r = sshkey_to_blob(kcopy, blob, blen);
391 	sshkey_free(kcopy);
392 	return r;
393 }
394 
395 /* Revoke a key blob. Ownership of blob is transferred to the tree */
396 static int
397 revoke_blob(struct revoked_blob_tree *rbt, u_char *blob, size_t len)
398 {
399 	struct revoked_blob *rb, *erb;
400 
401 	if ((rb = calloc(1, sizeof(*rb))) == NULL)
402 		return SSH_ERR_ALLOC_FAIL;
403 	rb->blob = blob;
404 	rb->len = len;
405 	erb = RB_INSERT(revoked_blob_tree, rbt, rb);
406 	if (erb != NULL) {
407 		free(rb->blob);
408 		free(rb);
409 	}
410 	return 0;
411 }
412 
413 int
414 ssh_krl_revoke_key_explicit(struct ssh_krl *krl, const struct sshkey *key)
415 {
416 	u_char *blob;
417 	size_t len;
418 	int r;
419 
420 	debug3("%s: revoke type %s", __func__, sshkey_type(key));
421 	if ((r = plain_key_blob(key, &blob, &len)) != 0)
422 		return r;
423 	return revoke_blob(&krl->revoked_keys, blob, len);
424 }
425 
426 static int
427 revoke_by_hash(struct revoked_blob_tree *target, const u_char *p, size_t len)
428 {
429 	u_char *blob;
430 	int r;
431 
432 	/* need to copy hash, as revoke_blob steals ownership */
433 	if ((blob = malloc(len)) == NULL)
434 		return SSH_ERR_SYSTEM_ERROR;
435 	memcpy(blob, p, len);
436 	if ((r = revoke_blob(target, blob, len)) != 0) {
437 		free(blob);
438 		return r;
439 	}
440 	return 0;
441 }
442 
443 int
444 ssh_krl_revoke_key_sha1(struct ssh_krl *krl, const u_char *p, size_t len)
445 {
446 	debug3("%s: revoke by sha1", __func__);
447 	if (len != 20)
448 		return SSH_ERR_INVALID_FORMAT;
449 	return revoke_by_hash(&krl->revoked_sha1s, p, len);
450 }
451 
452 int
453 ssh_krl_revoke_key_sha256(struct ssh_krl *krl, const u_char *p, size_t len)
454 {
455 	debug3("%s: revoke by sha256", __func__);
456 	if (len != 32)
457 		return SSH_ERR_INVALID_FORMAT;
458 	return revoke_by_hash(&krl->revoked_sha256s, p, len);
459 }
460 
461 int
462 ssh_krl_revoke_key(struct ssh_krl *krl, const struct sshkey *key)
463 {
464 	/* XXX replace with SHA256? */
465 	if (!sshkey_is_cert(key))
466 		return ssh_krl_revoke_key_explicit(krl, key);
467 
468 	if (key->cert->serial == 0) {
469 		return ssh_krl_revoke_cert_by_key_id(krl,
470 		    key->cert->signature_key,
471 		    key->cert->key_id);
472 	} else {
473 		return ssh_krl_revoke_cert_by_serial(krl,
474 		    key->cert->signature_key,
475 		    key->cert->serial);
476 	}
477 }
478 
479 /*
480  * Select the most compact section type to emit next in a KRL based on
481  * the current section type, the run length of contiguous revoked serial
482  * numbers and the gaps from the last and to the next revoked serial.
483  * Applies a mostly-accurate bit cost model to select the section type
484  * that will minimise the size of the resultant KRL.
485  */
486 static int
487 choose_next_state(int current_state, u_int64_t contig, int final,
488     u_int64_t last_gap, u_int64_t next_gap, int *force_new_section)
489 {
490 	int new_state;
491 	u_int64_t cost, cost_list, cost_range, cost_bitmap, cost_bitmap_restart;
492 
493 	/*
494 	 * Avoid unsigned overflows.
495 	 * The limits are high enough to avoid confusing the calculations.
496 	 */
497 	contig = MINIMUM(contig, 1ULL<<31);
498 	last_gap = MINIMUM(last_gap, 1ULL<<31);
499 	next_gap = MINIMUM(next_gap, 1ULL<<31);
500 
501 	/*
502 	 * Calculate the cost to switch from the current state to candidates.
503 	 * NB. range sections only ever contain a single range, so their
504 	 * switching cost is independent of the current_state.
505 	 */
506 	cost_list = cost_bitmap = cost_bitmap_restart = 0;
507 	cost_range = 8;
508 	switch (current_state) {
509 	case KRL_SECTION_CERT_SERIAL_LIST:
510 		cost_bitmap_restart = cost_bitmap = 8 + 64;
511 		break;
512 	case KRL_SECTION_CERT_SERIAL_BITMAP:
513 		cost_list = 8;
514 		cost_bitmap_restart = 8 + 64;
515 		break;
516 	case KRL_SECTION_CERT_SERIAL_RANGE:
517 	case 0:
518 		cost_bitmap_restart = cost_bitmap = 8 + 64;
519 		cost_list = 8;
520 	}
521 
522 	/* Estimate base cost in bits of each section type */
523 	cost_list += 64 * contig + (final ? 0 : 8+64);
524 	cost_range += (2 * 64) + (final ? 0 : 8+64);
525 	cost_bitmap += last_gap + contig + (final ? 0 : MINIMUM(next_gap, 8+64));
526 	cost_bitmap_restart += contig + (final ? 0 : MINIMUM(next_gap, 8+64));
527 
528 	/* Convert to byte costs for actual comparison */
529 	cost_list = (cost_list + 7) / 8;
530 	cost_bitmap = (cost_bitmap + 7) / 8;
531 	cost_bitmap_restart = (cost_bitmap_restart + 7) / 8;
532 	cost_range = (cost_range + 7) / 8;
533 
534 	/* Now pick the best choice */
535 	*force_new_section = 0;
536 	new_state = KRL_SECTION_CERT_SERIAL_BITMAP;
537 	cost = cost_bitmap;
538 	if (cost_range < cost) {
539 		new_state = KRL_SECTION_CERT_SERIAL_RANGE;
540 		cost = cost_range;
541 	}
542 	if (cost_list < cost) {
543 		new_state = KRL_SECTION_CERT_SERIAL_LIST;
544 		cost = cost_list;
545 	}
546 	if (cost_bitmap_restart < cost) {
547 		new_state = KRL_SECTION_CERT_SERIAL_BITMAP;
548 		*force_new_section = 1;
549 		cost = cost_bitmap_restart;
550 	}
551 	KRL_DBG(("%s: contig %llu last_gap %llu next_gap %llu final %d, costs:"
552 	    "list %llu range %llu bitmap %llu new bitmap %llu, "
553 	    "selected 0x%02x%s", __func__, (long long unsigned)contig,
554 	    (long long unsigned)last_gap, (long long unsigned)next_gap, final,
555 	    (long long unsigned)cost_list, (long long unsigned)cost_range,
556 	    (long long unsigned)cost_bitmap,
557 	    (long long unsigned)cost_bitmap_restart, new_state,
558 	    *force_new_section ? " restart" : ""));
559 	return new_state;
560 }
561 
562 static int
563 put_bitmap(struct sshbuf *buf, struct bitmap *bitmap)
564 {
565 	size_t len;
566 	u_char *blob;
567 	int r;
568 
569 	len = bitmap_nbytes(bitmap);
570 	if ((blob = malloc(len)) == NULL)
571 		return SSH_ERR_ALLOC_FAIL;
572 	if (bitmap_to_string(bitmap, blob, len) != 0) {
573 		free(blob);
574 		return SSH_ERR_INTERNAL_ERROR;
575 	}
576 	r = sshbuf_put_bignum2_bytes(buf, blob, len);
577 	free(blob);
578 	return r;
579 }
580 
581 /* Generate a KRL_SECTION_CERTIFICATES KRL section */
582 static int
583 revoked_certs_generate(struct revoked_certs *rc, struct sshbuf *buf)
584 {
585 	int final, force_new_sect, r = SSH_ERR_INTERNAL_ERROR;
586 	u_int64_t i, contig, gap, last = 0, bitmap_start = 0;
587 	struct revoked_serial *rs, *nrs;
588 	struct revoked_key_id *rki;
589 	int next_state, state = 0;
590 	struct sshbuf *sect;
591 	struct bitmap *bitmap = NULL;
592 
593 	if ((sect = sshbuf_new()) == NULL)
594 		return SSH_ERR_ALLOC_FAIL;
595 
596 	/* Store the header: optional CA scope key, reserved */
597 	if (rc->ca_key == NULL) {
598 		if ((r = sshbuf_put_string(buf, NULL, 0)) != 0)
599 			goto out;
600 	} else {
601 		if ((r = sshkey_puts(rc->ca_key, buf)) != 0)
602 			goto out;
603 	}
604 	if ((r = sshbuf_put_string(buf, NULL, 0)) != 0)
605 		goto out;
606 
607 	/* Store the revoked serials.  */
608 	for (rs = RB_MIN(revoked_serial_tree, &rc->revoked_serials);
609 	     rs != NULL;
610 	     rs = RB_NEXT(revoked_serial_tree, &rc->revoked_serials, rs)) {
611 		KRL_DBG(("%s: serial %llu:%llu state 0x%02x", __func__,
612 		    (long long unsigned)rs->lo, (long long unsigned)rs->hi,
613 		    state));
614 
615 		/* Check contiguous length and gap to next section (if any) */
616 		nrs = RB_NEXT(revoked_serial_tree, &rc->revoked_serials, rs);
617 		final = nrs == NULL;
618 		gap = nrs == NULL ? 0 : nrs->lo - rs->hi;
619 		contig = 1 + (rs->hi - rs->lo);
620 
621 		/* Choose next state based on these */
622 		next_state = choose_next_state(state, contig, final,
623 		    state == 0 ? 0 : rs->lo - last, gap, &force_new_sect);
624 
625 		/*
626 		 * If the current section is a range section or has a different
627 		 * type to the next section, then finish it off now.
628 		 */
629 		if (state != 0 && (force_new_sect || next_state != state ||
630 		    state == KRL_SECTION_CERT_SERIAL_RANGE)) {
631 			KRL_DBG(("%s: finish state 0x%02x", __func__, state));
632 			switch (state) {
633 			case KRL_SECTION_CERT_SERIAL_LIST:
634 			case KRL_SECTION_CERT_SERIAL_RANGE:
635 				break;
636 			case KRL_SECTION_CERT_SERIAL_BITMAP:
637 				if ((r = put_bitmap(sect, bitmap)) != 0)
638 					goto out;
639 				bitmap_free(bitmap);
640 				bitmap = NULL;
641 				break;
642 			}
643 			if ((r = sshbuf_put_u8(buf, state)) != 0 ||
644 			    (r = sshbuf_put_stringb(buf, sect)) != 0)
645 				goto out;
646 			sshbuf_reset(sect);
647 		}
648 
649 		/* If we are starting a new section then prepare it now */
650 		if (next_state != state || force_new_sect) {
651 			KRL_DBG(("%s: start state 0x%02x", __func__,
652 			    next_state));
653 			state = next_state;
654 			sshbuf_reset(sect);
655 			switch (state) {
656 			case KRL_SECTION_CERT_SERIAL_LIST:
657 			case KRL_SECTION_CERT_SERIAL_RANGE:
658 				break;
659 			case KRL_SECTION_CERT_SERIAL_BITMAP:
660 				if ((bitmap = bitmap_new()) == NULL) {
661 					r = SSH_ERR_ALLOC_FAIL;
662 					goto out;
663 				}
664 				bitmap_start = rs->lo;
665 				if ((r = sshbuf_put_u64(sect,
666 				    bitmap_start)) != 0)
667 					goto out;
668 				break;
669 			}
670 		}
671 
672 		/* Perform section-specific processing */
673 		switch (state) {
674 		case KRL_SECTION_CERT_SERIAL_LIST:
675 			for (i = 0; i < contig; i++) {
676 				if ((r = sshbuf_put_u64(sect, rs->lo + i)) != 0)
677 					goto out;
678 			}
679 			break;
680 		case KRL_SECTION_CERT_SERIAL_RANGE:
681 			if ((r = sshbuf_put_u64(sect, rs->lo)) != 0 ||
682 			    (r = sshbuf_put_u64(sect, rs->hi)) != 0)
683 				goto out;
684 			break;
685 		case KRL_SECTION_CERT_SERIAL_BITMAP:
686 			if (rs->lo - bitmap_start > INT_MAX) {
687 				error("%s: insane bitmap gap", __func__);
688 				goto out;
689 			}
690 			for (i = 0; i < contig; i++) {
691 				if (bitmap_set_bit(bitmap,
692 				    rs->lo + i - bitmap_start) != 0) {
693 					r = SSH_ERR_ALLOC_FAIL;
694 					goto out;
695 				}
696 			}
697 			break;
698 		}
699 		last = rs->hi;
700 	}
701 	/* Flush the remaining section, if any */
702 	if (state != 0) {
703 		KRL_DBG(("%s: serial final flush for state 0x%02x",
704 		    __func__, state));
705 		switch (state) {
706 		case KRL_SECTION_CERT_SERIAL_LIST:
707 		case KRL_SECTION_CERT_SERIAL_RANGE:
708 			break;
709 		case KRL_SECTION_CERT_SERIAL_BITMAP:
710 			if ((r = put_bitmap(sect, bitmap)) != 0)
711 				goto out;
712 			bitmap_free(bitmap);
713 			bitmap = NULL;
714 			break;
715 		}
716 		if ((r = sshbuf_put_u8(buf, state)) != 0 ||
717 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
718 			goto out;
719 	}
720 	KRL_DBG(("%s: serial done ", __func__));
721 
722 	/* Now output a section for any revocations by key ID */
723 	sshbuf_reset(sect);
724 	RB_FOREACH(rki, revoked_key_id_tree, &rc->revoked_key_ids) {
725 		KRL_DBG(("%s: key ID %s", __func__, rki->key_id));
726 		if ((r = sshbuf_put_cstring(sect, rki->key_id)) != 0)
727 			goto out;
728 	}
729 	if (sshbuf_len(sect) != 0) {
730 		if ((r = sshbuf_put_u8(buf, KRL_SECTION_CERT_KEY_ID)) != 0 ||
731 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
732 			goto out;
733 	}
734 	r = 0;
735  out:
736 	bitmap_free(bitmap);
737 	sshbuf_free(sect);
738 	return r;
739 }
740 
741 int
742 ssh_krl_to_blob(struct ssh_krl *krl, struct sshbuf *buf,
743     struct sshkey **sign_keys, u_int nsign_keys)
744 {
745 	int r = SSH_ERR_INTERNAL_ERROR;
746 	struct revoked_certs *rc;
747 	struct revoked_blob *rb;
748 	struct sshbuf *sect;
749 	u_char *sblob = NULL;
750 	size_t slen, i;
751 
752 	if (krl->generated_date == 0)
753 		krl->generated_date = time(NULL);
754 
755 	if ((sect = sshbuf_new()) == NULL)
756 		return SSH_ERR_ALLOC_FAIL;
757 
758 	/* Store the header */
759 	if ((r = sshbuf_put(buf, KRL_MAGIC, sizeof(KRL_MAGIC) - 1)) != 0 ||
760 	    (r = sshbuf_put_u32(buf, KRL_FORMAT_VERSION)) != 0 ||
761 	    (r = sshbuf_put_u64(buf, krl->krl_version)) != 0 ||
762 	    (r = sshbuf_put_u64(buf, krl->generated_date)) != 0 ||
763 	    (r = sshbuf_put_u64(buf, krl->flags)) != 0 ||
764 	    (r = sshbuf_put_string(buf, NULL, 0)) != 0 ||
765 	    (r = sshbuf_put_cstring(buf, krl->comment)) != 0)
766 		goto out;
767 
768 	/* Store sections for revoked certificates */
769 	TAILQ_FOREACH(rc, &krl->revoked_certs, entry) {
770 		sshbuf_reset(sect);
771 		if ((r = revoked_certs_generate(rc, sect)) != 0)
772 			goto out;
773 		if ((r = sshbuf_put_u8(buf, KRL_SECTION_CERTIFICATES)) != 0 ||
774 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
775 			goto out;
776 	}
777 
778 	/* Finally, output sections for revocations by public key/hash */
779 	sshbuf_reset(sect);
780 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_keys) {
781 		KRL_DBG(("%s: key len %zu ", __func__, rb->len));
782 		if ((r = sshbuf_put_string(sect, rb->blob, rb->len)) != 0)
783 			goto out;
784 	}
785 	if (sshbuf_len(sect) != 0) {
786 		if ((r = sshbuf_put_u8(buf, KRL_SECTION_EXPLICIT_KEY)) != 0 ||
787 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
788 			goto out;
789 	}
790 	sshbuf_reset(sect);
791 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_sha1s) {
792 		KRL_DBG(("%s: hash len %zu ", __func__, rb->len));
793 		if ((r = sshbuf_put_string(sect, rb->blob, rb->len)) != 0)
794 			goto out;
795 	}
796 	if (sshbuf_len(sect) != 0) {
797 		if ((r = sshbuf_put_u8(buf,
798 		    KRL_SECTION_FINGERPRINT_SHA1)) != 0 ||
799 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
800 			goto out;
801 	}
802 	sshbuf_reset(sect);
803 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_sha256s) {
804 		KRL_DBG(("%s: hash len %zu ", __func__, rb->len));
805 		if ((r = sshbuf_put_string(sect, rb->blob, rb->len)) != 0)
806 			goto out;
807 	}
808 	if (sshbuf_len(sect) != 0) {
809 		if ((r = sshbuf_put_u8(buf,
810 		    KRL_SECTION_FINGERPRINT_SHA256)) != 0 ||
811 		    (r = sshbuf_put_stringb(buf, sect)) != 0)
812 			goto out;
813 	}
814 
815 	for (i = 0; i < nsign_keys; i++) {
816 		KRL_DBG(("%s: signature key %s", __func__,
817 		    sshkey_ssh_name(sign_keys[i])));
818 		if ((r = sshbuf_put_u8(buf, KRL_SECTION_SIGNATURE)) != 0 ||
819 		    (r = sshkey_puts(sign_keys[i], buf)) != 0)
820 			goto out;
821 
822 		if ((r = sshkey_sign(sign_keys[i], &sblob, &slen,
823 		    sshbuf_ptr(buf), sshbuf_len(buf), NULL, NULL, 0)) != 0)
824 			goto out;
825 		KRL_DBG(("%s: signature sig len %zu", __func__, slen));
826 		if ((r = sshbuf_put_string(buf, sblob, slen)) != 0)
827 			goto out;
828 	}
829 
830 	r = 0;
831  out:
832 	free(sblob);
833 	sshbuf_free(sect);
834 	return r;
835 }
836 
837 static void
838 format_timestamp(u_int64_t timestamp, char *ts, size_t nts)
839 {
840 	time_t t;
841 	struct tm *tm;
842 
843 	t = timestamp;
844 	tm = localtime(&t);
845 	if (tm == NULL)
846 		strlcpy(ts, "<INVALID>", nts);
847 	else {
848 		*ts = '\0';
849 		strftime(ts, nts, "%Y%m%dT%H%M%S", tm);
850 	}
851 }
852 
853 static int
854 parse_revoked_certs(struct sshbuf *buf, struct ssh_krl *krl)
855 {
856 	int r = SSH_ERR_INTERNAL_ERROR;
857 	u_char type;
858 	const u_char *blob;
859 	size_t blen, nbits;
860 	struct sshbuf *subsect = NULL;
861 	u_int64_t serial, serial_lo, serial_hi;
862 	struct bitmap *bitmap = NULL;
863 	char *key_id = NULL;
864 	struct sshkey *ca_key = NULL;
865 
866 	if ((subsect = sshbuf_new()) == NULL)
867 		return SSH_ERR_ALLOC_FAIL;
868 
869 	/* Header: key, reserved */
870 	if ((r = sshbuf_get_string_direct(buf, &blob, &blen)) != 0 ||
871 	    (r = sshbuf_skip_string(buf)) != 0)
872 		goto out;
873 	if (blen != 0 && (r = sshkey_from_blob(blob, blen, &ca_key)) != 0)
874 		goto out;
875 
876 	while (sshbuf_len(buf) > 0) {
877 		sshbuf_free(subsect);
878 		subsect = NULL;
879 		if ((r = sshbuf_get_u8(buf, &type)) != 0 ||
880 		    (r = sshbuf_froms(buf, &subsect)) != 0)
881 			goto out;
882 		KRL_DBG(("%s: subsection type 0x%02x", __func__, type));
883 		/* sshbuf_dump(subsect, stderr); */
884 
885 		switch (type) {
886 		case KRL_SECTION_CERT_SERIAL_LIST:
887 			while (sshbuf_len(subsect) > 0) {
888 				if ((r = sshbuf_get_u64(subsect, &serial)) != 0)
889 					goto out;
890 				if ((r = ssh_krl_revoke_cert_by_serial(krl,
891 				    ca_key, serial)) != 0)
892 					goto out;
893 			}
894 			break;
895 		case KRL_SECTION_CERT_SERIAL_RANGE:
896 			if ((r = sshbuf_get_u64(subsect, &serial_lo)) != 0 ||
897 			    (r = sshbuf_get_u64(subsect, &serial_hi)) != 0)
898 				goto out;
899 			if ((r = ssh_krl_revoke_cert_by_serial_range(krl,
900 			    ca_key, serial_lo, serial_hi)) != 0)
901 				goto out;
902 			break;
903 		case KRL_SECTION_CERT_SERIAL_BITMAP:
904 			if ((bitmap = bitmap_new()) == NULL) {
905 				r = SSH_ERR_ALLOC_FAIL;
906 				goto out;
907 			}
908 			if ((r = sshbuf_get_u64(subsect, &serial_lo)) != 0 ||
909 			    (r = sshbuf_get_bignum2_bytes_direct(subsect,
910 			    &blob, &blen)) != 0)
911 				goto out;
912 			if (bitmap_from_string(bitmap, blob, blen) != 0) {
913 				r = SSH_ERR_INVALID_FORMAT;
914 				goto out;
915 			}
916 			nbits = bitmap_nbits(bitmap);
917 			for (serial = 0; serial < (u_int64_t)nbits; serial++) {
918 				if (serial > 0 && serial_lo + serial == 0) {
919 					error("%s: bitmap wraps u64", __func__);
920 					r = SSH_ERR_INVALID_FORMAT;
921 					goto out;
922 				}
923 				if (!bitmap_test_bit(bitmap, serial))
924 					continue;
925 				if ((r = ssh_krl_revoke_cert_by_serial(krl,
926 				    ca_key, serial_lo + serial)) != 0)
927 					goto out;
928 			}
929 			bitmap_free(bitmap);
930 			bitmap = NULL;
931 			break;
932 		case KRL_SECTION_CERT_KEY_ID:
933 			while (sshbuf_len(subsect) > 0) {
934 				if ((r = sshbuf_get_cstring(subsect,
935 				    &key_id, NULL)) != 0)
936 					goto out;
937 				if ((r = ssh_krl_revoke_cert_by_key_id(krl,
938 				    ca_key, key_id)) != 0)
939 					goto out;
940 				free(key_id);
941 				key_id = NULL;
942 			}
943 			break;
944 		default:
945 			error("Unsupported KRL certificate section %u", type);
946 			r = SSH_ERR_INVALID_FORMAT;
947 			goto out;
948 		}
949 		if (sshbuf_len(subsect) > 0) {
950 			error("KRL certificate section contains unparsed data");
951 			r = SSH_ERR_INVALID_FORMAT;
952 			goto out;
953 		}
954 	}
955 
956 	r = 0;
957  out:
958 	if (bitmap != NULL)
959 		bitmap_free(bitmap);
960 	free(key_id);
961 	sshkey_free(ca_key);
962 	sshbuf_free(subsect);
963 	return r;
964 }
965 
966 static int
967 blob_section(struct sshbuf *sect, struct revoked_blob_tree *target_tree,
968     size_t expected_len)
969 {
970 	u_char *rdata = NULL;
971 	size_t rlen = 0;
972 	int r;
973 
974 	while (sshbuf_len(sect) > 0) {
975 		if ((r = sshbuf_get_string(sect, &rdata, &rlen)) != 0)
976 			return r;
977 		if (expected_len != 0 && rlen != expected_len) {
978 			error("%s: bad length", __func__);
979 			free(rdata);
980 			return SSH_ERR_INVALID_FORMAT;
981 		}
982 		if ((r = revoke_blob(target_tree, rdata, rlen)) != 0) {
983 			free(rdata);
984 			return r;
985 		}
986 	}
987 	return 0;
988 }
989 
990 /* Attempt to parse a KRL, checking its signature (if any) with sign_ca_keys. */
991 int
992 ssh_krl_from_blob(struct sshbuf *buf, struct ssh_krl **krlp,
993     const struct sshkey **sign_ca_keys, size_t nsign_ca_keys)
994 {
995 	struct sshbuf *copy = NULL, *sect = NULL;
996 	struct ssh_krl *krl = NULL;
997 	char timestamp[64];
998 	int r = SSH_ERR_INTERNAL_ERROR, sig_seen;
999 	struct sshkey *key = NULL, **ca_used = NULL, **tmp_ca_used;
1000 	u_char type;
1001 	const u_char *blob;
1002 	size_t i, j, sig_off, sects_off, blen, nca_used;
1003 	u_int format_version;
1004 
1005 	nca_used = 0;
1006 	*krlp = NULL;
1007 	if (sshbuf_len(buf) < sizeof(KRL_MAGIC) - 1 ||
1008 	    memcmp(sshbuf_ptr(buf), KRL_MAGIC, sizeof(KRL_MAGIC) - 1) != 0) {
1009 		debug3("%s: not a KRL", __func__);
1010 		return SSH_ERR_KRL_BAD_MAGIC;
1011 	}
1012 
1013 	/* Take a copy of the KRL buffer so we can verify its signature later */
1014 	if ((copy = sshbuf_fromb(buf)) == NULL) {
1015 		r = SSH_ERR_ALLOC_FAIL;
1016 		goto out;
1017 	}
1018 	if ((r = sshbuf_consume(copy, sizeof(KRL_MAGIC) - 1)) != 0)
1019 		goto out;
1020 
1021 	if ((krl = ssh_krl_init()) == NULL) {
1022 		error("%s: alloc failed", __func__);
1023 		goto out;
1024 	}
1025 
1026 	if ((r = sshbuf_get_u32(copy, &format_version)) != 0)
1027 		goto out;
1028 	if (format_version != KRL_FORMAT_VERSION) {
1029 		r = SSH_ERR_INVALID_FORMAT;
1030 		goto out;
1031 	}
1032 	if ((r = sshbuf_get_u64(copy, &krl->krl_version)) != 0 ||
1033 	    (r = sshbuf_get_u64(copy, &krl->generated_date)) != 0 ||
1034 	    (r = sshbuf_get_u64(copy, &krl->flags)) != 0 ||
1035 	    (r = sshbuf_skip_string(copy)) != 0 ||
1036 	    (r = sshbuf_get_cstring(copy, &krl->comment, NULL)) != 0)
1037 		goto out;
1038 
1039 	format_timestamp(krl->generated_date, timestamp, sizeof(timestamp));
1040 	debug("KRL version %llu generated at %s%s%s",
1041 	    (long long unsigned)krl->krl_version, timestamp,
1042 	    *krl->comment ? ": " : "", krl->comment);
1043 
1044 	/*
1045 	 * 1st pass: verify signatures, if any. This is done to avoid
1046 	 * detailed parsing of data whose provenance is unverified.
1047 	 */
1048 	sig_seen = 0;
1049 	if (sshbuf_len(buf) < sshbuf_len(copy)) {
1050 		/* Shouldn't happen */
1051 		r = SSH_ERR_INTERNAL_ERROR;
1052 		goto out;
1053 	}
1054 	sects_off = sshbuf_len(buf) - sshbuf_len(copy);
1055 	while (sshbuf_len(copy) > 0) {
1056 		if ((r = sshbuf_get_u8(copy, &type)) != 0 ||
1057 		    (r = sshbuf_get_string_direct(copy, &blob, &blen)) != 0)
1058 			goto out;
1059 		KRL_DBG(("%s: first pass, section 0x%02x", __func__, type));
1060 		if (type != KRL_SECTION_SIGNATURE) {
1061 			if (sig_seen) {
1062 				error("KRL contains non-signature section "
1063 				    "after signature");
1064 				r = SSH_ERR_INVALID_FORMAT;
1065 				goto out;
1066 			}
1067 			/* Not interested for now. */
1068 			continue;
1069 		}
1070 		sig_seen = 1;
1071 		/* First string component is the signing key */
1072 		if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
1073 			r = SSH_ERR_INVALID_FORMAT;
1074 			goto out;
1075 		}
1076 		if (sshbuf_len(buf) < sshbuf_len(copy)) {
1077 			/* Shouldn't happen */
1078 			r = SSH_ERR_INTERNAL_ERROR;
1079 			goto out;
1080 		}
1081 		sig_off = sshbuf_len(buf) - sshbuf_len(copy);
1082 		/* Second string component is the signature itself */
1083 		if ((r = sshbuf_get_string_direct(copy, &blob, &blen)) != 0) {
1084 			r = SSH_ERR_INVALID_FORMAT;
1085 			goto out;
1086 		}
1087 		/* Check signature over entire KRL up to this point */
1088 		if ((r = sshkey_verify(key, blob, blen,
1089 		    sshbuf_ptr(buf), sig_off, NULL, 0, NULL)) != 0)
1090 			goto out;
1091 		/* Check if this key has already signed this KRL */
1092 		for (i = 0; i < nca_used; i++) {
1093 			if (sshkey_equal(ca_used[i], key)) {
1094 				error("KRL signed more than once with "
1095 				    "the same key");
1096 				r = SSH_ERR_INVALID_FORMAT;
1097 				goto out;
1098 			}
1099 		}
1100 		/* Record keys used to sign the KRL */
1101 		tmp_ca_used = recallocarray(ca_used, nca_used, nca_used + 1,
1102 		    sizeof(*ca_used));
1103 		if (tmp_ca_used == NULL) {
1104 			r = SSH_ERR_ALLOC_FAIL;
1105 			goto out;
1106 		}
1107 		ca_used = tmp_ca_used;
1108 		ca_used[nca_used++] = key;
1109 		key = NULL;
1110 	}
1111 
1112 	if (sshbuf_len(copy) != 0) {
1113 		/* Shouldn't happen */
1114 		r = SSH_ERR_INTERNAL_ERROR;
1115 		goto out;
1116 	}
1117 
1118 	/*
1119 	 * 2nd pass: parse and load the KRL, skipping the header to the point
1120 	 * where the section start.
1121 	 */
1122 	sshbuf_free(copy);
1123 	if ((copy = sshbuf_fromb(buf)) == NULL) {
1124 		r = SSH_ERR_ALLOC_FAIL;
1125 		goto out;
1126 	}
1127 	if ((r = sshbuf_consume(copy, sects_off)) != 0)
1128 		goto out;
1129 	while (sshbuf_len(copy) > 0) {
1130 		sshbuf_free(sect);
1131 		sect = NULL;
1132 		if ((r = sshbuf_get_u8(copy, &type)) != 0 ||
1133 		    (r = sshbuf_froms(copy, &sect)) != 0)
1134 			goto out;
1135 		KRL_DBG(("%s: second pass, section 0x%02x", __func__, type));
1136 
1137 		switch (type) {
1138 		case KRL_SECTION_CERTIFICATES:
1139 			if ((r = parse_revoked_certs(sect, krl)) != 0)
1140 				goto out;
1141 			break;
1142 		case KRL_SECTION_EXPLICIT_KEY:
1143 			if ((r = blob_section(sect,
1144 			    &krl->revoked_keys, 0)) != 0)
1145 				goto out;
1146 			break;
1147 		case KRL_SECTION_FINGERPRINT_SHA1:
1148 			if ((r = blob_section(sect,
1149 			    &krl->revoked_sha1s, 20)) != 0)
1150 				goto out;
1151 			break;
1152 		case KRL_SECTION_FINGERPRINT_SHA256:
1153 			if ((r = blob_section(sect,
1154 			    &krl->revoked_sha256s, 32)) != 0)
1155 				goto out;
1156 			break;
1157 		case KRL_SECTION_SIGNATURE:
1158 			/* Handled above, but still need to stay in synch */
1159 			sshbuf_free(sect);
1160 			sect = NULL;
1161 			if ((r = sshbuf_skip_string(copy)) != 0)
1162 				goto out;
1163 			break;
1164 		default:
1165 			error("Unsupported KRL section %u", type);
1166 			r = SSH_ERR_INVALID_FORMAT;
1167 			goto out;
1168 		}
1169 		if (sect != NULL && sshbuf_len(sect) > 0) {
1170 			error("KRL section contains unparsed data");
1171 			r = SSH_ERR_INVALID_FORMAT;
1172 			goto out;
1173 		}
1174 	}
1175 
1176 	/* Check that the key(s) used to sign the KRL weren't revoked */
1177 	sig_seen = 0;
1178 	for (i = 0; i < nca_used; i++) {
1179 		if (ssh_krl_check_key(krl, ca_used[i]) == 0)
1180 			sig_seen = 1;
1181 		else {
1182 			sshkey_free(ca_used[i]);
1183 			ca_used[i] = NULL;
1184 		}
1185 	}
1186 	if (nca_used && !sig_seen) {
1187 		error("All keys used to sign KRL were revoked");
1188 		r = SSH_ERR_KEY_REVOKED;
1189 		goto out;
1190 	}
1191 
1192 	/* If we have CA keys, then verify that one was used to sign the KRL */
1193 	if (sig_seen && nsign_ca_keys != 0) {
1194 		sig_seen = 0;
1195 		for (i = 0; !sig_seen && i < nsign_ca_keys; i++) {
1196 			for (j = 0; j < nca_used; j++) {
1197 				if (ca_used[j] == NULL)
1198 					continue;
1199 				if (sshkey_equal(ca_used[j], sign_ca_keys[i])) {
1200 					sig_seen = 1;
1201 					break;
1202 				}
1203 			}
1204 		}
1205 		if (!sig_seen) {
1206 			r = SSH_ERR_SIGNATURE_INVALID;
1207 			error("KRL not signed with any trusted key");
1208 			goto out;
1209 		}
1210 	}
1211 
1212 	*krlp = krl;
1213 	r = 0;
1214  out:
1215 	if (r != 0)
1216 		ssh_krl_free(krl);
1217 	for (i = 0; i < nca_used; i++)
1218 		sshkey_free(ca_used[i]);
1219 	free(ca_used);
1220 	sshkey_free(key);
1221 	sshbuf_free(copy);
1222 	sshbuf_free(sect);
1223 	return r;
1224 }
1225 
1226 /* Checks certificate serial number and key ID revocation */
1227 static int
1228 is_cert_revoked(const struct sshkey *key, struct revoked_certs *rc)
1229 {
1230 	struct revoked_serial rs, *ers;
1231 	struct revoked_key_id rki, *erki;
1232 
1233 	/* Check revocation by cert key ID */
1234 	memset(&rki, 0, sizeof(rki));
1235 	rki.key_id = key->cert->key_id;
1236 	erki = RB_FIND(revoked_key_id_tree, &rc->revoked_key_ids, &rki);
1237 	if (erki != NULL) {
1238 		KRL_DBG(("%s: revoked by key ID", __func__));
1239 		return SSH_ERR_KEY_REVOKED;
1240 	}
1241 
1242 	/*
1243 	 * Zero serials numbers are ignored (it's the default when the
1244 	 * CA doesn't specify one).
1245 	 */
1246 	if (key->cert->serial == 0)
1247 		return 0;
1248 
1249 	memset(&rs, 0, sizeof(rs));
1250 	rs.lo = rs.hi = key->cert->serial;
1251 	ers = RB_FIND(revoked_serial_tree, &rc->revoked_serials, &rs);
1252 	if (ers != NULL) {
1253 		KRL_DBG(("%s: revoked serial %llu matched %llu:%llu", __func__,
1254 		    key->cert->serial, ers->lo, ers->hi));
1255 		return SSH_ERR_KEY_REVOKED;
1256 	}
1257 	return 0;
1258 }
1259 
1260 /* Checks whether a given key/cert is revoked. Does not check its CA */
1261 static int
1262 is_key_revoked(struct ssh_krl *krl, const struct sshkey *key)
1263 {
1264 	struct revoked_blob rb, *erb;
1265 	struct revoked_certs *rc;
1266 	int r;
1267 
1268 	/* Check explicitly revoked hashes first */
1269 	memset(&rb, 0, sizeof(rb));
1270 	if ((r = sshkey_fingerprint_raw(key, SSH_DIGEST_SHA1,
1271 	    &rb.blob, &rb.len)) != 0)
1272 		return r;
1273 	erb = RB_FIND(revoked_blob_tree, &krl->revoked_sha1s, &rb);
1274 	free(rb.blob);
1275 	if (erb != NULL) {
1276 		KRL_DBG(("%s: revoked by key SHA1", __func__));
1277 		return SSH_ERR_KEY_REVOKED;
1278 	}
1279 	memset(&rb, 0, sizeof(rb));
1280 	if ((r = sshkey_fingerprint_raw(key, SSH_DIGEST_SHA256,
1281 	    &rb.blob, &rb.len)) != 0)
1282 		return r;
1283 	erb = RB_FIND(revoked_blob_tree, &krl->revoked_sha256s, &rb);
1284 	free(rb.blob);
1285 	if (erb != NULL) {
1286 		KRL_DBG(("%s: revoked by key SHA256", __func__));
1287 		return SSH_ERR_KEY_REVOKED;
1288 	}
1289 
1290 	/* Next, explicit keys */
1291 	memset(&rb, 0, sizeof(rb));
1292 	if ((r = plain_key_blob(key, &rb.blob, &rb.len)) != 0)
1293 		return r;
1294 	erb = RB_FIND(revoked_blob_tree, &krl->revoked_keys, &rb);
1295 	free(rb.blob);
1296 	if (erb != NULL) {
1297 		KRL_DBG(("%s: revoked by explicit key", __func__));
1298 		return SSH_ERR_KEY_REVOKED;
1299 	}
1300 
1301 	if (!sshkey_is_cert(key))
1302 		return 0;
1303 
1304 	/* Check cert revocation for the specified CA */
1305 	if ((r = revoked_certs_for_ca_key(krl, key->cert->signature_key,
1306 	    &rc, 0)) != 0)
1307 		return r;
1308 	if (rc != NULL) {
1309 		if ((r = is_cert_revoked(key, rc)) != 0)
1310 			return r;
1311 	}
1312 	/* Check cert revocation for the wildcard CA */
1313 	if ((r = revoked_certs_for_ca_key(krl, NULL, &rc, 0)) != 0)
1314 		return r;
1315 	if (rc != NULL) {
1316 		if ((r = is_cert_revoked(key, rc)) != 0)
1317 			return r;
1318 	}
1319 
1320 	KRL_DBG(("%s: %llu no match", __func__, key->cert->serial));
1321 	return 0;
1322 }
1323 
1324 int
1325 ssh_krl_check_key(struct ssh_krl *krl, const struct sshkey *key)
1326 {
1327 	int r;
1328 
1329 	KRL_DBG(("%s: checking key", __func__));
1330 	if ((r = is_key_revoked(krl, key)) != 0)
1331 		return r;
1332 	if (sshkey_is_cert(key)) {
1333 		debug2("%s: checking CA key", __func__);
1334 		if ((r = is_key_revoked(krl, key->cert->signature_key)) != 0)
1335 			return r;
1336 	}
1337 	KRL_DBG(("%s: key okay", __func__));
1338 	return 0;
1339 }
1340 
1341 int
1342 ssh_krl_file_contains_key(const char *path, const struct sshkey *key)
1343 {
1344 	struct sshbuf *krlbuf = NULL;
1345 	struct ssh_krl *krl = NULL;
1346 	int oerrno = 0, r;
1347 
1348 	if (path == NULL)
1349 		return 0;
1350 	if ((r = sshbuf_load_file(path, &krlbuf)) != 0) {
1351 		oerrno = errno;
1352 		goto out;
1353 	}
1354 	if ((r = ssh_krl_from_blob(krlbuf, &krl, NULL, 0)) != 0)
1355 		goto out;
1356 	debug2("%s: checking KRL %s", __func__, path);
1357 	r = ssh_krl_check_key(krl, key);
1358  out:
1359 	sshbuf_free(krlbuf);
1360 	ssh_krl_free(krl);
1361 	if (r != 0)
1362 		errno = oerrno;
1363 	return r;
1364 }
1365 
1366 int
1367 krl_dump(struct ssh_krl *krl, FILE *f)
1368 {
1369 	struct sshkey *key = NULL;
1370 	struct revoked_blob *rb;
1371 	struct revoked_certs *rc;
1372 	struct revoked_serial *rs;
1373 	struct revoked_key_id *rki;
1374 	int r, ret = 0;
1375 	char *fp, timestamp[64];
1376 
1377 	/* Try to print in a KRL spec-compatible format */
1378 	format_timestamp(krl->generated_date, timestamp, sizeof(timestamp));
1379 	fprintf(f, "# KRL version %llu\n",
1380 	    (unsigned long long)krl->krl_version);
1381 	fprintf(f, "# Generated at %s\n", timestamp);
1382 	if (krl->comment != NULL && *krl->comment != '\0') {
1383 		r = INT_MAX;
1384 		asmprintf(&fp, INT_MAX, &r, "%s", krl->comment);
1385 		fprintf(f, "# Comment: %s\n", fp);
1386 		free(fp);
1387 	}
1388 	fputc('\n', f);
1389 
1390 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_keys) {
1391 		if ((r = sshkey_from_blob(rb->blob, rb->len, &key)) != 0) {
1392 			ret = SSH_ERR_INVALID_FORMAT;
1393 			error("Parse key in KRL: %s", ssh_err(r));
1394 			continue;
1395 		}
1396 		if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1397 		    SSH_FP_DEFAULT)) == NULL) {
1398 			ret = SSH_ERR_INVALID_FORMAT;
1399 			error("sshkey_fingerprint failed");
1400 			continue;
1401 		}
1402 		fprintf(f, "hash: SHA256:%s # %s\n", fp, sshkey_ssh_name(key));
1403 		free(fp);
1404 		free(key);
1405 	}
1406 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_sha256s) {
1407 		fp = tohex(rb->blob, rb->len);
1408 		fprintf(f, "hash: SHA256:%s\n", fp);
1409 		free(fp);
1410 	}
1411 	RB_FOREACH(rb, revoked_blob_tree, &krl->revoked_sha1s) {
1412 		/*
1413 		 * There is not KRL spec keyword for raw SHA1 hashes, so
1414 		 * print them as comments.
1415 		 */
1416 		fp = tohex(rb->blob, rb->len);
1417 		fprintf(f, "# hash SHA1:%s\n", fp);
1418 		free(fp);
1419 	}
1420 
1421 	TAILQ_FOREACH(rc, &krl->revoked_certs, entry) {
1422 		fputc('\n', f);
1423 		if (rc->ca_key == NULL)
1424 			fprintf(f, "# Wildcard CA\n");
1425 		else {
1426 			if ((fp = sshkey_fingerprint(rc->ca_key,
1427 			    SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL) {
1428 				ret = SSH_ERR_INVALID_FORMAT;
1429 				error("sshkey_fingerprint failed");
1430 				continue;
1431 			}
1432 			fprintf(f, "# CA key %s %s\n",
1433 			    sshkey_ssh_name(rc->ca_key), fp);
1434 			free(fp);
1435 		}
1436 		RB_FOREACH(rs, revoked_serial_tree, &rc->revoked_serials) {
1437 			if (rs->lo == rs->hi) {
1438 				fprintf(f, "serial: %llu\n",
1439 				    (unsigned long long)rs->lo);
1440 			} else {
1441 				fprintf(f, "serial: %llu-%llu\n",
1442 				    (unsigned long long)rs->lo,
1443 				    (unsigned long long)rs->hi);
1444 			}
1445 		}
1446 		RB_FOREACH(rki, revoked_key_id_tree, &rc->revoked_key_ids) {
1447 			/*
1448 			 * We don't want key IDs with embedded newlines to
1449 			 * mess up the display.
1450 			 */
1451 			r = INT_MAX;
1452 			asmprintf(&fp, INT_MAX, &r, "%s", rki->key_id);
1453 			fprintf(f, "id: %s\n", fp);
1454 			free(fp);
1455 		}
1456 	}
1457 	return ret;
1458 }
1459