1 #include "cert_stack.h"
2 
3 #include <sys/queue.h>
4 
5 #include "resource.h"
6 #include "str_token.h"
7 #include "thread_var.h"
8 #include "data_structure/array_list.h"
9 #include "object/name.h"
10 
11 enum defer_node_type {
12 	DNT_SEPARATOR,
13 	DNT_CERT,
14 };
15 
16 struct defer_node {
17 	enum defer_node_type type;
18 
19 	/**
20 	 * This field is only relevant if @type == PCT_CERT.
21 	 * Do not dereference members otherwise.
22 	 */
23 	struct deferred_cert deferred;
24 
25 	/** Used by certstack. Points to the next stacked certificate. */
26 	SLIST_ENTRY(defer_node) next;
27 };
28 
29 SLIST_HEAD(defer_stack, defer_node);
30 
31 struct serial_number {
32 	BIGNUM *number;
33 	char *file; /* File where this serial number was found. */
34 };
35 
36 STATIC_ARRAY_LIST(serial_numbers, struct serial_number)
37 
38 struct subject_name {
39 	struct rfc5280_name *name;
40 	char *file; /* File where this subject name was found. */
41 };
42 
43 STATIC_ARRAY_LIST(subjects, struct subject_name)
44 
45 /**
46  * Cached certificate data.
47  */
48 struct metadata_node {
49 	struct rpki_uri *uri;
50 	struct resources *resources;
51 	/*
52 	 * Serial numbers of the children.
53 	 * This is an unsorted array list for two reasons: Certificates usually
54 	 * don't have many children, and I'm running out of time.
55 	 */
56 	struct serial_numbers serials;
57 	struct subjects subjects;
58 
59 	/*
60 	 * Certificate repository "level". This aims to identify if the
61 	 * certificate is located at a distinct server than its father (common
62 	 * case when the RIRs delegate RPKI repositories).
63 	 */
64 	unsigned int level;
65 
66 	/** Used by certstack. Points to the next stacked certificate. */
67 	SLIST_ENTRY(metadata_node) next;
68 };
69 
70 SLIST_HEAD(metadata_stack, metadata_node);
71 
72 /**
73  * This is the foundation through which we pull off our iterative traversal,
74  * as opposed to a stack-threatening recursive one.
75  *
76  * It is a bunch of data that replaces the one that would normally be allocated
77  * in the function stack.
78  */
79 struct cert_stack {
80 	/**
81 	 * Defer stack. Certificates we haven't iterated through yet.
82 	 *
83 	 * Every time a certificate validates successfully, its children are
84 	 * stored here so they can be traversed later.
85 	 */
86 	struct defer_stack defers;
87 
88 	/**
89 	 * x509 stack. Parents of the certificate we're currently iterating
90 	 * through.
91 	 * Formatted for immediate libcrypto consumption.
92 	 */
93 	STACK_OF(X509) *x509s;
94 
95 	/**
96 	 * Stacked additional data to each @x509 certificate.
97 	 *
98 	 * (These two stacks should always have the same size. The reason why I
99 	 * don't combine them is because libcrypto's validation function needs
100 	 * the X509 stack, and I'm not creating it over and over again.)
101 	 *
102 	 * (This is a SLIST and not a STACK_OF because the OpenSSL stack
103 	 * implementation is different than the LibreSSL one, and the latter is
104 	 * seemingly not intended to be used outside of its library.)
105 	 */
106 	struct metadata_stack metas;
107 };
108 
109 int
certstack_create(struct cert_stack ** result)110 certstack_create(struct cert_stack **result)
111 {
112 	struct cert_stack *stack;
113 
114 	stack = malloc(sizeof(struct cert_stack));
115 	if (stack == NULL)
116 		return pr_enomem();
117 
118 	stack->x509s = sk_X509_new_null();
119 	if (stack->x509s == NULL) {
120 		free(stack);
121 		return val_crypto_err("sk_X509_new_null() returned NULL");
122 	}
123 
124 	SLIST_INIT(&stack->defers);
125 	SLIST_INIT(&stack->metas);
126 
127 	*result = stack;
128 	return 0;
129 }
130 
131 static void
defer_destroy(struct defer_node * defer)132 defer_destroy(struct defer_node *defer)
133 {
134 	switch (defer->type) {
135 	case DNT_SEPARATOR:
136 		break;
137 	case DNT_CERT:
138 		uri_refput(defer->deferred.uri);
139 		rpp_refput(defer->deferred.pp);
140 		break;
141 	}
142 
143 	free(defer);
144 }
145 
146 static void
serial_cleanup(struct serial_number * serial)147 serial_cleanup(struct serial_number *serial)
148 {
149 	BN_free(serial->number);
150 	free(serial->file);
151 }
152 
153 static void
subject_cleanup(struct subject_name * subject)154 subject_cleanup(struct subject_name *subject)
155 {
156 	x509_name_put(subject->name);
157 	free(subject->file);
158 }
159 
160 static void
meta_destroy(struct metadata_node * meta)161 meta_destroy(struct metadata_node *meta)
162 {
163 	uri_refput(meta->uri);
164 	resources_destroy(meta->resources);
165 	serial_numbers_cleanup(&meta->serials, serial_cleanup);
166 	subjects_cleanup(&meta->subjects, subject_cleanup);
167 	free(meta);
168 }
169 
170 void
certstack_destroy(struct cert_stack * stack)171 certstack_destroy(struct cert_stack *stack)
172 {
173 	unsigned int stack_size;
174 	struct metadata_node *meta;
175 	struct defer_node *post;
176 
177 	stack_size = 0;
178 	while (!SLIST_EMPTY(&stack->defers)) {
179 		post = SLIST_FIRST(&stack->defers);
180 		SLIST_REMOVE_HEAD(&stack->defers, next);
181 		defer_destroy(post);
182 		stack_size++;
183 	}
184 	pr_val_debug("Deleted %u deferred certificates.", stack_size);
185 
186 	pr_val_debug("Deleting %d stacked x509s.", sk_X509_num(stack->x509s));
187 	sk_X509_pop_free(stack->x509s, X509_free);
188 
189 	stack_size = 0;
190 	while (!SLIST_EMPTY(&stack->metas)) {
191 		meta = SLIST_FIRST(&stack->metas);
192 		SLIST_REMOVE_HEAD(&stack->metas, next);
193 		meta_destroy(meta);
194 		stack_size++;
195 	}
196 	pr_val_debug("Deleted %u metadatas.", stack_size);
197 
198 	free(stack);
199 }
200 
201 int
deferstack_push(struct cert_stack * stack,struct deferred_cert * deferred)202 deferstack_push(struct cert_stack *stack, struct deferred_cert *deferred)
203 {
204 	struct defer_node *node;
205 
206 	node = malloc(sizeof(struct defer_node));
207 	if (node == NULL)
208 		return pr_enomem();
209 
210 	node->type = DNT_CERT;
211 	node->deferred = *deferred;
212 	uri_refget(deferred->uri);
213 	rpp_refget(deferred->pp);
214 	SLIST_INSERT_HEAD(&stack->defers, node, next);
215 	return 0;
216 }
217 
218 static void
x509stack_pop(struct cert_stack * stack)219 x509stack_pop(struct cert_stack *stack)
220 {
221 	X509 *cert;
222 	struct metadata_node *meta;
223 
224 	cert = sk_X509_pop(stack->x509s);
225 	if (cert == NULL)
226 		pr_crit("Attempted to pop empty X509 stack");
227 	X509_free(cert);
228 
229 	meta = SLIST_FIRST(&stack->metas);
230 	if (meta == NULL)
231 		pr_crit("Attempted to pop empty metadata stack");
232 	SLIST_REMOVE_HEAD(&stack->metas, next);
233 	meta_destroy(meta);
234 }
235 
236 /**
237  * Contract: Returns either 0 or -ENOENT. No other outcomes.
238  */
239 int
deferstack_pop(struct cert_stack * stack,struct deferred_cert * result)240 deferstack_pop(struct cert_stack *stack, struct deferred_cert *result)
241 {
242 	struct defer_node *node;
243 
244 again:	node = SLIST_FIRST(&stack->defers);
245 	if (node == NULL)
246 		return -ENOENT;
247 
248 	if (node->type == DNT_SEPARATOR) {
249 		x509stack_pop(stack);
250 
251 		SLIST_REMOVE_HEAD(&stack->defers, next);
252 		defer_destroy(node);
253 		goto again;
254 	}
255 
256 	*result = node->deferred;
257 	uri_refget(node->deferred.uri);
258 	rpp_refget(node->deferred.pp);
259 
260 	SLIST_REMOVE_HEAD(&stack->defers, next);
261 	defer_destroy(node);
262 	return 0;
263 }
264 
265 bool
deferstack_is_empty(struct cert_stack * stack)266 deferstack_is_empty(struct cert_stack *stack)
267 {
268 	return SLIST_EMPTY(&stack->defers);
269 }
270 
271 static int
init_resources(X509 * x509,enum rpki_policy policy,enum cert_type type,struct resources ** _result)272 init_resources(X509 *x509, enum rpki_policy policy, enum cert_type type,
273     struct resources **_result)
274 {
275 	struct resources *result;
276 	int error;
277 
278 	result = resources_create(false);
279 	if (result == NULL)
280 		return pr_enomem();
281 
282 	resources_set_policy(result, policy);
283 	error = certificate_get_resources(x509, result, type);
284 	if (error)
285 		goto fail;
286 
287 	/*
288 	 * rfc8630#section-2.3
289 	 * "The INR extension(s) of this TA MUST contain a non-empty set of
290 	 * number resources."
291 	 * The "It MUST NOT use the "inherit" form of the INR extension(s)"
292 	 * part is already handled in certificate_get_resources().
293 	 */
294 	if (type == TA && resources_empty(result)) {
295 		error = pr_val_err("Trust Anchor certificate does not define any number resources.");
296 		goto fail;
297 	}
298 
299 	*_result = result;
300 	return 0;
301 
302 fail:
303 	resources_destroy(result);
304 	return error;
305 }
306 
307 static int
init_level(struct cert_stack * stack,unsigned int * _result)308 init_level(struct cert_stack *stack, unsigned int *_result)
309 {
310 	struct metadata_node *head_meta;
311 	unsigned int work_repo_level;
312 	unsigned int result;
313 
314 	/*
315 	 * Bruh, I don't understand the point of this block.
316 	 * Why can't it just be `result = working_repo_peek_level();`?
317 	 */
318 
319 	result = 0;
320 	work_repo_level = working_repo_peek_level();
321 	head_meta = SLIST_FIRST(&stack->metas);
322 	if (head_meta != NULL && work_repo_level > head_meta->level)
323 		result = work_repo_level;
324 
325 	*_result = result;
326 	return 0;
327 }
328 
329 static struct defer_node *
create_separator(void)330 create_separator(void)
331 {
332 	struct defer_node *result;
333 
334 	result = malloc(sizeof(struct defer_node));
335 	if (result == NULL)
336 		return NULL;
337 
338 	result->type = DNT_SEPARATOR;
339 	return result;
340 }
341 
342 /** Steals ownership of @x509 on success. */
343 int
x509stack_push(struct cert_stack * stack,struct rpki_uri * uri,X509 * x509,enum rpki_policy policy,enum cert_type type)344 x509stack_push(struct cert_stack *stack, struct rpki_uri *uri, X509 *x509,
345     enum rpki_policy policy, enum cert_type type)
346 {
347 	struct metadata_node *meta;
348 	struct defer_node *defer_separator;
349 	int ok;
350 	int error;
351 
352 	meta = malloc(sizeof(struct metadata_node));
353 	if (meta == NULL)
354 		return pr_enomem();
355 
356 	meta->uri = uri;
357 	uri_refget(uri);
358 	serial_numbers_init(&meta->serials);
359 	subjects_init(&meta->subjects);
360 
361 	error = init_resources(x509, policy, type, &meta->resources);
362 	if (error)
363 		goto cleanup_subjects;
364 
365 	error = init_level(stack, &meta->level); /* Does not need a revert */
366 	if (error)
367 		goto destroy_resources;
368 
369 	defer_separator = create_separator();
370 	if (defer_separator == NULL) {
371 		error = pr_enomem();
372 		goto destroy_resources;
373 	}
374 
375 	ok = sk_X509_push(stack->x509s, x509);
376 	if (ok <= 0) {
377 		error = val_crypto_err(
378 		    "Could not add certificate to trusted stack: %d", ok);
379 		goto destroy_separator;
380 	}
381 
382 	SLIST_INSERT_HEAD(&stack->defers, defer_separator, next);
383 	SLIST_INSERT_HEAD(&stack->metas, meta, next);
384 
385 	return 0;
386 
387 destroy_separator:
388 	free(defer_separator);
389 destroy_resources:
390 	resources_destroy(meta->resources);
391 cleanup_subjects:
392 	subjects_cleanup(&meta->subjects, subject_cleanup);
393 	serial_numbers_cleanup(&meta->serials, serial_cleanup);
394 	uri_refput(meta->uri);
395 	free(meta);
396 	return error;
397 }
398 
399 /**
400  * This one is intended to revert a recent x509 push.
401  * Reverts that particular push.
402  *
403  * (x509 stack elements are otherwise indirectly popped through
404  * deferstack_pop().)
405  */
406 void
x509stack_cancel(struct cert_stack * stack)407 x509stack_cancel(struct cert_stack *stack)
408 {
409 	struct defer_node *defer_separator;
410 
411 	x509stack_pop(stack);
412 
413 	defer_separator = SLIST_FIRST(&stack->defers);
414 	if (defer_separator == NULL)
415 		pr_crit("Attempted to pop empty defer stack");
416 	SLIST_REMOVE_HEAD(&stack->defers, next);
417 	defer_destroy(defer_separator);
418 }
419 
420 X509 *
x509stack_peek(struct cert_stack * stack)421 x509stack_peek(struct cert_stack *stack)
422 {
423 	return sk_X509_value(stack->x509s, sk_X509_num(stack->x509s) - 1);
424 }
425 
426 /** Does not grab reference. */
427 struct rpki_uri *
x509stack_peek_uri(struct cert_stack * stack)428 x509stack_peek_uri(struct cert_stack *stack)
429 {
430 	struct metadata_node *meta = SLIST_FIRST(&stack->metas);
431 	return (meta != NULL) ? meta->uri : NULL;
432 }
433 
434 struct resources *
x509stack_peek_resources(struct cert_stack * stack)435 x509stack_peek_resources(struct cert_stack *stack)
436 {
437 	struct metadata_node *meta = SLIST_FIRST(&stack->metas);
438 	return (meta != NULL) ? meta->resources : NULL;
439 }
440 
441 unsigned int
x509stack_peek_level(struct cert_stack * stack)442 x509stack_peek_level(struct cert_stack *stack)
443 {
444 	struct metadata_node *meta = SLIST_FIRST(&stack->metas);
445 	return (meta != NULL) ? meta->level : 0;
446 }
447 
448 static int
get_current_file_name(char ** _result)449 get_current_file_name(char **_result)
450 {
451 	char const *tmp;
452 	char *result;
453 
454 	tmp = fnstack_peek();
455 	if (tmp == NULL)
456 		pr_crit("The file name stack is empty.");
457 
458 	result = strdup(tmp);
459 	if (result == NULL)
460 		return pr_enomem();
461 
462 	*_result = result;
463 	return 0;
464 }
465 
466 /**
467  * Intended to validate serial number uniqueness.
468  * "Stores" the serial number in the current relevant certificate metadata,
469  * and complains if there's a collision. That's all.
470  *
471  * This function will steal ownership of @number on success.
472  */
473 int
x509stack_store_serial(struct cert_stack * stack,BIGNUM * number)474 x509stack_store_serial(struct cert_stack *stack, BIGNUM *number)
475 {
476 	struct metadata_node *meta;
477 	struct serial_number *cursor;
478 	array_index i;
479 	struct serial_number duplicate;
480 	char *string;
481 	int error;
482 
483 	/* Remember to free @number if you return 0 but don't store it. */
484 
485 	meta = SLIST_FIRST(&stack->metas);
486 	if (meta == NULL) {
487 		BN_free(number);
488 		return 0; /* The TA lacks siblings, so serial is unique. */
489 	}
490 
491 	/*
492 	 * Note: This is is reported as a warning, even though duplicate serial
493 	 * numbers are clearly a violation of the RFC and common sense.
494 	 *
495 	 * But it cannot be simply upgraded into an error because we are
496 	 * realizing the problem too late; our traversal is depth-first, so we
497 	 * already approved the other bogus certificate and its children.
498 	 * (I don't think changing to a breath-first traversal would be a good
499 	 * idea; the RAM usage would skyrocket because, since we need the entire
500 	 * certificate path to the root to validate any certificate, we would
501 	 * end up having the entire tree loaded in memory by the time we're done
502 	 * traversing.)
503 	 *
504 	 * So instead of arbitrarily approving one certificate but not the
505 	 * other, we will accept both but report a warning.
506 	 *
507 	 * Also: It's pretty odd; a significant amount of certificates seem to
508 	 * be breaking this rule. Maybe we're the only ones catching it?
509 	 *
510 	 * TODO I haven't seen this warning in a while. Review.
511 	 */
512 	ARRAYLIST_FOREACH(&meta->serials, cursor, i) {
513 		if (BN_cmp(cursor->number, number) == 0) {
514 			BN2string(number, &string);
515 			pr_val_warn("Serial number '%s' is not unique. (Also found in '%s'.)",
516 			    string, cursor->file);
517 			BN_free(number);
518 			free(string);
519 			return 0;
520 		}
521 	}
522 
523 	duplicate.number = number;
524 	error = get_current_file_name(&duplicate.file);
525 	if (error)
526 		return error;
527 
528 	error = serial_numbers_add(&meta->serials, &duplicate);
529 	if (error)
530 		free(duplicate.file);
531 
532 	return error;
533 }
534 
535 /**
536  * Intended to validate subject uniqueness.
537  * "Stores" the subject in the current relevant certificate metadata, and
538  * complains if there's a collision. The @cb should check the primary key of
539  * the subject, it will be called when a subject isn't unique (certificate
540  * shares the subject but not the public key). That's all.
541  */
542 int
x509stack_store_subject(struct cert_stack * stack,struct rfc5280_name * subject,subject_pk_check_cb cb,void * arg)543 x509stack_store_subject(struct cert_stack *stack, struct rfc5280_name *subject,
544     subject_pk_check_cb cb, void *arg)
545 {
546 	struct metadata_node *meta;
547 	struct subject_name *cursor;
548 	array_index i;
549 	struct subject_name duplicate;
550 	bool duplicated;
551 	int error;
552 
553 	/*
554 	 * There's something that's not clicking with me:
555 	 *
556 	 * "Each distinct subordinate CA and
557 	 * EE certified by the issuer MUST be identified using a subject name
558 	 * that is unique per issuer.  In this context, 'distinct' is defined as
559 	 * an entity and a given public key."
560 	 *
561 	 * Does the last sentence have any significance to us? I don't even
562 	 * understand why the requirement exists. 5280 and 6487 don't even
563 	 * define "entity." We'll take the closest definition from the context,
564 	 * specifically from RFC 6484 or RFC 6481 (both RFCs don't define
565 	 * "entity" explicitly, but use the word in a way that it can be
566 	 * inferred what it means).
567 	 *
568 	 * "An issuer SHOULD use a different
569 	 * subject name if the subject's key pair has changed (i.e., when the CA
570 	 * issues a certificate as part of re-keying the subject.)"
571 	 *
572 	 * It's really weird that it seems to be rewording the same requirement
573 	 * except the first version is defined as MUST and the second one is
574 	 * defined as SHOULD.
575 	 *
576 	 * Ugh. Okay. Let's use some common sense. There are four possible
577 	 * situations:
578 	 *
579 	 * - Certificates do not share name nor public key. We should accept
580 	 *   this.
581 	 * - Certificates share name, but not public key. We should reject this.
582 	 * - Certificates share public key, but not name. This is basically
583 	 *   impossible, but fine nonetheless. Accept.
584 	 *   (But maybe issue a warning. It sounds like the two children can
585 	 *   impersonate each other.)
586 	 * - Certificates share name and public key. This likely means that we
587 	 *   are looking at two different versions of the same certificate.
588 	 *   Accept. (see rfc6484#section-4.7.1 for an example)
589 	 *
590 	 */
591 
592 	meta = SLIST_FIRST(&stack->metas);
593 	if (meta == NULL)
594 		return 0; /* The TA lacks siblings, so subject is unique. */
595 
596 	/* See the large comment in certstack_x509_store_serial(). */
597 	duplicated = false;
598 	ARRAYLIST_FOREACH(&meta->subjects, cursor, i) {
599 		if (x509_name_equals(cursor->name, subject)) {
600 			error = cb(&duplicated, cursor->file, arg);
601 			if (error)
602 				return error;
603 
604 			if (!duplicated)
605 				continue;
606 
607 			char const *serial = x509_name_serialNumber(subject);
608 			pr_val_warn("Subject name '%s%s%s' is not unique. (Also found in '%s'.)",
609 			    x509_name_commonName(subject),
610 			    (serial != NULL) ? "/" : "",
611 			    (serial != NULL) ? serial : "",
612 			    cursor->file);
613 			return 0;
614 		}
615 	}
616 
617 	duplicate.name = subject;
618 	x509_name_get(subject);
619 
620 	error = get_current_file_name(&duplicate.file);
621 	if (error)
622 		goto revert_name;
623 
624 	error = subjects_add(&meta->subjects, &duplicate);
625 	if (error)
626 		goto revert_file;
627 
628 	return 0;
629 
630 revert_file:
631 	free(duplicate.file);
632 revert_name:
633 	x509_name_put(subject);
634 	return error;
635 }
636 
STACK_OF(X509)637 STACK_OF(X509) *
638 certstack_get_x509s(struct cert_stack *stack)
639 {
640 	return stack->x509s;
641 }
642 
643 int
certstack_get_x509_num(struct cert_stack * stack)644 certstack_get_x509_num(struct cert_stack *stack)
645 {
646 	return sk_X509_num(stack->x509s);
647 }
648