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