xref: /freebsd/crypto/openssh/sshsig.c (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
1 /* $OpenBSD: sshsig.c,v 1.29 2022/03/30 04:27:51 djm Exp $ */
2 /*
3  * Copyright (c) 2019 Google LLC
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include "includes.h"
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <unistd.h>
26 
27 #include "authfd.h"
28 #include "authfile.h"
29 #include "log.h"
30 #include "misc.h"
31 #include "sshbuf.h"
32 #include "sshsig.h"
33 #include "ssherr.h"
34 #include "sshkey.h"
35 #include "match.h"
36 #include "digest.h"
37 
38 #define SIG_VERSION		0x01
39 #define MAGIC_PREAMBLE		"SSHSIG"
40 #define MAGIC_PREAMBLE_LEN	(sizeof(MAGIC_PREAMBLE) - 1)
41 #define BEGIN_SIGNATURE		"-----BEGIN SSH SIGNATURE-----\n"
42 #define END_SIGNATURE		"-----END SSH SIGNATURE-----"
43 #define RSA_SIGN_ALG		"rsa-sha2-512" /* XXX maybe make configurable */
44 #define RSA_SIGN_ALLOWED	"rsa-sha2-512,rsa-sha2-256"
45 #define HASHALG_DEFAULT		"sha512" /* XXX maybe make configurable */
46 #define HASHALG_ALLOWED		"sha256,sha512"
47 
48 int
49 sshsig_armor(const struct sshbuf *blob, struct sshbuf **out)
50 {
51 	struct sshbuf *buf = NULL;
52 	int r = SSH_ERR_INTERNAL_ERROR;
53 
54 	*out = NULL;
55 
56 	if ((buf = sshbuf_new()) == NULL) {
57 		error_f("sshbuf_new failed");
58 		r = SSH_ERR_ALLOC_FAIL;
59 		goto out;
60 	}
61 
62 	if ((r = sshbuf_put(buf, BEGIN_SIGNATURE,
63 	    sizeof(BEGIN_SIGNATURE)-1)) != 0) {
64 		error_fr(r, "sshbuf_putf");
65 		goto out;
66 	}
67 
68 	if ((r = sshbuf_dtob64(blob, buf, 1)) != 0) {
69 		error_fr(r, "base64 encode signature");
70 		goto out;
71 	}
72 
73 	if ((r = sshbuf_put(buf, END_SIGNATURE,
74 	    sizeof(END_SIGNATURE)-1)) != 0 ||
75 	    (r = sshbuf_put_u8(buf, '\n')) != 0) {
76 		error_fr(r, "sshbuf_put");
77 		goto out;
78 	}
79 	/* success */
80 	*out = buf;
81 	buf = NULL; /* transferred */
82 	r = 0;
83  out:
84 	sshbuf_free(buf);
85 	return r;
86 }
87 
88 int
89 sshsig_dearmor(struct sshbuf *sig, struct sshbuf **out)
90 {
91 	int r;
92 	size_t eoffset = 0;
93 	struct sshbuf *buf = NULL;
94 	struct sshbuf *sbuf = NULL;
95 	char *b64 = NULL;
96 
97 	if ((sbuf = sshbuf_fromb(sig)) == NULL) {
98 		error_f("sshbuf_fromb failed");
99 		return SSH_ERR_ALLOC_FAIL;
100 	}
101 
102 	if ((r = sshbuf_cmp(sbuf, 0,
103 	    BEGIN_SIGNATURE, sizeof(BEGIN_SIGNATURE)-1)) != 0) {
104 		error("Couldn't parse signature: missing header");
105 		goto done;
106 	}
107 
108 	if ((r = sshbuf_consume(sbuf, sizeof(BEGIN_SIGNATURE)-1)) != 0) {
109 		error_fr(r, "consume");
110 		goto done;
111 	}
112 
113 	if ((r = sshbuf_find(sbuf, 0, "\n" END_SIGNATURE,
114 	    sizeof("\n" END_SIGNATURE)-1, &eoffset)) != 0) {
115 		error("Couldn't parse signature: missing footer");
116 		goto done;
117 	}
118 
119 	if ((r = sshbuf_consume_end(sbuf, sshbuf_len(sbuf)-eoffset)) != 0) {
120 		error_fr(r, "consume");
121 		goto done;
122 	}
123 
124 	if ((b64 = sshbuf_dup_string(sbuf)) == NULL) {
125 		error_f("sshbuf_dup_string failed");
126 		r = SSH_ERR_ALLOC_FAIL;
127 		goto done;
128 	}
129 
130 	if ((buf = sshbuf_new()) == NULL) {
131 		error_f("sshbuf_new() failed");
132 		r = SSH_ERR_ALLOC_FAIL;
133 		goto done;
134 	}
135 
136 	if ((r = sshbuf_b64tod(buf, b64)) != 0) {
137 		error_fr(r, "decode base64");
138 		goto done;
139 	}
140 
141 	/* success */
142 	*out = buf;
143 	r = 0;
144 	buf = NULL; /* transferred */
145 done:
146 	sshbuf_free(buf);
147 	sshbuf_free(sbuf);
148 	free(b64);
149 	return r;
150 }
151 
152 static int
153 sshsig_wrap_sign(struct sshkey *key, const char *hashalg,
154     const char *sk_provider, const char *sk_pin, const struct sshbuf *h_message,
155     const char *sig_namespace, struct sshbuf **out,
156     sshsig_signer *signer, void *signer_ctx)
157 {
158 	int r;
159 	size_t slen = 0;
160 	u_char *sig = NULL;
161 	struct sshbuf *blob = NULL;
162 	struct sshbuf *tosign = NULL;
163 	const char *sign_alg = NULL;
164 
165 	if ((tosign = sshbuf_new()) == NULL ||
166 	    (blob = sshbuf_new()) == NULL) {
167 		error_f("sshbuf_new failed");
168 		r = SSH_ERR_ALLOC_FAIL;
169 		goto done;
170 	}
171 
172 	if ((r = sshbuf_put(tosign, MAGIC_PREAMBLE, MAGIC_PREAMBLE_LEN)) != 0 ||
173 	    (r = sshbuf_put_cstring(tosign, sig_namespace)) != 0 ||
174 	    (r = sshbuf_put_string(tosign, NULL, 0)) != 0 || /* reserved */
175 	    (r = sshbuf_put_cstring(tosign, hashalg)) != 0 ||
176 	    (r = sshbuf_put_stringb(tosign, h_message)) != 0) {
177 		error_fr(r, "assemble message to sign");
178 		goto done;
179 	}
180 
181 	/* If using RSA keys then default to a good signature algorithm */
182 	if (sshkey_type_plain(key->type) == KEY_RSA)
183 		sign_alg = RSA_SIGN_ALG;
184 
185 	if (signer != NULL) {
186 		if ((r = signer(key, &sig, &slen,
187 		    sshbuf_ptr(tosign), sshbuf_len(tosign),
188 		    sign_alg, sk_provider, sk_pin, 0, signer_ctx)) != 0) {
189 			error_r(r, "Couldn't sign message (signer)");
190 			goto done;
191 		}
192 	} else {
193 		if ((r = sshkey_sign(key, &sig, &slen,
194 		    sshbuf_ptr(tosign), sshbuf_len(tosign),
195 		    sign_alg, sk_provider, sk_pin, 0)) != 0) {
196 			error_r(r, "Couldn't sign message");
197 			goto done;
198 		}
199 	}
200 
201 	if ((r = sshbuf_put(blob, MAGIC_PREAMBLE, MAGIC_PREAMBLE_LEN)) != 0 ||
202 	    (r = sshbuf_put_u32(blob, SIG_VERSION)) != 0 ||
203 	    (r = sshkey_puts(key, blob)) != 0 ||
204 	    (r = sshbuf_put_cstring(blob, sig_namespace)) != 0 ||
205 	    (r = sshbuf_put_string(blob, NULL, 0)) != 0 || /* reserved */
206 	    (r = sshbuf_put_cstring(blob, hashalg)) != 0 ||
207 	    (r = sshbuf_put_string(blob, sig, slen)) != 0) {
208 		error_fr(r, "assemble signature object");
209 		goto done;
210 	}
211 
212 	if (out != NULL) {
213 		*out = blob;
214 		blob = NULL;
215 	}
216 	r = 0;
217 done:
218 	free(sig);
219 	sshbuf_free(blob);
220 	sshbuf_free(tosign);
221 	return r;
222 }
223 
224 /* Check preamble and version. */
225 static int
226 sshsig_parse_preamble(struct sshbuf *buf)
227 {
228 	int r = SSH_ERR_INTERNAL_ERROR;
229 	uint32_t sversion;
230 
231 	if ((r = sshbuf_cmp(buf, 0, MAGIC_PREAMBLE, MAGIC_PREAMBLE_LEN)) != 0 ||
232 	    (r = sshbuf_consume(buf, (sizeof(MAGIC_PREAMBLE)-1))) != 0 ||
233 	    (r = sshbuf_get_u32(buf, &sversion)) != 0) {
234 		error("Couldn't verify signature: invalid format");
235 		return r;
236 	}
237 
238 	if (sversion > SIG_VERSION) {
239 		error("Signature version %lu is larger than supported "
240 		    "version %u", (unsigned long)sversion, SIG_VERSION);
241 		return SSH_ERR_INVALID_FORMAT;
242 	}
243 	return 0;
244 }
245 
246 static int
247 sshsig_check_hashalg(const char *hashalg)
248 {
249 	if (hashalg == NULL ||
250 	    match_pattern_list(hashalg, HASHALG_ALLOWED, 0) == 1)
251 		return 0;
252 	error_f("unsupported hash algorithm \"%.100s\"", hashalg);
253 	return SSH_ERR_SIGN_ALG_UNSUPPORTED;
254 }
255 
256 static int
257 sshsig_peek_hashalg(struct sshbuf *signature, char **hashalgp)
258 {
259 	struct sshbuf *buf = NULL;
260 	char *hashalg = NULL;
261 	int r = SSH_ERR_INTERNAL_ERROR;
262 
263 	if (hashalgp != NULL)
264 		*hashalgp = NULL;
265 	if ((buf = sshbuf_fromb(signature)) == NULL)
266 		return SSH_ERR_ALLOC_FAIL;
267 	if ((r = sshsig_parse_preamble(buf)) != 0)
268 		goto done;
269 	if ((r = sshbuf_get_string_direct(buf, NULL, NULL)) != 0 ||
270 	    (r = sshbuf_get_string_direct(buf, NULL, NULL)) != 0 ||
271 	    (r = sshbuf_get_string(buf, NULL, NULL)) != 0 ||
272 	    (r = sshbuf_get_cstring(buf, &hashalg, NULL)) != 0 ||
273 	    (r = sshbuf_get_string_direct(buf, NULL, NULL)) != 0) {
274 		error_fr(r, "parse signature object");
275 		goto done;
276 	}
277 
278 	/* success */
279 	r = 0;
280 	*hashalgp = hashalg;
281 	hashalg = NULL;
282  done:
283 	free(hashalg);
284 	sshbuf_free(buf);
285 	return r;
286 }
287 
288 static int
289 sshsig_wrap_verify(struct sshbuf *signature, const char *hashalg,
290     const struct sshbuf *h_message, const char *expect_namespace,
291     struct sshkey **sign_keyp, struct sshkey_sig_details **sig_details)
292 {
293 	int r = SSH_ERR_INTERNAL_ERROR;
294 	struct sshbuf *buf = NULL, *toverify = NULL;
295 	struct sshkey *key = NULL;
296 	const u_char *sig;
297 	char *got_namespace = NULL, *sigtype = NULL, *sig_hashalg = NULL;
298 	size_t siglen;
299 
300 	debug_f("verify message length %zu", sshbuf_len(h_message));
301 	if (sig_details != NULL)
302 		*sig_details = NULL;
303 	if (sign_keyp != NULL)
304 		*sign_keyp = NULL;
305 
306 	if ((toverify = sshbuf_new()) == NULL) {
307 		error_f("sshbuf_new failed");
308 		r = SSH_ERR_ALLOC_FAIL;
309 		goto done;
310 	}
311 	if ((r = sshbuf_put(toverify, MAGIC_PREAMBLE,
312 	    MAGIC_PREAMBLE_LEN)) != 0 ||
313 	    (r = sshbuf_put_cstring(toverify, expect_namespace)) != 0 ||
314 	    (r = sshbuf_put_string(toverify, NULL, 0)) != 0 || /* reserved */
315 	    (r = sshbuf_put_cstring(toverify, hashalg)) != 0 ||
316 	    (r = sshbuf_put_stringb(toverify, h_message)) != 0) {
317 		error_fr(r, "assemble message to verify");
318 		goto done;
319 	}
320 
321 	if ((r = sshsig_parse_preamble(signature)) != 0)
322 		goto done;
323 
324 	if ((r = sshkey_froms(signature, &key)) != 0 ||
325 	    (r = sshbuf_get_cstring(signature, &got_namespace, NULL)) != 0 ||
326 	    (r = sshbuf_get_string(signature, NULL, NULL)) != 0 ||
327 	    (r = sshbuf_get_cstring(signature, &sig_hashalg, NULL)) != 0 ||
328 	    (r = sshbuf_get_string_direct(signature, &sig, &siglen)) != 0) {
329 		error_fr(r, "parse signature object");
330 		goto done;
331 	}
332 
333 	if (sshbuf_len(signature) != 0) {
334 		error("Signature contains trailing data");
335 		r = SSH_ERR_INVALID_FORMAT;
336 		goto done;
337 	}
338 
339 	if (strcmp(expect_namespace, got_namespace) != 0) {
340 		error("Couldn't verify signature: namespace does not match");
341 		debug_f("expected namespace \"%s\" received \"%s\"",
342 		    expect_namespace, got_namespace);
343 		r = SSH_ERR_SIGNATURE_INVALID;
344 		goto done;
345 	}
346 	if (strcmp(hashalg, sig_hashalg) != 0) {
347 		error("Couldn't verify signature: hash algorithm mismatch");
348 		debug_f("expected algorithm \"%s\" received \"%s\"",
349 		    hashalg, sig_hashalg);
350 		r = SSH_ERR_SIGNATURE_INVALID;
351 		goto done;
352 	}
353 	/* Ensure that RSA keys use an acceptable signature algorithm */
354 	if (sshkey_type_plain(key->type) == KEY_RSA) {
355 		if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0) {
356 			error_r(r, "Couldn't verify signature: unable to get "
357 			    "signature type");
358 			goto done;
359 		}
360 		if (match_pattern_list(sigtype, RSA_SIGN_ALLOWED, 0) != 1) {
361 			error("Couldn't verify signature: unsupported RSA "
362 			    "signature algorithm %s", sigtype);
363 			r = SSH_ERR_SIGN_ALG_UNSUPPORTED;
364 			goto done;
365 		}
366 	}
367 	if ((r = sshkey_verify(key, sig, siglen, sshbuf_ptr(toverify),
368 	    sshbuf_len(toverify), NULL, 0, sig_details)) != 0) {
369 		error_r(r, "Signature verification failed");
370 		goto done;
371 	}
372 
373 	/* success */
374 	r = 0;
375 	if (sign_keyp != NULL) {
376 		*sign_keyp = key;
377 		key = NULL; /* transferred */
378 	}
379 done:
380 	free(got_namespace);
381 	free(sigtype);
382 	free(sig_hashalg);
383 	sshbuf_free(buf);
384 	sshbuf_free(toverify);
385 	sshkey_free(key);
386 	return r;
387 }
388 
389 static int
390 hash_buffer(const struct sshbuf *m, const char *hashalg, struct sshbuf **bp)
391 {
392 	char *hex, hash[SSH_DIGEST_MAX_LENGTH];
393 	int alg, r = SSH_ERR_INTERNAL_ERROR;
394 	struct sshbuf *b = NULL;
395 
396 	*bp = NULL;
397 	memset(hash, 0, sizeof(hash));
398 
399 	if ((r = sshsig_check_hashalg(hashalg)) != 0)
400 		return r;
401 	if ((alg = ssh_digest_alg_by_name(hashalg)) == -1) {
402 		error_f("can't look up hash algorithm %s", hashalg);
403 		return SSH_ERR_INTERNAL_ERROR;
404 	}
405 	if ((r = ssh_digest_buffer(alg, m, hash, sizeof(hash))) != 0) {
406 		error_fr(r, "ssh_digest_buffer");
407 		return r;
408 	}
409 	if ((hex = tohex(hash, ssh_digest_bytes(alg))) != NULL) {
410 		debug3_f("final hash: %s", hex);
411 		freezero(hex, strlen(hex));
412 	}
413 	if ((b = sshbuf_new()) == NULL) {
414 		r = SSH_ERR_ALLOC_FAIL;
415 		goto out;
416 	}
417 	if ((r = sshbuf_put(b, hash, ssh_digest_bytes(alg))) != 0) {
418 		error_fr(r, "sshbuf_put");
419 		goto out;
420 	}
421 	*bp = b;
422 	b = NULL; /* transferred */
423 	/* success */
424 	r = 0;
425  out:
426 	sshbuf_free(b);
427 	explicit_bzero(hash, sizeof(hash));
428 	return r;
429 }
430 
431 int
432 sshsig_signb(struct sshkey *key, const char *hashalg,
433     const char *sk_provider, const char *sk_pin,
434     const struct sshbuf *message, const char *sig_namespace,
435     struct sshbuf **out, sshsig_signer *signer, void *signer_ctx)
436 {
437 	struct sshbuf *b = NULL;
438 	int r = SSH_ERR_INTERNAL_ERROR;
439 
440 	if (hashalg == NULL)
441 		hashalg = HASHALG_DEFAULT;
442 	if (out != NULL)
443 		*out = NULL;
444 	if ((r = hash_buffer(message, hashalg, &b)) != 0) {
445 		error_fr(r, "hash buffer");
446 		goto out;
447 	}
448 	if ((r = sshsig_wrap_sign(key, hashalg, sk_provider, sk_pin, b,
449 	    sig_namespace, out, signer, signer_ctx)) != 0)
450 		goto out;
451 	/* success */
452 	r = 0;
453  out:
454 	sshbuf_free(b);
455 	return r;
456 }
457 
458 int
459 sshsig_verifyb(struct sshbuf *signature, const struct sshbuf *message,
460     const char *expect_namespace, struct sshkey **sign_keyp,
461     struct sshkey_sig_details **sig_details)
462 {
463 	struct sshbuf *b = NULL;
464 	int r = SSH_ERR_INTERNAL_ERROR;
465 	char *hashalg = NULL;
466 
467 	if (sig_details != NULL)
468 		*sig_details = NULL;
469 	if (sign_keyp != NULL)
470 		*sign_keyp = NULL;
471 	if ((r = sshsig_peek_hashalg(signature, &hashalg)) != 0)
472 		return r;
473 	debug_f("signature made with hash \"%s\"", hashalg);
474 	if ((r = hash_buffer(message, hashalg, &b)) != 0) {
475 		error_fr(r, "hash buffer");
476 		goto out;
477 	}
478 	if ((r = sshsig_wrap_verify(signature, hashalg, b, expect_namespace,
479 	    sign_keyp, sig_details)) != 0)
480 		goto out;
481 	/* success */
482 	r = 0;
483  out:
484 	sshbuf_free(b);
485 	free(hashalg);
486 	return r;
487 }
488 
489 static int
490 hash_file(int fd, const char *hashalg, struct sshbuf **bp)
491 {
492 	char *hex, rbuf[8192], hash[SSH_DIGEST_MAX_LENGTH];
493 	ssize_t n, total = 0;
494 	struct ssh_digest_ctx *ctx;
495 	int alg, oerrno, r = SSH_ERR_INTERNAL_ERROR;
496 	struct sshbuf *b = NULL;
497 
498 	*bp = NULL;
499 	memset(hash, 0, sizeof(hash));
500 
501 	if ((r = sshsig_check_hashalg(hashalg)) != 0)
502 		return r;
503 	if ((alg = ssh_digest_alg_by_name(hashalg)) == -1) {
504 		error_f("can't look up hash algorithm %s", hashalg);
505 		return SSH_ERR_INTERNAL_ERROR;
506 	}
507 	if ((ctx = ssh_digest_start(alg)) == NULL) {
508 		error_f("ssh_digest_start failed");
509 		return SSH_ERR_INTERNAL_ERROR;
510 	}
511 	for (;;) {
512 		if ((n = read(fd, rbuf, sizeof(rbuf))) == -1) {
513 			if (errno == EINTR || errno == EAGAIN)
514 				continue;
515 			oerrno = errno;
516 			error_f("read: %s", strerror(errno));
517 			ssh_digest_free(ctx);
518 			errno = oerrno;
519 			r = SSH_ERR_SYSTEM_ERROR;
520 			goto out;
521 		} else if (n == 0) {
522 			debug2_f("hashed %zu bytes", total);
523 			break; /* EOF */
524 		}
525 		total += (size_t)n;
526 		if ((r = ssh_digest_update(ctx, rbuf, (size_t)n)) != 0) {
527 			error_fr(r, "ssh_digest_update");
528 			goto out;
529 		}
530 	}
531 	if ((r = ssh_digest_final(ctx, hash, sizeof(hash))) != 0) {
532 		error_fr(r, "ssh_digest_final");
533 		goto out;
534 	}
535 	if ((hex = tohex(hash, ssh_digest_bytes(alg))) != NULL) {
536 		debug3_f("final hash: %s", hex);
537 		freezero(hex, strlen(hex));
538 	}
539 	if ((b = sshbuf_new()) == NULL) {
540 		r = SSH_ERR_ALLOC_FAIL;
541 		goto out;
542 	}
543 	if ((r = sshbuf_put(b, hash, ssh_digest_bytes(alg))) != 0) {
544 		error_fr(r, "sshbuf_put");
545 		goto out;
546 	}
547 	*bp = b;
548 	b = NULL; /* transferred */
549 	/* success */
550 	r = 0;
551  out:
552 	sshbuf_free(b);
553 	ssh_digest_free(ctx);
554 	explicit_bzero(hash, sizeof(hash));
555 	return r;
556 }
557 
558 int
559 sshsig_sign_fd(struct sshkey *key, const char *hashalg,
560     const char *sk_provider, const char *sk_pin,
561     int fd, const char *sig_namespace, struct sshbuf **out,
562     sshsig_signer *signer, void *signer_ctx)
563 {
564 	struct sshbuf *b = NULL;
565 	int r = SSH_ERR_INTERNAL_ERROR;
566 
567 	if (hashalg == NULL)
568 		hashalg = HASHALG_DEFAULT;
569 	if (out != NULL)
570 		*out = NULL;
571 	if ((r = hash_file(fd, hashalg, &b)) != 0) {
572 		error_fr(r, "hash_file");
573 		return r;
574 	}
575 	if ((r = sshsig_wrap_sign(key, hashalg, sk_provider, sk_pin, b,
576 	    sig_namespace, out, signer, signer_ctx)) != 0)
577 		goto out;
578 	/* success */
579 	r = 0;
580  out:
581 	sshbuf_free(b);
582 	return r;
583 }
584 
585 int
586 sshsig_verify_fd(struct sshbuf *signature, int fd,
587     const char *expect_namespace, struct sshkey **sign_keyp,
588     struct sshkey_sig_details **sig_details)
589 {
590 	struct sshbuf *b = NULL;
591 	int r = SSH_ERR_INTERNAL_ERROR;
592 	char *hashalg = NULL;
593 
594 	if (sig_details != NULL)
595 		*sig_details = NULL;
596 	if (sign_keyp != NULL)
597 		*sign_keyp = NULL;
598 	if ((r = sshsig_peek_hashalg(signature, &hashalg)) != 0)
599 		return r;
600 	debug_f("signature made with hash \"%s\"", hashalg);
601 	if ((r = hash_file(fd, hashalg, &b)) != 0) {
602 		error_fr(r, "hash_file");
603 		goto out;
604 	}
605 	if ((r = sshsig_wrap_verify(signature, hashalg, b, expect_namespace,
606 	    sign_keyp, sig_details)) != 0)
607 		goto out;
608 	/* success */
609 	r = 0;
610  out:
611 	sshbuf_free(b);
612 	free(hashalg);
613 	return r;
614 }
615 
616 struct sshsigopt {
617 	int ca;
618 	char *namespaces;
619 	uint64_t valid_after, valid_before;
620 };
621 
622 struct sshsigopt *
623 sshsigopt_parse(const char *opts, const char *path, u_long linenum,
624     const char **errstrp)
625 {
626 	struct sshsigopt *ret;
627 	int r;
628 	char *opt;
629 	const char *errstr = NULL;
630 
631 	if ((ret = calloc(1, sizeof(*ret))) == NULL)
632 		return NULL;
633 	if (opts == NULL || *opts == '\0')
634 		return ret; /* Empty options yields empty options :) */
635 
636 	while (*opts && *opts != ' ' && *opts != '\t') {
637 		/* flag options */
638 		if ((r = opt_flag("cert-authority", 0, &opts)) != -1) {
639 			ret->ca = 1;
640 		} else if (opt_match(&opts, "namespaces")) {
641 			if (ret->namespaces != NULL) {
642 				errstr = "multiple \"namespaces\" clauses";
643 				goto fail;
644 			}
645 			ret->namespaces = opt_dequote(&opts, &errstr);
646 			if (ret->namespaces == NULL)
647 				goto fail;
648 		} else if (opt_match(&opts, "valid-after")) {
649 			if (ret->valid_after != 0) {
650 				errstr = "multiple \"valid-after\" clauses";
651 				goto fail;
652 			}
653 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
654 				goto fail;
655 			if (parse_absolute_time(opt, &ret->valid_after) != 0 ||
656 			    ret->valid_after == 0) {
657 				free(opt);
658 				errstr = "invalid \"valid-after\" time";
659 				goto fail;
660 			}
661 			free(opt);
662 		} else if (opt_match(&opts, "valid-before")) {
663 			if (ret->valid_before != 0) {
664 				errstr = "multiple \"valid-before\" clauses";
665 				goto fail;
666 			}
667 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
668 				goto fail;
669 			if (parse_absolute_time(opt, &ret->valid_before) != 0 ||
670 			    ret->valid_before == 0) {
671 				free(opt);
672 				errstr = "invalid \"valid-before\" time";
673 				goto fail;
674 			}
675 			free(opt);
676 		}
677 		/*
678 		 * Skip the comma, and move to the next option
679 		 * (or break out if there are no more).
680 		 */
681 		if (*opts == '\0' || *opts == ' ' || *opts == '\t')
682 			break;		/* End of options. */
683 		/* Anything other than a comma is an unknown option */
684 		if (*opts != ',') {
685 			errstr = "unknown key option";
686 			goto fail;
687 		}
688 		opts++;
689 		if (*opts == '\0') {
690 			errstr = "unexpected end-of-options";
691 			goto fail;
692 		}
693 	}
694 	/* final consistency check */
695 	if (ret->valid_after != 0 && ret->valid_before != 0 &&
696 	    ret->valid_before <= ret->valid_after) {
697 		errstr = "\"valid-before\" time is before \"valid-after\"";
698 		goto fail;
699 	}
700 	/* success */
701 	return ret;
702  fail:
703 	if (errstrp != NULL)
704 		*errstrp = errstr;
705 	sshsigopt_free(ret);
706 	return NULL;
707 }
708 
709 void
710 sshsigopt_free(struct sshsigopt *opts)
711 {
712 	if (opts == NULL)
713 		return;
714 	free(opts->namespaces);
715 	free(opts);
716 }
717 
718 static int
719 parse_principals_key_and_options(const char *path, u_long linenum, char *line,
720     const char *required_principal, char **principalsp, struct sshkey **keyp,
721     struct sshsigopt **sigoptsp)
722 {
723 	char *opts = NULL, *tmp, *cp, *principals = NULL;
724 	const char *reason = NULL;
725 	struct sshsigopt *sigopts = NULL;
726 	struct sshkey *key = NULL;
727 	int r = SSH_ERR_INTERNAL_ERROR;
728 
729 	if (principalsp != NULL)
730 		*principalsp = NULL;
731 	if (sigoptsp != NULL)
732 		*sigoptsp = NULL;
733 	if (keyp != NULL)
734 		*keyp = NULL;
735 
736 	cp = line;
737 	cp = cp + strspn(cp, " \t"); /* skip leading whitespace */
738 	if (*cp == '#' || *cp == '\0')
739 		return SSH_ERR_KEY_NOT_FOUND; /* blank or all-comment line */
740 
741 	/* format: identity[,identity...] [option[,option...]] key */
742 	if ((tmp = strdelimw(&cp)) == NULL || cp == NULL) {
743 		error("%s:%lu: invalid line", path, linenum);
744 		r = SSH_ERR_INVALID_FORMAT;
745 		goto out;
746 	}
747 	if ((principals = strdup(tmp)) == NULL) {
748 		error_f("strdup failed");
749 		r = SSH_ERR_ALLOC_FAIL;
750 		goto out;
751 	}
752 	/*
753 	 * Bail out early if we're looking for a particular principal and this
754 	 * line does not list it.
755 	 */
756 	if (required_principal != NULL) {
757 		if (match_pattern_list(required_principal,
758 		    principals, 0) != 1) {
759 			/* principal didn't match */
760 			r = SSH_ERR_KEY_NOT_FOUND;
761 			goto out;
762 		}
763 		debug_f("%s:%lu: matched principal \"%s\"",
764 		    path, linenum, required_principal);
765 	}
766 
767 	if ((key = sshkey_new(KEY_UNSPEC)) == NULL) {
768 		error_f("sshkey_new failed");
769 		r = SSH_ERR_ALLOC_FAIL;
770 		goto out;
771 	}
772 	if (sshkey_read(key, &cp) != 0) {
773 		/* no key? Check for options */
774 		opts = cp;
775 		if (sshkey_advance_past_options(&cp) != 0) {
776 			error("%s:%lu: invalid options", path, linenum);
777 			r = SSH_ERR_INVALID_FORMAT;
778 			goto out;
779 		}
780 		if (cp == NULL || *cp == '\0') {
781 			error("%s:%lu: missing key", path, linenum);
782 			r = SSH_ERR_INVALID_FORMAT;
783 			goto out;
784 		}
785 		*cp++ = '\0';
786 		skip_space(&cp);
787 		if (sshkey_read(key, &cp) != 0) {
788 			error("%s:%lu: invalid key", path, linenum);
789 			r = SSH_ERR_INVALID_FORMAT;
790 			goto out;
791 		}
792 	}
793 	debug3("%s:%lu: options %s", path, linenum, opts == NULL ? "" : opts);
794 	if ((sigopts = sshsigopt_parse(opts, path, linenum, &reason)) == NULL) {
795 		error("%s:%lu: bad options: %s", path, linenum, reason);
796 		r = SSH_ERR_INVALID_FORMAT;
797 		goto out;
798 	}
799 	/* success */
800 	if (principalsp != NULL) {
801 		*principalsp = principals;
802 		principals = NULL; /* transferred */
803 	}
804 	if (sigoptsp != NULL) {
805 		*sigoptsp = sigopts;
806 		sigopts = NULL; /* transferred */
807 	}
808 	if (keyp != NULL) {
809 		*keyp = key;
810 		key = NULL; /* transferred */
811 	}
812 	r = 0;
813  out:
814 	free(principals);
815 	sshsigopt_free(sigopts);
816 	sshkey_free(key);
817 	return r;
818 }
819 
820 static int
821 cert_filter_principals(const char *path, u_long linenum,
822     char **principalsp, const struct sshkey *cert, uint64_t verify_time)
823 {
824 	char *cp, *oprincipals, *principals;
825 	const char *reason;
826 	struct sshbuf *nprincipals;
827 	int r = SSH_ERR_INTERNAL_ERROR, success = 0;
828 	u_int i;
829 
830 	oprincipals = principals = *principalsp;
831 	*principalsp = NULL;
832 
833 	if ((nprincipals = sshbuf_new()) == NULL) {
834 		r = SSH_ERR_ALLOC_FAIL;
835 		goto out;
836 	}
837 
838 	while ((cp = strsep(&principals, ",")) != NULL && *cp != '\0') {
839 		/* Check certificate validity */
840 		if ((r = sshkey_cert_check_authority(cert, 0, 1, 0,
841 		    verify_time, NULL, &reason)) != 0) {
842 			debug("%s:%lu: principal \"%s\" not authorized: %s",
843 			    path, linenum, cp, reason);
844 			continue;
845 		}
846 		/* Return all matching principal names from the cert */
847 		for (i = 0; i < cert->cert->nprincipals; i++) {
848 			if (match_pattern(cert->cert->principals[i], cp)) {
849 				if ((r = sshbuf_putf(nprincipals, "%s%s",
850 					sshbuf_len(nprincipals) != 0 ? "," : "",
851 						cert->cert->principals[i])) != 0) {
852 					error_f("buffer error");
853 					goto out;
854 				}
855 			}
856 		}
857 	}
858 	if (sshbuf_len(nprincipals) == 0) {
859 		error("%s:%lu: no valid principals found", path, linenum);
860 		r = SSH_ERR_KEY_CERT_INVALID;
861 		goto out;
862 	}
863 	if ((principals = sshbuf_dup_string(nprincipals)) == NULL) {
864 		error_f("buffer error");
865 		goto out;
866 	}
867 	/* success */
868 	success = 1;
869 	*principalsp = principals;
870  out:
871 	sshbuf_free(nprincipals);
872 	free(oprincipals);
873 	return success ? 0 : r;
874 }
875 
876 static int
877 check_allowed_keys_line(const char *path, u_long linenum, char *line,
878     const struct sshkey *sign_key, const char *principal,
879     const char *sig_namespace, uint64_t verify_time, char **principalsp)
880 {
881 	struct sshkey *found_key = NULL;
882 	char *principals = NULL;
883 	int r, success = 0;
884 	const char *reason = NULL;
885 	struct sshsigopt *sigopts = NULL;
886 	char tvalid[64], tverify[64];
887 
888 	if (principalsp != NULL)
889 		*principalsp = NULL;
890 
891 	/* Parse the line */
892 	if ((r = parse_principals_key_and_options(path, linenum, line,
893 	    principal, &principals, &found_key, &sigopts)) != 0) {
894 		/* error already logged */
895 		goto done;
896 	}
897 
898 	if (!sigopts->ca && sshkey_equal(found_key, sign_key)) {
899 		/* Exact match of key */
900 		debug("%s:%lu: matched key", path, linenum);
901 	} else if (sigopts->ca && sshkey_is_cert(sign_key) &&
902 	    sshkey_equal_public(sign_key->cert->signature_key, found_key)) {
903 		if (principal) {
904 			/* Match certificate CA key with specified principal */
905 			if ((r = sshkey_cert_check_authority(sign_key, 0, 1, 0,
906 			    verify_time, principal, &reason)) != 0) {
907 				error("%s:%lu: certificate not authorized: %s",
908 				    path, linenum, reason);
909 				goto done;
910 			}
911 			debug("%s:%lu: matched certificate CA key",
912 			    path, linenum);
913 		} else {
914 			/* No principal specified - find all matching ones */
915 			if ((r = cert_filter_principals(path, linenum,
916 			    &principals, sign_key, verify_time)) != 0) {
917 				/* error already displayed */
918 				debug_r(r, "%s:%lu: cert_filter_principals",
919 				    path, linenum);
920 				goto done;
921 			}
922 			debug("%s:%lu: matched certificate CA key",
923 			    path, linenum);
924 		}
925 	} else {
926 		/* Didn't match key */
927 		goto done;
928 	}
929 
930 	/* Check whether options preclude the use of this key */
931 	if (sigopts->namespaces != NULL && sig_namespace != NULL &&
932 	    match_pattern_list(sig_namespace, sigopts->namespaces, 0) != 1) {
933 		error("%s:%lu: key is not permitted for use in signature "
934 		    "namespace \"%s\"", path, linenum, sig_namespace);
935 		goto done;
936 	}
937 
938 	/* check key time validity */
939 	format_absolute_time((uint64_t)verify_time, tverify, sizeof(tverify));
940 	if (sigopts->valid_after != 0 &&
941 	    (uint64_t)verify_time < sigopts->valid_after) {
942 		format_absolute_time(sigopts->valid_after,
943 		    tvalid, sizeof(tvalid));
944 		error("%s:%lu: key is not yet valid: "
945 		    "verify time %s < valid-after %s", path, linenum,
946 		    tverify, tvalid);
947 		goto done;
948 	}
949 	if (sigopts->valid_before != 0 &&
950 	    (uint64_t)verify_time > sigopts->valid_before) {
951 		format_absolute_time(sigopts->valid_before,
952 		    tvalid, sizeof(tvalid));
953 		error("%s:%lu: key has expired: "
954 		    "verify time %s > valid-before %s", path, linenum,
955 		    tverify, tvalid);
956 		goto done;
957 	}
958 	success = 1;
959 
960  done:
961 	if (success && principalsp != NULL) {
962 		*principalsp = principals;
963 		principals = NULL; /* transferred */
964 	}
965 	free(principals);
966 	sshkey_free(found_key);
967 	sshsigopt_free(sigopts);
968 	return success ? 0 : SSH_ERR_KEY_NOT_FOUND;
969 }
970 
971 int
972 sshsig_check_allowed_keys(const char *path, const struct sshkey *sign_key,
973     const char *principal, const char *sig_namespace, uint64_t verify_time)
974 {
975 	FILE *f = NULL;
976 	char *line = NULL;
977 	size_t linesize = 0;
978 	u_long linenum = 0;
979 	int r = SSH_ERR_INTERNAL_ERROR, oerrno;
980 
981 	/* Check key and principal against file */
982 	if ((f = fopen(path, "r")) == NULL) {
983 		oerrno = errno;
984 		error("Unable to open allowed keys file \"%s\": %s",
985 		    path, strerror(errno));
986 		errno = oerrno;
987 		return SSH_ERR_SYSTEM_ERROR;
988 	}
989 
990 	while (getline(&line, &linesize, f) != -1) {
991 		linenum++;
992 		r = check_allowed_keys_line(path, linenum, line, sign_key,
993 		    principal, sig_namespace, verify_time, NULL);
994 		free(line);
995 		line = NULL;
996 		linesize = 0;
997 		if (r == SSH_ERR_KEY_NOT_FOUND)
998 			continue;
999 		else if (r == 0) {
1000 			/* success */
1001 			fclose(f);
1002 			return 0;
1003 		} else
1004 			break;
1005 	}
1006 	/* Either we hit an error parsing or we simply didn't find the key */
1007 	fclose(f);
1008 	free(line);
1009 	return r == 0 ? SSH_ERR_KEY_NOT_FOUND : r;
1010 }
1011 
1012 int
1013 sshsig_find_principals(const char *path, const struct sshkey *sign_key,
1014     uint64_t verify_time, char **principals)
1015 {
1016 	FILE *f = NULL;
1017 	char *line = NULL;
1018 	size_t linesize = 0;
1019 	u_long linenum = 0;
1020 	int r = SSH_ERR_INTERNAL_ERROR, oerrno;
1021 
1022 	if ((f = fopen(path, "r")) == NULL) {
1023 		oerrno = errno;
1024 		error("Unable to open allowed keys file \"%s\": %s",
1025 		    path, strerror(errno));
1026 		errno = oerrno;
1027 		return SSH_ERR_SYSTEM_ERROR;
1028 	}
1029 
1030 	r = SSH_ERR_KEY_NOT_FOUND;
1031 	while (getline(&line, &linesize, f) != -1) {
1032 		linenum++;
1033 		r = check_allowed_keys_line(path, linenum, line,
1034 		    sign_key, NULL, NULL, verify_time, principals);
1035 		free(line);
1036 		line = NULL;
1037 		linesize = 0;
1038 		if (r == SSH_ERR_KEY_NOT_FOUND)
1039 			continue;
1040 		else if (r == 0) {
1041 			/* success */
1042 			fclose(f);
1043 			return 0;
1044 		} else
1045 			break;
1046 	}
1047 	free(line);
1048 	/* Either we hit an error parsing or we simply didn't find the key */
1049 	if (ferror(f) != 0) {
1050 		oerrno = errno;
1051 		fclose(f);
1052 		error("Unable to read allowed keys file \"%s\": %s",
1053 		    path, strerror(errno));
1054 		errno = oerrno;
1055 		return SSH_ERR_SYSTEM_ERROR;
1056 	}
1057 	fclose(f);
1058 	return r == 0 ? SSH_ERR_KEY_NOT_FOUND : r;
1059 }
1060 
1061 int
1062 sshsig_match_principals(const char *path, const char *principal,
1063     char ***principalsp, size_t *nprincipalsp)
1064 {
1065 	FILE *f = NULL;
1066 	char *found, *line = NULL, **principals = NULL, **tmp;
1067 	size_t i, nprincipals = 0, linesize = 0;
1068 	u_long linenum = 0;
1069 	int oerrno = 0, r, ret = 0;
1070 
1071 	if (principalsp != NULL)
1072 		*principalsp = NULL;
1073 	if (nprincipalsp != NULL)
1074 		*nprincipalsp = 0;
1075 
1076 	/* Check key and principal against file */
1077 	if ((f = fopen(path, "r")) == NULL) {
1078 		oerrno = errno;
1079 		error("Unable to open allowed keys file \"%s\": %s",
1080 		    path, strerror(errno));
1081 		errno = oerrno;
1082 		return SSH_ERR_SYSTEM_ERROR;
1083 	}
1084 
1085 	while (getline(&line, &linesize, f) != -1) {
1086 		linenum++;
1087 		/* Parse the line */
1088 		if ((r = parse_principals_key_and_options(path, linenum, line,
1089 		    principal, &found, NULL, NULL)) != 0) {
1090 			if (r == SSH_ERR_KEY_NOT_FOUND)
1091 				continue;
1092 			ret = r;
1093 			oerrno = errno;
1094 			break; /* unexpected error */
1095 		}
1096 		if ((tmp = recallocarray(principals, nprincipals,
1097 		    nprincipals + 1, sizeof(*principals))) == NULL) {
1098 			ret = SSH_ERR_ALLOC_FAIL;
1099 			free(found);
1100 			break;
1101 		}
1102 		principals = tmp;
1103 		principals[nprincipals++] = found; /* transferred */
1104 		free(line);
1105 		line = NULL;
1106 		linesize = 0;
1107 	}
1108 	fclose(f);
1109 
1110 	if (ret == 0) {
1111 		if (nprincipals == 0)
1112 			ret = SSH_ERR_KEY_NOT_FOUND;
1113 		if (principalsp != NULL) {
1114 			*principalsp = principals;
1115 			principals = NULL; /* transferred */
1116 		}
1117 		if (nprincipalsp != 0) {
1118 			*nprincipalsp = nprincipals;
1119 			nprincipals = 0;
1120 		}
1121 	}
1122 
1123 	for (i = 0; i < nprincipals; i++)
1124 		free(principals[i]);
1125 	free(principals);
1126 
1127 	errno = oerrno;
1128 	return ret;
1129 }
1130 
1131 int
1132 sshsig_get_pubkey(struct sshbuf *signature, struct sshkey **pubkey)
1133 {
1134 	struct sshkey *pk = NULL;
1135 	int r = SSH_ERR_SIGNATURE_INVALID;
1136 
1137 	if (pubkey == NULL)
1138 		return SSH_ERR_INTERNAL_ERROR;
1139 	if ((r = sshsig_parse_preamble(signature)) != 0)
1140 		return r;
1141 	if ((r = sshkey_froms(signature, &pk)) != 0)
1142 		return r;
1143 
1144 	*pubkey = pk;
1145 	pk = NULL;
1146 	return 0;
1147 }
1148