Added support for client certificates (both client-side and server-side, but still...
[BearSSL] / inc / bearssl_x509.h
1 /*
2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #ifndef BR_BEARSSL_X509_H__
26 #define BR_BEARSSL_X509_H__
27
28 #include <stddef.h>
29 #include <stdint.h>
30
31 #include "bearssl_ec.h"
32 #include "bearssl_hash.h"
33 #include "bearssl_rsa.h"
34
35 /** \file bearssl_x509.h
36 *
37 * # X.509 Certificate Chain Processing
38 *
39 * An X.509 processing engine receives an X.509 chain, chunk by chunk,
40 * as received from a SSL/TLS client or server (the client receives the
41 * server's certificate chain, and the server receives the client's
42 * certificate chain if it requested a client certificate). The chain
43 * is thus injected in the engine in SSL order (end-entity first).
44 *
45 * The engine's job is to return the public key to use for SSL/TLS.
46 * How exactly that key is obtained and verified is entirely up to the
47 * engine.
48 *
49 * **The "known key" engine** returns a public key which is already known
50 * from out-of-band information (e.g. the client _remembers_ the key from
51 * a previous connection, as in the usual SSH model). This is the simplest
52 * engine since it simply ignores the chain, thereby avoiding the need
53 * for any decoding logic.
54 *
55 * **The "minimal" engine** implements minimal X.509 decoding and chain
56 * validation:
57 *
58 * - The provided chain should validate "as is". There is no attempt
59 * at reordering, skipping or downloading extra certificates.
60 *
61 * - X.509 v1, v2 and v3 certificates are supported.
62 *
63 * - Trust anchors are a DN and a public key. Each anchor is either a
64 * "CA" anchor, or a non-CA.
65 *
66 * - If the end-entity certificate matches a non-CA anchor (subject DN
67 * is equal to the non-CA name, and public key is also identical to
68 * the anchor key), then this is a _direct trust_ case and the
69 * remaining certificates are ignored.
70 *
71 * - Unless direct trust is applied, the chain must be verifiable up to
72 * a certificate whose issuer DN matches the DN from a "CA" trust anchor,
73 * and whose signature is verifiable against that anchor's public key.
74 * Subsequent certificates in the chain are ignored.
75 *
76 * - The engine verifies subject/issuer DN matching, and enforces
77 * processing of Basic Constraints and Key Usage extensions. The
78 * Authority Key Identifier, Subject Key Identifier, Issuer Alt Name,
79 * Subject Directory Attribute, CRL Distribution Points, Freshest CRL,
80 * Authority Info Access and Subject Info Access extensions are
81 * ignored. The Subject Alt Name is decoded for the end-entity
82 * certificate under some conditions (see below). Other extensions
83 * are ignored if non-critical, or imply chain rejection if critical.
84 *
85 * - The Subject Alt Name extension is parsed for names of type `dNSName`
86 * when decoding the end-entity certificate, and only if there is a
87 * server name to match. If there is no SAN extension, then the
88 * Common Name from the subjectDN is used. That name matching is
89 * case-insensitive and honours a single starting wildcard (i.e. if
90 * the name in the certificate starts with "`*.`" then this matches
91 * any word as first element). Note: this name matching is performed
92 * also in the "direct trust" model.
93 *
94 * - DN matching is byte-to-byte equality (a future version might
95 * include some limited processing for case-insensitive matching and
96 * whitespace normalisation).
97 *
98 * - Successful validation produces a public key type but also a set
99 * of allowed usages (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
100 * The caller is responsible for checking that the key type and
101 * usages are compatible with the expected values (e.g. with the
102 * selected cipher suite, when the client validates the server's
103 * certificate).
104 *
105 * **Important caveats:**
106 *
107 * - The "minimal" engine does not check revocation status. The relevant
108 * extensions are ignored, and CRL or OCSP responses are not gathered
109 * or checked.
110 *
111 * - The "minimal" engine does not currently support Name Constraints
112 * (some basic functionality to handle sub-domains may be added in a
113 * later version).
114 *
115 * - The decoder is not "validating" in the sense that it won't reject
116 * some certificates with invalid field values when these fields are
117 * not actually processed.
118 */
119
120 /*
121 * X.509 error codes are in the 32..63 range.
122 */
123
124 /** \brief X.509 status: validation was successful; this is not actually
125 an error. */
126 #define BR_ERR_X509_OK 32
127
128 /** \brief X.509 status: invalid value in an ASN.1 structure. */
129 #define BR_ERR_X509_INVALID_VALUE 33
130
131 /** \brief X.509 status: truncated certificate. */
132 #define BR_ERR_X509_TRUNCATED 34
133
134 /** \brief X.509 status: empty certificate chain (no certificate at all). */
135 #define BR_ERR_X509_EMPTY_CHAIN 35
136
137 /** \brief X.509 status: decoding error: inner element extends beyond
138 outer element size. */
139 #define BR_ERR_X509_INNER_TRUNC 36
140
141 /** \brief X.509 status: decoding error: unsupported tag class (application
142 or private). */
143 #define BR_ERR_X509_BAD_TAG_CLASS 37
144
145 /** \brief X.509 status: decoding error: unsupported tag value. */
146 #define BR_ERR_X509_BAD_TAG_VALUE 38
147
148 /** \brief X.509 status: decoding error: indefinite length. */
149 #define BR_ERR_X509_INDEFINITE_LENGTH 39
150
151 /** \brief X.509 status: decoding error: extraneous element. */
152 #define BR_ERR_X509_EXTRA_ELEMENT 40
153
154 /** \brief X.509 status: decoding error: unexpected element. */
155 #define BR_ERR_X509_UNEXPECTED 41
156
157 /** \brief X.509 status: decoding error: expected constructed element, but
158 is primitive. */
159 #define BR_ERR_X509_NOT_CONSTRUCTED 42
160
161 /** \brief X.509 status: decoding error: expected primitive element, but
162 is constructed. */
163 #define BR_ERR_X509_NOT_PRIMITIVE 43
164
165 /** \brief X.509 status: decoding error: BIT STRING length is not multiple
166 of 8. */
167 #define BR_ERR_X509_PARTIAL_BYTE 44
168
169 /** \brief X.509 status: decoding error: BOOLEAN value has invalid length. */
170 #define BR_ERR_X509_BAD_BOOLEAN 45
171
172 /** \brief X.509 status: decoding error: value is off-limits. */
173 #define BR_ERR_X509_OVERFLOW 46
174
175 /** \brief X.509 status: invalid distinguished name. */
176 #define BR_ERR_X509_BAD_DN 47
177
178 /** \brief X.509 status: invalid date/time representation. */
179 #define BR_ERR_X509_BAD_TIME 48
180
181 /** \brief X.509 status: certificate contains unsupported features that
182 cannot be ignored. */
183 #define BR_ERR_X509_UNSUPPORTED 49
184
185 /** \brief X.509 status: key or signature size exceeds internal limits. */
186 #define BR_ERR_X509_LIMIT_EXCEEDED 50
187
188 /** \brief X.509 status: key type does not match that which was expected. */
189 #define BR_ERR_X509_WRONG_KEY_TYPE 51
190
191 /** \brief X.509 status: signature is invalid. */
192 #define BR_ERR_X509_BAD_SIGNATURE 52
193
194 /** \brief X.509 status: validation time is unknown. */
195 #define BR_ERR_X509_TIME_UNKNOWN 53
196
197 /** \brief X.509 status: certificate is expired or not yet valid. */
198 #define BR_ERR_X509_EXPIRED 54
199
200 /** \brief X.509 status: issuer/subject DN mismatch in the chain. */
201 #define BR_ERR_X509_DN_MISMATCH 55
202
203 /** \brief X.509 status: expected server name was not found in the chain. */
204 #define BR_ERR_X509_BAD_SERVER_NAME 56
205
206 /** \brief X.509 status: unknown critical extension in certificate. */
207 #define BR_ERR_X509_CRITICAL_EXTENSION 57
208
209 /** \brief X.509 status: not a CA, or path length constraint violation */
210 #define BR_ERR_X509_NOT_CA 58
211
212 /** \brief X.509 status: Key Usage extension prohibits intended usage. */
213 #define BR_ERR_X509_FORBIDDEN_KEY_USAGE 59
214
215 /** \brief X.509 status: public key found in certificate is too small. */
216 #define BR_ERR_X509_WEAK_PUBLIC_KEY 60
217
218 /** \brief X.509 status: chain could not be linked to a trust anchor. */
219 #define BR_ERR_X509_NOT_TRUSTED 62
220
221 /**
222 * \brief Aggregate structure for public keys.
223 */
224 typedef struct {
225 /** \brief Key type: `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC` */
226 unsigned char key_type;
227 /** \brief Actual public key. */
228 union {
229 /** \brief RSA public key. */
230 br_rsa_public_key rsa;
231 /** \brief EC public key. */
232 br_ec_public_key ec;
233 } key;
234 } br_x509_pkey;
235
236 /**
237 * \brief Distinguished Name (X.500) structure.
238 *
239 * The DN is DER-encoded.
240 */
241 typedef struct {
242 /** \brief Encoded DN data. */
243 unsigned char *data;
244 /** \brief Encoded DN length (in bytes). */
245 size_t len;
246 } br_x500_name;
247
248 /**
249 * \brief Trust anchor structure.
250 */
251 typedef struct {
252 /** \brief Encoded DN (X.500 name). */
253 br_x500_name dn;
254 /** \brief Anchor flags (e.g. `BR_X509_TA_CA`). */
255 unsigned flags;
256 /** \brief Anchor public key. */
257 br_x509_pkey pkey;
258 } br_x509_trust_anchor;
259
260 /**
261 * \brief Trust anchor flag: CA.
262 *
263 * A "CA" anchor is deemed fit to verify signatures on certificates.
264 * A "non-CA" anchor is accepted only for direct trust (server's
265 * certificate name and key match the anchor).
266 */
267 #define BR_X509_TA_CA 0x0001
268
269 /*
270 * Key type: combination of a basic key type (low 4 bits) and some
271 * optional flags.
272 *
273 * For a public key, the basic key type only is set.
274 *
275 * For an expected key type, the flags indicate the intended purpose(s)
276 * for the key; the basic key type may be set to 0 to indicate that any
277 * key type compatible with the indicated purpose is acceptable.
278 */
279 /** \brief Key type: algorithm is RSA. */
280 #define BR_KEYTYPE_RSA 1
281 /** \brief Key type: algorithm is EC. */
282 #define BR_KEYTYPE_EC 2
283
284 /**
285 * \brief Key type: usage is "key exchange".
286 *
287 * This value is combined (with bitwise OR) with the algorithm
288 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
289 * validation engine that it should find a public key of that type,
290 * fit for key exchanges (e.g. `TLS_RSA_*` and `TLS_ECDH_*` cipher
291 * suites).
292 */
293 #define BR_KEYTYPE_KEYX 0x10
294
295 /**
296 * \brief Key type: usage is "signature".
297 *
298 * This value is combined (with bitwise OR) with the algorithm
299 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
300 * validation engine that it should find a public key of that type,
301 * fit for signatures (e.g. `TLS_ECDHE_*` cipher suites).
302 */
303 #define BR_KEYTYPE_SIGN 0x20
304
305 /*
306 * start_chain Called when a new chain is started. If 'server_name'
307 * is not NULL and non-empty, then it is a name that
308 * should be looked for in the EE certificate (in the
309 * SAN extension as dNSName, or in the subjectDN's CN
310 * if there is no SAN extension).
311 * The caller ensures that the provided 'server_name'
312 * pointer remains valid throughout validation.
313 *
314 * start_cert Begins a new certificate in the chain. The provided
315 * length is in bytes; this is the total certificate length.
316 *
317 * append Get some additional bytes for the current certificate.
318 *
319 * end_cert Ends the current certificate.
320 *
321 * end_chain Called at the end of the chain. Returned value is
322 * 0 on success, or a non-zero error code.
323 *
324 * get_pkey Returns the EE certificate public key.
325 *
326 * For a complete chain, start_chain() and end_chain() are always
327 * called. For each certificate, start_cert(), some append() calls, then
328 * end_cert() are called, in that order. There may be no append() call
329 * at all if the certificate is empty (which is not valid but may happen
330 * if the peer sends exactly that).
331 *
332 * get_pkey() shall return a pointer to a structure that is valid as
333 * long as a new chain is not started. This may be a sub-structure
334 * within the context for the engine. This function MAY return a valid
335 * pointer to a public key even in some cases of validation failure,
336 * depending on the validation engine.
337 */
338
339 /**
340 * \brief Class type for an X.509 engine.
341 *
342 * A certificate chain validation uses a caller-allocated context, which
343 * contains the running state for that validation. Methods are called
344 * in due order:
345 *
346 * - `start_chain()` is called at the start of the validation.
347 * - Certificates are processed one by one, in SSL order (end-entity
348 * comes first). For each certificate, the following methods are
349 * called:
350 *
351 * - `start_cert()` at the beginning of the certificate.
352 * - `append()` is called zero, one or more times, to provide
353 * the certificate (possibly in chunks).
354 * - `end_cert()` at the end of the certificate.
355 *
356 * - `end_chain()` is called when the last certificate in the chain
357 * was processed.
358 * - `get_pkey()` is called after chain processing, if the chain
359 * validation was succesfull.
360 *
361 * A context structure may be reused; the `start_chain()` method shall
362 * ensure (re)initialisation.
363 */
364 typedef struct br_x509_class_ br_x509_class;
365 struct br_x509_class_ {
366 /**
367 * \brief X.509 context size, in bytes.
368 */
369 size_t context_size;
370
371 /**
372 * \brief Start a new chain.
373 *
374 * This method shall set the vtable (first field) of the context
375 * structure.
376 *
377 * The `server_name`, if not `NULL`, will be considered as a
378 * fully qualified domain name, to be matched against the `dNSName`
379 * elements of the end-entity certificate's SAN extension (if there
380 * is no SAN, then the Common Name from the subjectDN will be used).
381 * If `server_name` is `NULL` then no such matching is performed.
382 *
383 * \param ctx validation context.
384 * \param server_name server name to match (or `NULL`).
385 */
386 void (*start_chain)(const br_x509_class **ctx,
387 const char *server_name);
388
389 /**
390 * \brief Start a new certificate.
391 *
392 * \param ctx validation context.
393 * \param length new certificate length (in bytes).
394 */
395 void (*start_cert)(const br_x509_class **ctx, uint32_t length);
396
397 /**
398 * \brief Receive some bytes for the current certificate.
399 *
400 * This function may be called several times in succession for
401 * a given certificate. The caller guarantees that for each
402 * call, `len` is not zero, and the sum of all chunk lengths
403 * for a certificate matches the total certificate length which
404 * was provided in the previous `start_cert()` call.
405 *
406 * If the new certificate is empty (no byte at all) then this
407 * function won't be called at all.
408 *
409 * \param ctx validation context.
410 * \param buf certificate data chunk.
411 * \param len certificate data chunk length (in bytes).
412 */
413 void (*append)(const br_x509_class **ctx,
414 const unsigned char *buf, size_t len);
415
416 /**
417 * \brief Finish the current certificate.
418 *
419 * This function is called when the end of the current certificate
420 * is reached.
421 *
422 * \param ctx validation context.
423 */
424 void (*end_cert)(const br_x509_class **ctx);
425
426 /**
427 * \brief Finish the chain.
428 *
429 * This function is called at the end of the chain. It shall
430 * return either 0 if the validation was successful, or a
431 * non-zero error code. The `BR_ERR_X509_*` constants are
432 * error codes, though other values may be possible.
433 *
434 * \param ctx validation context.
435 * \return 0 on success, or a non-zero error code.
436 */
437 unsigned (*end_chain)(const br_x509_class **ctx);
438
439 /**
440 * \brief Get the resulting end-entity public key.
441 *
442 * The decoded public key is returned. The returned pointer
443 * may be valid only as long as the context structure is
444 * unmodified, i.e. it may cease to be valid if the context
445 * is released or reused.
446 *
447 * This function _may_ return `NULL` if the validation failed.
448 * However, returning a public key does not mean that the
449 * validation was wholly successful; some engines may return
450 * a decoded public key even if the chain did not end on a
451 * trusted anchor.
452 *
453 * If validation succeeded and `usage` is not `NULL`, then
454 * `*usage` is filled with a combination of `BR_KEYTYPE_SIGN`
455 * and/or `BR_KEYTYPE_KEYX` that specifies the validated key
456 * usage types. It is the caller's responsibility to check
457 * that value against the intended use of the public key.
458 *
459 * \param ctx validation context.
460 * \return the end-entity public key, or `NULL`.
461 */
462 const br_x509_pkey *(*get_pkey)(
463 const br_x509_class *const *ctx, unsigned *usages);
464 };
465
466 /**
467 * \brief The "known key" X.509 engine structure.
468 *
469 * The structure contents are opaque (they shall not be accessed directly),
470 * except for the first field (the vtable).
471 *
472 * The "known key" engine returns an externally configured public key,
473 * and totally ignores the certificate contents.
474 */
475 typedef struct {
476 /** \brief Reference to the context vtable. */
477 const br_x509_class *vtable;
478 #ifndef BR_DOXYGEN_IGNORE
479 br_x509_pkey pkey;
480 unsigned usages;
481 #endif
482 } br_x509_knownkey_context;
483
484 /**
485 * \brief Class instance for the "known key" X.509 engine.
486 */
487 extern const br_x509_class br_x509_knownkey_vtable;
488
489 /**
490 * \brief Initialize a "known key" X.509 engine with a known RSA public key.
491 *
492 * The `usages` parameter indicates the allowed key usages for that key
493 * (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
494 *
495 * The provided pointers are linked in, not copied, so they must remain
496 * valid while the public key may be in usage.
497 *
498 * \param ctx context to initialise.
499 * \param pk known public key.
500 * \param usages allowed key usages.
501 */
502 void br_x509_knownkey_init_rsa(br_x509_knownkey_context *ctx,
503 const br_rsa_public_key *pk, unsigned usages);
504
505 /**
506 * \brief Initialize a "known key" X.509 engine with a known EC public key.
507 *
508 * The `usages` parameter indicates the allowed key usages for that key
509 * (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
510 *
511 * The provided pointers are linked in, not copied, so they must remain
512 * valid while the public key may be in usage.
513 *
514 * \param ctx context to initialise.
515 * \param pk known public key.
516 * \param usages allowed key usages.
517 */
518 void br_x509_knownkey_init_ec(br_x509_knownkey_context *ctx,
519 const br_ec_public_key *pk, unsigned usages);
520
521 #ifndef BR_DOXYGEN_IGNORE
522 /*
523 * The minimal X.509 engine has some state buffers which must be large
524 * enough to simultaneously accommodate:
525 * -- the public key extracted from the current certificate;
526 * -- the signature on the current certificate or on the previous
527 * certificate;
528 * -- the public key extracted from the EE certificate.
529 *
530 * We store public key elements in their raw unsigned big-endian
531 * encoding. We want to support up to RSA-4096 with a short (up to 64
532 * bits) public exponent, thus a buffer for a public key must have
533 * length at least 520 bytes. Similarly, a RSA-4096 signature has length
534 * 512 bytes.
535 *
536 * Though RSA public exponents can formally be as large as the modulus
537 * (mathematically, even larger exponents would work, but PKCS#1 forbids
538 * them), exponents that do not fit on 32 bits are extremely rare,
539 * notably because some widespread implementations (e.g. Microsoft's
540 * CryptoAPI) don't support them. Moreover, large public exponent do not
541 * seem to imply any tangible security benefit, and they increase the
542 * cost of public key operations. The X.509 "minimal" engine will tolerate
543 * public exponents of arbitrary size as long as the modulus and the
544 * exponent can fit together in the dedicated buffer.
545 *
546 * EC public keys are shorter than RSA public keys; even with curve
547 * NIST P-521 (the largest curve we care to support), a public key is
548 * encoded over 133 bytes only.
549 */
550 #define BR_X509_BUFSIZE_KEY 520
551 #define BR_X509_BUFSIZE_SIG 512
552 #endif
553
554 /**
555 * \brief The "minimal" X.509 engine structure.
556 *
557 * The structure contents are opaque (they shall not be accessed directly),
558 * except for the first field (the vtable).
559 *
560 * The "minimal" engine performs a rudimentary but serviceable X.509 path
561 * validation.
562 */
563 typedef struct {
564 const br_x509_class *vtable;
565
566 #ifndef BR_DOXYGEN_IGNORE
567 /* Structure for returning the EE public key. */
568 br_x509_pkey pkey;
569
570 /* CPU for the T0 virtual machine. */
571 struct {
572 uint32_t *dp;
573 uint32_t *rp;
574 const unsigned char *ip;
575 } cpu;
576 uint32_t dp_stack[32];
577 uint32_t rp_stack[32];
578 int err;
579
580 /* Server name to match with the SAN / CN of the EE certificate. */
581 const char *server_name;
582
583 /* Validated key usages. */
584 unsigned char key_usages;
585
586 /* Explicitly set date and time. */
587 uint32_t days, seconds;
588
589 /* Current certificate length (in bytes). Set to 0 when the
590 certificate has been fully processed. */
591 uint32_t cert_length;
592
593 /* Number of certificates processed so far in the current chain.
594 It is incremented at the end of the processing of a certificate,
595 so it is 0 for the EE. */
596 uint32_t num_certs;
597
598 /* Certificate data chunk. */
599 const unsigned char *hbuf;
600 size_t hlen;
601
602 /* The pad serves as destination for various operations. */
603 unsigned char pad[256];
604
605 /* Buffer for EE public key data. */
606 unsigned char ee_pkey_data[BR_X509_BUFSIZE_KEY];
607
608 /* Buffer for currently decoded public key. */
609 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
610
611 /* Signature type: signer key type, offset to the hash
612 function OID (in the T0 data block) and hash function
613 output length (TBS hash length). */
614 unsigned char cert_signer_key_type;
615 uint16_t cert_sig_hash_oid;
616 unsigned char cert_sig_hash_len;
617
618 /* Current/last certificate signature. */
619 unsigned char cert_sig[BR_X509_BUFSIZE_SIG];
620 uint16_t cert_sig_len;
621
622 /* Minimum RSA key length (difference in bytes from 128). */
623 int16_t min_rsa_size;
624
625 /* Configured trust anchors. */
626 const br_x509_trust_anchor *trust_anchors;
627 size_t trust_anchors_num;
628
629 /*
630 * Multi-hasher for the TBS.
631 */
632 unsigned char do_mhash;
633 br_multihash_context mhash;
634 unsigned char tbs_hash[64];
635
636 /*
637 * Simple hasher for the subject/issuer DN.
638 */
639 unsigned char do_dn_hash;
640 const br_hash_class *dn_hash_impl;
641 br_hash_compat_context dn_hash;
642 unsigned char current_dn_hash[64];
643 unsigned char next_dn_hash[64];
644 unsigned char saved_dn_hash[64];
645
646 /*
647 * Public key cryptography implementations (signature verification).
648 */
649 br_rsa_pkcs1_vrfy irsa;
650 br_ecdsa_vrfy iecdsa;
651 const br_ec_impl *iec;
652 #endif
653
654 } br_x509_minimal_context;
655
656 /**
657 * \brief Class instance for the "minimal" X.509 engine.
658 */
659 extern const br_x509_class br_x509_minimal_vtable;
660
661 /**
662 * \brief Initialise a "minimal" X.509 engine.
663 *
664 * The `dn_hash_impl` parameter shall be a hash function internally used
665 * to match X.500 names (subject/issuer DN, and anchor names). Any standard
666 * hash function may be used, but a collision-resistant hash function is
667 * advised.
668 *
669 * After initialization, some implementations for signature verification
670 * (hash functions and signature algorithms) MUST be added.
671 *
672 * \param ctx context to initialise.
673 * \param dn_hash_impl hash function for DN comparisons.
674 * \param trust_anchors trust anchors.
675 * \param trust_anchors_num number of trust anchors.
676 */
677 void br_x509_minimal_init(br_x509_minimal_context *ctx,
678 const br_hash_class *dn_hash_impl,
679 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
680
681 /**
682 * \brief Set a supported hash function in an X.509 "minimal" engine.
683 *
684 * Hash functions are used with signature verification algorithms.
685 * Once initialised (with `br_x509_minimal_init()`), the context must
686 * be configured with the hash functions it shall support for that
687 * purpose. The hash function identifier MUST be one of the standard
688 * hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,
689 * SHA-384 and SHA-512).
690 *
691 * If `impl` is `NULL`, this _removes_ support for the designated
692 * hash function.
693 *
694 * \param ctx validation context.
695 * \param id hash function identifier (from 1 to 6).
696 * \param impl hash function implementation (or `NULL`).
697 */
698 static inline void
699 br_x509_minimal_set_hash(br_x509_minimal_context *ctx,
700 int id, const br_hash_class *impl)
701 {
702 br_multihash_setimpl(&ctx->mhash, id, impl);
703 }
704
705 /**
706 * \brief Set a RSA signature verification implementation in the X.509
707 * "minimal" engine.
708 *
709 * Once initialised (with `br_x509_minimal_init()`), the context must
710 * be configured with the signature verification implementations that
711 * it is supposed to support. If `irsa` is `0`, then the RSA support
712 * is disabled.
713 *
714 * \param ctx validation context.
715 * \param irsa RSA signature verification implementation (or `0`).
716 */
717 static inline void
718 br_x509_minimal_set_rsa(br_x509_minimal_context *ctx,
719 br_rsa_pkcs1_vrfy irsa)
720 {
721 ctx->irsa = irsa;
722 }
723
724 /**
725 * \brief Set a ECDSA signature verification implementation in the X.509
726 * "minimal" engine.
727 *
728 * Once initialised (with `br_x509_minimal_init()`), the context must
729 * be configured with the signature verification implementations that
730 * it is supposed to support.
731 *
732 * If `iecdsa` is `0`, then this call disables ECDSA support; in that
733 * case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function
734 * that verifies ECDSA signatures with format "asn1", and it will use
735 * `iec` as underlying elliptic curve support.
736 *
737 * \param ctx validation context.
738 * \param iec elliptic curve implementation (or `NULL`).
739 * \param iecdsa ECDSA implementation (or `0`).
740 */
741 static inline void
742 br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx,
743 const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)
744 {
745 ctx->iecdsa = iecdsa;
746 ctx->iec = iec;
747 }
748
749 /**
750 * \brief Set the validation time for the X.509 "minimal" engine.
751 *
752 * The validation time is set as two 32-bit integers, for days and
753 * seconds since a fixed epoch:
754 *
755 * - Days are counted in a proleptic Gregorian calendar since
756 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
757 * it is also traditionally known as "1 BC".
758 *
759 * - Seconds are counted since midnight, from 0 to 86400 (a count of
760 * 86400 is possible only if a leap second happened).
761 *
762 * The validation date and time is understood in the UTC time zone.
763 *
764 * If the validation date and time are not explicitly set, but BearSSL
765 * was compiled with support for the system clock on the underlying
766 * platform, then the current time will automatically be used. Otherwise,
767 * not setting the validation date and time implies a validation
768 * failure (except in case of direct trust of the EE key).
769 *
770 * \param ctx validation context.
771 * \param days days since January 1st, 0 AD (Gregorian calendar).
772 * \param seconds seconds since midnight (0 to 86400).
773 */
774 static inline void
775 br_x509_minimal_set_time(br_x509_minimal_context *ctx,
776 uint32_t days, uint32_t seconds)
777 {
778 ctx->days = days;
779 ctx->seconds = seconds;
780 }
781
782 /**
783 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
784 * engine).
785 *
786 * The RSA key length is expressed in bytes. The default minimum key
787 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
788 * than the configured length will be rejected, implying validation
789 * failure. This setting applies to keys extracted from certificates
790 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
791 *
792 * \param ctx validation context.
793 * \param byte_length minimum RSA key length, **in bytes** (not bits).
794 */
795 static inline void
796 br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
797 {
798 ctx->min_rsa_size = (int16_t)(byte_length - 128);
799 }
800
801 /**
802 * \brief X.509 decoder context.
803 *
804 * This structure is _not_ for X.509 validation, but for extracting
805 * names and public keys from encoded certificates. Intended usage is
806 * to use (self-signed) certificates as trust anchors.
807 *
808 * Contents are opaque and shall not be accessed directly.
809 */
810 typedef struct {
811
812 #ifndef BR_DOXYGEN_IGNORE
813 /* Structure for returning the public key. */
814 br_x509_pkey pkey;
815
816 /* CPU for the T0 virtual machine. */
817 struct {
818 uint32_t *dp;
819 uint32_t *rp;
820 const unsigned char *ip;
821 } cpu;
822 uint32_t dp_stack[32];
823 uint32_t rp_stack[32];
824 int err;
825
826 /* The pad serves as destination for various operations. */
827 unsigned char pad[256];
828
829 /* Flag set when decoding succeeds. */
830 unsigned char decoded;
831
832 /* Validity dates. */
833 uint32_t notbefore_days, notbefore_seconds;
834 uint32_t notafter_days, notafter_seconds;
835
836 /* The "CA" flag. This is set to true if the certificate contains
837 a Basic Constraints extension that asserts CA status. */
838 unsigned char isCA;
839
840 /* DN processing: the subject DN is extracted and pushed to the
841 provided callback. */
842 unsigned char copy_dn;
843 void *append_dn_ctx;
844 void (*append_dn)(void *ctx, const void *buf, size_t len);
845
846 /* Certificate data chunk. */
847 const unsigned char *hbuf;
848 size_t hlen;
849
850 /* Buffer for decoded public key. */
851 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
852
853 /* Type of key and hash function used in the certificate signature. */
854 unsigned char signer_key_type;
855 unsigned char signer_hash_id;
856 #endif
857
858 } br_x509_decoder_context;
859
860 /**
861 * \brief Initialise an X.509 decoder context for processing a new
862 * certificate.
863 *
864 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
865 * will be invoked to receive, chunk by chunk, the certificate's
866 * subject DN. If `append_dn` is `0` then the subject DN will be
867 * ignored.
868 *
869 * \param ctx X.509 decoder context to initialise.
870 * \param append_dn DN receiver callback (or `0`).
871 * \param append_dn_ctx context for the DN receiver callback.
872 */
873 void br_x509_decoder_init(br_x509_decoder_context *ctx,
874 void (*append_dn)(void *ctx, const void *buf, size_t len),
875 void *append_dn_ctx);
876
877 /**
878 * \brief Push some certificate bytes into a decoder context.
879 *
880 * If `len` is non-zero, then that many bytes are pushed, from address
881 * `data`, into the provided decoder context.
882 *
883 * \param ctx X.509 decoder context.
884 * \param data certificate data chunk.
885 * \param len certificate data chunk length (in bytes).
886 */
887 void br_x509_decoder_push(br_x509_decoder_context *ctx,
888 const void *data, size_t len);
889
890 /**
891 * \brief Obtain the decoded public key.
892 *
893 * Returned value is a pointer to a structure internal to the decoder
894 * context; releasing or reusing the decoder context invalidates that
895 * structure.
896 *
897 * If decoding was not finished, or failed, then `NULL` is returned.
898 *
899 * \param ctx X.509 decoder context.
900 * \return the public key, or `NULL` on unfinished/error.
901 */
902 static inline br_x509_pkey *
903 br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
904 {
905 if (ctx->decoded && ctx->err == 0) {
906 return &ctx->pkey;
907 } else {
908 return NULL;
909 }
910 }
911
912 /**
913 * \brief Get decoder error status.
914 *
915 * If no error was reported yet but the certificate decoding is not
916 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
917 * was successful, then 0 is returned.
918 *
919 * \param ctx X.509 decoder context.
920 * \return 0 on successful decoding, or a non-zero error code.
921 */
922 static inline int
923 br_x509_decoder_last_error(br_x509_decoder_context *ctx)
924 {
925 if (ctx->err != 0) {
926 return ctx->err;
927 }
928 if (!ctx->decoded) {
929 return BR_ERR_X509_TRUNCATED;
930 }
931 return 0;
932 }
933
934 /**
935 * \brief Get the "isCA" flag from an X.509 decoder context.
936 *
937 * This flag is set if the decoded certificate claims to be a CA through
938 * a Basic Constraints extension. This flag should not be read before
939 * decoding completed successfully.
940 *
941 * \param ctx X.509 decoder context.
942 * \return the "isCA" flag.
943 */
944 static inline int
945 br_x509_decoder_isCA(br_x509_decoder_context *ctx)
946 {
947 return ctx->isCA;
948 }
949
950 /**
951 * \brief Get the issuing CA key type (type of algorithm used to sign the
952 * decoded certificate).
953 *
954 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
955 * if the signature type was not recognised.
956 *
957 * \param ctx X.509 decoder context.
958 * \return the issuing CA key type.
959 */
960 static inline int
961 br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
962 {
963 return ctx->signer_key_type;
964 }
965
966 /**
967 * \brief Get the identifier for the hash function used to sign the decoded
968 * certificate.
969 *
970 * This is 0 if the hash function was not recognised.
971 *
972 * \param ctx X.509 decoder context.
973 * \return the signature hash function identifier.
974 */
975 static inline int
976 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
977 {
978 return ctx->signer_hash_id;
979 }
980
981 /**
982 * \brief Type for an X.509 certificate (DER-encoded).
983 */
984 typedef struct {
985 /** \brief The DER-encoded certificate data. */
986 unsigned char *data;
987 /** \brief The DER-encoded certificate length (in bytes). */
988 size_t data_len;
989 } br_x509_certificate;
990
991 /**
992 * \brief Private key decoder context.
993 *
994 * The private key decoder recognises RSA and EC private keys, either in
995 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
996 * archive (again DER-encoded).
997 *
998 * Structure contents are opaque and shall not be accessed directly.
999 */
1000 typedef struct {
1001 #ifndef BR_DOXYGEN_IGNORE
1002 /* Structure for returning the private key. */
1003 union {
1004 br_rsa_private_key rsa;
1005 br_ec_private_key ec;
1006 } key;
1007
1008 /* CPU for the T0 virtual machine. */
1009 struct {
1010 uint32_t *dp;
1011 uint32_t *rp;
1012 const unsigned char *ip;
1013 } cpu;
1014 uint32_t dp_stack[32];
1015 uint32_t rp_stack[32];
1016 int err;
1017
1018 /* Private key data chunk. */
1019 const unsigned char *hbuf;
1020 size_t hlen;
1021
1022 /* The pad serves as destination for various operations. */
1023 unsigned char pad[256];
1024
1025 /* Decoded key type; 0 until decoding is complete. */
1026 unsigned char key_type;
1027
1028 /* Buffer for the private key elements. It shall be large enough
1029 to accommodate all elements for a RSA-4096 private key (roughly
1030 five 2048-bit integers, possibly a bit more). */
1031 unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];
1032 #endif
1033 } br_skey_decoder_context;
1034
1035 /**
1036 * \brief Initialise a private key decoder context.
1037 *
1038 * \param ctx key decoder context to initialise.
1039 */
1040 void br_skey_decoder_init(br_skey_decoder_context *ctx);
1041
1042 /**
1043 * \brief Push some data bytes into a private key decoder context.
1044 *
1045 * If `len` is non-zero, then that many data bytes, starting at address
1046 * `data`, are pushed into the decoder.
1047 *
1048 * \param ctx key decoder context.
1049 * \param data private key data chunk.
1050 * \param len private key data chunk length (in bytes).
1051 */
1052 void br_skey_decoder_push(br_skey_decoder_context *ctx,
1053 const void *data, size_t len);
1054
1055 /**
1056 * \brief Get the decoding status for a private key.
1057 *
1058 * Decoding status is 0 on success, or a non-zero error code. If the
1059 * decoding is unfinished when this function is called, then the
1060 * status code `BR_ERR_X509_TRUNCATED` is returned.
1061 *
1062 * \param ctx key decoder context.
1063 * \return 0 on successful decoding, or a non-zero error code.
1064 */
1065 static inline int
1066 br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
1067 {
1068 if (ctx->err != 0) {
1069 return ctx->err;
1070 }
1071 if (ctx->key_type == 0) {
1072 return BR_ERR_X509_TRUNCATED;
1073 }
1074 return 0;
1075 }
1076
1077 /**
1078 * \brief Get the decoded private key type.
1079 *
1080 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1081 * not finished or failed, then 0 is returned.
1082 *
1083 * \param ctx key decoder context.
1084 * \return decoded private key type, or 0.
1085 */
1086 static inline int
1087 br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
1088 {
1089 if (ctx->err == 0) {
1090 return ctx->key_type;
1091 } else {
1092 return 0;
1093 }
1094 }
1095
1096 /**
1097 * \brief Get the decoded RSA private key.
1098 *
1099 * This function returns `NULL` if the decoding failed, or is not
1100 * finished, or the key is not RSA. The returned pointer references
1101 * structures within the context that can become invalid if the context
1102 * is reused or released.
1103 *
1104 * \param ctx key decoder context.
1105 * \return decoded RSA private key, or `NULL`.
1106 */
1107 static inline const br_rsa_private_key *
1108 br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
1109 {
1110 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {
1111 return &ctx->key.rsa;
1112 } else {
1113 return NULL;
1114 }
1115 }
1116
1117 /**
1118 * \brief Get the decoded EC private key.
1119 *
1120 * This function returns `NULL` if the decoding failed, or is not
1121 * finished, or the key is not EC. The returned pointer references
1122 * structures within the context that can become invalid if the context
1123 * is reused or released.
1124 *
1125 * \param ctx key decoder context.
1126 * \return decoded EC private key, or `NULL`.
1127 */
1128 static inline const br_ec_private_key *
1129 br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
1130 {
1131 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {
1132 return &ctx->key.ec;
1133 } else {
1134 return NULL;
1135 }
1136 }
1137
1138 #endif