84e73dc2bf02544139f662acf1ca36a3496f5fef
[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 * - When doing validation, a target public key type is provided. That
99 * type is the combination of a key algorithm (RSA or EC) and an
100 * intended key usage (key exchange or signature); in the context
101 * of a SSL/TLS client validating a server's certificate, the algorithm
102 * and usage are obtained from the cipher suite (e.g. ECDHE_RSA means
103 * that an RSA key for signatures is expected).
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 Trust anchor structure.
238 */
239 typedef struct {
240 /** \brief Encoded DN (X.500 name). */
241 unsigned char *dn;
242 /** \brief Encoded DN length (in bytes). */
243 size_t dn_len;
244 /** \brief Anchor flags (e.g. `BR_X509_TA_CA`). */
245 unsigned flags;
246 /** \brief Anchor public key. */
247 br_x509_pkey pkey;
248 } br_x509_trust_anchor;
249
250 /**
251 * \brief Trust anchor flag: CA.
252 *
253 * A "CA" anchor is deemed fit to verify signatures on certificates.
254 * A "non-CA" anchor is accepted only for direct trust (server's
255 * certificate name and key match the anchor).
256 */
257 #define BR_X509_TA_CA 0x0001
258
259 /*
260 * Key type: combination of a basic key type (low 4 bits) and some
261 * optional flags.
262 *
263 * For a public key, the basic key type only is set.
264 *
265 * For an expected key type, the flags indicate the intended purpose(s)
266 * for the key; the basic key type may be set to 0 to indicate that any
267 * key type compatible with the indicated purpose is acceptable.
268 */
269 /** \brief Key type: algorithm is RSA. */
270 #define BR_KEYTYPE_RSA 1
271 /** \brief Key type: algorithm is EC. */
272 #define BR_KEYTYPE_EC 2
273
274 /**
275 * \brief Key type: usage is "key exchange".
276 *
277 * This value is combined (with bitwise OR) with the algorithm
278 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
279 * validation engine that it should find a public key of that type,
280 * fit for key exchanges (e.g. `TLS_RSA_*` and `TLS_ECDH_*` cipher
281 * suites).
282 */
283 #define BR_KEYTYPE_KEYX 0x10
284
285 /**
286 * \brief Key type: usage is "signature".
287 *
288 * This value is combined (with bitwise OR) with the algorithm
289 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
290 * validation engine that it should find a public key of that type,
291 * fit for signatures (e.g. `TLS_ECDHE_*` cipher suites).
292 */
293 #define BR_KEYTYPE_SIGN 0x20
294
295 /*
296 * start_chain Called when a new chain is started. If 'server_name'
297 * is not NULL and non-empty, then it is a name that
298 * should be looked for in the EE certificate (in the
299 * SAN extension as dNSName, or in the subjectDN's CN
300 * if there is no SAN extension).
301 * The caller ensures that the provided 'server_name'
302 * pointer remains valid throughout validation.
303 *
304 * start_cert Begins a new certificate in the chain. The provided
305 * length is in bytes; this is the total certificate length.
306 *
307 * append Get some additional bytes for the current certificate.
308 *
309 * end_cert Ends the current certificate.
310 *
311 * end_chain Called at the end of the chain. Returned value is
312 * 0 on success, or a non-zero error code.
313 *
314 * get_pkey Returns the EE certificate public key.
315 *
316 * For a complete chain, start_chain() and end_chain() are always
317 * called. For each certificate, start_cert(), some append() calls, then
318 * end_cert() are called, in that order. There may be no append() call
319 * at all if the certificate is empty (which is not valid but may happen
320 * if the peer sends exactly that).
321 *
322 * get_pkey() shall return a pointer to a structure that is valid as
323 * long as a new chain is not started. This may be a sub-structure
324 * within the context for the engine. This function MAY return a valid
325 * pointer to a public key even in some cases of validation failure,
326 * depending on the validation engine.
327 */
328
329 /**
330 * \brief Class type for an X.509 engine.
331 *
332 * A certificate chain validation uses a caller-allocated context, which
333 * contains the running state for that validation. Methods are called
334 * in due order:
335 *
336 * - `start_chain()` is called at the start of the validation.
337 * - Certificates are processed one by one, in SSL order (end-entity
338 * comes first). For each certificate, the following methods are
339 * called:
340 *
341 * - `start_cert()` at the beginning of the certificate.
342 * - `append()` is called zero, one or more times, to provide
343 * the certificate (possibly in chunks).
344 * - `end_cert()` at the end of the certificate.
345 *
346 * - `end_chain()` is called when the last certificate in the chain
347 * was processed.
348 * - `get_pkey()` is called after chain processing, if the chain
349 * validation was succesfull.
350 *
351 * A context structure may be reused; the `start_chain()` method shall
352 * ensure (re)initialisation.
353 */
354 typedef struct br_x509_class_ br_x509_class;
355 struct br_x509_class_ {
356 /**
357 * \brief X.509 context size, in bytes.
358 */
359 size_t context_size;
360
361 /**
362 * \brief Start a new chain.
363 *
364 * This method shall set the vtable (first field) of the context
365 * structure.
366 *
367 * The `expected_key_type` is a combination of the algorithm type
368 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) and the key usage
369 * (`BR_KEYTYPE_KEYX` or `BR_KEYTYPE_SIGN`).
370 *
371 * The `server_name`, if not `NULL`, will be considered as a
372 * fully qualified domain name, to be matched against the `dNSName`
373 * elements of the end-entity certificate's SAN extension (if there
374 * is no SAN, then the Common Name from the subjectDN will be used).
375 * If `server_name` is `NULL` then no such matching is performed.
376 *
377 * \param ctx validation context.
378 * \param expected_key_type expected key type (algorithm and usage).
379 * \param server_name server name to match (or `NULL`).
380 */
381 void (*start_chain)(const br_x509_class **ctx,
382 unsigned expected_key_type,
383 const char *server_name);
384
385 /**
386 * \brief Start a new certificate.
387 *
388 * \param ctx validation context.
389 * \param length new certificate length (in bytes).
390 */
391 void (*start_cert)(const br_x509_class **ctx, uint32_t length);
392
393 /**
394 * \brief Receive some bytes for the current certificate.
395 *
396 * This function may be called several times in succession for
397 * a given certificate. The caller guarantees that for each
398 * call, `len` is not zero, and the sum of all chunk lengths
399 * for a certificate matches the total certificate length which
400 * was provided in the previous `start_cert()` call.
401 *
402 * If the new certificate is empty (no byte at all) then this
403 * function won't be called at all.
404 *
405 * \param ctx validation context.
406 * \param buf certificate data chunk.
407 * \param len certificate data chunk length (in bytes).
408 */
409 void (*append)(const br_x509_class **ctx,
410 const unsigned char *buf, size_t len);
411
412 /**
413 * \brief Finish the current certificate.
414 *
415 * This function is called when the end of the current certificate
416 * is reached.
417 *
418 * \param ctx validation context.
419 */
420 void (*end_cert)(const br_x509_class **ctx);
421
422 /**
423 * \brief Finish the chain.
424 *
425 * This function is called at the end of the chain. It shall
426 * return either 0 if the validation was successful, or a
427 * non-zero error code. The `BR_ERR_X509_*` constants are
428 * error codes, though other values may be possible.
429 *
430 * \param ctx validation context.
431 * \return 0 on success, or a non-zero error code.
432 */
433 unsigned (*end_chain)(const br_x509_class **ctx);
434
435 /**
436 * \brief Get the resulting end-entity public key.
437 *
438 * The decoded public key is returned. The returned pointer
439 * may be valid only as long as the context structure is
440 * unmodified, i.e. it may cease to be valid if the context
441 * is released or reused.
442 *
443 * This function _may_ return `NULL` if the validation failed.
444 * However, returning a public key does not mean that the
445 * validation was wholly successful; some engines may return
446 * a decoded public key even if the chain did not end on a
447 * trusted anchor.
448 *
449 * \param ctx validation context.
450 * \return the end-entity public key, or `NULL`.
451 */
452 const br_x509_pkey *(*get_pkey)(const br_x509_class *const *ctx);
453 };
454
455 /**
456 * \brief The "known key" X.509 engine structure.
457 *
458 * The structure contents are opaque (they shall not be accessed directly),
459 * except for the first field (the vtable).
460 *
461 * The "known key" engine returns an externally configured public key,
462 * and totally ignores the certificate contents.
463 */
464 typedef struct {
465 /** \brief Reference to the context vtable. */
466 const br_x509_class *vtable;
467 #ifndef BR_DOXYGEN_IGNORE
468 br_x509_pkey pkey;
469 #endif
470 } br_x509_knownkey_context;
471
472 /**
473 * \brief Class instance for the "known key" X.509 engine.
474 */
475 extern const br_x509_class br_x509_knownkey_vtable;
476
477 /**
478 * \brief Initialize a "known key" X.509 engine with a known RSA public key.
479 *
480 * The provided pointers are linked in, not copied, so they must remain
481 * valid while the public key may be in usage.
482 *
483 * \param ctx context to initialise.
484 * \param pk known public key.
485 */
486 void br_x509_knownkey_init_rsa(br_x509_knownkey_context *ctx,
487 const br_rsa_public_key *pk);
488
489 /**
490 * \brief Initialize a "known key" X.509 engine with a known EC public key.
491 *
492 * The provided pointers are linked in, not copied, so they must remain
493 * valid while the public key may be in usage.
494 *
495 * \param ctx context to initialise.
496 * \param pk known public key.
497 */
498 void br_x509_knownkey_init_ec(br_x509_knownkey_context *ctx,
499 const br_ec_public_key *pk);
500
501 #ifndef BR_DOXYGEN_IGNORE
502 /*
503 * The minimal X.509 engine has some state buffers which must be large
504 * enough to simultaneously accommodate:
505 * -- the public key extracted from the current certificate;
506 * -- the signature on the current certificate or on the previous
507 * certificate;
508 * -- the public key extracted from the EE certificate.
509 *
510 * We store public key elements in their raw unsigned big-endian
511 * encoding. We want to support up to RSA-4096 with a short (up to 64
512 * bits) public exponent, thus a buffer for a public key must have
513 * length at least 520 bytes. Similarly, a RSA-4096 signature has length
514 * 512 bytes.
515 *
516 * Though RSA public exponents can formally be as large as the modulus
517 * (mathematically, even larger exponents would work, but PKCS#1 forbids
518 * them), exponents that do not fit on 32 bits are extremely rare,
519 * notably because some widespread implementations (e.g. Microsoft's
520 * CryptoAPI) don't support them. Moreover, large public exponent do not
521 * seem to imply any tangible security benefit, and they increase the
522 * cost of public key operations. The X.509 "minimal" engine will tolerate
523 * public exponents of arbitrary size as long as the modulus and the
524 * exponent can fit together in the dedicated buffer.
525 *
526 * EC public keys are shorter than RSA public keys; even with curve
527 * NIST P-521 (the largest curve we care to support), a public key is
528 * encoded over 133 bytes only.
529 */
530 #define BR_X509_BUFSIZE_KEY 520
531 #define BR_X509_BUFSIZE_SIG 512
532 #endif
533
534 /**
535 * \brief The "minimal" X.509 engine structure.
536 *
537 * The structure contents are opaque (they shall not be accessed directly),
538 * except for the first field (the vtable).
539 *
540 * The "minimal" engine performs a rudimentary but serviceable X.509 path
541 * validation.
542 */
543 typedef struct {
544 const br_x509_class *vtable;
545
546 #ifndef BR_DOXYGEN_IGNORE
547 /* Structure for returning the EE public key. */
548 br_x509_pkey pkey;
549
550 /* CPU for the T0 virtual machine. */
551 struct {
552 uint32_t *dp;
553 uint32_t *rp;
554 const unsigned char *ip;
555 } cpu;
556 uint32_t dp_stack[32];
557 uint32_t rp_stack[32];
558 int err;
559
560 /* Server name to match with the SAN / CN of the EE certificate. */
561 const char *server_name;
562
563 /* Expected EE key type and usage. */
564 unsigned char expected_key_type;
565
566 /* Explicitly set date and time. */
567 uint32_t days, seconds;
568
569 /* Current certificate length (in bytes). Set to 0 when the
570 certificate has been fully processed. */
571 uint32_t cert_length;
572
573 /* Number of certificates processed so far in the current chain.
574 It is incremented at the end of the processing of a certificate,
575 so it is 0 for the EE. */
576 uint32_t num_certs;
577
578 /* Certificate data chunk. */
579 const unsigned char *hbuf;
580 size_t hlen;
581
582 /* The pad serves as destination for various operations. */
583 unsigned char pad[256];
584
585 /* Buffer for EE public key data. */
586 unsigned char ee_pkey_data[BR_X509_BUFSIZE_KEY];
587
588 /* Buffer for currently decoded public key. */
589 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
590
591 /* Signature type: signer key type, offset to the hash
592 function OID (in the T0 data block) and hash function
593 output length (TBS hash length). */
594 unsigned char cert_signer_key_type;
595 uint16_t cert_sig_hash_oid;
596 unsigned char cert_sig_hash_len;
597
598 /* Current/last certificate signature. */
599 unsigned char cert_sig[BR_X509_BUFSIZE_SIG];
600 uint16_t cert_sig_len;
601
602 /* Minimum RSA key length (difference in bytes from 128). */
603 int16_t min_rsa_size;
604
605 /* Configured trust anchors. */
606 const br_x509_trust_anchor *trust_anchors;
607 size_t trust_anchors_num;
608
609 /*
610 * Multi-hasher for the TBS.
611 */
612 unsigned char do_mhash;
613 br_multihash_context mhash;
614 unsigned char tbs_hash[64];
615
616 /*
617 * Simple hasher for the subject/issuer DN.
618 */
619 unsigned char do_dn_hash;
620 const br_hash_class *dn_hash_impl;
621 br_hash_compat_context dn_hash;
622 unsigned char current_dn_hash[64];
623 unsigned char next_dn_hash[64];
624 unsigned char saved_dn_hash[64];
625
626 /*
627 * Public key cryptography implementations (signature verification).
628 */
629 br_rsa_pkcs1_vrfy irsa;
630 br_ecdsa_vrfy iecdsa;
631 const br_ec_impl *iec;
632 #endif
633
634 } br_x509_minimal_context;
635
636 /**
637 * \brief Class instance for the "minimal" X.509 engine.
638 */
639 extern const br_x509_class br_x509_minimal_vtable;
640
641 /**
642 * \brief Initialise a "minimal" X.509 engine.
643 *
644 * The `dn_hash_impl` parameter shall be a hash function internally used
645 * to match X.500 names (subject/issuer DN, and anchor names). Any standard
646 * hash function may be used, but a collision-resistant hash function is
647 * advised.
648 *
649 * After initialization, some implementations for signature verification
650 * (hash functions and signature algorithms) MUST be added.
651 *
652 * \param ctx context to initialise.
653 * \param dn_hash_impl hash function for DN comparisons.
654 * \param trust_anchors trust anchors.
655 * \param trust_anchors_num number of trust anchors.
656 */
657 void br_x509_minimal_init(br_x509_minimal_context *ctx,
658 const br_hash_class *dn_hash_impl,
659 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
660
661 /**
662 * \brief Set a supported hash function in an X.509 "minimal" engine.
663 *
664 * Hash functions are used with signature verification algorithms.
665 * Once initialised (with `br_x509_minimal_init()`), the context must
666 * be configured with the hash functions it shall support for that
667 * purpose. The hash function identifier MUST be one of the standard
668 * hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,
669 * SHA-384 and SHA-512).
670 *
671 * If `impl` is `NULL`, this _removes_ support for the designated
672 * hash function.
673 *
674 * \param ctx validation context.
675 * \param id hash function identifier (from 1 to 6).
676 * \param impl hash function implementation (or `NULL`).
677 */
678 static inline void
679 br_x509_minimal_set_hash(br_x509_minimal_context *ctx,
680 int id, const br_hash_class *impl)
681 {
682 br_multihash_setimpl(&ctx->mhash, id, impl);
683 }
684
685 /**
686 * \brief Set a RSA signature verification implementation in the X.509
687 * "minimal" engine.
688 *
689 * Once initialised (with `br_x509_minimal_init()`), the context must
690 * be configured with the signature verification implementations that
691 * it is supposed to support. If `irsa` is `0`, then the RSA support
692 * is disabled.
693 *
694 * \param ctx validation context.
695 * \param irsa RSA signature verification implementation (or `0`).
696 */
697 static inline void
698 br_x509_minimal_set_rsa(br_x509_minimal_context *ctx,
699 br_rsa_pkcs1_vrfy irsa)
700 {
701 ctx->irsa = irsa;
702 }
703
704 /**
705 * \brief Set a ECDSA signature verification implementation in the X.509
706 * "minimal" engine.
707 *
708 * Once initialised (with `br_x509_minimal_init()`), the context must
709 * be configured with the signature verification implementations that
710 * it is supposed to support.
711 *
712 * If `iecdsa` is `0`, then this call disables ECDSA support; in that
713 * case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function
714 * that verifies ECDSA signatures with format "asn1", and it will use
715 * `iec` as underlying elliptic curve support.
716 *
717 * \param ctx validation context.
718 * \param iec elliptic curve implementation (or `NULL`).
719 * \param iecdsa ECDSA implementation (or `0`).
720 */
721 static inline void
722 br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx,
723 const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)
724 {
725 ctx->iecdsa = iecdsa;
726 ctx->iec = iec;
727 }
728
729 /**
730 * \brief Set the validation time for the X.509 "minimal" engine.
731 *
732 * The validation time is set as two 32-bit integers, for days and
733 * seconds since a fixed epoch:
734 *
735 * - Days are counted in a proleptic Gregorian calendar since
736 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
737 * it is also traditionally known as "1 BC".
738 *
739 * - Seconds are counted since midnight, from 0 to 86400 (a count of
740 * 86400 is possible only if a leap second happened).
741 *
742 * The validation date and time is understood in the UTC time zone.
743 *
744 * If the validation date and time are not explicitly set, but BearSSL
745 * was compiled with support for the system clock on the underlying
746 * platform, then the current time will automatically be used. Otherwise,
747 * not setting the validation date and time implies a validation
748 * failure (except in case of direct trust of the EE key).
749 *
750 * \param ctx validation context.
751 * \param days days since January 1st, 0 AD (Gregorian calendar).
752 * \param seconds seconds since midnight (0 to 86400).
753 */
754 static inline void
755 br_x509_minimal_set_time(br_x509_minimal_context *ctx,
756 uint32_t days, uint32_t seconds)
757 {
758 ctx->days = days;
759 ctx->seconds = seconds;
760 }
761
762 /**
763 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
764 * engine).
765 *
766 * The RSA key length is expressed in bytes. The default minimum key
767 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
768 * than the configured length will be rejected, implying validation
769 * failure. This setting applies to keys extracted from certificates
770 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
771 *
772 * \param ctx validation context.
773 * \param byte_length minimum RSA key length, **in bytes** (not bits).
774 */
775 static inline void
776 br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
777 {
778 ctx->min_rsa_size = (int16_t)(byte_length - 128);
779 }
780
781 /**
782 * \brief X.509 decoder context.
783 *
784 * This structure is _not_ for X.509 validation, but for extracting
785 * names and public keys from encoded certificates. Intended usage is
786 * to use (self-signed) certificates as trust anchors.
787 *
788 * Contents are opaque and shall not be accessed directly.
789 */
790 typedef struct {
791
792 #ifndef BR_DOXYGEN_IGNORE
793 /* Structure for returning the public key. */
794 br_x509_pkey pkey;
795
796 /* CPU for the T0 virtual machine. */
797 struct {
798 uint32_t *dp;
799 uint32_t *rp;
800 const unsigned char *ip;
801 } cpu;
802 uint32_t dp_stack[32];
803 uint32_t rp_stack[32];
804 int err;
805
806 /* The pad serves as destination for various operations. */
807 unsigned char pad[256];
808
809 /* Flag set when decoding succeeds. */
810 unsigned char decoded;
811
812 /* Validity dates. */
813 uint32_t notbefore_days, notbefore_seconds;
814 uint32_t notafter_days, notafter_seconds;
815
816 /* The "CA" flag. This is set to true if the certificate contains
817 a Basic Constraints extension that asserts CA status. */
818 unsigned char isCA;
819
820 /* DN processing: the subject DN is extracted and pushed to the
821 provided callback. */
822 unsigned char copy_dn;
823 void *append_dn_ctx;
824 void (*append_dn)(void *ctx, const void *buf, size_t len);
825
826 /* Certificate data chunk. */
827 const unsigned char *hbuf;
828 size_t hlen;
829
830 /* Buffer for decoded public key. */
831 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
832
833 /* Type of key and hash function used in the certificate signature. */
834 unsigned char signer_key_type;
835 unsigned char signer_hash_id;
836 #endif
837
838 } br_x509_decoder_context;
839
840 /**
841 * \brief Initialise an X.509 decoder context for processing a new
842 * certificate.
843 *
844 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
845 * will be invoked to receive, chunk by chunk, the certificate's
846 * subject DN. If `append_dn` is `0` then the subject DN will be
847 * ignored.
848 *
849 * \param ctx X.509 decoder context to initialise.
850 * \param append_dn DN receiver callback (or `0`).
851 * \param append_dn_ctx context for the DN receiver callback.
852 */
853 void br_x509_decoder_init(br_x509_decoder_context *ctx,
854 void (*append_dn)(void *ctx, const void *buf, size_t len),
855 void *append_dn_ctx);
856
857 /**
858 * \brief Push some certificate bytes into a decoder context.
859 *
860 * If `len` is non-zero, then that many bytes are pushed, from address
861 * `data`, into the provided decoder context.
862 *
863 * \param ctx X.509 decoder context.
864 * \param data certificate data chunk.
865 * \param len certificate data chunk length (in bytes).
866 */
867 void br_x509_decoder_push(br_x509_decoder_context *ctx,
868 const void *data, size_t len);
869
870 /**
871 * \brief Obtain the decoded public key.
872 *
873 * Returned value is a pointer to a structure internal to the decoder
874 * context; releasing or reusing the decoder context invalidates that
875 * structure.
876 *
877 * If decoding was not finished, or failed, then `NULL` is returned.
878 *
879 * \param ctx X.509 decoder context.
880 * \return the public key, or `NULL` on unfinished/error.
881 */
882 static inline br_x509_pkey *
883 br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
884 {
885 if (ctx->decoded && ctx->err == 0) {
886 return &ctx->pkey;
887 } else {
888 return NULL;
889 }
890 }
891
892 /**
893 * \brief Get decoder error status.
894 *
895 * If no error was reported yet but the certificate decoding is not
896 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
897 * was successful, then 0 is returned.
898 *
899 * \param ctx X.509 decoder context.
900 * \return 0 on successful decoding, or a non-zero error code.
901 */
902 static inline int
903 br_x509_decoder_last_error(br_x509_decoder_context *ctx)
904 {
905 if (ctx->err != 0) {
906 return ctx->err;
907 }
908 if (!ctx->decoded) {
909 return BR_ERR_X509_TRUNCATED;
910 }
911 return 0;
912 }
913
914 /**
915 * \brief Get the "isCA" flag from an X.509 decoder context.
916 *
917 * This flag is set if the decoded certificate claims to be a CA through
918 * a Basic Constraints extension. This flag should not be read before
919 * decoding completed successfully.
920 *
921 * \param ctx X.509 decoder context.
922 * \return the "isCA" flag.
923 */
924 static inline int
925 br_x509_decoder_isCA(br_x509_decoder_context *ctx)
926 {
927 return ctx->isCA;
928 }
929
930 /**
931 * \brief Get the issuing CA key type (type of algorithm used to sign the
932 * decoded certificate).
933 *
934 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
935 * if the signature type was not recognised.
936 *
937 * \param ctx X.509 decoder context.
938 * \return the issuing CA key type.
939 */
940 static inline int
941 br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
942 {
943 return ctx->signer_key_type;
944 }
945
946 /**
947 * \brief Get the identifier for the hash function used to sign the decoded
948 * certificate.
949 *
950 * This is 0 if the hash function was not recognised.
951 *
952 * \param ctx X.509 decoder context.
953 * \return the signature hash function identifier.
954 */
955 static inline int
956 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
957 {
958 return ctx->signer_hash_id;
959 }
960
961 /**
962 * \brief Type for an X.509 certificate (DER-encoded).
963 */
964 typedef struct {
965 /** \brief The DER-encoded certificate data. */
966 unsigned char *data;
967 /** \brief The DER-encoded certificate length (in bytes). */
968 size_t data_len;
969 } br_x509_certificate;
970
971 /**
972 * \brief Private key decoder context.
973 *
974 * The private key decoder recognises RSA and EC private keys, either in
975 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
976 * archive (again DER-encoded).
977 *
978 * Structure contents are opaque and shall not be accessed directly.
979 */
980 typedef struct {
981 #ifndef BR_DOXYGEN_IGNORE
982 /* Structure for returning the private key. */
983 union {
984 br_rsa_private_key rsa;
985 br_ec_private_key ec;
986 } key;
987
988 /* CPU for the T0 virtual machine. */
989 struct {
990 uint32_t *dp;
991 uint32_t *rp;
992 const unsigned char *ip;
993 } cpu;
994 uint32_t dp_stack[32];
995 uint32_t rp_stack[32];
996 int err;
997
998 /* Private key data chunk. */
999 const unsigned char *hbuf;
1000 size_t hlen;
1001
1002 /* The pad serves as destination for various operations. */
1003 unsigned char pad[256];
1004
1005 /* Decoded key type; 0 until decoding is complete. */
1006 unsigned char key_type;
1007
1008 /* Buffer for the private key elements. It shall be large enough
1009 to accommodate all elements for a RSA-4096 private key (roughly
1010 five 2048-bit integers, possibly a bit more). */
1011 unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];
1012 #endif
1013 } br_skey_decoder_context;
1014
1015 /**
1016 * \brief Initialise a private key decoder context.
1017 *
1018 * \param ctx key decoder context to initialise.
1019 */
1020 void br_skey_decoder_init(br_skey_decoder_context *ctx);
1021
1022 /**
1023 * \brief Push some data bytes into a private key decoder context.
1024 *
1025 * If `len` is non-zero, then that many data bytes, starting at address
1026 * `data`, are pushed into the decoder.
1027 *
1028 * \param ctx key decoder context.
1029 * \param data private key data chunk.
1030 * \param len private key data chunk length (in bytes).
1031 */
1032 void br_skey_decoder_push(br_skey_decoder_context *ctx,
1033 const void *data, size_t len);
1034
1035 /**
1036 * \brief Get the decoding status for a private key.
1037 *
1038 * Decoding status is 0 on success, or a non-zero error code. If the
1039 * decoding is unfinished when this function is called, then the
1040 * status code `BR_ERR_X509_TRUNCATED` is returned.
1041 *
1042 * \param ctx key decoder context.
1043 * \return 0 on successful decoding, or a non-zero error code.
1044 */
1045 static inline int
1046 br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
1047 {
1048 if (ctx->err != 0) {
1049 return ctx->err;
1050 }
1051 if (ctx->key_type == 0) {
1052 return BR_ERR_X509_TRUNCATED;
1053 }
1054 return 0;
1055 }
1056
1057 /**
1058 * \brief Get the decoded private key type.
1059 *
1060 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1061 * not finished or failed, then 0 is returned.
1062 *
1063 * \param ctx key decoder context.
1064 * \return decoded private key type, or 0.
1065 */
1066 static inline int
1067 br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
1068 {
1069 if (ctx->err == 0) {
1070 return ctx->key_type;
1071 } else {
1072 return 0;
1073 }
1074 }
1075
1076 /**
1077 * \brief Get the decoded RSA private key.
1078 *
1079 * This function returns `NULL` if the decoding failed, or is not
1080 * finished, or the key is not RSA. The returned pointer references
1081 * structures within the context that can become invalid if the context
1082 * is reused or released.
1083 *
1084 * \param ctx key decoder context.
1085 * \return decoded RSA private key, or `NULL`.
1086 */
1087 static inline const br_rsa_private_key *
1088 br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
1089 {
1090 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {
1091 return &ctx->key.rsa;
1092 } else {
1093 return NULL;
1094 }
1095 }
1096
1097 /**
1098 * \brief Get the decoded EC private key.
1099 *
1100 * This function returns `NULL` if the decoding failed, or is not
1101 * finished, or the key is not EC. The returned pointer references
1102 * structures within the context that can become invalid if the context
1103 * is reused or released.
1104 *
1105 * \param ctx key decoder context.
1106 * \return decoded EC private key, or `NULL`.
1107 */
1108 static inline const br_ec_private_key *
1109 br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
1110 {
1111 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {
1112 return &ctx->key.ec;
1113 } else {
1114 return NULL;
1115 }
1116 }
1117
1118 #endif