1 #include "certificate.h"
2 
3 #include <errno.h>
4 #include <stdint.h> /* SIZE_MAX */
5 #include <syslog.h>
6 #include <time.h>
7 #include <openssl/asn1.h>
8 #include <sys/socket.h>
9 
10 #include "algorithm.h"
11 #include "config.h"
12 #include "extension.h"
13 #include "log.h"
14 #include "nid.h"
15 #include "reqs_errors.h"
16 #include "str_token.h"
17 #include "thread_var.h"
18 #include "asn1/decode.h"
19 #include "asn1/oid.h"
20 #include "asn1/asn1c/IPAddrBlocks.h"
21 #include "crypto/hash.h"
22 #include "incidence/incidence.h"
23 #include "object/bgpsec.h"
24 #include "object/name.h"
25 #include "object/manifest.h"
26 #include "object/signed_object.h"
27 #include "rrdp/rrdp_loader.h"
28 #include "rsync/rsync.h"
29 
30 /* Just to prevent some line breaking. */
31 #define GN_URI uniformResourceIdentifier
32 
33 /*
34  * The X509V3_EXT_METHOD that references NID_sinfo_access uses the AIA item.
35  * The SIA's d2i function, therefore, returns AIAs.
36  * They are the same as far as LibreSSL is concerned.
37  */
38 typedef AUTHORITY_INFO_ACCESS SIGNATURE_INFO_ACCESS;
39 
40 struct ski_arguments {
41 	X509 *cert;
42 	OCTET_STRING_t *sid;
43 };
44 
45 struct sia_uri {
46 	uint8_t position;
47 	struct rpki_uri *uri;
48 };
49 
50 struct sia_ca_uris {
51 	struct sia_uri caRepository;
52 	struct sia_uri rpkiNotify;
53 	struct sia_uri mft;
54 };
55 
56 struct bgpsec_ski {
57 	X509 *cert;
58 	unsigned char **ski_data;
59 };
60 
61 /* Callback method to fetch repository objects */
62 typedef int (access_method_exec)(struct sia_ca_uris *);
63 
64 static void
sia_ca_uris_init(struct sia_ca_uris * sia_uris)65 sia_ca_uris_init(struct sia_ca_uris *sia_uris)
66 {
67 	sia_uris->caRepository.uri = NULL;
68 	sia_uris->rpkiNotify.uri = NULL;
69 	sia_uris->mft.uri = NULL;
70 }
71 
72 static void
sia_ca_uris_cleanup(struct sia_ca_uris * sia_uris)73 sia_ca_uris_cleanup(struct sia_ca_uris *sia_uris)
74 {
75 	if (sia_uris->caRepository.uri != NULL)
76 		uri_refput(sia_uris->caRepository.uri);
77 	if (sia_uris->rpkiNotify.uri != NULL)
78 		uri_refput(sia_uris->rpkiNotify.uri);
79 	if (sia_uris->mft.uri != NULL)
80 		uri_refput(sia_uris->mft.uri);
81 }
82 
83 static void
debug_serial_number(BIGNUM * number)84 debug_serial_number(BIGNUM *number)
85 {
86 	char *number_str;
87 
88 	number_str = BN_bn2dec(number);
89 	if (number_str == NULL) {
90 		val_crypto_err("Could not convert BN to string");
91 		return;
92 	}
93 
94 	pr_val_debug("serial Number: %s", number_str);
95 	free(number_str);
96 }
97 
98 static int
validate_serial_number(X509 * cert)99 validate_serial_number(X509 *cert)
100 {
101 	struct validation *state;
102 	BIGNUM *number;
103 	int error;
104 
105 	state = state_retrieve();
106 	if (state == NULL)
107 		return -EINVAL;
108 
109 	number = ASN1_INTEGER_to_BN(X509_get0_serialNumber(cert), NULL);
110 	if (number == NULL)
111 		return val_crypto_err("Could not parse certificate serial number");
112 
113 	if (log_val_enabled(LOG_DEBUG))
114 		debug_serial_number(number);
115 
116 	error = x509stack_store_serial(validation_certstack(state), number);
117 	if (error)
118 		BN_free(number);
119 
120 	return error;
121 }
122 
123 static int
validate_signature_algorithm(X509 * cert)124 validate_signature_algorithm(X509 *cert)
125 {
126 	int nid = OBJ_obj2nid(X509_get0_tbs_sigalg(cert)->algorithm);
127 	return validate_certificate_signature_algorithm(nid, "Certificate");
128 }
129 
130 static int
validate_issuer(X509 * cert,bool is_ta)131 validate_issuer(X509 *cert, bool is_ta)
132 {
133 	X509_NAME *issuer;
134 	struct rfc5280_name *name;
135 	int error;
136 
137 	issuer = X509_get_issuer_name(cert);
138 
139 	if (!is_ta)
140 		return validate_issuer_name("Certificate", issuer);
141 
142 	/* TODO wait. Shouldn't we check subject == issuer? */
143 
144 	error = x509_name_decode(issuer, "issuer", &name);
145 	if (error)
146 		return error;
147 	pr_val_debug("Issuer: %s", x509_name_commonName(name));
148 
149 	x509_name_put(name);
150 	return 0;
151 }
152 
153 /*
154  * Compare public keys, call @diff_alg_cb when the algorithm is different, call
155  * @diff_pk_cb when the public key is different; return 0 if both are equal.
156  */
157 static int
spki_cmp(X509_PUBKEY * tal_spki,X509_PUBKEY * cert_spki,int (* diff_alg_cb)(void),int (* diff_pk_cb)(void))158 spki_cmp(X509_PUBKEY *tal_spki, X509_PUBKEY *cert_spki,
159     int (*diff_alg_cb)(void), int (*diff_pk_cb)(void))
160 {
161 	ASN1_OBJECT *tal_alg;
162 	ASN1_OBJECT *cert_alg;
163 
164 	unsigned char const *tal_spk, *cert_spk;
165 	int tal_spk_len, cert_spk_len;
166 
167 	int ok;
168 
169 	ok = X509_PUBKEY_get0_param(&tal_alg, &tal_spk, &tal_spk_len, NULL,
170 	    tal_spki);
171 	if (!ok)
172 		return val_crypto_err("X509_PUBKEY_get0_param() 1 returned %d", ok);
173 	ok = X509_PUBKEY_get0_param(&cert_alg, &cert_spk, &cert_spk_len, NULL,
174 	    cert_spki);
175 	if (!ok)
176 		return val_crypto_err("X509_PUBKEY_get0_param() 2 returned %d", ok);
177 
178 	if (OBJ_cmp(tal_alg, cert_alg) != 0)
179 		return diff_alg_cb();
180 	if (tal_spk_len != cert_spk_len)
181 		return diff_pk_cb();
182 	if (memcmp(tal_spk, cert_spk, cert_spk_len) != 0)
183 		return diff_pk_cb();
184 
185 	return 0;
186 }
187 
188 /** Call whenever the public key is different and the subject is the same**/
189 static int
cert_different_pk_err(void)190 cert_different_pk_err(void)
191 {
192 	return 1;
193 }
194 
195 /*
196  * Beware: this function skips a lot (maybe all) RPKI validations for a signed
197  * object, and clearly expects that the signed object has at least one
198  * certificate.
199  *
200  * Allocates @result, don't forget to release it.
201  *
202  * It has been placed here to minimize the risk of misuse.
203  */
204 static int
cert_from_signed_object(struct rpki_uri * uri,uint8_t ** result,int * size)205 cert_from_signed_object(struct rpki_uri *uri, uint8_t **result, int *size)
206 {
207 	struct signed_object sobj;
208 	ANY_t *cert;
209 	unsigned char *tmp;
210 	int error;
211 
212 	error = signed_object_decode(&sobj, uri);
213 	if (error)
214 		return error;
215 
216 	cert = sobj.sdata.decoded->certificates->list.array[0];
217 
218 	tmp = malloc(cert->size);
219 	if (tmp == NULL) {
220 		signed_object_cleanup(&sobj);
221 		return pr_enomem();
222 	}
223 
224 	memcpy(tmp, cert->buf, cert->size);
225 
226 	*result = tmp;
227 	(*size) = cert->size;
228 
229 	signed_object_cleanup(&sobj);
230 	return 0;
231 }
232 
233 static int
check_dup_public_key(bool * duplicated,char const * file,void * arg)234 check_dup_public_key(bool *duplicated, char const *file, void *arg)
235 {
236 	X509 *curr_cert = arg; /* Current cert */
237 	X509 *rcvd_cert;
238 	X509_PUBKEY *curr_pk, *rcvd_pk;
239 	struct rpki_uri *uri;
240 	uint8_t *tmp;
241 	int tmp_size;
242 	int error;
243 
244 	uri = NULL;
245 	rcvd_cert = NULL;
246 	tmp_size = 0;
247 
248 	error = uri_create_rsync_str(&uri, file, strlen(file));
249 	if (error)
250 		return error;
251 
252 	/* Check if it's '.cer', otherwise treat as a signed object */
253 	if (uri_is_certificate(uri)) {
254 		error = certificate_load(uri, &rcvd_cert);
255 		if (error)
256 			goto free_uri;
257 	} else {
258 		error = cert_from_signed_object(uri, &tmp, &tmp_size);
259 		if (error)
260 			goto free_uri;
261 
262 		rcvd_cert = d2i_X509(NULL, (const unsigned char **) &tmp,
263 		    tmp_size);
264 		free(tmp); /* Release at once */
265 		if (rcvd_cert == NULL) {
266 			error = val_crypto_err("Signed object's '%s' 'certificate' element does not decode into a Certificate",
267 			    uri_val_get_printable(uri));
268 			goto free_uri;
269 		}
270 	}
271 
272 	curr_pk = X509_get_X509_PUBKEY(curr_cert);
273 	if (curr_pk == NULL) {
274 		error = val_crypto_err("X509_get_X509_PUBKEY() returned NULL");
275 		goto free_cert;
276 	}
277 
278 	rcvd_pk = X509_get_X509_PUBKEY(rcvd_cert);
279 	if (rcvd_pk == NULL) {
280 		error = val_crypto_err("X509_get_X509_PUBKEY() returned NULL");
281 		goto free_cert;
282 	}
283 
284 	/*
285 	 * The function response will be:
286 	 *   < 0 if there's an error
287 	 *   = 0 if the PKs are equal
288 	 *   > 0 if the PKs are different
289 	 */
290 	error = spki_cmp(curr_pk, rcvd_pk, cert_different_pk_err,
291 	    cert_different_pk_err);
292 
293 	if (error < 0)
294 		goto free_cert;
295 
296 	/* No error, a positive value means the name is duplicated */
297 	if (error)
298 		(*duplicated) = true;
299 	error = 0;
300 
301 free_cert:
302 	X509_free(rcvd_cert);
303 free_uri:
304 	uri_refput(uri);
305 	return error;
306 }
307 
308 static int
validate_subject(X509 * cert)309 validate_subject(X509 *cert)
310 {
311 	struct validation *state;
312 	struct rfc5280_name *name;
313 	int error;
314 
315 	state = state_retrieve();
316 	if (state == NULL)
317 		return -EINVAL;
318 
319 	error = x509_name_decode(X509_get_subject_name(cert), "subject", &name);
320 	if (error)
321 		return error;
322 	pr_val_debug("Subject: %s", x509_name_commonName(name));
323 
324 	error = x509stack_store_subject(validation_certstack(state), name,
325 	    check_dup_public_key, cert);
326 
327 	x509_name_put(name);
328 	return error;
329 }
330 
331 static int
root_different_alg_err(void)332 root_different_alg_err(void)
333 {
334 	return pr_val_err("TAL's public key algorithm is different than the root certificate's public key algorithm.");
335 }
336 
337 static int
root_different_pk_err(void)338 root_different_pk_err(void)
339 {
340 	return pr_val_err("TAL's public key is different than the root certificate's public key.");
341 }
342 
343 static int
validate_spki(X509_PUBKEY * cert_spki)344 validate_spki(X509_PUBKEY *cert_spki)
345 {
346 	struct validation *state;
347 	struct tal *tal;
348 
349 	X509_PUBKEY *tal_spki;
350 	unsigned char const *_tal_spki;
351 	size_t _tal_spki_len;
352 
353 	state = state_retrieve();
354 	if (state == NULL)
355 		return -EINVAL;
356 
357 	tal = validation_tal(state);
358 	if (tal == NULL)
359 		pr_crit("Validation state has no TAL.");
360 
361 	/*
362 	 * We have a problem at this point:
363 	 *
364 	 * RFC 8630 says "The public key used to verify the trust anchor MUST be
365 	 * the same as the subjectPublicKeyInfo in the CA certificate and in the
366 	 * TAL."
367 	 *
368 	 * It seems that libcrypto decodes the Subject Public Key Info (SPKI)
369 	 * and gives us the Subject Public Key (SPK) instead. So we can't just
370 	 * compare the two keys just like that.
371 	 *
372 	 * Luckily, the only other component of the SPKI is the algorithm
373 	 * identifier. So doing a field-by-field comparison is not too much
374 	 * trouble. We'll have to decode the TAL's SPKI though.
375 	 *
376 	 * Reminder: "X509_PUBKEY" and "Subject Public Key Info" are synonyms.
377 	 */
378 
379 	fnstack_push(tal_get_file_name(tal));
380 	tal_get_spki(tal, &_tal_spki, &_tal_spki_len);
381 	tal_spki = d2i_X509_PUBKEY(NULL, &_tal_spki, _tal_spki_len);
382 	fnstack_pop();
383 
384 	if (tal_spki == NULL) {
385 		op_crypto_err("The TAL's public key cannot be decoded");
386 		goto fail1;
387 	}
388 
389 	if (spki_cmp(tal_spki, cert_spki, root_different_alg_err,
390 	    root_different_pk_err) != 0)
391 		goto fail2;
392 
393 	X509_PUBKEY_free(tal_spki);
394 	validation_pubkey_valid(state);
395 	return 0;
396 
397 fail2:
398 	X509_PUBKEY_free(tal_spki);
399 fail1:
400 	validation_pubkey_invalid(state);
401 	return -EINVAL;
402 }
403 
404 /*
405  * RFC 7935 Section 3:
406  * "The RSA key pairs used to compute the signatures MUST have a
407  * 2048-bit modulus and a public exponent (e) of 65,537."
408  */
409 static int
validate_subject_public_key(X509_PUBKEY * pubkey)410 validate_subject_public_key(X509_PUBKEY *pubkey)
411 {
412 #define MODULUS 2048
413 #define EXPONENT "65537"
414 	const RSA *rsa;
415 	const BIGNUM *exp;
416 	char *exp_str;
417 	int modulus;
418 	int error;
419 
420 	rsa = EVP_PKEY_get0_RSA(X509_PUBKEY_get0(pubkey));
421 	if (rsa == NULL)
422 		return val_crypto_err("EVP_PKEY_get0_RSA() returned NULL");
423 
424 	modulus = RSA_bits(rsa);
425 	if (modulus != MODULUS)
426 		return pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) modulus is %d bits, not %d bits.",
427 		    modulus, MODULUS);
428 
429 	RSA_get0_key(rsa, NULL, &exp, NULL);
430 	if (exp == NULL)
431 		return pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) exponent isn't set, must be "
432 		    EXPONENT " bits.");
433 
434 	exp_str = BN_bn2dec(exp);
435 	if (exp_str == NULL)
436 		return val_crypto_err("Couldn't get subjectPublicKey exponent string");
437 
438 	if (strcmp(EXPONENT, exp_str) != 0) {
439 		error = pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) exponent is %s, must be "
440 		    EXPONENT " bits.", exp_str);
441 		free(exp_str);
442 		return error;
443 	}
444 	free(exp_str);
445 
446 	return 0;
447 #undef EXPONENT
448 #undef MODULUS
449 }
450 
451 static int
validate_public_key(X509 * cert,enum cert_type type)452 validate_public_key(X509 *cert, enum cert_type type)
453 {
454 	X509_PUBKEY *pubkey;
455 	X509_ALGOR *pa;
456 	ASN1_OBJECT *alg;
457 	int ok;
458 	int error;
459 
460 	/* Reminder: X509_PUBKEY is the same as SubjectPublicKeyInfo. */
461 	pubkey = X509_get_X509_PUBKEY(cert);
462 	if (pubkey == NULL)
463 		return val_crypto_err("X509_get_X509_PUBKEY() returned NULL");
464 
465 	ok = X509_PUBKEY_get0_param(&alg, NULL, NULL, &pa, pubkey);
466 	if (!ok)
467 		return val_crypto_err("X509_PUBKEY_get0_param() returned %d", ok);
468 
469 	if (type == BGPSEC)
470 		return validate_certificate_public_key_algorithm_bgpsec(pa);
471 
472 	error = validate_certificate_public_key_algorithm(pa);
473 	if (error)
474 		return error;
475 
476 	error = validate_subject_public_key(pubkey);
477 	if (error)
478 		return error;
479 
480 	/*
481 	 * BTW: WTF. About that algorithm:
482 	 *
483 	 * RFC 6485: "The value for the associated parameters from that clause
484 	 * [RFC4055] MUST also be used for the parameters field."
485 	 * RFC 4055: "Implementations MUST accept the parameters being absent as
486 	 * well as present."
487 	 *
488 	 * Either the RFCs found a convoluted way of saying nothing, or I'm not
489 	 * getting the message.
490 	 */
491 
492 	if (type == TA) {
493 		error = validate_spki(pubkey);
494 		if (error)
495 			return error;
496 	}
497 
498 	return 0;
499 }
500 
501 int
certificate_validate_rfc6487(X509 * cert,enum cert_type type)502 certificate_validate_rfc6487(X509 *cert, enum cert_type type)
503 {
504 	int error;
505 
506 	/*
507 	 * I'm simply assuming that libcrypto implements RFC 5280. (I mean, it's
508 	 * not really stated anywhere AFAIK, but since OpenSSL is supposedly the
509 	 * quintessential crypto lib implementation, and RFC 5280 is supposedly
510 	 * the generic certificate RFC, it's fair to say it does a well enough
511 	 * job for all practical purposes.)
512 	 *
513 	 * But it's obvious that we can't assume that LibreSSL implements RFC
514 	 * 6487. It clearly doesn't.
515 	 *
516 	 * So here we go.
517 	 */
518 
519 	/* rfc6487#section-4.1 */
520 	if (X509_get_version(cert) != 2)
521 		return pr_val_err("Certificate version is not v3.");
522 
523 	/* rfc6487#section-4.2 */
524 	error = validate_serial_number(cert);
525 	if (error)
526 		return error;
527 
528 	/* rfc6487#section-4.3 */
529 	error = validate_signature_algorithm(cert);
530 	if (error)
531 		return error;
532 
533 	/* rfc6487#section-4.4 */
534 	error = validate_issuer(cert, type == TA);
535 	if (error)
536 		return error;
537 
538 	/*
539 	 * rfc6487#section-4.5
540 	 *
541 	 * "An issuer SHOULD use a different subject name if the subject's
542 	 * key pair has changed" (it's a SHOULD, so [for now] avoid validation)
543 	 */
544 	error = validate_subject(cert);
545 	if (error)
546 		return error;
547 
548 	/* rfc6487#section-4.6 */
549 	/* libcrypto already does this. */
550 
551 	/* rfc6487#section-4.7 */
552 	/* Fragment of rfc8630#section-2.3 */
553 	error = validate_public_key(cert, type);
554 	if (error)
555 		return error;
556 
557 	/* We'll validate extensions later. */
558 	return 0;
559 }
560 
561 struct progress {
562 	size_t offset;
563 	size_t remaining;
564 };
565 
566 /**
567  * Skip the "T" part of a TLV.
568  */
569 static void
skip_t(ANY_t * content,struct progress * p,unsigned int tag)570 skip_t(ANY_t *content, struct progress *p, unsigned int tag)
571 {
572 	/*
573 	 * BTW: I made these errors critical because the signedData is supposed
574 	 * to be validated by this point.
575 	 */
576 
577 	if (content->buf[p->offset] != tag)
578 		pr_crit("Expected tag 0x%x, got 0x%x", tag,
579 		    content->buf[p->offset]);
580 
581 	if (p->remaining == 0)
582 		pr_crit("Buffer seems to be truncated");
583 	p->offset++;
584 	p->remaining--;
585 }
586 
587 /**
588  * Skip the "TL" part of a TLV.
589  */
590 static void
skip_tl(ANY_t * content,struct progress * p,unsigned int tag)591 skip_tl(ANY_t *content, struct progress *p, unsigned int tag)
592 {
593 	ssize_t len_len; /* Length of the length field */
594 	ber_tlv_len_t value_len; /* Length of the value */
595 
596 	skip_t(content, p, tag);
597 
598 	len_len = ber_fetch_length(true, &content->buf[p->offset], p->remaining,
599 	    &value_len);
600 	if (len_len == -1)
601 		pr_crit("Could not decipher length (Cause is unknown)");
602 	if (len_len == 0)
603 		pr_crit("Buffer seems to be truncated");
604 
605 	p->offset += len_len;
606 	p->remaining -= len_len;
607 }
608 
609 static void
skip_tlv(ANY_t * content,struct progress * p,unsigned int tag)610 skip_tlv(ANY_t *content, struct progress *p, unsigned int tag)
611 {
612 	int is_constructed;
613 	int skip;
614 
615 	is_constructed = BER_TLV_CONSTRUCTED(&content->buf[p->offset]);
616 
617 	skip_t(content, p, tag);
618 
619 	skip = ber_skip_length(NULL, is_constructed, &content->buf[p->offset],
620 	    p->remaining);
621 	if (skip == -1)
622 		pr_crit("Could not skip length (Cause is unknown)");
623 	if (skip == 0)
624 		pr_crit("Buffer seems to be truncated");
625 
626 	p->offset += skip;
627 	p->remaining -= skip;
628 }
629 
630 /**
631  * A structure that points to the LV part of a signedAttrs TLV.
632  */
633 struct encoded_signedAttrs {
634 	const uint8_t *buffer;
635 	ber_tlv_len_t size;
636 };
637 
638 static void
find_signedAttrs(ANY_t * signedData,struct encoded_signedAttrs * result)639 find_signedAttrs(ANY_t *signedData, struct encoded_signedAttrs *result)
640 {
641 #define INTEGER_TAG		0x02
642 #define SEQUENCE_TAG		0x30
643 #define SET_TAG			0x31
644 
645 	struct progress p;
646 	ssize_t len_len;
647 
648 	/* Reference: rfc5652-12.1.asn1 */
649 
650 	p.offset = 0;
651 	p.remaining = signedData->size;
652 
653 	/* SignedData: SEQUENCE */
654 	skip_tl(signedData, &p, SEQUENCE_TAG);
655 
656 	/* SignedData.version: CMSVersion -> INTEGER */
657 	skip_tlv(signedData, &p, INTEGER_TAG);
658 	/* SignedData.digestAlgorithms: DigestAlgorithmIdentifiers -> SET */
659 	skip_tlv(signedData, &p, SET_TAG);
660 	/* SignedData.encapContentInfo: EncapsulatedContentInfo -> SEQUENCE */
661 	skip_tlv(signedData, &p, SEQUENCE_TAG);
662 	/* SignedData.certificates: CertificateSet -> SET */
663 	skip_tlv(signedData, &p, 0xA0);
664 	/* SignedData.signerInfos: SignerInfos -> SET OF SEQUENCE */
665 	skip_tl(signedData, &p, SET_TAG);
666 	skip_tl(signedData, &p, SEQUENCE_TAG);
667 
668 	/* SignedData.signerInfos.version: CMSVersion -> INTEGER */
669 	skip_tlv(signedData, &p, INTEGER_TAG);
670 	/*
671 	 * SignedData.signerInfos.sid: SignerIdentifier -> CHOICE -> always
672 	 * subjectKeyIdentifier, which is a [0].
673 	 */
674 	skip_tlv(signedData, &p, 0x80);
675 	/* SignedData.signerInfos.digestAlgorithm: DigestAlgorithmIdentifier
676 	 * -> AlgorithmIdentifier -> SEQUENCE */
677 	skip_tlv(signedData, &p, SEQUENCE_TAG);
678 
679 	/* SignedData.signerInfos.signedAttrs: SignedAttributes -> SET */
680 	/* We will need to replace the tag 0xA0 with 0x31, so skip it as well */
681 	skip_t(signedData, &p, 0xA0);
682 
683 	result->buffer = &signedData->buf[p.offset];
684 	len_len = ber_fetch_length(true, result->buffer,
685 	    p.remaining, &result->size);
686 	if (len_len == -1)
687 		pr_crit("Could not decipher length (Cause is unknown)");
688 	if (len_len == 0)
689 		pr_crit("Buffer seems to be truncated");
690 	result->size += len_len;
691 }
692 
693 /*
694  * TODO (next iteration) there exists a thing called "PKCS7_NOVERIFY", which
695  * skips unnecessary validations when using the PKCS7 API. Maybe the methods
696  * we're using have something similar.
697  */
698 int
certificate_validate_signature(X509 * cert,ANY_t * signedData,SignatureValue_t * signature)699 certificate_validate_signature(X509 *cert, ANY_t *signedData,
700     SignatureValue_t *signature)
701 {
702 	static const uint8_t EXPLICIT_SET_OF_TAG = 0x31;
703 
704 	X509_PUBKEY *public_key;
705 	EVP_MD_CTX *ctx;
706 	struct encoded_signedAttrs signedAttrs;
707 	int error;
708 
709 	public_key = X509_get_X509_PUBKEY(cert);
710 	if (public_key == NULL)
711 		return val_crypto_err("Certificate seems to lack a public key");
712 
713 	/* Create the Message Digest Context */
714 	ctx = EVP_MD_CTX_create();
715 	if (ctx == NULL)
716 		return val_crypto_err("EVP_MD_CTX_create() error");
717 
718 	if (1 != EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL,
719 	    X509_PUBKEY_get0(public_key))) {
720 		error = val_crypto_err("EVP_DigestVerifyInit() error");
721 		goto end;
722 	}
723 
724 	/*
725 	 * When the [signedAttrs] field is present
726 	 * (...),
727 	 * the result is the message
728 	 * digest of the complete DER encoding of the SignedAttrs value
729 	 * contained in the signedAttrs field.
730 	 * (...)
731 	 * A separate encoding
732 	 * of the signedAttrs field is performed for message digest calculation.
733 	 * The IMPLICIT [0] tag in the signedAttrs is not used for the DER
734 	 * encoding, rather an EXPLICIT SET OF tag is used.  That is, the DER
735 	 * encoding of the EXPLICIT SET OF tag, rather than of the IMPLICIT [0]
736 	 * tag, MUST be included in the message digest calculation along with
737 	 * the length and content octets of the SignedAttributes value.
738 	 *               (https://tools.ietf.org/html/rfc5652#section-5.4)
739 	 *
740 	 * FYI: IMPLICIT [0] is 0xA0, and EXPLICIT SET OF is 0x31.
741 	 *
742 	 * I can officially declare that these requirements are a gargantuan
743 	 * pain in the ass. Through the validation, we need access to the
744 	 * signedAttrs thingo in both encoded and decoded versions.
745 	 * (We need the decoded version for the sake of profile validation
746 	 * during validate_signed_attrs(), and the encoded version to check
747 	 * the signature of the SO right here.)
748 	 * Getting the encoded version is the problem. We have two options:
749 	 *
750 	 * 1. Re-encode the decoded version.
751 	 * 2. Extract the encoded version from the original BER SignedData.
752 	 *
753 	 * The first one sounded less efficient but more straightforward, but
754 	 * I couldn't pull it off because there's some memory bug with asn1c's
755 	 * encoding function that core dumps the fuck out of everything. It's
756 	 * caused by undefined behavior that triggers who knows where.
757 	 *
758 	 * There's another problem with that approach: If we DER-encode the
759 	 * signedAttrs, we have no guarantee that the signature will match
760 	 * because of the very real possibility that whoever signed used BER
761 	 * instead.
762 	 *
763 	 * One drawback for the second option is that obviously there's no API
764 	 * for it. asn1c encodes and decodes; there's no method for extracting
765 	 * a particular encoded object out of an encoded container. We need to
766 	 * do the parsing ourselves. But it's not that bad because of of
767 	 * ber_fetch_length() and ber_skip_length().
768 	 *
769 	 * Second option it is.
770 	 */
771 
772 	find_signedAttrs(signedData, &signedAttrs);
773 
774 	error = EVP_DigestVerifyUpdate(ctx, &EXPLICIT_SET_OF_TAG,
775 	    sizeof(EXPLICIT_SET_OF_TAG));
776 	if (1 != error) {
777 		error = val_crypto_err("EVP_DigestVerifyInit() error");
778 		goto end;
779 	}
780 
781 	error = EVP_DigestVerifyUpdate(ctx, signedAttrs.buffer,
782 	    signedAttrs.size);
783 	if (1 != error) {
784 		error = val_crypto_err("EVP_DigestVerifyInit() error");
785 		goto end;
786 	}
787 
788 	if (1 != EVP_DigestVerifyFinal(ctx, signature->buf, signature->size)) {
789 		error = val_crypto_err("Signed Object's signature is invalid");
790 		goto end;
791 	}
792 
793 	error = 0;
794 
795 end:
796 	EVP_MD_CTX_free(ctx);
797 	return error;
798 }
799 
800 int
certificate_load(struct rpki_uri * uri,X509 ** result)801 certificate_load(struct rpki_uri *uri, X509 **result)
802 {
803 	X509 *cert = NULL;
804 	BIO *bio;
805 	int error;
806 
807 	bio = BIO_new(BIO_s_file());
808 	if (bio == NULL)
809 		return val_crypto_err("BIO_new(BIO_s_file()) returned NULL");
810 	if (BIO_read_filename(bio, uri_get_local(uri)) <= 0) {
811 		error = val_crypto_err("Error reading certificate");
812 		goto end;
813 	}
814 
815 	cert = d2i_X509_bio(bio, NULL);
816 	if (cert == NULL) {
817 		error = val_crypto_err("Error parsing certificate");
818 		goto end;
819 	}
820 
821 	*result = cert;
822 	error = 0;
823 end:
824 	BIO_free(bio);
825 	return error;
826 }
827 
828 /*
829  * Allocates a clone of @original_crl and pushes it to @crls.
830  *
831  * Don't forget to pop from @crls and release the popped CRL.
832  */
833 static int
update_crl_time(STACK_OF (X509_CRL)* crls,X509_CRL * original_crl)834 update_crl_time(STACK_OF(X509_CRL) *crls, X509_CRL *original_crl)
835 {
836 	ASN1_TIME *tm;
837 	X509_CRL *clone;
838 	time_t t;
839 	int error;
840 
841 	error = get_current_time(&t);
842 	if (error)
843 		return error;
844 
845 	/*
846 	 * Yes, this is an awful hack. The other options were:
847 	 * - Use X509_V_FLAG_NO_CHECK_TIME parameter, but this avoids also the
848 	 *   time check for the certificate.
849 	 * - Avoid whole CRL check, but since we don't implement the
850 	 *   certificate chain validation, we can't assure that the CRL has
851 	 *   only the nextUpdate field wrong (maybe there are other invalid
852 	 *   things).
853 	 */
854 	tm = ASN1_TIME_adj(NULL, t, 0, 60);
855 	if (tm == NULL)
856 		return pr_val_err("Crypto function ASN1_TIME_adj() returned error");
857 
858 	clone = X509_CRL_dup(original_crl);
859 	if (clone == NULL) {
860 		ASN1_STRING_free(tm);
861 		return pr_enomem();
862 	}
863 
864 	X509_CRL_set1_nextUpdate(clone, tm);
865 	ASN1_STRING_free(tm);
866 
867 	error = sk_X509_CRL_push(crls, clone);
868 	if (error <= 0) {
869 		X509_CRL_free(clone);
870 		return val_crypto_err("Error calling sk_X509_CRL_push()");
871 	}
872 
873 	return 0;
874 }
875 
876 /*
877  * Retry certificate validation without CRL time validation.
878  */
879 static int
verify_cert_crl_stale(struct validation * state,X509 * cert,STACK_OF (X509_CRL)* crls)880 verify_cert_crl_stale(struct validation *state, X509 *cert,
881     STACK_OF(X509_CRL) *crls)
882 {
883 	X509_STORE_CTX *ctx;
884 	X509_CRL *original_crl, *clone;
885 	int error;
886 	int ok;
887 
888 	ctx = X509_STORE_CTX_new();
889 	if (ctx == NULL) {
890 		val_crypto_err("X509_STORE_CTX_new() returned NULL");
891 		return -EINVAL;
892 	}
893 
894 	/* Returns 0 or 1 , all callers test ! only. */
895 	ok = X509_STORE_CTX_init(ctx, validation_store(state), cert, NULL);
896 	if (!ok) {
897 		error = val_crypto_err("X509_STORE_CTX_init() returned %d", ok);
898 		goto release_ctx;
899 	}
900 
901 	original_crl = sk_X509_CRL_pop(crls);
902 	error = update_crl_time(crls, original_crl);
903 	if (error)
904 		goto push_original;
905 
906 	X509_STORE_CTX_trusted_stack(ctx,
907 	    certstack_get_x509s(validation_certstack(state)));
908 	X509_STORE_CTX_set0_crls(ctx, crls);
909 
910 	ok = X509_verify_cert(ctx);
911 	if (ok > 0) {
912 		error = 0; /* Happy path */
913 		goto pop_clone;
914 	}
915 
916 	error = X509_STORE_CTX_get_error(ctx);
917 	if (error)
918 		error = pr_val_err("Certificate validation failed: %s",
919 		    X509_verify_cert_error_string(error));
920 	else
921 		error = val_crypto_err("Certificate validation failed: %d", ok);
922 
923 pop_clone:
924 	clone = sk_X509_CRL_pop(crls);
925 	if (clone == NULL)
926 		error = pr_val_err("Error calling sk_X509_CRL_pop()");
927 	else
928 		X509_CRL_free(clone);
929 push_original:
930 	/* Try to return to the "regular" CRL chain */
931 	ok = sk_X509_CRL_push(crls, original_crl);
932 	if (ok <= 0)
933 		error = val_crypto_err("Could not return CRL to a CRL stack");
934 release_ctx:
935 	X509_STORE_CTX_free(ctx);
936 	return error;
937 
938 }
939 
940 int
certificate_validate_chain(X509 * cert,STACK_OF (X509_CRL)* crls)941 certificate_validate_chain(X509 *cert, STACK_OF(X509_CRL) *crls)
942 {
943 	/* Reference: openbsd/src/usr.bin/openssl/verify.c */
944 
945 	struct validation *state;
946 	X509_STORE_CTX *ctx;
947 	int ok;
948 	int error;
949 
950 	if (crls == NULL)
951 		return 0; /* Certificate is TA; no chain validation needed. */
952 
953 	state = state_retrieve();
954 	if (state == NULL)
955 		return -EINVAL;
956 
957 	ctx = X509_STORE_CTX_new();
958 	if (ctx == NULL) {
959 		val_crypto_err("X509_STORE_CTX_new() returned NULL");
960 		return -EINVAL;
961 	}
962 
963 	/* Returns 0 or 1 , all callers test ! only. */
964 	ok = X509_STORE_CTX_init(ctx, validation_store(state), cert, NULL);
965 	if (!ok) {
966 		val_crypto_err("X509_STORE_CTX_init() returned %d", ok);
967 		goto abort;
968 	}
969 
970 	X509_STORE_CTX_trusted_stack(ctx,
971 	    certstack_get_x509s(validation_certstack(state)));
972 	X509_STORE_CTX_set0_crls(ctx, crls);
973 
974 	/*
975 	 * HERE'S THE MEAT OF LIBCRYPTO'S VALIDATION.
976 	 *
977 	 * Can return negative codes, all callers do <= 0.
978 	 *
979 	 * Debugging BTW: If you're looking for ctx->verify,
980 	 * it might be internal_verify() from x509_vfy.c.
981 	 */
982 	ok = X509_verify_cert(ctx);
983 	if (ok <= 0) {
984 		/*
985 		 * ARRRRGGGGGGGGGGGGG
986 		 * Do not use val_crypto_err() here; for some reason the proper
987 		 * error code is stored in the context.
988 		 */
989 		error = X509_STORE_CTX_get_error(ctx);
990 		if (error) {
991 			if (error != X509_V_ERR_CRL_HAS_EXPIRED) {
992 				pr_val_err("Certificate validation failed: %s",
993 				    X509_verify_cert_error_string(error));
994 				goto abort;
995 			}
996 			if (incidence(INID_CRL_STALE, "CRL is stale/expired"))
997 				goto abort;
998 
999 			X509_STORE_CTX_free(ctx);
1000 			if (incidence_get_action(INID_CRL_STALE) == INAC_WARN)
1001 				pr_val_info("Re-validating avoiding CRL time check");
1002 			return verify_cert_crl_stale(state, cert, crls);
1003 		} else {
1004 			/*
1005 			 * ...But don't trust X509_STORE_CTX_get_error() either.
1006 			 * That said, there's not much to do about !error,
1007 			 * so hope for the best.
1008 			 */
1009 			val_crypto_err("Certificate validation failed: %d", ok);
1010 		}
1011 
1012 		goto abort;
1013 	}
1014 
1015 	X509_STORE_CTX_free(ctx);
1016 	return 0;
1017 
1018 abort:
1019 	X509_STORE_CTX_free(ctx);
1020 	return -EINVAL;
1021 }
1022 
1023 static int
handle_ip_extension(X509_EXTENSION * ext,struct resources * resources)1024 handle_ip_extension(X509_EXTENSION *ext, struct resources *resources)
1025 {
1026 	ASN1_OCTET_STRING *string;
1027 	struct IPAddrBlocks *blocks;
1028 	OCTET_STRING_t *family;
1029 	int i;
1030 	int error;
1031 
1032 	string = X509_EXTENSION_get_data(ext);
1033 	error = asn1_decode(string->data, string->length, &asn_DEF_IPAddrBlocks,
1034 	    (void **) &blocks, true, false);
1035 	if (error)
1036 		return error;
1037 
1038 	/*
1039 	 * rfc3779#section-2.2.3.3, rfc6487#section-4.8.10:
1040 	 * We're expecting either one element (IPv4 or IPv6) or two elements
1041 	 * (IPv4 then IPv6).
1042 	 */
1043 	switch (blocks->list.count) {
1044 	case 1:
1045 		break;
1046 	case 2:
1047 		family = &blocks->list.array[0]->addressFamily;
1048 		if (get_addr_family(family) != AF_INET) {
1049 			error = pr_val_err("First IP address block listed is not v4.");
1050 			goto end;
1051 		}
1052 		family = &blocks->list.array[1]->addressFamily;
1053 		if (get_addr_family(family) != AF_INET6) {
1054 			error = pr_val_err("Second IP address block listed is not v6.");
1055 			goto end;
1056 		}
1057 		break;
1058 	default:
1059 		error = pr_val_err("Got %d IP address blocks Expected; 1 or 2 expected.",
1060 		    blocks->list.count);
1061 		goto end;
1062 	}
1063 
1064 	for (i = 0; i < blocks->list.count && !error; i++)
1065 		error = resources_add_ip(resources, blocks->list.array[i]);
1066 
1067 end:
1068 	ASN_STRUCT_FREE(asn_DEF_IPAddrBlocks, blocks);
1069 	return error;
1070 }
1071 
1072 static int
handle_asn_extension(X509_EXTENSION * ext,struct resources * resources,bool allow_inherit)1073 handle_asn_extension(X509_EXTENSION *ext, struct resources *resources,
1074     bool allow_inherit)
1075 {
1076 	ASN1_OCTET_STRING *string;
1077 	struct ASIdentifiers *ids;
1078 	int error;
1079 
1080 	string = X509_EXTENSION_get_data(ext);
1081 	error = asn1_decode(string->data, string->length,
1082 	    &asn_DEF_ASIdentifiers, (void **) &ids, true, false);
1083 	if (error)
1084 		return error;
1085 
1086 	error = resources_add_asn(resources, ids, allow_inherit);
1087 
1088 	ASN_STRUCT_FREE(asn_DEF_ASIdentifiers, ids);
1089 	return error;
1090 }
1091 
1092 static int
__certificate_get_resources(X509 * cert,struct resources * resources,int addr_nid,int asn_nid,int bad_addr_nid,int bad_asn_nid,char const * policy_rfc,char const * bad_ext_rfc,bool allow_asn_inherit)1093 __certificate_get_resources(X509 *cert, struct resources *resources,
1094     int addr_nid, int asn_nid, int bad_addr_nid, int bad_asn_nid,
1095     char const *policy_rfc, char const *bad_ext_rfc, bool allow_asn_inherit)
1096 {
1097 	X509_EXTENSION *ext;
1098 	int nid;
1099 	int i;
1100 	int error;
1101 	bool ip_ext_found = false;
1102 	bool asn_ext_found = false;
1103 
1104 	/* Reference: X509_get_ext_d2i */
1105 	/* rfc6487#section-2 */
1106 
1107 	for (i = 0; i < X509_get_ext_count(cert); i++) {
1108 		ext = X509_get_ext(cert, i);
1109 		nid = OBJ_obj2nid(X509_EXTENSION_get_object(ext));
1110 
1111 		if (nid == addr_nid) {
1112 			if (ip_ext_found)
1113 				return pr_val_err("Multiple IP extensions found.");
1114 			if (!X509_EXTENSION_get_critical(ext))
1115 				return pr_val_err("The IP extension is not marked as critical.");
1116 
1117 			pr_val_debug("IP {");
1118 			error = handle_ip_extension(ext, resources);
1119 			pr_val_debug("}");
1120 			ip_ext_found = true;
1121 
1122 			if (error)
1123 				return error;
1124 
1125 		} else if (nid == asn_nid) {
1126 			if (asn_ext_found)
1127 				return pr_val_err("Multiple AS extensions found.");
1128 			if (!X509_EXTENSION_get_critical(ext))
1129 				return pr_val_err("The AS extension is not marked as critical.");
1130 
1131 			pr_val_debug("ASN {");
1132 			error = handle_asn_extension(ext, resources,
1133 			    allow_asn_inherit);
1134 			pr_val_debug("}");
1135 			asn_ext_found = true;
1136 
1137 			if (error)
1138 				return error;
1139 
1140 		} else if (nid == bad_addr_nid) {
1141 			return pr_val_err("Certificate has an RFC%s policy, but contains an RFC%s IP extension.",
1142 			    policy_rfc, bad_ext_rfc);
1143 		} else if (nid == bad_asn_nid) {
1144 			return pr_val_err("Certificate has an RFC%s policy, but contains an RFC%s ASN extension.",
1145 			    policy_rfc, bad_ext_rfc);
1146 		}
1147 	}
1148 
1149 	if (!ip_ext_found && !asn_ext_found)
1150 		return pr_val_err("Certificate lacks both IP and AS extension.");
1151 
1152 	return 0;
1153 }
1154 
1155 /**
1156  * Copies the resources from @cert to @resources.
1157  */
1158 int
certificate_get_resources(X509 * cert,struct resources * resources,enum cert_type type)1159 certificate_get_resources(X509 *cert, struct resources *resources,
1160     enum cert_type type)
1161 {
1162 	enum rpki_policy policy;
1163 
1164 	policy = resources_get_policy(resources);
1165 	switch (policy) {
1166 	case RPKI_POLICY_RFC6484:
1167 		return __certificate_get_resources(cert, resources,
1168 		    NID_sbgp_ipAddrBlock, NID_sbgp_autonomousSysNum,
1169 		    nid_ipAddrBlocksv2(), nid_autonomousSysIdsv2(),
1170 		    "6484", "8360", type != BGPSEC);
1171 	case RPKI_POLICY_RFC8360:
1172 		return __certificate_get_resources(cert, resources,
1173 		    nid_ipAddrBlocksv2(), nid_autonomousSysIdsv2(),
1174 		    NID_sbgp_ipAddrBlock, NID_sbgp_autonomousSysNum,
1175 		    "8360", "6484", type != BGPSEC);
1176 	}
1177 
1178 	pr_crit("Unknown policy: %u", policy);
1179 }
1180 
1181 static bool
is_rsync(ASN1_IA5STRING * uri)1182 is_rsync(ASN1_IA5STRING *uri)
1183 {
1184 	static char const *const PREFIX = "rsync://";
1185 	size_t prefix_len = strlen(PREFIX);
1186 
1187 	return (uri->length >= prefix_len)
1188 	    ? (strncmp((char *) uri->data, PREFIX, strlen(PREFIX)) == 0)
1189 	    : false;
1190 }
1191 
1192 static bool
is_rsync_uri(GENERAL_NAME * name)1193 is_rsync_uri(GENERAL_NAME *name)
1194 {
1195 	return name->type == GEN_URI && is_rsync(name->d.GN_URI);
1196 }
1197 
1198 static int
handle_rpkiManifest(struct rpki_uri * uri,uint8_t pos,void * arg)1199 handle_rpkiManifest(struct rpki_uri *uri, uint8_t pos, void *arg)
1200 {
1201 	struct sia_uri *mft = arg;
1202 	mft->position = pos;
1203 	mft->uri = uri;
1204 	uri_refget(uri);
1205 	return 0;
1206 }
1207 
1208 static int
handle_caRepository(struct rpki_uri * uri,uint8_t pos,void * arg)1209 handle_caRepository(struct rpki_uri *uri, uint8_t pos, void *arg)
1210 {
1211 	struct sia_uri *repo = arg;
1212 	pr_val_debug("caRepository: %s", uri_val_get_printable(uri));
1213 	repo->position = pos;
1214 	repo->uri = uri;
1215 	uri_refget(uri);
1216 	return 0;
1217 }
1218 
1219 static int
handle_rpkiNotify(struct rpki_uri * uri,uint8_t pos,void * arg)1220 handle_rpkiNotify(struct rpki_uri *uri, uint8_t pos, void *arg)
1221 {
1222 	struct sia_uri *notify = arg;
1223 	pr_val_debug("rpkiNotify: %s", uri_val_get_printable(uri));
1224 	notify->position = pos;
1225 	notify->uri = uri;
1226 	uri_refget(uri);
1227 	return 0;
1228 }
1229 
1230 static int
handle_signedObject(struct rpki_uri * uri,uint8_t pos,void * arg)1231 handle_signedObject(struct rpki_uri *uri, uint8_t pos, void *arg)
1232 {
1233 	struct certificate_refs *refs = arg;
1234 	pr_val_debug("signedObject: %s", uri_val_get_printable(uri));
1235 	refs->signedObject = uri;
1236 	uri_refget(uri);
1237 	return 0;
1238 }
1239 
1240 static int
handle_bc(X509_EXTENSION * ext,void * arg)1241 handle_bc(X509_EXTENSION *ext, void *arg)
1242 {
1243 	BASIC_CONSTRAINTS *bc;
1244 	int error;
1245 
1246 	bc = X509V3_EXT_d2i(ext);
1247 	if (bc == NULL)
1248 		return cannot_decode(ext_bc());
1249 
1250 	/*
1251 	 * 'The issuer determines whether the "cA" boolean is set.'
1252 	 * ................................. Uh-huh. So nothing then.
1253 	 * Well, libcrypto should do the RFC 5280 thing with it anyway.
1254 	 */
1255 
1256 	error = (bc->pathlen == NULL)
1257 	    ? 0
1258 	    : pr_val_err("%s extension contains a Path Length Constraint.",
1259 	          ext_bc()->name);
1260 
1261 	BASIC_CONSTRAINTS_free(bc);
1262 	return error;
1263 }
1264 
1265 static int
handle_ski_ca(X509_EXTENSION * ext,void * arg)1266 handle_ski_ca(X509_EXTENSION *ext, void *arg)
1267 {
1268 	ASN1_OCTET_STRING *ski;
1269 	int error;
1270 
1271 	ski = X509V3_EXT_d2i(ext);
1272 	if (ski == NULL)
1273 		return cannot_decode(ext_ski());
1274 
1275 	error = validate_public_key_hash(arg, ski);
1276 
1277 	ASN1_OCTET_STRING_free(ski);
1278 	return error;
1279 }
1280 
1281 static int
handle_ski_ee(X509_EXTENSION * ext,void * arg)1282 handle_ski_ee(X509_EXTENSION *ext, void *arg)
1283 {
1284 	struct ski_arguments *args;
1285 	ASN1_OCTET_STRING *ski;
1286 	OCTET_STRING_t *sid;
1287 	int error;
1288 
1289 	ski = X509V3_EXT_d2i(ext);
1290 	if (ski == NULL)
1291 		return cannot_decode(ext_ski());
1292 
1293 	args = arg;
1294 	error = validate_public_key_hash(args->cert, ski);
1295 	if (error)
1296 		goto end;
1297 
1298 	/* rfc6488#section-2.1.6.2 */
1299 	/* rfc6488#section-3.1.c 2/2 */
1300 	sid = args->sid;
1301 	if (ski->length != sid->size
1302 	    || memcmp(ski->data, sid->buf, sid->size) != 0) {
1303 		error = pr_val_err("The EE certificate's subjectKeyIdentifier does not equal the Signed Object's sid.");
1304 	}
1305 
1306 end:
1307 	ASN1_OCTET_STRING_free(ski);
1308 	return error;
1309 }
1310 
1311 static int
handle_aki_ta(X509_EXTENSION * ext,void * arg)1312 handle_aki_ta(X509_EXTENSION *ext, void *arg)
1313 {
1314 	struct AUTHORITY_KEYID_st *aki;
1315 	ASN1_OCTET_STRING *ski;
1316 	int error;
1317 
1318 	aki = X509V3_EXT_d2i(ext);
1319 	if (aki == NULL)
1320 		return cannot_decode(ext_aki());
1321 	if (aki->keyid == NULL) {
1322 		error = pr_val_err("The '%s' extension lacks a keyIdentifier.",
1323 		    ext_aki()->name);
1324 		goto revert_aki;
1325 	}
1326 
1327 	ski = X509_get_ext_d2i(arg, NID_subject_key_identifier, NULL, NULL);
1328 	if (ski == NULL) {
1329 		pr_val_err("Certificate lacks the '%s' extension.",
1330 		    ext_ski()->name);
1331 		error = -ESRCH;
1332 		goto revert_aki;
1333 	}
1334 
1335 	if (ASN1_OCTET_STRING_cmp(aki->keyid, ski) != 0) {
1336 		error = pr_val_err("The '%s' does not equal the '%s'.",
1337 		    ext_aki()->name, ext_ski()->name);
1338 		goto revert_ski;
1339 	}
1340 
1341 	error = 0;
1342 
1343 revert_ski:
1344 	ASN1_BIT_STRING_free(ski);
1345 revert_aki:
1346 	AUTHORITY_KEYID_free(aki);
1347 	return error;
1348 }
1349 
1350 static int
handle_ku(X509_EXTENSION * ext,unsigned char byte1)1351 handle_ku(X509_EXTENSION *ext, unsigned char byte1)
1352 {
1353 	/*
1354 	 * About the key usage string: At time of writing, it's 9 bits long.
1355 	 * But zeroized rightmost bits can be omitted.
1356 	 * This implementation assumes that the ninth bit should always be zero.
1357 	 */
1358 
1359 	ASN1_BIT_STRING *ku;
1360 	unsigned char data[2];
1361 	int error = 0;
1362 
1363 	ku = X509V3_EXT_d2i(ext);
1364 	if (ku == NULL)
1365 		return cannot_decode(ext_ku());
1366 
1367 	if (ku->length == 0) {
1368 		error = pr_val_err("%s bit string has no enabled bits.",
1369 		    ext_ku()->name);
1370 		goto end;
1371 	}
1372 
1373 	memset(data, 0, sizeof(data));
1374 	memcpy(data, ku->data, ku->length);
1375 
1376 	if (ku->data[0] != byte1) {
1377 		error = pr_val_err("Illegal key usage flag string: %d%d%d%d%d%d%d%d%d",
1378 		    !!(ku->data[0] & 0x80u), !!(ku->data[0] & 0x40u),
1379 		    !!(ku->data[0] & 0x20u), !!(ku->data[0] & 0x10u),
1380 		    !!(ku->data[0] & 0x08u), !!(ku->data[0] & 0x04u),
1381 		    !!(ku->data[0] & 0x02u), !!(ku->data[0] & 0x01u),
1382 		    !!(ku->data[1] & 0x80u));
1383 		goto end;
1384 	}
1385 
1386 end:
1387 	ASN1_BIT_STRING_free(ku);
1388 	return error;
1389 }
1390 
1391 static int
handle_ku_ca(X509_EXTENSION * ext,void * arg)1392 handle_ku_ca(X509_EXTENSION *ext, void *arg)
1393 {
1394 	return handle_ku(ext, 0x06);
1395 }
1396 
1397 static int
handle_ku_ee(X509_EXTENSION * ext,void * arg)1398 handle_ku_ee(X509_EXTENSION *ext, void *arg)
1399 {
1400 	return handle_ku(ext, 0x80);
1401 }
1402 
1403 static int
handle_cdp(X509_EXTENSION * ext,void * arg)1404 handle_cdp(X509_EXTENSION *ext, void *arg)
1405 {
1406 	struct certificate_refs *refs = arg;
1407 	STACK_OF(DIST_POINT) *crldp;
1408 	DIST_POINT *dp;
1409 	GENERAL_NAMES *names;
1410 	GENERAL_NAME *name;
1411 	int i;
1412 	int error = 0;
1413 	char const *error_msg;
1414 
1415 	crldp = X509V3_EXT_d2i(ext);
1416 	if (crldp == NULL)
1417 		return cannot_decode(ext_cdp());
1418 
1419 	if (sk_DIST_POINT_num(crldp) != 1) {
1420 		error = pr_val_err("The %s extension has %d distribution points. (1 expected)",
1421 		    ext_cdp()->name, sk_DIST_POINT_num(crldp));
1422 		goto end;
1423 	}
1424 
1425 	dp = sk_DIST_POINT_value(crldp, 0);
1426 
1427 	if (dp->CRLissuer != NULL) {
1428 		error_msg = "has a CRLIssuer field";
1429 		goto dist_point_error;
1430 	}
1431 	if (dp->reasons != NULL) {
1432 		error_msg = "has a Reasons field";
1433 		goto dist_point_error;
1434 	}
1435 
1436 	if (dp->distpoint == NULL) {
1437 		error_msg = "lacks a distributionPoint field";
1438 		goto dist_point_error;
1439 	}
1440 
1441 	/* Bleargh. There's no enum. 0 is fullname, 1 is relativename. */
1442 	switch (dp->distpoint->type) {
1443 	case 0:
1444 		break;
1445 	case 1:
1446 		error_msg = "has a relative name";
1447 		goto dist_point_error;
1448 	default:
1449 		error_msg = "has an unknown type of name";
1450 		goto dist_point_error;
1451 	}
1452 
1453 	names = dp->distpoint->name.fullname;
1454 	for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1455 		name = sk_GENERAL_NAME_value(names, i);
1456 		if (is_rsync_uri(name)) {
1457 			/*
1458 			 * Since we're parsing and validating the manifest's CRL
1459 			 * at some point, I think that all we need to do now is
1460 			 * compare this CRL URI to that one's.
1461 			 *
1462 			 * But there is a problem:
1463 			 * The manifest's CRL might not have been parsed at this
1464 			 * point. In fact, it's guaranteed to not have been
1465 			 * parsed if the certificate we're validating is the EE
1466 			 * certificate of the manifest itself.
1467 			 *
1468 			 * So we will store the URI in @refs, and validate it
1469 			 * later.
1470 			 */
1471 			error = ia5s2string(name->d.GN_URI, &refs->crldp);
1472 			goto end;
1473 		}
1474 	}
1475 
1476 	error_msg = "lacks an RSYNC URI";
1477 
1478 dist_point_error:
1479 	error = pr_val_err("The %s extension's distribution point %s.",
1480 	    ext_cdp()->name, error_msg);
1481 
1482 end:
1483 	sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1484 	return error;
1485 }
1486 
1487 /**
1488  * The RFC does not explain AD validation very well. This is personal
1489  * interpretation, influenced by Tim Bruijnzeels's response
1490  * (https://mailarchive.ietf.org/arch/msg/sidr/4ycmff9jEU4VU9gGK5RyhZ7JYsQ)
1491  * (I'm being a bit more lax than he suggested.)
1492  *
1493  * 1. Only one NID needs to be searched at a time. (This is currently somewhat
1494  *    of a coincidence, and will probably be superseded at some point. But I'm
1495  *    not going to complicate this until it's necessary.)
1496  * 2. The NID MUST be found, otherwise the certificate is invalid.
1497  * 3. The NID can be found more than once.
1498  * 4. All access descriptions that match the NID must be URLs.
1499  * 5. Precisely one of those matches will be an RSYNC URL, and it's the only one
1500  *    we are required to support.
1501  *    (I would have gone with "at least one of those matches", but I don't know
1502  *    what to do with the other ones.)
1503  * 6. Other access descriptions that do not match the NID are allowed and
1504  *    supposed to be ignored.
1505  * 7. Other access descriptions that match the NID but do not have RSYNC URIs
1506  *    are also allowed, and also supposed to be ignored.
1507  */
1508 static int
handle_ad(char const * ia_name,SIGNATURE_INFO_ACCESS * ia,char const * ad_name,int ad_nid,int uri_flags,bool required,int (* cb)(struct rpki_uri *,uint8_t,void *),void * arg)1509 handle_ad(char const *ia_name, SIGNATURE_INFO_ACCESS *ia,
1510     char const *ad_name, int ad_nid, int uri_flags, bool required,
1511     int (*cb)(struct rpki_uri *, uint8_t, void *), void *arg)
1512 {
1513 # define AD_METHOD ((uri_flags & URI_VALID_RSYNC) == URI_VALID_RSYNC ? \
1514 	"RSYNC" : \
1515 	(((uri_flags & URI_VALID_HTTPS) == URI_VALID_HTTPS) ? \
1516 	"HTTPS" : "RSYNC/HTTPS"))
1517 	ACCESS_DESCRIPTION *ad;
1518 	struct rpki_uri *uri;
1519 	bool found = false;
1520 	unsigned int i;
1521 	int error;
1522 
1523 	for (i = 0; i < sk_ACCESS_DESCRIPTION_num(ia); i++) {
1524 		ad = sk_ACCESS_DESCRIPTION_value(ia, i);
1525 		if (OBJ_obj2nid(ad->method) == ad_nid) {
1526 			error = uri_create_ad(&uri, ad, uri_flags);
1527 			switch (error) {
1528 			case 0:
1529 				break;
1530 			case ENOTRSYNC:
1531 				continue;
1532 			case ENOTHTTPS:
1533 				continue;
1534 			case ENOTSUPPORTED:
1535 				continue;
1536 			default:
1537 				return error;
1538 			}
1539 
1540 			if (found) {
1541 				uri_refput(uri);
1542 				return pr_val_err("Extension '%s' has multiple '%s' %s URIs.",
1543 				    ia_name, ad_name, AD_METHOD);
1544 			}
1545 
1546 			error = cb(uri, i, arg);
1547 			if (error) {
1548 				uri_refput(uri);
1549 				return error;
1550 			}
1551 
1552 			uri_refput(uri);
1553 			found = true;
1554 		}
1555 	}
1556 
1557 	if (required && !found) {
1558 		pr_val_err("Extension '%s' lacks a '%s' valid %s URI.", ia_name,
1559 		    ad_name, AD_METHOD);
1560 		return -ESRCH;
1561 	}
1562 
1563 	return 0;
1564 }
1565 
1566 static int
handle_caIssuers(struct rpki_uri * uri,uint8_t pos,void * arg)1567 handle_caIssuers(struct rpki_uri *uri, uint8_t pos, void *arg)
1568 {
1569 	struct certificate_refs *refs = arg;
1570 	/*
1571 	 * Bringing the parent certificate's URI all the way
1572 	 * over here is too much trouble, so do the handle_cdp()
1573 	 * hack.
1574 	 */
1575 	refs->caIssuers = uri;
1576 	uri_refget(uri);
1577 	return 0;
1578 }
1579 
1580 static int
handle_aia(X509_EXTENSION * ext,void * arg)1581 handle_aia(X509_EXTENSION *ext, void *arg)
1582 {
1583 	AUTHORITY_INFO_ACCESS *aia;
1584 	int error;
1585 
1586 	aia = X509V3_EXT_d2i(ext);
1587 	if (aia == NULL)
1588 		return cannot_decode(ext_aia());
1589 
1590 	error = handle_ad("AIA", aia, "caIssuers", NID_ad_ca_issuers,
1591 	    URI_VALID_RSYNC, true, handle_caIssuers, arg);
1592 
1593 	AUTHORITY_INFO_ACCESS_free(aia);
1594 	return error;
1595 }
1596 
1597 static int
handle_sia_ca(X509_EXTENSION * ext,void * arg)1598 handle_sia_ca(X509_EXTENSION *ext, void *arg)
1599 {
1600 	SIGNATURE_INFO_ACCESS *sia;
1601 	struct sia_ca_uris *uris = arg;
1602 	int error;
1603 
1604 	sia = X509V3_EXT_d2i(ext);
1605 	if (sia == NULL)
1606 		return cannot_decode(ext_sia());
1607 
1608 	/* rsync, still the preferred and required */
1609 	error = handle_ad("SIA", sia, "caRepository", NID_caRepository,
1610 	    URI_VALID_RSYNC, true, handle_caRepository, &uris->caRepository);
1611 	if (error)
1612 		goto end;
1613 
1614 	/* HTTPS RRDP */
1615 	error = handle_ad("SIA", sia, "rpkiNotify", nid_rpkiNotify(),
1616 	    URI_VALID_HTTPS | URI_USE_RRDP_WORKSPACE, false, handle_rpkiNotify,
1617 	    &uris->rpkiNotify);
1618 	if (error)
1619 		goto end;
1620 
1621 	/*
1622 	 * Store the manifest URI in @mft.
1623 	 * (We won't actually touch the manifest until we know the certificate
1624 	 * is fully valid.)
1625 	 */
1626 	error = handle_ad("SIA", sia, "rpkiManifest", nid_rpkiManifest(),
1627 	    URI_VALID_RSYNC, true, handle_rpkiManifest, &uris->mft);
1628 
1629 end:
1630 	AUTHORITY_INFO_ACCESS_free(sia);
1631 	return error;
1632 }
1633 
1634 static int
handle_sia_ee(X509_EXTENSION * ext,void * arg)1635 handle_sia_ee(X509_EXTENSION *ext, void *arg)
1636 {
1637 	SIGNATURE_INFO_ACCESS *sia;
1638 	int error;
1639 
1640 	sia = X509V3_EXT_d2i(ext);
1641 	if (sia == NULL)
1642 		return cannot_decode(ext_sia());
1643 
1644 	error = handle_ad("SIA", sia, "signedObject", nid_signedObject(),
1645 	    URI_VALID_RSYNC, true, handle_signedObject, arg);
1646 
1647 	AUTHORITY_INFO_ACCESS_free(sia);
1648 	return error;
1649 }
1650 
1651 static int
handle_cp(X509_EXTENSION * ext,void * arg)1652 handle_cp(X509_EXTENSION *ext, void *arg)
1653 {
1654 	enum rpki_policy *policy = arg;
1655 	CERTIFICATEPOLICIES *cp;
1656 	POLICYINFO *pi;
1657 	POLICYQUALINFO *pqi;
1658 	int error, nid_cp, nid_qt_cps, pqi_num;
1659 
1660 	error = 0;
1661 	cp = X509V3_EXT_d2i(ext);
1662 	if (cp == NULL)
1663 		return cannot_decode(ext_cp());
1664 
1665 	if (sk_POLICYINFO_num(cp) != 1) {
1666 		error = pr_val_err("The %s extension has %d policy information's. (1 expected)",
1667 		    ext_cp()->name, sk_POLICYINFO_num(cp));
1668 		goto end;
1669 	}
1670 
1671 	/* rfc7318#section-2 and consider rfc8360#section-4.2.1 */
1672 	pi = sk_POLICYINFO_value(cp, 0);
1673 	nid_cp = OBJ_obj2nid(pi->policyid);
1674 	if (nid_cp == nid_certPolicyRpki()) {
1675 		if (policy != NULL)
1676 			*policy = RPKI_POLICY_RFC6484;
1677 	} else if (nid_cp == nid_certPolicyRpkiV2()) {
1678 		pr_val_debug("Found RFC8360 policy!");
1679 		if (policy != NULL)
1680 			*policy = RPKI_POLICY_RFC8360;
1681 	} else {
1682 		error = pr_val_err("Invalid certificate policy OID, isn't 'id-cp-ipAddr-asNumber' nor 'id-cp-ipAddr-asNumber-v2'");
1683 		goto end;
1684 	}
1685 
1686 	/* Exactly one policy qualifier MAY be included (so none is also valid) */
1687 	if (pi->qualifiers == NULL)
1688 		goto end;
1689 
1690 	pqi_num = sk_POLICYQUALINFO_num(pi->qualifiers);
1691 	if (pqi_num == 0)
1692 		goto end;
1693 	if (pqi_num != 1) {
1694 		error = pr_val_err("The %s extension has %d policy qualifiers. (none or only 1 expected)",
1695 		    ext_cp()->name, pqi_num);
1696 		goto end;
1697 	}
1698 
1699 	pqi = sk_POLICYQUALINFO_value(pi->qualifiers, 0);
1700 	nid_qt_cps = OBJ_obj2nid(pqi->pqualid);
1701 	if (nid_qt_cps != NID_id_qt_cps) {
1702 		error = pr_val_err("Policy qualifier ID isn't Certification Practice Statement (CPS)");
1703 		goto end;
1704 	}
1705 end:
1706 	CERTIFICATEPOLICIES_free(cp);
1707 	return error;
1708 }
1709 
1710 static int
handle_ir(X509_EXTENSION * ext,void * arg)1711 handle_ir(X509_EXTENSION *ext, void *arg)
1712 {
1713 	return 0; /* Handled in certificate_get_resources(). */
1714 }
1715 
1716 static int
handle_ar(X509_EXTENSION * ext,void * arg)1717 handle_ar(X509_EXTENSION *ext, void *arg)
1718 {
1719 	return 0; /* Handled in certificate_get_resources(). */
1720 }
1721 
1722 /**
1723  * Validates the certificate extensions, Trust Anchor style.
1724  *
1725  * Depending on the Access Description preference at SIA, the rpki_uri's at
1726  * @sia_uris will be allocated.
1727  */
1728 static int
certificate_validate_extensions_ta(X509 * cert,struct sia_ca_uris * sia_uris,enum rpki_policy * policy)1729 certificate_validate_extensions_ta(X509 *cert, struct sia_ca_uris *sia_uris,
1730     enum rpki_policy *policy)
1731 {
1732 	struct extension_handler handlers[] = {
1733 	   /* ext        reqd   handler        arg       */
1734 	    { ext_bc(),  true,  handle_bc,               },
1735 	    { ext_ski(), true,  handle_ski_ca, cert      },
1736 	    { ext_aki(), false, handle_aki_ta, cert      },
1737 	    { ext_ku(),  true,  handle_ku_ca,            },
1738 	    { ext_sia(), true,  handle_sia_ca, sia_uris  },
1739 	    { ext_cp(),  true,  handle_cp,     policy    },
1740 	    { ext_ir(),  false, handle_ir,               },
1741 	    { ext_ar(),  false, handle_ar,               },
1742 	    { ext_ir2(), false, handle_ir,               },
1743 	    { ext_ar2(), false, handle_ar,               },
1744 	    { NULL },
1745 	};
1746 
1747 	return handle_extensions(handlers, X509_get0_extensions(cert));
1748 }
1749 
1750 /**
1751  * Validates the certificate extensions, (intermediate) Certificate Authority
1752  * style.
1753  *
1754  * Depending on the Access Description preference at SIA, the rpki_uri's at
1755  * @sia_uris will be allocated.
1756  * Also initializes the fourth argument with the references found in the
1757  * extensions.
1758  */
1759 static int
certificate_validate_extensions_ca(X509 * cert,struct sia_ca_uris * sia_uris,struct certificate_refs * refs,enum rpki_policy * policy)1760 certificate_validate_extensions_ca(X509 *cert, struct sia_ca_uris *sia_uris,
1761     struct certificate_refs *refs, enum rpki_policy *policy)
1762 {
1763 	struct extension_handler handlers[] = {
1764 	   /* ext        reqd   handler        arg       */
1765 	    { ext_bc(),  true,  handle_bc,               },
1766 	    { ext_ski(), true,  handle_ski_ca, cert      },
1767 	    { ext_aki(), true,  handle_aki,              },
1768 	    { ext_ku(),  true,  handle_ku_ca,            },
1769 	    { ext_cdp(), true,  handle_cdp,    refs      },
1770 	    { ext_aia(), true,  handle_aia,    refs      },
1771 	    { ext_sia(), true,  handle_sia_ca, sia_uris  },
1772 	    { ext_cp(),  true,  handle_cp,     policy    },
1773 	    { ext_ir(),  false, handle_ir,               },
1774 	    { ext_ar(),  false, handle_ar,               },
1775 	    { ext_ir2(), false, handle_ir,               },
1776 	    { ext_ar2(), false, handle_ar,               },
1777 	    { NULL },
1778 	};
1779 
1780 	return handle_extensions(handlers, X509_get0_extensions(cert));
1781 }
1782 
1783 int
certificate_validate_extensions_ee(X509 * cert,OCTET_STRING_t * sid,struct certificate_refs * refs,enum rpki_policy * policy)1784 certificate_validate_extensions_ee(X509 *cert, OCTET_STRING_t *sid,
1785     struct certificate_refs *refs, enum rpki_policy *policy)
1786 {
1787 	struct ski_arguments ski_args;
1788 	struct extension_handler handlers[] = {
1789 	   /* ext        reqd   handler        arg       */
1790 	    { ext_ski(), true,  handle_ski_ee, &ski_args },
1791 	    { ext_aki(), true,  handle_aki,              },
1792 	    { ext_ku(),  true,  handle_ku_ee,            },
1793 	    { ext_cdp(), true,  handle_cdp,    refs      },
1794 	    { ext_aia(), true,  handle_aia,    refs      },
1795 	    { ext_sia(), true,  handle_sia_ee, refs      },
1796 	    { ext_cp(),  true,  handle_cp,     policy    },
1797 	    { ext_ir(),  false, handle_ir,               },
1798 	    { ext_ar(),  false, handle_ar,               },
1799 	    { ext_ir2(), false, handle_ir,               },
1800 	    { ext_ar2(), false, handle_ar,               },
1801 	    { NULL },
1802 	};
1803 
1804 	ski_args.cert = cert;
1805 	ski_args.sid = sid;
1806 
1807 	return handle_extensions(handlers, X509_get0_extensions(cert));
1808 }
1809 
1810 static bool
has_bgpsec_router_eku(X509 * cert)1811 has_bgpsec_router_eku(X509 *cert)
1812 {
1813 	EXTENDED_KEY_USAGE *eku;
1814 	int i;
1815 	int nid;
1816 
1817 	eku = X509_get_ext_d2i(cert, NID_ext_key_usage, NULL, NULL);
1818 	if (eku == NULL)
1819 		return false;
1820 
1821 	/* RFC 8209#section-3.1.3.2: Unknown KeyPurposeIds are allowed. */
1822 	for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1823 		nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(eku, i));
1824 		if (nid == nid_bgpsecRouter()) {
1825 			EXTENDED_KEY_USAGE_free(eku);
1826 			return true;
1827 		}
1828 	}
1829 
1830 	EXTENDED_KEY_USAGE_free(eku);
1831 	return false;
1832 }
1833 
1834 /*
1835  * Assumption: Meant to be used exclusively in the context of parsing a .cer
1836  * certificate.
1837  */
1838 static int
get_certificate_type(X509 * cert,bool is_ta,enum cert_type * result)1839 get_certificate_type(X509 *cert, bool is_ta, enum cert_type *result)
1840 {
1841 	if (is_ta) {
1842 		*result = TA;
1843 		return 0;
1844 	}
1845 
1846 	if (X509_check_ca(cert) == 1) {
1847 		*result = CA;
1848 		return 0;
1849 	}
1850 
1851 	if (has_bgpsec_router_eku(cert)) {
1852 		*result = BGPSEC;
1853 		return 0;
1854 	}
1855 
1856 	*result = EE; /* Shuts up nonsense gcc 8.3 warning */
1857 	return pr_val_err("Certificate is not TA, CA nor BGPsec. Ignoring...");
1858 }
1859 
1860 /*
1861  * It does some of the things from validate_issuer(), but we can not wait for
1862  * such validation, since at this point the RSYNC URI at AIA extension must be
1863  * verified to comply with rfc6487#section-4.8.7
1864  */
1865 static int
force_aia_validation(struct rpki_uri * caIssuers,X509 * son)1866 force_aia_validation(struct rpki_uri *caIssuers, X509 *son)
1867 {
1868 	X509 *parent;
1869 	struct rfc5280_name *son_name;
1870 	struct rfc5280_name *parent_name;
1871 	int error;
1872 
1873 	pr_val_debug("AIA's URI didn't matched parent URI, trying to SYNC");
1874 
1875 	/* RSYNC is still the preferred access mechanism, force the sync */
1876 	do {
1877 		error = rsync_download_files(caIssuers, false, true);
1878 		if (!error)
1879 			break;
1880 		if (error == EREQFAILED) {
1881 			pr_val_info("AIA URI couldn't be downloaded, trying to search locally");
1882 			break;
1883 		}
1884 		return error;
1885 	} while (0);
1886 
1887 	error = certificate_load(caIssuers, &parent);
1888 	if (error)
1889 		return error;
1890 
1891 	error = x509_name_decode(X509_get_subject_name(parent), "subject",
1892 	    &parent_name);
1893 	if (error)
1894 		goto free_parent;
1895 
1896 	error = x509_name_decode(X509_get_issuer_name(son), "issuer",
1897 	    &son_name);
1898 	if (error)
1899 		goto free_parent_name;
1900 
1901 	if (x509_name_equals(parent_name, son_name))
1902 		error = 0; /* Everything its ok */
1903 	else
1904 		error = pr_val_err("Certificate subject from AIA ('%s') isn't issuer of this certificate.",
1905 		    uri_val_get_printable(caIssuers));
1906 
1907 	x509_name_put(son_name);
1908 free_parent_name:
1909 	x509_name_put(parent_name);
1910 free_parent:
1911 	X509_free(parent);
1912 	return error;
1913 }
1914 
1915 int
certificate_validate_aia(struct rpki_uri * caIssuers,X509 * cert)1916 certificate_validate_aia(struct rpki_uri *caIssuers, X509 *cert)
1917 {
1918 	struct validation *state;
1919 	struct rpki_uri *parent;
1920 
1921 	if (caIssuers == NULL)
1922 		pr_crit("Certificate's AIA was not recorded.");
1923 
1924 	state = state_retrieve();
1925 	if (state == NULL)
1926 		return -EINVAL;
1927 	parent = x509stack_peek_uri(validation_certstack(state));
1928 	if (parent == NULL)
1929 		pr_crit("Certificate has no parent.");
1930 
1931 	/*
1932 	 * There are two possible issues here, specifically at first level root
1933 	 * certificate's childs:
1934 	 *
1935 	 * - Considering that the root certificate can be published at one or
1936 	 *   more rsync or HTTPS URIs (RFC 8630), the validation is done
1937 	 *   considering the first valid downloaded certificate URI from the
1938 	 *   list of URIs; so, that URI doesn't necessarily matches AIA. And
1939 	 *   this issue is more likely to happen if the 'shuffle-uris' flag
1940 	 *   is active an a TAL has more than one rsync/HTTPS uri.
1941 	 *
1942 	 * - If the TAL has only one URI, and such URI is HTTPS, the root
1943 	 *   certificate will be located at a distinct point that what it's
1944 	 *   expected, so this might be an error if such certificate (root
1945 	 *   certificate) isn't published at an rsync repository. See RFC 6487
1946 	 *   section-4.8.7:
1947 	 *
1948 	 *   "The preferred URI access mechanisms is "rsync", and an rsync URI
1949 	 *   [RFC5781] MUST be specified with an accessMethod value of
1950 	 *   id-ad-caIssuers.  The URI MUST reference the point of publication
1951 	 *   of the certificate where this Issuer is the subject (the issuer's
1952 	 *   immediate superior certificate)."
1953 	 *
1954 	 * As of today, this is a common scenario, since most of the TALs have
1955 	 * an HTTPS URI.
1956 	 */
1957 	if (uri_equals(caIssuers, parent))
1958 		return 0;
1959 
1960 	/*
1961 	 * Avoid the check at direct TA childs, otherwise try to match the
1962 	 * immediate superior subject with the current issuer. This will force
1963 	 * an RSYNC of AIA's URI, load the certificate and do the comparison.
1964 	 */
1965 	return certstack_get_x509_num(validation_certstack(state)) == 1 ?
1966 	    0 :
1967 	    force_aia_validation(caIssuers, cert);
1968 }
1969 
1970 /*
1971  * Verify that the manifest file actually exists at the local repository, if it
1972  * doesn't exist then discard the repository (which can result in a attempt
1973  * to fetch data from another repository).
1974  */
1975 static int
verify_mft_loc(struct rpki_uri * mft_uri)1976 verify_mft_loc(struct rpki_uri *mft_uri)
1977 {
1978 	if (!valid_file_or_dir(uri_get_local(mft_uri), true, false,
1979 	    __pr_val_err))
1980 		return -EINVAL; /* Error already logged */
1981 
1982 	return 0;
1983 }
1984 
1985 /*
1986  * Verify the manifest location at the local RRDP workspace.
1987  *
1988  * Don't log in case the @mft_uri doesn't exist at the RRDP workspace.
1989  */
1990 static int
verify_rrdp_mft_loc(struct rpki_uri * mft_uri)1991 verify_rrdp_mft_loc(struct rpki_uri *mft_uri)
1992 {
1993 	struct rpki_uri *tmp;
1994 	int error;
1995 
1996 	if (db_rrdp_uris_workspace_get() == NULL)
1997 		return -ENOENT;
1998 
1999 	tmp = NULL;
2000 	error = uri_create_rsync_str_rrdp(&tmp, uri_get_global(mft_uri),
2001 	    uri_get_global_len(mft_uri));
2002 	if (error)
2003 		return error;
2004 
2005 	if (!valid_file_or_dir(uri_get_local(tmp), true, false, NULL)) {
2006 		uri_refput(tmp);
2007 		return -ENOENT;
2008 	}
2009 
2010 	uri_refput(tmp);
2011 	return 0;
2012 }
2013 
2014 static int
replace_rrdp_mft_uri(struct sia_uri * sia_mft)2015 replace_rrdp_mft_uri(struct sia_uri *sia_mft)
2016 {
2017 	struct rpki_uri *tmp;
2018 	int error;
2019 
2020 	tmp = NULL;
2021 	error = uri_create_rsync_str_rrdp(&tmp,
2022 	    uri_get_global(sia_mft->uri),
2023 	    uri_get_global_len(sia_mft->uri));
2024 	if (error)
2025 		return error;
2026 
2027 	uri_refput(sia_mft->uri);
2028 	sia_mft->uri = tmp;
2029 
2030 	return 0;
2031 }
2032 
2033 static int
exec_rrdp_method(struct sia_ca_uris * sia_uris)2034 exec_rrdp_method(struct sia_ca_uris *sia_uris)
2035 {
2036 	bool data_updated;
2037 	int error;
2038 
2039 	/* Start working on the RRDP local workspace */
2040 	error = db_rrdp_uris_workspace_enable();
2041 	if (error)
2042 		return error;
2043 
2044 	data_updated = false;
2045 	error = rrdp_load(sia_uris->rpkiNotify.uri, &data_updated);
2046 	if (error)
2047 		goto err;
2048 
2049 	error = verify_rrdp_mft_loc(sia_uris->mft.uri);
2050 	switch(error) {
2051 	case 0:
2052 		/* MFT exists, great! We're good to go. */
2053 		break;
2054 	case -ENOENT:
2055 		/* Doesn't exist and the RRDP data was updated: error */
2056 		if (data_updated)
2057 			goto err;
2058 
2059 		/* Otherwise, force the snapshot processing and check again */
2060 		error = rrdp_reload_snapshot(sia_uris->rpkiNotify.uri);
2061 		if (error)
2062 			goto err;
2063 		error = verify_rrdp_mft_loc(sia_uris->mft.uri);
2064 		if (error)
2065 			goto err;
2066 		break;
2067 	default:
2068 		goto err;
2069 	}
2070 
2071 	/* Successfully loaded (or no updates yet), update MFT local URI */
2072 	error = replace_rrdp_mft_uri(&sia_uris->mft);
2073 	if (error)
2074 		goto err;
2075 
2076 	return 0;
2077 err:
2078 	db_rrdp_uris_workspace_disable();
2079 	return error;
2080 }
2081 
2082 static int
exec_rsync_method(struct sia_ca_uris * sia_uris)2083 exec_rsync_method(struct sia_ca_uris *sia_uris)
2084 {
2085 	int error;
2086 
2087 	/* Stop working on the RRDP local workspace */
2088 	db_rrdp_uris_workspace_disable();
2089 	error = rsync_download_files(sia_uris->caRepository.uri, false, false);
2090 	if (error)
2091 		return error;
2092 
2093 	return verify_mft_loc(sia_uris->mft.uri);
2094 }
2095 
2096 /*
2097  * Currently only two access methods are supported, just consider those two:
2098  * rsync and RRDP. If a new access method is supported, this function must
2099  * change (and probably the sia_ca_uris struct as well).
2100  *
2101  * Both access method callbacks must verify the manifest existence.
2102  */
2103 static int
use_access_method(struct sia_ca_uris * sia_uris,access_method_exec rsync_cb,access_method_exec rrdp_cb,bool new_level,bool * retry_repo_sync)2104 use_access_method(struct sia_ca_uris *sia_uris,
2105     access_method_exec rsync_cb, access_method_exec rrdp_cb, bool new_level,
2106     bool *retry_repo_sync)
2107 {
2108 	access_method_exec *cb_primary;
2109 	access_method_exec *cb_secondary;
2110 	rrdp_req_status_t rrdp_req_status;
2111 	bool primary_rrdp;
2112 	int upd_error;
2113 	int error;
2114 
2115 	/*
2116 	 * By default, RRDP has a greater priority than rsync.
2117 	 * See "http.priority" default value.
2118 	 */
2119 	primary_rrdp = true;
2120 	(*retry_repo_sync) = true;
2121 
2122 	/*
2123 	 * Very specific scenario, yet possible:
2124 	 * - Still working at the same repository level
2125 	 * - The previous object was working on an RRDP repository
2126 	 * - This certificate doesn't have an update notification URI
2127 	 *
2128 	 * Probably the object does exist at the RRDP repository, so check if
2129 	 * that's the case. Otherwise, just keep going.
2130 	 *
2131 	 * The main reason, is a (possible) hole at RFC 8182. Apparently, the
2132 	 * CA childs aren't obligated to have the same RRDP accessMethod than
2133 	 * their parent, so there's no problem if they don't use it at all; not
2134 	 * even if such childs (and even the grandchilds or anyone below that
2135 	 * level) "reside" at the RRDP repository.
2136 	 */
2137 	if (!new_level && db_rrdp_uris_workspace_get() != NULL &&
2138 	    sia_uris->rpkiNotify.uri == NULL &&
2139 	    verify_rrdp_mft_loc(sia_uris->mft.uri) == 0) {
2140 		(*retry_repo_sync) = false;
2141 		return replace_rrdp_mft_uri(&sia_uris->mft);
2142 	}
2143 
2144 	/*
2145 	 * RSYNC will always be present (at least for now, see
2146 	 * rfc6487#section-4.8.8.1). If rsync is disabled, the cb will take
2147 	 * care of that.
2148 	 */
2149 	if (sia_uris->rpkiNotify.uri == NULL) {
2150 		primary_rrdp = false;
2151 		error = rsync_cb(sia_uris);
2152 		if (!error)
2153 			return 0;
2154 		goto verify_mft;
2155 	}
2156 
2157 	/*
2158 	 * There isn't any restriction about the preferred access method of
2159 	 * children CAs being the same as the parent CA.
2160 	 *
2161 	 * Two possible scenarios arise:
2162 	 * 1) CA Parent didn't utilized (or didn't had) an RRDP update
2163 	 *    notification URI.
2164 	 * 2) CA Parent successfully utilized an RRDP update notification URI.
2165 	 *
2166 	 * Step (1) is simple, do the check of the preferred access method.
2167 	 * Step (2) must do something different.
2168 	 * - If RRDP URI was already successfully visited, don't care
2169 	 *   preference, don't execute access method.
2170 	 */
2171 	error = db_rrdp_uris_get_request_status(
2172 	    uri_get_global(sia_uris->rpkiNotify.uri), &rrdp_req_status);
2173 	if (error ==  0 && rrdp_req_status == RRDP_URI_REQ_VISITED) {
2174 		error = db_rrdp_uris_workspace_enable();
2175 		if (error) {
2176 			db_rrdp_uris_workspace_disable();
2177 			return error;
2178 		}
2179 		(*retry_repo_sync) = false;
2180 		return replace_rrdp_mft_uri(&sia_uris->mft);
2181 	}
2182 
2183 	/* Use CA's or configured priority? */
2184 	if (config_get_rsync_priority() == config_get_http_priority())
2185 		primary_rrdp = sia_uris->caRepository.position
2186 		    > sia_uris->rpkiNotify.position;
2187 	else
2188 		primary_rrdp = config_get_rsync_priority()
2189 		    < config_get_http_priority();
2190 
2191 	cb_primary = primary_rrdp ? rrdp_cb : rsync_cb;
2192 	cb_secondary = primary_rrdp ? rsync_cb : rrdp_cb;
2193 
2194 	/* Try with the preferred; in case of error, try with the next one */
2195 	error = cb_primary(sia_uris);
2196 	if (!error) {
2197 		(*retry_repo_sync) = !primary_rrdp;
2198 		return 0;
2199 	}
2200 
2201 	if (primary_rrdp) {
2202 		working_repo_push(uri_get_global(sia_uris->rpkiNotify.uri));
2203 		if (error != -EPERM)
2204 			pr_val_info("Couldn't fetch data from RRDP repository '%s', trying to fetch data now from '%s'.",
2205 			    uri_get_global(sia_uris->rpkiNotify.uri),
2206 			    uri_get_global(sia_uris->caRepository.uri));
2207 		else
2208 			pr_val_info("RRDP repository '%s' download/processing returned error previously, now I will try to fetch data from '%s'.",
2209 			    uri_get_global(sia_uris->rpkiNotify.uri),
2210 			    uri_get_global(sia_uris->caRepository.uri));
2211 	} else {
2212 		working_repo_push(uri_get_global(sia_uris->caRepository.uri));
2213 		pr_val_info("Couldn't fetch data from repository '%s', trying to fetch data now from RRDP '%s'.",
2214 		    uri_get_global(sia_uris->caRepository.uri),
2215 		    uri_get_global(sia_uris->rpkiNotify.uri));
2216 	}
2217 
2218 	/* Retry if rrdp was the first option but failed */
2219 	(*retry_repo_sync) = primary_rrdp;
2220 	error = cb_secondary(sia_uris);
2221 	/* No need to remember the working repository anymore */
2222 	working_repo_pop();
2223 
2224 verify_mft:
2225 	/* Reach here on error or when both access methods were utilized */
2226 	switch (error) {
2227 	case 0:
2228 		/* Remove the error'd URI, since we got the repo files */
2229 		if (working_repo_peek() != NULL)
2230 			reqs_errors_rem_uri(working_repo_peek());
2231 		break;
2232 	case EREQFAILED:
2233 		/* Log that we'll try to work with a local copy */
2234 		pr_val_warn("Trying to work with the local cache files.");
2235 		(*retry_repo_sync) = false;
2236 		break;
2237 	case -EPERM:
2238 		/*
2239 		 * Specific RRPD error: the URI error'd on the first try, so
2240 		 * we'll keep trying with the local files
2241 		 */
2242 		(*retry_repo_sync) = false;
2243 		break;
2244 	default:
2245 		return error;
2246 	}
2247 
2248 	/* Error and the primary access method was RRDP? Use its workspace */
2249 	if (error && primary_rrdp) {
2250 		db_rrdp_uris_workspace_enable();
2251 		upd_error = replace_rrdp_mft_uri(&sia_uris->mft);
2252 		if (upd_error)
2253 			return upd_error;
2254 	}
2255 
2256 	/* Look for the manifest */
2257 	return verify_mft_loc(sia_uris->mft.uri);
2258 }
2259 
2260 /*
2261  * Get the rsync server part from an rsync URI.
2262  *
2263  * If the URI is:
2264  *   rsync://<server>/<service/<file path>
2265  * This will return:
2266  *   rsync://<server>
2267  */
2268 static int
get_rsync_server_uri(struct rpki_uri * src,char ** result,size_t * result_len)2269 get_rsync_server_uri(struct rpki_uri *src, char **result, size_t *result_len)
2270 {
2271 	char const *global;
2272 	char *tmp;
2273 	size_t global_len;
2274 	unsigned int slashes;
2275 	size_t i;
2276 
2277 	global = uri_get_global(src);
2278 	global_len = uri_get_global_len(src);
2279 	slashes = 0;
2280 
2281 	for (i = 0; i < global_len; i++) {
2282 		if (global[i] == '/') {
2283 			slashes++;
2284 			if (slashes == 3)
2285 				break;
2286 		}
2287 	}
2288 
2289 	tmp = malloc(i + 1);
2290 	if (tmp == NULL)
2291 		return pr_enomem();
2292 
2293 	strncpy(tmp, global, i);
2294 	tmp[i] = '\0';
2295 
2296 	*result_len = i;
2297 	*result = tmp;
2298 
2299 	return 0;
2300 }
2301 
2302 static int
set_repository_level(bool is_ta,struct validation * state,struct rpki_uri * cert_uri,struct sia_ca_uris * sia_uris,bool * updated)2303 set_repository_level(bool is_ta, struct validation *state,
2304     struct rpki_uri *cert_uri, struct sia_ca_uris *sia_uris, bool *updated)
2305 {
2306 	char *parent_server, *current_server;
2307 	size_t parent_server_len, current_server_len;
2308 	unsigned int new_level;
2309 	bool update;
2310 	int error;
2311 
2312 	new_level = 0;
2313 	if (is_ta || cert_uri == NULL) {
2314 		working_repo_push_level(new_level);
2315 		return 0;
2316 	}
2317 
2318 	/* Warning killer */
2319 	parent_server = NULL;
2320 	current_server = NULL;
2321 	parent_server_len = 0;
2322 	current_server_len = 0;
2323 
2324 	/* Both are rsync URIs, check the server part */
2325 	error = get_rsync_server_uri(cert_uri, &parent_server,
2326 	    &parent_server_len);
2327 	if (error)
2328 		return error;
2329 
2330 	error = get_rsync_server_uri(sia_uris->caRepository.uri,
2331 	    &current_server, &current_server_len);
2332 	if (error) {
2333 		free(parent_server);
2334 		return error;
2335 	}
2336 
2337 	if (parent_server_len != current_server_len) {
2338 		update = true;
2339 		goto end;
2340 	}
2341 
2342 	update = (strcmp(parent_server, current_server) != 0);
2343 end:
2344 	new_level = x509stack_peek_level(validation_certstack(state));
2345 	if (update)
2346 		new_level++;
2347 
2348 	working_repo_push_level(new_level);
2349 
2350 	free(parent_server);
2351 	free(current_server);
2352 
2353 	(*updated) = update;
2354 	return 0;
2355 }
2356 
2357 /** Boilerplate code for CA certificate validation and recursive traversal. */
2358 int
certificate_traverse(struct rpp * rpp_parent,struct rpki_uri * cert_uri)2359 certificate_traverse(struct rpp *rpp_parent, struct rpki_uri *cert_uri)
2360 {
2361 /** Is the CA certificate the TA certificate? */
2362 #define IS_TA (rpp_parent == NULL)
2363 
2364 	struct validation *state;
2365 	int total_parents;
2366 	STACK_OF(X509_CRL) *rpp_parent_crl;
2367 	X509 *cert;
2368 	struct sia_ca_uris sia_uris;
2369 	struct certificate_refs refs;
2370 	enum rpki_policy policy;
2371 	enum cert_type type;
2372 	struct rpp *pp;
2373 	bool repo_retry;
2374 	bool new_level;
2375 	int error;
2376 
2377 	state = state_retrieve();
2378 	if (state == NULL)
2379 		return -EINVAL;
2380 	total_parents = certstack_get_x509_num(validation_certstack(state));
2381 	if (total_parents >= config_get_max_cert_depth())
2382 		return pr_val_err("Certificate chain maximum depth exceeded.");
2383 
2384 	/* Debug cert type */
2385 	if (IS_TA)
2386 		pr_val_debug("TA Certificate '%s' {",
2387 		    uri_val_get_printable(cert_uri));
2388 	else
2389 		pr_val_debug("Certificate '%s' {",
2390 		    uri_val_get_printable(cert_uri));
2391 
2392 	fnstack_push_uri(cert_uri);
2393 
2394 	error = rpp_crl(rpp_parent, &rpp_parent_crl);
2395 	if (error)
2396 		goto revert_fnstack_and_debug;
2397 
2398 	/* -- Validate the certificate (@cert) -- */
2399 	error = certificate_load(cert_uri, &cert);
2400 	if (error)
2401 		goto revert_fnstack_and_debug;
2402 	error = certificate_validate_chain(cert, rpp_parent_crl);
2403 	if (error)
2404 		goto revert_cert;
2405 
2406 	error = get_certificate_type(cert, IS_TA, &type);
2407 	if (error)
2408 		goto revert_cert;
2409 
2410 	/* Debug cert type */
2411 	switch (type) {
2412 	case TA:
2413 		break;
2414 	case CA:
2415 		pr_val_debug("Type: CA");
2416 		break;
2417 	case BGPSEC:
2418 		pr_val_debug("Type: BGPsec EE. Ignoring...");
2419 		goto revert_cert;
2420 	case EE:
2421 		pr_val_debug("Type: unexpected, validated as CA");
2422 		break;
2423 	}
2424 
2425 	error = certificate_validate_rfc6487(cert, type);
2426 	if (error)
2427 		goto revert_cert;
2428 
2429 	sia_ca_uris_init(&sia_uris);
2430 	memset(&refs, 0, sizeof(refs));
2431 
2432 	switch (type) {
2433 	case TA:
2434 		error = certificate_validate_extensions_ta(cert, &sia_uris,
2435 		    &policy);
2436 		break;
2437 	default:
2438 		/* Validate as a CA */
2439 		error = certificate_validate_extensions_ca(cert, &sia_uris,
2440 		    &refs, &policy);
2441 		break;
2442 	}
2443 	if (error)
2444 		goto revert_uris;
2445 
2446 	if (!IS_TA) {
2447 		error = certificate_validate_aia(refs.caIssuers, cert);
2448 		if (error)
2449 			goto revert_uris;
2450 	}
2451 
2452 	error = refs_validate_ca(&refs, rpp_parent);
2453 	if (error)
2454 		goto revert_uris;
2455 
2456 	/* Identify if this is a new repository before fetching it */
2457 	new_level = false;
2458 	error = set_repository_level(IS_TA, state, cert_uri, &sia_uris,
2459 	    &new_level);
2460 	if (error)
2461 		goto revert_uris;
2462 
2463 	/*
2464 	 * RFC 6481 section 5: "when the repository publication point contents
2465 	 * are updated, a repository operator cannot assure RPs that the
2466 	 * manifest contents and the repository contents will be precisely
2467 	 * aligned at all times"
2468 	 *
2469 	 * Trying to avoid this issue, download the CA repository and validate
2470 	 * manifest (and its content) again.
2471 	 *
2472 	 * Avoid to re-download the repo if the mft was fetched with RRDP.
2473 	 */
2474 	repo_retry = true;
2475 	error = use_access_method(&sia_uris, exec_rsync_method,
2476 	    exec_rrdp_method, new_level, &repo_retry);
2477 	if (error)
2478 		goto revert_uris;
2479 
2480 	do {
2481 		/* Validate the manifest (@mft) pointed by the certificate */
2482 		error = x509stack_push(validation_certstack(state), cert_uri,
2483 		    cert, policy, IS_TA);
2484 		if (error)
2485 			goto revert_uris;
2486 
2487 		cert = NULL; /* Ownership stolen */
2488 
2489 		error = handle_manifest(sia_uris.mft.uri, !repo_retry, &pp);
2490 		if (error == 0 || !repo_retry)
2491 			break;
2492 
2493 		/*
2494 		 * Don't reach here if:
2495 		 * - Manifest is valid.
2496 		 * - Working with local files due to a download error.
2497 		 * - RRDP was utilized to fetch the manifest.
2498 		 * - There was a previous attempt to re-fetch the repository.
2499 		 */
2500 		pr_val_info("Retrying repository download to discard 'transient inconsistency' manifest issue (see RFC 6481 section 5) '%s'",
2501 		    uri_val_get_printable(sia_uris.caRepository.uri));
2502 		error = rsync_download_files(sia_uris.caRepository.uri, false, true);
2503 		if (error)
2504 			break;
2505 
2506 		/* Cancel stack, reload certificate (no need to revalidate) */
2507 		x509stack_cancel(validation_certstack(state));
2508 		error = certificate_load(cert_uri, &cert);
2509 		if (error)
2510 			goto revert_uris;
2511 
2512 		repo_retry = false;
2513 	} while (true);
2514 
2515 	if (error) {
2516 		x509stack_cancel(validation_certstack(state));
2517 		goto revert_uris;
2518 	}
2519 
2520 	/* -- Validate & traverse the RPP (@pp) described by the manifest -- */
2521 	rpp_traverse(pp);
2522 
2523 	rpp_refput(pp);
2524 revert_uris:
2525 	sia_ca_uris_cleanup(&sia_uris);
2526 	refs_cleanup(&refs);
2527 revert_cert:
2528 	if (cert != NULL)
2529 		X509_free(cert);
2530 revert_fnstack_and_debug:
2531 	fnstack_pop();
2532 	pr_val_debug("}");
2533 	return error;
2534 }
2535