2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
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:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
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
25 #ifndef BR_BEARSSL_X509_H__
26 #define BR_BEARSSL_X509_H__
31 #include "bearssl_ec.h"
32 #include "bearssl_hash.h"
33 #include "bearssl_rsa.h"
39 /** \file bearssl_x509.h
41 * # X.509 Certificate Chain Processing
43 * An X.509 processing engine receives an X.509 chain, chunk by chunk,
44 * as received from a SSL/TLS client or server (the client receives the
45 * server's certificate chain, and the server receives the client's
46 * certificate chain if it requested a client certificate). The chain
47 * is thus injected in the engine in SSL order (end-entity first).
49 * The engine's job is to return the public key to use for SSL/TLS.
50 * How exactly that key is obtained and verified is entirely up to the
53 * **The "known key" engine** returns a public key which is already known
54 * from out-of-band information (e.g. the client _remembers_ the key from
55 * a previous connection, as in the usual SSH model). This is the simplest
56 * engine since it simply ignores the chain, thereby avoiding the need
57 * for any decoding logic.
59 * **The "minimal" engine** implements minimal X.509 decoding and chain
62 * - The provided chain should validate "as is". There is no attempt
63 * at reordering, skipping or downloading extra certificates.
65 * - X.509 v1, v2 and v3 certificates are supported.
67 * - Trust anchors are a DN and a public key. Each anchor is either a
68 * "CA" anchor, or a non-CA.
70 * - If the end-entity certificate matches a non-CA anchor (subject DN
71 * is equal to the non-CA name, and public key is also identical to
72 * the anchor key), then this is a _direct trust_ case and the
73 * remaining certificates are ignored.
75 * - Unless direct trust is applied, the chain must be verifiable up to
76 * a certificate whose issuer DN matches the DN from a "CA" trust anchor,
77 * and whose signature is verifiable against that anchor's public key.
78 * Subsequent certificates in the chain are ignored.
80 * - The engine verifies subject/issuer DN matching, and enforces
81 * processing of Basic Constraints and Key Usage extensions. The
82 * Authority Key Identifier, Subject Key Identifier, Issuer Alt Name,
83 * Subject Directory Attribute, CRL Distribution Points, Freshest CRL,
84 * Authority Info Access and Subject Info Access extensions are
85 * ignored. The Subject Alt Name is decoded for the end-entity
86 * certificate under some conditions (see below). Other extensions
87 * are ignored if non-critical, or imply chain rejection if critical.
89 * - The Subject Alt Name extension is parsed for names of type `dNSName`
90 * when decoding the end-entity certificate, and only if there is a
91 * server name to match. If there is no SAN extension, then the
92 * Common Name from the subjectDN is used. That name matching is
93 * case-insensitive and honours a single starting wildcard (i.e. if
94 * the name in the certificate starts with "`*.`" then this matches
95 * any word as first element). Note: this name matching is performed
96 * also in the "direct trust" model.
98 * - DN matching is byte-to-byte equality (a future version might
99 * include some limited processing for case-insensitive matching and
100 * whitespace normalisation).
102 * - Successful validation produces a public key type but also a set
103 * of allowed usages (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
104 * The caller is responsible for checking that the key type and
105 * usages are compatible with the expected values (e.g. with the
106 * selected cipher suite, when the client validates the server's
109 * **Important caveats:**
111 * - The "minimal" engine does not check revocation status. The relevant
112 * extensions are ignored, and CRL or OCSP responses are not gathered
115 * - The "minimal" engine does not currently support Name Constraints
116 * (some basic functionality to handle sub-domains may be added in a
119 * - The decoder is not "validating" in the sense that it won't reject
120 * some certificates with invalid field values when these fields are
121 * not actually processed.
125 * X.509 error codes are in the 32..63 range.
128 /** \brief X.509 status: validation was successful; this is not actually
130 #define BR_ERR_X509_OK 32
132 /** \brief X.509 status: invalid value in an ASN.1 structure. */
133 #define BR_ERR_X509_INVALID_VALUE 33
135 /** \brief X.509 status: truncated certificate. */
136 #define BR_ERR_X509_TRUNCATED 34
138 /** \brief X.509 status: empty certificate chain (no certificate at all). */
139 #define BR_ERR_X509_EMPTY_CHAIN 35
141 /** \brief X.509 status: decoding error: inner element extends beyond
142 outer element size. */
143 #define BR_ERR_X509_INNER_TRUNC 36
145 /** \brief X.509 status: decoding error: unsupported tag class (application
147 #define BR_ERR_X509_BAD_TAG_CLASS 37
149 /** \brief X.509 status: decoding error: unsupported tag value. */
150 #define BR_ERR_X509_BAD_TAG_VALUE 38
152 /** \brief X.509 status: decoding error: indefinite length. */
153 #define BR_ERR_X509_INDEFINITE_LENGTH 39
155 /** \brief X.509 status: decoding error: extraneous element. */
156 #define BR_ERR_X509_EXTRA_ELEMENT 40
158 /** \brief X.509 status: decoding error: unexpected element. */
159 #define BR_ERR_X509_UNEXPECTED 41
161 /** \brief X.509 status: decoding error: expected constructed element, but
163 #define BR_ERR_X509_NOT_CONSTRUCTED 42
165 /** \brief X.509 status: decoding error: expected primitive element, but
167 #define BR_ERR_X509_NOT_PRIMITIVE 43
169 /** \brief X.509 status: decoding error: BIT STRING length is not multiple
171 #define BR_ERR_X509_PARTIAL_BYTE 44
173 /** \brief X.509 status: decoding error: BOOLEAN value has invalid length. */
174 #define BR_ERR_X509_BAD_BOOLEAN 45
176 /** \brief X.509 status: decoding error: value is off-limits. */
177 #define BR_ERR_X509_OVERFLOW 46
179 /** \brief X.509 status: invalid distinguished name. */
180 #define BR_ERR_X509_BAD_DN 47
182 /** \brief X.509 status: invalid date/time representation. */
183 #define BR_ERR_X509_BAD_TIME 48
185 /** \brief X.509 status: certificate contains unsupported features that
186 cannot be ignored. */
187 #define BR_ERR_X509_UNSUPPORTED 49
189 /** \brief X.509 status: key or signature size exceeds internal limits. */
190 #define BR_ERR_X509_LIMIT_EXCEEDED 50
192 /** \brief X.509 status: key type does not match that which was expected. */
193 #define BR_ERR_X509_WRONG_KEY_TYPE 51
195 /** \brief X.509 status: signature is invalid. */
196 #define BR_ERR_X509_BAD_SIGNATURE 52
198 /** \brief X.509 status: validation time is unknown. */
199 #define BR_ERR_X509_TIME_UNKNOWN 53
201 /** \brief X.509 status: certificate is expired or not yet valid. */
202 #define BR_ERR_X509_EXPIRED 54
204 /** \brief X.509 status: issuer/subject DN mismatch in the chain. */
205 #define BR_ERR_X509_DN_MISMATCH 55
207 /** \brief X.509 status: expected server name was not found in the chain. */
208 #define BR_ERR_X509_BAD_SERVER_NAME 56
210 /** \brief X.509 status: unknown critical extension in certificate. */
211 #define BR_ERR_X509_CRITICAL_EXTENSION 57
213 /** \brief X.509 status: not a CA, or path length constraint violation */
214 #define BR_ERR_X509_NOT_CA 58
216 /** \brief X.509 status: Key Usage extension prohibits intended usage. */
217 #define BR_ERR_X509_FORBIDDEN_KEY_USAGE 59
219 /** \brief X.509 status: public key found in certificate is too small. */
220 #define BR_ERR_X509_WEAK_PUBLIC_KEY 60
222 /** \brief X.509 status: chain could not be linked to a trust anchor. */
223 #define BR_ERR_X509_NOT_TRUSTED 62
226 * \brief Aggregate structure for public keys.
229 /** \brief Key type: `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC` */
230 unsigned char key_type;
231 /** \brief Actual public key. */
233 /** \brief RSA public key. */
234 br_rsa_public_key rsa;
235 /** \brief EC public key. */
241 * \brief Distinguished Name (X.500) structure.
243 * The DN is DER-encoded.
246 /** \brief Encoded DN data. */
248 /** \brief Encoded DN length (in bytes). */
253 * \brief Trust anchor structure.
256 /** \brief Encoded DN (X.500 name). */
258 /** \brief Anchor flags (e.g. `BR_X509_TA_CA`). */
260 /** \brief Anchor public key. */
262 } br_x509_trust_anchor;
265 * \brief Trust anchor flag: CA.
267 * A "CA" anchor is deemed fit to verify signatures on certificates.
268 * A "non-CA" anchor is accepted only for direct trust (server's
269 * certificate name and key match the anchor).
271 #define BR_X509_TA_CA 0x0001
274 * Key type: combination of a basic key type (low 4 bits) and some
277 * For a public key, the basic key type only is set.
279 * For an expected key type, the flags indicate the intended purpose(s)
280 * for the key; the basic key type may be set to 0 to indicate that any
281 * key type compatible with the indicated purpose is acceptable.
283 /** \brief Key type: algorithm is RSA. */
284 #define BR_KEYTYPE_RSA 1
285 /** \brief Key type: algorithm is EC. */
286 #define BR_KEYTYPE_EC 2
289 * \brief Key type: usage is "key exchange".
291 * This value is combined (with bitwise OR) with the algorithm
292 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
293 * validation engine that it should find a public key of that type,
294 * fit for key exchanges (e.g. `TLS_RSA_*` and `TLS_ECDH_*` cipher
297 #define BR_KEYTYPE_KEYX 0x10
300 * \brief Key type: usage is "signature".
302 * This value is combined (with bitwise OR) with the algorithm
303 * (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509
304 * validation engine that it should find a public key of that type,
305 * fit for signatures (e.g. `TLS_ECDHE_*` cipher suites).
307 #define BR_KEYTYPE_SIGN 0x20
310 * start_chain Called when a new chain is started. If 'server_name'
311 * is not NULL and non-empty, then it is a name that
312 * should be looked for in the EE certificate (in the
313 * SAN extension as dNSName, or in the subjectDN's CN
314 * if there is no SAN extension).
315 * The caller ensures that the provided 'server_name'
316 * pointer remains valid throughout validation.
318 * start_cert Begins a new certificate in the chain. The provided
319 * length is in bytes; this is the total certificate length.
321 * append Get some additional bytes for the current certificate.
323 * end_cert Ends the current certificate.
325 * end_chain Called at the end of the chain. Returned value is
326 * 0 on success, or a non-zero error code.
328 * get_pkey Returns the EE certificate public key.
330 * For a complete chain, start_chain() and end_chain() are always
331 * called. For each certificate, start_cert(), some append() calls, then
332 * end_cert() are called, in that order. There may be no append() call
333 * at all if the certificate is empty (which is not valid but may happen
334 * if the peer sends exactly that).
336 * get_pkey() shall return a pointer to a structure that is valid as
337 * long as a new chain is not started. This may be a sub-structure
338 * within the context for the engine. This function MAY return a valid
339 * pointer to a public key even in some cases of validation failure,
340 * depending on the validation engine.
344 * \brief Class type for an X.509 engine.
346 * A certificate chain validation uses a caller-allocated context, which
347 * contains the running state for that validation. Methods are called
350 * - `start_chain()` is called at the start of the validation.
351 * - Certificates are processed one by one, in SSL order (end-entity
352 * comes first). For each certificate, the following methods are
355 * - `start_cert()` at the beginning of the certificate.
356 * - `append()` is called zero, one or more times, to provide
357 * the certificate (possibly in chunks).
358 * - `end_cert()` at the end of the certificate.
360 * - `end_chain()` is called when the last certificate in the chain
362 * - `get_pkey()` is called after chain processing, if the chain
363 * validation was successful.
365 * A context structure may be reused; the `start_chain()` method shall
366 * ensure (re)initialisation.
368 typedef struct br_x509_class_ br_x509_class;
369 struct br_x509_class_ {
371 * \brief X.509 context size, in bytes.
376 * \brief Start a new chain.
378 * This method shall set the vtable (first field) of the context
381 * The `server_name`, if not `NULL`, will be considered as a
382 * fully qualified domain name, to be matched against the `dNSName`
383 * elements of the end-entity certificate's SAN extension (if there
384 * is no SAN, then the Common Name from the subjectDN will be used).
385 * If `server_name` is `NULL` then no such matching is performed.
387 * \param ctx validation context.
388 * \param server_name server name to match (or `NULL`).
390 void (*start_chain)(const br_x509_class **ctx,
391 const char *server_name);
394 * \brief Start a new certificate.
396 * \param ctx validation context.
397 * \param length new certificate length (in bytes).
399 void (*start_cert)(const br_x509_class **ctx, uint32_t length);
402 * \brief Receive some bytes for the current certificate.
404 * This function may be called several times in succession for
405 * a given certificate. The caller guarantees that for each
406 * call, `len` is not zero, and the sum of all chunk lengths
407 * for a certificate matches the total certificate length which
408 * was provided in the previous `start_cert()` call.
410 * If the new certificate is empty (no byte at all) then this
411 * function won't be called at all.
413 * \param ctx validation context.
414 * \param buf certificate data chunk.
415 * \param len certificate data chunk length (in bytes).
417 void (*append)(const br_x509_class **ctx,
418 const unsigned char *buf, size_t len);
421 * \brief Finish the current certificate.
423 * This function is called when the end of the current certificate
426 * \param ctx validation context.
428 void (*end_cert)(const br_x509_class **ctx);
431 * \brief Finish the chain.
433 * This function is called at the end of the chain. It shall
434 * return either 0 if the validation was successful, or a
435 * non-zero error code. The `BR_ERR_X509_*` constants are
436 * error codes, though other values may be possible.
438 * \param ctx validation context.
439 * \return 0 on success, or a non-zero error code.
441 unsigned (*end_chain)(const br_x509_class **ctx);
444 * \brief Get the resulting end-entity public key.
446 * The decoded public key is returned. The returned pointer
447 * may be valid only as long as the context structure is
448 * unmodified, i.e. it may cease to be valid if the context
449 * is released or reused.
451 * This function _may_ return `NULL` if the validation failed.
452 * However, returning a public key does not mean that the
453 * validation was wholly successful; some engines may return
454 * a decoded public key even if the chain did not end on a
457 * If validation succeeded and `usage` is not `NULL`, then
458 * `*usage` is filled with a combination of `BR_KEYTYPE_SIGN`
459 * and/or `BR_KEYTYPE_KEYX` that specifies the validated key
460 * usage types. It is the caller's responsibility to check
461 * that value against the intended use of the public key.
463 * \param ctx validation context.
464 * \return the end-entity public key, or `NULL`.
466 const br_x509_pkey *(*get_pkey)(
467 const br_x509_class *const *ctx, unsigned *usages);
471 * \brief The "known key" X.509 engine structure.
473 * The structure contents are opaque (they shall not be accessed directly),
474 * except for the first field (the vtable).
476 * The "known key" engine returns an externally configured public key,
477 * and totally ignores the certificate contents.
480 /** \brief Reference to the context vtable. */
481 const br_x509_class *vtable;
482 #ifndef BR_DOXYGEN_IGNORE
486 } br_x509_knownkey_context;
489 * \brief Class instance for the "known key" X.509 engine.
491 extern const br_x509_class br_x509_knownkey_vtable;
494 * \brief Initialize a "known key" X.509 engine with a known RSA public key.
496 * The `usages` parameter indicates the allowed key usages for that key
497 * (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
499 * The provided pointers are linked in, not copied, so they must remain
500 * valid while the public key may be in usage.
502 * \param ctx context to initialise.
503 * \param pk known public key.
504 * \param usages allowed key usages.
506 void br_x509_knownkey_init_rsa(br_x509_knownkey_context *ctx,
507 const br_rsa_public_key *pk, unsigned usages);
510 * \brief Initialize a "known key" X.509 engine with a known EC public key.
512 * The `usages` parameter indicates the allowed key usages for that key
513 * (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).
515 * The provided pointers are linked in, not copied, so they must remain
516 * valid while the public key may be in usage.
518 * \param ctx context to initialise.
519 * \param pk known public key.
520 * \param usages allowed key usages.
522 void br_x509_knownkey_init_ec(br_x509_knownkey_context *ctx,
523 const br_ec_public_key *pk, unsigned usages);
525 #ifndef BR_DOXYGEN_IGNORE
527 * The minimal X.509 engine has some state buffers which must be large
528 * enough to simultaneously accommodate:
529 * -- the public key extracted from the current certificate;
530 * -- the signature on the current certificate or on the previous
532 * -- the public key extracted from the EE certificate.
534 * We store public key elements in their raw unsigned big-endian
535 * encoding. We want to support up to RSA-4096 with a short (up to 64
536 * bits) public exponent, thus a buffer for a public key must have
537 * length at least 520 bytes. Similarly, a RSA-4096 signature has length
540 * Though RSA public exponents can formally be as large as the modulus
541 * (mathematically, even larger exponents would work, but PKCS#1 forbids
542 * them), exponents that do not fit on 32 bits are extremely rare,
543 * notably because some widespread implementations (e.g. Microsoft's
544 * CryptoAPI) don't support them. Moreover, large public exponent do not
545 * seem to imply any tangible security benefit, and they increase the
546 * cost of public key operations. The X.509 "minimal" engine will tolerate
547 * public exponents of arbitrary size as long as the modulus and the
548 * exponent can fit together in the dedicated buffer.
550 * EC public keys are shorter than RSA public keys; even with curve
551 * NIST P-521 (the largest curve we care to support), a public key is
552 * encoded over 133 bytes only.
554 #define BR_X509_BUFSIZE_KEY 520
555 #define BR_X509_BUFSIZE_SIG 512
559 * \brief Type for receiving a name element.
561 * An array of such structures can be provided to the X.509 decoding
562 * engines. If the specified elements are found in the certificate
563 * subject DN or the SAN extension, then the name contents are copied
564 * as zero-terminated strings into the buffer.
566 * The decoder converts TeletexString and BMPString to UTF8String, and
567 * ensures that the resulting string is zero-terminated. If the string
568 * does not fit in the provided buffer, then the copy is aborted and an
573 * \brief Element OID.
575 * For X.500 name elements (to be extracted from the subject DN),
576 * this is the encoded OID for the requested name element; the
577 * first byte shall contain the length of the DER-encoded OID
578 * value, followed by the OID value (for instance, OID 2.5.4.3,
579 * for id-at-commonName, will be `03 55 04 03`). This is
580 * equivalent to full DER encoding with the length but without
583 * For SAN name elements, the first byte (`oid[0]`) has value 0,
584 * followed by another byte that matches the expected GeneralName
585 * tag. Allowed second byte values are then:
591 * - 6: `uniformResourceIdentifier`
595 * If first and second byte are 0, then this is a SAN element of
596 * type `otherName`; the `oid[]` array should then contain, right
597 * after the two bytes of value 0, an encoded OID (with the same
598 * conventions as for X.500 name elements). If a match is found
599 * for that OID, then the corresponding name element will be
600 * extracted, as long as it is a supported string type.
602 const unsigned char *oid;
605 * \brief Destination buffer.
610 * \brief Length (in bytes) of the destination buffer.
612 * The buffer MUST NOT be smaller than 1 byte.
617 * \brief Decoding status.
619 * Status is 0 if the name element was not found, 1 if it was
620 * found and decoded, or -1 on error. Error conditions include
621 * an unrecognised encoding, an invalid encoding, or a string
622 * too large for the destination buffer.
629 * \brief The "minimal" X.509 engine structure.
631 * The structure contents are opaque (they shall not be accessed directly),
632 * except for the first field (the vtable).
634 * The "minimal" engine performs a rudimentary but serviceable X.509 path
638 const br_x509_class *vtable;
640 #ifndef BR_DOXYGEN_IGNORE
641 /* Structure for returning the EE public key. */
644 /* CPU for the T0 virtual machine. */
648 const unsigned char *ip;
650 uint32_t dp_stack[32];
651 uint32_t rp_stack[32];
654 /* Server name to match with the SAN / CN of the EE certificate. */
655 const char *server_name;
657 /* Validated key usages. */
658 unsigned char key_usages;
660 /* Explicitly set date and time. */
661 uint32_t days, seconds;
663 /* Current certificate length (in bytes). Set to 0 when the
664 certificate has been fully processed. */
665 uint32_t cert_length;
667 /* Number of certificates processed so far in the current chain.
668 It is incremented at the end of the processing of a certificate,
669 so it is 0 for the EE. */
672 /* Certificate data chunk. */
673 const unsigned char *hbuf;
676 /* The pad serves as destination for various operations. */
677 unsigned char pad[256];
679 /* Buffer for EE public key data. */
680 unsigned char ee_pkey_data[BR_X509_BUFSIZE_KEY];
682 /* Buffer for currently decoded public key. */
683 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
685 /* Signature type: signer key type, offset to the hash
686 function OID (in the T0 data block) and hash function
687 output length (TBS hash length). */
688 unsigned char cert_signer_key_type;
689 uint16_t cert_sig_hash_oid;
690 unsigned char cert_sig_hash_len;
692 /* Current/last certificate signature. */
693 unsigned char cert_sig[BR_X509_BUFSIZE_SIG];
694 uint16_t cert_sig_len;
696 /* Minimum RSA key length (difference in bytes from 128). */
697 int16_t min_rsa_size;
699 /* Configured trust anchors. */
700 const br_x509_trust_anchor *trust_anchors;
701 size_t trust_anchors_num;
704 * Multi-hasher for the TBS.
706 unsigned char do_mhash;
707 br_multihash_context mhash;
708 unsigned char tbs_hash[64];
711 * Simple hasher for the subject/issuer DN.
713 unsigned char do_dn_hash;
714 const br_hash_class *dn_hash_impl;
715 br_hash_compat_context dn_hash;
716 unsigned char current_dn_hash[64];
717 unsigned char next_dn_hash[64];
718 unsigned char saved_dn_hash[64];
721 * Name elements to gather.
723 br_name_element *name_elts;
724 size_t num_name_elts;
727 * Public key cryptography implementations (signature verification).
729 br_rsa_pkcs1_vrfy irsa;
730 br_ecdsa_vrfy iecdsa;
731 const br_ec_impl *iec;
734 } br_x509_minimal_context;
737 * \brief Class instance for the "minimal" X.509 engine.
739 extern const br_x509_class br_x509_minimal_vtable;
742 * \brief Initialise a "minimal" X.509 engine.
744 * The `dn_hash_impl` parameter shall be a hash function internally used
745 * to match X.500 names (subject/issuer DN, and anchor names). Any standard
746 * hash function may be used, but a collision-resistant hash function is
749 * After initialization, some implementations for signature verification
750 * (hash functions and signature algorithms) MUST be added.
752 * \param ctx context to initialise.
753 * \param dn_hash_impl hash function for DN comparisons.
754 * \param trust_anchors trust anchors.
755 * \param trust_anchors_num number of trust anchors.
757 void br_x509_minimal_init(br_x509_minimal_context *ctx,
758 const br_hash_class *dn_hash_impl,
759 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
762 * \brief Set a supported hash function in an X.509 "minimal" engine.
764 * Hash functions are used with signature verification algorithms.
765 * Once initialised (with `br_x509_minimal_init()`), the context must
766 * be configured with the hash functions it shall support for that
767 * purpose. The hash function identifier MUST be one of the standard
768 * hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,
769 * SHA-384 and SHA-512).
771 * If `impl` is `NULL`, this _removes_ support for the designated
774 * \param ctx validation context.
775 * \param id hash function identifier (from 1 to 6).
776 * \param impl hash function implementation (or `NULL`).
779 br_x509_minimal_set_hash(br_x509_minimal_context *ctx,
780 int id, const br_hash_class *impl)
782 br_multihash_setimpl(&ctx->mhash, id, impl);
786 * \brief Set a RSA signature verification implementation in the X.509
789 * Once initialised (with `br_x509_minimal_init()`), the context must
790 * be configured with the signature verification implementations that
791 * it is supposed to support. If `irsa` is `0`, then the RSA support
794 * \param ctx validation context.
795 * \param irsa RSA signature verification implementation (or `0`).
798 br_x509_minimal_set_rsa(br_x509_minimal_context *ctx,
799 br_rsa_pkcs1_vrfy irsa)
805 * \brief Set a ECDSA signature verification implementation in the X.509
808 * Once initialised (with `br_x509_minimal_init()`), the context must
809 * be configured with the signature verification implementations that
810 * it is supposed to support.
812 * If `iecdsa` is `0`, then this call disables ECDSA support; in that
813 * case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function
814 * that verifies ECDSA signatures with format "asn1", and it will use
815 * `iec` as underlying elliptic curve support.
817 * \param ctx validation context.
818 * \param iec elliptic curve implementation (or `NULL`).
819 * \param iecdsa ECDSA implementation (or `0`).
822 br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx,
823 const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)
825 ctx->iecdsa = iecdsa;
830 * \brief Initialise a "minimal" X.509 engine with default algorithms.
832 * This function performs the same job as `br_x509_minimal_init()`, but
833 * also sets implementations for RSA, ECDSA, and the standard hash
836 * \param ctx context to initialise.
837 * \param trust_anchors trust anchors.
838 * \param trust_anchors_num number of trust anchors.
840 void br_x509_minimal_init_full(br_x509_minimal_context *ctx,
841 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
844 * \brief Set the validation time for the X.509 "minimal" engine.
846 * The validation time is set as two 32-bit integers, for days and
847 * seconds since a fixed epoch:
849 * - Days are counted in a proleptic Gregorian calendar since
850 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
851 * it is also traditionally known as "1 BC".
853 * - Seconds are counted since midnight, from 0 to 86400 (a count of
854 * 86400 is possible only if a leap second happened).
856 * The validation date and time is understood in the UTC time zone.
858 * If the validation date and time are not explicitly set, but BearSSL
859 * was compiled with support for the system clock on the underlying
860 * platform, then the current time will automatically be used. Otherwise,
861 * not setting the validation date and time implies a validation
862 * failure (except in case of direct trust of the EE key).
864 * \param ctx validation context.
865 * \param days days since January 1st, 0 AD (Gregorian calendar).
866 * \param seconds seconds since midnight (0 to 86400).
869 br_x509_minimal_set_time(br_x509_minimal_context *ctx,
870 uint32_t days, uint32_t seconds)
873 ctx->seconds = seconds;
877 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
880 * The RSA key length is expressed in bytes. The default minimum key
881 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
882 * than the configured length will be rejected, implying validation
883 * failure. This setting applies to keys extracted from certificates
884 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
886 * \param ctx validation context.
887 * \param byte_length minimum RSA key length, **in bytes** (not bits).
890 br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
892 ctx->min_rsa_size = (int16_t)(byte_length - 128);
896 * \brief Set the name elements to gather.
898 * The provided array is linked in the context. The elements are
899 * gathered from the EE certificate. If the same element type is
900 * requested several times, then the relevant structures will be filled
901 * in the order the matching values are encountered in the certificate.
903 * \param ctx validation context.
904 * \param elts array of name element structures to fill.
905 * \param num_elts number of name element structures to fill.
908 br_x509_minimal_set_name_elements(br_x509_minimal_context *ctx,
909 br_name_element *elts, size_t num_elts)
911 ctx->name_elts = elts;
912 ctx->num_name_elts = num_elts;
916 * \brief X.509 decoder context.
918 * This structure is _not_ for X.509 validation, but for extracting
919 * names and public keys from encoded certificates. Intended usage is
920 * to use (self-signed) certificates as trust anchors.
922 * Contents are opaque and shall not be accessed directly.
926 #ifndef BR_DOXYGEN_IGNORE
927 /* Structure for returning the public key. */
930 /* CPU for the T0 virtual machine. */
934 const unsigned char *ip;
936 uint32_t dp_stack[32];
937 uint32_t rp_stack[32];
940 /* The pad serves as destination for various operations. */
941 unsigned char pad[256];
943 /* Flag set when decoding succeeds. */
944 unsigned char decoded;
946 /* Validity dates. */
947 uint32_t notbefore_days, notbefore_seconds;
948 uint32_t notafter_days, notafter_seconds;
950 /* The "CA" flag. This is set to true if the certificate contains
951 a Basic Constraints extension that asserts CA status. */
954 /* DN processing: the subject DN is extracted and pushed to the
955 provided callback. */
956 unsigned char copy_dn;
958 void (*append_dn)(void *ctx, const void *buf, size_t len);
960 /* Certificate data chunk. */
961 const unsigned char *hbuf;
964 /* Buffer for decoded public key. */
965 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
967 /* Type of key and hash function used in the certificate signature. */
968 unsigned char signer_key_type;
969 unsigned char signer_hash_id;
972 } br_x509_decoder_context;
975 * \brief Initialise an X.509 decoder context for processing a new
978 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
979 * will be invoked to receive, chunk by chunk, the certificate's
980 * subject DN. If `append_dn` is `0` then the subject DN will be
983 * \param ctx X.509 decoder context to initialise.
984 * \param append_dn DN receiver callback (or `0`).
985 * \param append_dn_ctx context for the DN receiver callback.
987 void br_x509_decoder_init(br_x509_decoder_context *ctx,
988 void (*append_dn)(void *ctx, const void *buf, size_t len),
989 void *append_dn_ctx);
992 * \brief Push some certificate bytes into a decoder context.
994 * If `len` is non-zero, then that many bytes are pushed, from address
995 * `data`, into the provided decoder context.
997 * \param ctx X.509 decoder context.
998 * \param data certificate data chunk.
999 * \param len certificate data chunk length (in bytes).
1001 void br_x509_decoder_push(br_x509_decoder_context *ctx,
1002 const void *data, size_t len);
1005 * \brief Obtain the decoded public key.
1007 * Returned value is a pointer to a structure internal to the decoder
1008 * context; releasing or reusing the decoder context invalidates that
1011 * If decoding was not finished, or failed, then `NULL` is returned.
1013 * \param ctx X.509 decoder context.
1014 * \return the public key, or `NULL` on unfinished/error.
1016 static inline br_x509_pkey *
1017 br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
1019 if (ctx->decoded && ctx->err == 0) {
1027 * \brief Get decoder error status.
1029 * If no error was reported yet but the certificate decoding is not
1030 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
1031 * was successful, then 0 is returned.
1033 * \param ctx X.509 decoder context.
1034 * \return 0 on successful decoding, or a non-zero error code.
1037 br_x509_decoder_last_error(br_x509_decoder_context *ctx)
1039 if (ctx->err != 0) {
1042 if (!ctx->decoded) {
1043 return BR_ERR_X509_TRUNCATED;
1049 * \brief Get the "isCA" flag from an X.509 decoder context.
1051 * This flag is set if the decoded certificate claims to be a CA through
1052 * a Basic Constraints extension. This flag should not be read before
1053 * decoding completed successfully.
1055 * \param ctx X.509 decoder context.
1056 * \return the "isCA" flag.
1059 br_x509_decoder_isCA(br_x509_decoder_context *ctx)
1065 * \brief Get the issuing CA key type (type of algorithm used to sign the
1066 * decoded certificate).
1068 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
1069 * if the signature type was not recognised.
1071 * \param ctx X.509 decoder context.
1072 * \return the issuing CA key type.
1075 br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
1077 return ctx->signer_key_type;
1081 * \brief Get the identifier for the hash function used to sign the decoded
1084 * This is 0 if the hash function was not recognised.
1086 * \param ctx X.509 decoder context.
1087 * \return the signature hash function identifier.
1090 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
1092 return ctx->signer_hash_id;
1096 * \brief Type for an X.509 certificate (DER-encoded).
1099 /** \brief The DER-encoded certificate data. */
1100 unsigned char *data;
1101 /** \brief The DER-encoded certificate length (in bytes). */
1103 } br_x509_certificate;
1106 * \brief Private key decoder context.
1108 * The private key decoder recognises RSA and EC private keys, either in
1109 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
1110 * archive (again DER-encoded).
1112 * Structure contents are opaque and shall not be accessed directly.
1115 #ifndef BR_DOXYGEN_IGNORE
1116 /* Structure for returning the private key. */
1118 br_rsa_private_key rsa;
1119 br_ec_private_key ec;
1122 /* CPU for the T0 virtual machine. */
1126 const unsigned char *ip;
1128 uint32_t dp_stack[32];
1129 uint32_t rp_stack[32];
1132 /* Private key data chunk. */
1133 const unsigned char *hbuf;
1136 /* The pad serves as destination for various operations. */
1137 unsigned char pad[256];
1139 /* Decoded key type; 0 until decoding is complete. */
1140 unsigned char key_type;
1142 /* Buffer for the private key elements. It shall be large enough
1143 to accommodate all elements for a RSA-4096 private key (roughly
1144 five 2048-bit integers, possibly a bit more). */
1145 unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];
1147 } br_skey_decoder_context;
1150 * \brief Initialise a private key decoder context.
1152 * \param ctx key decoder context to initialise.
1154 void br_skey_decoder_init(br_skey_decoder_context *ctx);
1157 * \brief Push some data bytes into a private key decoder context.
1159 * If `len` is non-zero, then that many data bytes, starting at address
1160 * `data`, are pushed into the decoder.
1162 * \param ctx key decoder context.
1163 * \param data private key data chunk.
1164 * \param len private key data chunk length (in bytes).
1166 void br_skey_decoder_push(br_skey_decoder_context *ctx,
1167 const void *data, size_t len);
1170 * \brief Get the decoding status for a private key.
1172 * Decoding status is 0 on success, or a non-zero error code. If the
1173 * decoding is unfinished when this function is called, then the
1174 * status code `BR_ERR_X509_TRUNCATED` is returned.
1176 * \param ctx key decoder context.
1177 * \return 0 on successful decoding, or a non-zero error code.
1180 br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
1182 if (ctx->err != 0) {
1185 if (ctx->key_type == 0) {
1186 return BR_ERR_X509_TRUNCATED;
1192 * \brief Get the decoded private key type.
1194 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1195 * not finished or failed, then 0 is returned.
1197 * \param ctx key decoder context.
1198 * \return decoded private key type, or 0.
1201 br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
1203 if (ctx->err == 0) {
1204 return ctx->key_type;
1211 * \brief Get the decoded RSA private key.
1213 * This function returns `NULL` if the decoding failed, or is not
1214 * finished, or the key is not RSA. The returned pointer references
1215 * structures within the context that can become invalid if the context
1216 * is reused or released.
1218 * \param ctx key decoder context.
1219 * \return decoded RSA private key, or `NULL`.
1221 static inline const br_rsa_private_key *
1222 br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
1224 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {
1225 return &ctx->key.rsa;
1232 * \brief Get the decoded EC private key.
1234 * This function returns `NULL` if the decoding failed, or is not
1235 * finished, or the key is not EC. The returned pointer references
1236 * structures within the context that can become invalid if the context
1237 * is reused or released.
1239 * \param ctx key decoder context.
1240 * \return decoded EC private key, or `NULL`.
1242 static inline const br_ec_private_key *
1243 br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
1245 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {
1246 return &ctx->key.ec;
1253 * \brief Encode an RSA private key (raw DER format).
1255 * This function encodes the provided key into the "raw" format specified
1256 * in PKCS#1 (RFC 8017, Appendix C, type `RSAPrivateKey`), with DER
1259 * The key elements are:
1261 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1263 * - `pk`: the public key (`n` and `e`)
1265 * - `d` (size: `dlen` bytes): the private exponent
1267 * The public key elements, and the private exponent `d`, can be
1268 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1269 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1271 * If `dest` is not `NULL`, then the encoded key is written at that
1272 * address, and the encoded length (in bytes) is returned. If `dest` is
1273 * `NULL`, then nothing is written, but the encoded length is still
1274 * computed and returned.
1276 * \param dest the destination buffer (or `NULL`).
1277 * \param sk the RSA private key.
1278 * \param pk the RSA public key.
1279 * \param d the RSA private exponent.
1280 * \param dlen the RSA private exponent length (in bytes).
1281 * \return the encoded key length (in bytes).
1283 size_t br_encode_rsa_raw_der(void *dest, const br_rsa_private_key *sk,
1284 const br_rsa_public_key *pk, const void *d, size_t dlen);
1287 * \brief Encode an RSA private key (PKCS#8 DER format).
1289 * This function encodes the provided key into the PKCS#8 format
1290 * (RFC 5958, type `OneAsymmetricKey`). It wraps around the "raw DER"
1291 * format for the RSA key, as implemented by `br_encode_rsa_raw_der()`.
1293 * The key elements are:
1295 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1297 * - `pk`: the public key (`n` and `e`)
1299 * - `d` (size: `dlen` bytes): the private exponent
1301 * The public key elements, and the private exponent `d`, can be
1302 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1303 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1305 * If `dest` is not `NULL`, then the encoded key is written at that
1306 * address, and the encoded length (in bytes) is returned. If `dest` is
1307 * `NULL`, then nothing is written, but the encoded length is still
1308 * computed and returned.
1310 * \param dest the destination buffer (or `NULL`).
1311 * \param sk the RSA private key.
1312 * \param pk the RSA public key.
1313 * \param d the RSA private exponent.
1314 * \param dlen the RSA private exponent length (in bytes).
1315 * \return the encoded key length (in bytes).
1317 size_t br_encode_rsa_pkcs8_der(void *dest, const br_rsa_private_key *sk,
1318 const br_rsa_public_key *pk, const void *d, size_t dlen);
1321 * \brief Encode an EC private key (raw DER format).
1323 * This function encodes the provided key into the "raw" format specified
1324 * in RFC 5915 (type `ECPrivateKey`), with DER encoding rules.
1326 * The private key is provided in `sk`, the public key being `pk`. If
1327 * `pk` is `NULL`, then the encoded key will not include the public key
1328 * in its `publicKey` field (which is nominally optional).
1330 * If `dest` is not `NULL`, then the encoded key is written at that
1331 * address, and the encoded length (in bytes) is returned. If `dest` is
1332 * `NULL`, then nothing is written, but the encoded length is still
1333 * computed and returned.
1335 * If the key cannot be encoded (e.g. because there is no known OBJECT
1336 * IDENTIFIER for the used curve), then 0 is returned.
1338 * \param dest the destination buffer (or `NULL`).
1339 * \param sk the EC private key.
1340 * \param pk the EC public key (or `NULL`).
1341 * \return the encoded key length (in bytes), or 0.
1343 size_t br_encode_ec_raw_der(void *dest,
1344 const br_ec_private_key *sk, const br_ec_public_key *pk);
1347 * \brief Encode an EC private key (PKCS#8 DER format).
1349 * This function encodes the provided key into the PKCS#8 format
1350 * (RFC 5958, type `OneAsymmetricKey`). The curve is identified
1351 * by an OID provided as parameters to the `privateKeyAlgorithm`
1352 * field. The private key value (contents of the `privateKey` field)
1353 * contains the DER encoding of the `ECPrivateKey` type defined in
1354 * RFC 5915, without the `parameters` field (since they would be
1355 * redundant with the information in `privateKeyAlgorithm`).
1357 * The private key is provided in `sk`, the public key being `pk`. If
1358 * `pk` is not `NULL`, then the encoded public key is included in the
1359 * `publicKey` field of the private key value (but not in the `publicKey`
1360 * field of the PKCS#8 `OneAsymmetricKey` wrapper).
1362 * If `dest` is not `NULL`, then the encoded key is written at that
1363 * address, and the encoded length (in bytes) is returned. If `dest` is
1364 * `NULL`, then nothing is written, but the encoded length is still
1365 * computed and returned.
1367 * If the key cannot be encoded (e.g. because there is no known OBJECT
1368 * IDENTIFIER for the used curve), then 0 is returned.
1370 * \param dest the destination buffer (or `NULL`).
1371 * \param sk the EC private key.
1372 * \param pk the EC public key (or `NULL`).
1373 * \return the encoded key length (in bytes), or 0.
1375 size_t br_encode_ec_pkcs8_der(void *dest,
1376 const br_ec_private_key *sk, const br_ec_public_key *pk);
1379 * \brief PEM banner for RSA private key (raw).
1381 #define BR_ENCODE_PEM_RSA_RAW "RSA PRIVATE KEY"
1384 * \brief PEM banner for EC private key (raw).
1386 #define BR_ENCODE_PEM_EC_RAW "EC PRIVATE KEY"
1389 * \brief PEM banner for an RSA or EC private key in PKCS#8 format.
1391 #define BR_ENCODE_PEM_PKCS8 "PRIVATE KEY"