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 Callback for validity date checks.
631 * The function receives as parameter an arbitrary user-provided context,
632 * and the notBefore and notAfter dates specified in an X.509 certificate,
633 * both expressed as a number of days and a number of seconds:
635 * - Days are counted in a proleptic Gregorian calendar since
636 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
637 * it is also traditionally known as "1 BC".
639 * - Seconds are counted since midnight, from 0 to 86400 (a count of
640 * 86400 is possible only if a leap second happened).
642 * Each date and time is understood in the UTC time zone. The "Unix
643 * Epoch" (January 1st, 1970, 00:00 UTC) corresponds to days=719528 and
644 * seconds=0; the "Windows Epoch" (January 1st, 1601, 00:00 UTC) is
645 * days=584754, seconds=0.
647 * This function must return -1 if the current date is strictly before
648 * the "notBefore" time, or +1 if the current date is strictly after the
649 * "notAfter" time. If neither condition holds, then the function returns
650 * 0, which means that the current date falls within the validity range of
651 * the certificate. If the function returns a value distinct from -1, 0
652 * and +1, then this is interpreted as an unavailability of the current
653 * time, which normally ends the validation process with a
654 * `BR_ERR_X509_TIME_UNKNOWN` error.
656 * During path validation, this callback will be invoked for each
657 * considered X.509 certificate. Validation fails if any of the calls
658 * returns a non-zero value.
660 * The context value is an abritrary pointer set by the caller when
661 * configuring this callback.
663 * \param tctx context pointer.
664 * \param not_before_days notBefore date (days since Jan 1st, 0 AD).
665 * \param not_before_seconds notBefore time (seconds, at most 86400).
666 * \param not_after_days notAfter date (days since Jan 1st, 0 AD).
667 * \param not_after_seconds notAfter time (seconds, at most 86400).
668 * \return -1, 0 or +1.
670 typedef int (*br_x509_time_check
)(void *tctx
,
671 uint32_t not_before_days
, uint32_t not_before_seconds
,
672 uint32_t not_after_days
, uint32_t not_after_seconds
);
675 * \brief The "minimal" X.509 engine structure.
677 * The structure contents are opaque (they shall not be accessed directly),
678 * except for the first field (the vtable).
680 * The "minimal" engine performs a rudimentary but serviceable X.509 path
684 const br_x509_class
*vtable
;
686 #ifndef BR_DOXYGEN_IGNORE
687 /* Structure for returning the EE public key. */
690 /* CPU for the T0 virtual machine. */
694 const unsigned char *ip
;
696 uint32_t dp_stack
[31];
697 uint32_t rp_stack
[31];
700 /* Server name to match with the SAN / CN of the EE certificate. */
701 const char *server_name
;
703 /* Validated key usages. */
704 unsigned char key_usages
;
706 /* Explicitly set date and time. */
707 uint32_t days
, seconds
;
709 /* Current certificate length (in bytes). Set to 0 when the
710 certificate has been fully processed. */
711 uint32_t cert_length
;
713 /* Number of certificates processed so far in the current chain.
714 It is incremented at the end of the processing of a certificate,
715 so it is 0 for the EE. */
718 /* Certificate data chunk. */
719 const unsigned char *hbuf
;
722 /* The pad serves as destination for various operations. */
723 unsigned char pad
[256];
725 /* Buffer for EE public key data. */
726 unsigned char ee_pkey_data
[BR_X509_BUFSIZE_KEY
];
728 /* Buffer for currently decoded public key. */
729 unsigned char pkey_data
[BR_X509_BUFSIZE_KEY
];
731 /* Signature type: signer key type, offset to the hash
732 function OID (in the T0 data block) and hash function
733 output length (TBS hash length). */
734 unsigned char cert_signer_key_type
;
735 uint16_t cert_sig_hash_oid
;
736 unsigned char cert_sig_hash_len
;
738 /* Current/last certificate signature. */
739 unsigned char cert_sig
[BR_X509_BUFSIZE_SIG
];
740 uint16_t cert_sig_len
;
742 /* Minimum RSA key length (difference in bytes from 128). */
743 int16_t min_rsa_size
;
745 /* Configured trust anchors. */
746 const br_x509_trust_anchor
*trust_anchors
;
747 size_t trust_anchors_num
;
750 * Multi-hasher for the TBS.
752 unsigned char do_mhash
;
753 br_multihash_context mhash
;
754 unsigned char tbs_hash
[64];
757 * Simple hasher for the subject/issuer DN.
759 unsigned char do_dn_hash
;
760 const br_hash_class
*dn_hash_impl
;
761 br_hash_compat_context dn_hash
;
762 unsigned char current_dn_hash
[64];
763 unsigned char next_dn_hash
[64];
764 unsigned char saved_dn_hash
[64];
767 * Name elements to gather.
769 br_name_element
*name_elts
;
770 size_t num_name_elts
;
773 * Callback function (and context) to get the current date.
776 br_x509_time_check itime
;
779 * Public key cryptography implementations (signature verification).
781 br_rsa_pkcs1_vrfy irsa
;
782 br_ecdsa_vrfy iecdsa
;
783 const br_ec_impl
*iec
;
786 } br_x509_minimal_context
;
789 * \brief Class instance for the "minimal" X.509 engine.
791 extern const br_x509_class br_x509_minimal_vtable
;
794 * \brief Initialise a "minimal" X.509 engine.
796 * The `dn_hash_impl` parameter shall be a hash function internally used
797 * to match X.500 names (subject/issuer DN, and anchor names). Any standard
798 * hash function may be used, but a collision-resistant hash function is
801 * After initialization, some implementations for signature verification
802 * (hash functions and signature algorithms) MUST be added.
804 * \param ctx context to initialise.
805 * \param dn_hash_impl hash function for DN comparisons.
806 * \param trust_anchors trust anchors.
807 * \param trust_anchors_num number of trust anchors.
809 void br_x509_minimal_init(br_x509_minimal_context
*ctx
,
810 const br_hash_class
*dn_hash_impl
,
811 const br_x509_trust_anchor
*trust_anchors
, size_t trust_anchors_num
);
814 * \brief Set a supported hash function in an X.509 "minimal" engine.
816 * Hash functions are used with signature verification algorithms.
817 * Once initialised (with `br_x509_minimal_init()`), the context must
818 * be configured with the hash functions it shall support for that
819 * purpose. The hash function identifier MUST be one of the standard
820 * hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,
821 * SHA-384 and SHA-512).
823 * If `impl` is `NULL`, this _removes_ support for the designated
826 * \param ctx validation context.
827 * \param id hash function identifier (from 1 to 6).
828 * \param impl hash function implementation (or `NULL`).
831 br_x509_minimal_set_hash(br_x509_minimal_context
*ctx
,
832 int id
, const br_hash_class
*impl
)
834 br_multihash_setimpl(&ctx
->mhash
, id
, impl
);
838 * \brief Set a RSA signature verification implementation in the X.509
841 * Once initialised (with `br_x509_minimal_init()`), the context must
842 * be configured with the signature verification implementations that
843 * it is supposed to support. If `irsa` is `0`, then the RSA support
846 * \param ctx validation context.
847 * \param irsa RSA signature verification implementation (or `0`).
850 br_x509_minimal_set_rsa(br_x509_minimal_context
*ctx
,
851 br_rsa_pkcs1_vrfy irsa
)
857 * \brief Set a ECDSA signature verification implementation in the X.509
860 * Once initialised (with `br_x509_minimal_init()`), the context must
861 * be configured with the signature verification implementations that
862 * it is supposed to support.
864 * If `iecdsa` is `0`, then this call disables ECDSA support; in that
865 * case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function
866 * that verifies ECDSA signatures with format "asn1", and it will use
867 * `iec` as underlying elliptic curve support.
869 * \param ctx validation context.
870 * \param iec elliptic curve implementation (or `NULL`).
871 * \param iecdsa ECDSA implementation (or `0`).
874 br_x509_minimal_set_ecdsa(br_x509_minimal_context
*ctx
,
875 const br_ec_impl
*iec
, br_ecdsa_vrfy iecdsa
)
877 ctx
->iecdsa
= iecdsa
;
882 * \brief Initialise a "minimal" X.509 engine with default algorithms.
884 * This function performs the same job as `br_x509_minimal_init()`, but
885 * also sets implementations for RSA, ECDSA, and the standard hash
888 * \param ctx context to initialise.
889 * \param trust_anchors trust anchors.
890 * \param trust_anchors_num number of trust anchors.
892 void br_x509_minimal_init_full(br_x509_minimal_context
*ctx
,
893 const br_x509_trust_anchor
*trust_anchors
, size_t trust_anchors_num
);
896 * \brief Set the validation time for the X.509 "minimal" engine.
898 * The validation time is set as two 32-bit integers, for days and
899 * seconds since a fixed epoch:
901 * - Days are counted in a proleptic Gregorian calendar since
902 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
903 * it is also traditionally known as "1 BC".
905 * - Seconds are counted since midnight, from 0 to 86400 (a count of
906 * 86400 is possible only if a leap second happened).
908 * The validation date and time is understood in the UTC time zone. The
909 * "Unix Epoch" (January 1st, 1970, 00:00 UTC) corresponds to days=719528
910 * and seconds=0; the "Windows Epoch" (January 1st, 1601, 00:00 UTC) is
911 * days=584754, seconds=0.
913 * If the validation date and time are not explicitly set, but BearSSL
914 * was compiled with support for the system clock on the underlying
915 * platform, then the current time will automatically be used. Otherwise,
916 * not setting the validation date and time implies a validation
917 * failure (except in case of direct trust of the EE key).
919 * \param ctx validation context.
920 * \param days days since January 1st, 0 AD (Gregorian calendar).
921 * \param seconds seconds since midnight (0 to 86400).
924 br_x509_minimal_set_time(br_x509_minimal_context
*ctx
,
925 uint32_t days
, uint32_t seconds
)
928 ctx
->seconds
= seconds
;
933 * \brief Set the validity range callback function for the X.509
936 * The provided function will be invoked to check whether the validation
937 * date is within the validity range for a given X.509 certificate; a
938 * call will be issued for each considered certificate. The provided
939 * context pointer (itime_ctx) will be passed as first parameter to the
942 * \param tctx context for callback invocation.
943 * \param cb callback function.
946 br_x509_minimal_set_time_callback(br_x509_minimal_context
*ctx
,
947 void *itime_ctx
, br_x509_time_check itime
)
949 ctx
->itime_ctx
= itime_ctx
;
954 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
957 * The RSA key length is expressed in bytes. The default minimum key
958 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
959 * than the configured length will be rejected, implying validation
960 * failure. This setting applies to keys extracted from certificates
961 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
963 * \param ctx validation context.
964 * \param byte_length minimum RSA key length, **in bytes** (not bits).
967 br_x509_minimal_set_minrsa(br_x509_minimal_context
*ctx
, int byte_length
)
969 ctx
->min_rsa_size
= (int16_t)(byte_length
- 128);
973 * \brief Set the name elements to gather.
975 * The provided array is linked in the context. The elements are
976 * gathered from the EE certificate. If the same element type is
977 * requested several times, then the relevant structures will be filled
978 * in the order the matching values are encountered in the certificate.
980 * \param ctx validation context.
981 * \param elts array of name element structures to fill.
982 * \param num_elts number of name element structures to fill.
985 br_x509_minimal_set_name_elements(br_x509_minimal_context
*ctx
,
986 br_name_element
*elts
, size_t num_elts
)
988 ctx
->name_elts
= elts
;
989 ctx
->num_name_elts
= num_elts
;
993 * \brief X.509 decoder context.
995 * This structure is _not_ for X.509 validation, but for extracting
996 * names and public keys from encoded certificates. Intended usage is
997 * to use (self-signed) certificates as trust anchors.
999 * Contents are opaque and shall not be accessed directly.
1003 #ifndef BR_DOXYGEN_IGNORE
1004 /* Structure for returning the public key. */
1007 /* CPU for the T0 virtual machine. */
1011 const unsigned char *ip
;
1013 uint32_t dp_stack
[32];
1014 uint32_t rp_stack
[32];
1017 /* The pad serves as destination for various operations. */
1018 unsigned char pad
[256];
1020 /* Flag set when decoding succeeds. */
1021 unsigned char decoded
;
1023 /* Validity dates. */
1024 uint32_t notbefore_days
, notbefore_seconds
;
1025 uint32_t notafter_days
, notafter_seconds
;
1027 /* The "CA" flag. This is set to true if the certificate contains
1028 a Basic Constraints extension that asserts CA status. */
1031 /* DN processing: the subject DN is extracted and pushed to the
1032 provided callback. */
1033 unsigned char copy_dn
;
1034 void *append_dn_ctx
;
1035 void (*append_dn
)(void *ctx
, const void *buf
, size_t len
);
1037 /* Certificate data chunk. */
1038 const unsigned char *hbuf
;
1041 /* Buffer for decoded public key. */
1042 unsigned char pkey_data
[BR_X509_BUFSIZE_KEY
];
1044 /* Type of key and hash function used in the certificate signature. */
1045 unsigned char signer_key_type
;
1046 unsigned char signer_hash_id
;
1049 } br_x509_decoder_context
;
1052 * \brief Initialise an X.509 decoder context for processing a new
1055 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
1056 * will be invoked to receive, chunk by chunk, the certificate's
1057 * subject DN. If `append_dn` is `0` then the subject DN will be
1060 * \param ctx X.509 decoder context to initialise.
1061 * \param append_dn DN receiver callback (or `0`).
1062 * \param append_dn_ctx context for the DN receiver callback.
1064 void br_x509_decoder_init(br_x509_decoder_context
*ctx
,
1065 void (*append_dn
)(void *ctx
, const void *buf
, size_t len
),
1066 void *append_dn_ctx
);
1069 * \brief Push some certificate bytes into a decoder context.
1071 * If `len` is non-zero, then that many bytes are pushed, from address
1072 * `data`, into the provided decoder context.
1074 * \param ctx X.509 decoder context.
1075 * \param data certificate data chunk.
1076 * \param len certificate data chunk length (in bytes).
1078 void br_x509_decoder_push(br_x509_decoder_context
*ctx
,
1079 const void *data
, size_t len
);
1082 * \brief Obtain the decoded public key.
1084 * Returned value is a pointer to a structure internal to the decoder
1085 * context; releasing or reusing the decoder context invalidates that
1088 * If decoding was not finished, or failed, then `NULL` is returned.
1090 * \param ctx X.509 decoder context.
1091 * \return the public key, or `NULL` on unfinished/error.
1093 static inline br_x509_pkey
*
1094 br_x509_decoder_get_pkey(br_x509_decoder_context
*ctx
)
1096 if (ctx
->decoded
&& ctx
->err
== 0) {
1104 * \brief Get decoder error status.
1106 * If no error was reported yet but the certificate decoding is not
1107 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
1108 * was successful, then 0 is returned.
1110 * \param ctx X.509 decoder context.
1111 * \return 0 on successful decoding, or a non-zero error code.
1114 br_x509_decoder_last_error(br_x509_decoder_context
*ctx
)
1116 if (ctx
->err
!= 0) {
1119 if (!ctx
->decoded
) {
1120 return BR_ERR_X509_TRUNCATED
;
1126 * \brief Get the "isCA" flag from an X.509 decoder context.
1128 * This flag is set if the decoded certificate claims to be a CA through
1129 * a Basic Constraints extension. This flag should not be read before
1130 * decoding completed successfully.
1132 * \param ctx X.509 decoder context.
1133 * \return the "isCA" flag.
1136 br_x509_decoder_isCA(br_x509_decoder_context
*ctx
)
1142 * \brief Get the issuing CA key type (type of algorithm used to sign the
1143 * decoded certificate).
1145 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
1146 * if the signature type was not recognised.
1148 * \param ctx X.509 decoder context.
1149 * \return the issuing CA key type.
1152 br_x509_decoder_get_signer_key_type(br_x509_decoder_context
*ctx
)
1154 return ctx
->signer_key_type
;
1158 * \brief Get the identifier for the hash function used to sign the decoded
1161 * This is 0 if the hash function was not recognised.
1163 * \param ctx X.509 decoder context.
1164 * \return the signature hash function identifier.
1167 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context
*ctx
)
1169 return ctx
->signer_hash_id
;
1173 * \brief Type for an X.509 certificate (DER-encoded).
1176 /** \brief The DER-encoded certificate data. */
1177 unsigned char *data
;
1178 /** \brief The DER-encoded certificate length (in bytes). */
1180 } br_x509_certificate
;
1183 * \brief Private key decoder context.
1185 * The private key decoder recognises RSA and EC private keys, either in
1186 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
1187 * archive (again DER-encoded).
1189 * Structure contents are opaque and shall not be accessed directly.
1192 #ifndef BR_DOXYGEN_IGNORE
1193 /* Structure for returning the private key. */
1195 br_rsa_private_key rsa
;
1196 br_ec_private_key ec
;
1199 /* CPU for the T0 virtual machine. */
1203 const unsigned char *ip
;
1205 uint32_t dp_stack
[32];
1206 uint32_t rp_stack
[32];
1209 /* Private key data chunk. */
1210 const unsigned char *hbuf
;
1213 /* The pad serves as destination for various operations. */
1214 unsigned char pad
[256];
1216 /* Decoded key type; 0 until decoding is complete. */
1217 unsigned char key_type
;
1219 /* Buffer for the private key elements. It shall be large enough
1220 to accommodate all elements for a RSA-4096 private key (roughly
1221 five 2048-bit integers, possibly a bit more). */
1222 unsigned char key_data
[3 * BR_X509_BUFSIZE_SIG
];
1224 } br_skey_decoder_context
;
1227 * \brief Initialise a private key decoder context.
1229 * \param ctx key decoder context to initialise.
1231 void br_skey_decoder_init(br_skey_decoder_context
*ctx
);
1234 * \brief Push some data bytes into a private key decoder context.
1236 * If `len` is non-zero, then that many data bytes, starting at address
1237 * `data`, are pushed into the decoder.
1239 * \param ctx key decoder context.
1240 * \param data private key data chunk.
1241 * \param len private key data chunk length (in bytes).
1243 void br_skey_decoder_push(br_skey_decoder_context
*ctx
,
1244 const void *data
, size_t len
);
1247 * \brief Get the decoding status for a private key.
1249 * Decoding status is 0 on success, or a non-zero error code. If the
1250 * decoding is unfinished when this function is called, then the
1251 * status code `BR_ERR_X509_TRUNCATED` is returned.
1253 * \param ctx key decoder context.
1254 * \return 0 on successful decoding, or a non-zero error code.
1257 br_skey_decoder_last_error(const br_skey_decoder_context
*ctx
)
1259 if (ctx
->err
!= 0) {
1262 if (ctx
->key_type
== 0) {
1263 return BR_ERR_X509_TRUNCATED
;
1269 * \brief Get the decoded private key type.
1271 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1272 * not finished or failed, then 0 is returned.
1274 * \param ctx key decoder context.
1275 * \return decoded private key type, or 0.
1278 br_skey_decoder_key_type(const br_skey_decoder_context
*ctx
)
1280 if (ctx
->err
== 0) {
1281 return ctx
->key_type
;
1288 * \brief Get the decoded RSA private key.
1290 * This function returns `NULL` if the decoding failed, or is not
1291 * finished, or the key is not RSA. The returned pointer references
1292 * structures within the context that can become invalid if the context
1293 * is reused or released.
1295 * \param ctx key decoder context.
1296 * \return decoded RSA private key, or `NULL`.
1298 static inline const br_rsa_private_key
*
1299 br_skey_decoder_get_rsa(const br_skey_decoder_context
*ctx
)
1301 if (ctx
->err
== 0 && ctx
->key_type
== BR_KEYTYPE_RSA
) {
1302 return &ctx
->key
.rsa
;
1309 * \brief Get the decoded EC private key.
1311 * This function returns `NULL` if the decoding failed, or is not
1312 * finished, or the key is not EC. The returned pointer references
1313 * structures within the context that can become invalid if the context
1314 * is reused or released.
1316 * \param ctx key decoder context.
1317 * \return decoded EC private key, or `NULL`.
1319 static inline const br_ec_private_key
*
1320 br_skey_decoder_get_ec(const br_skey_decoder_context
*ctx
)
1322 if (ctx
->err
== 0 && ctx
->key_type
== BR_KEYTYPE_EC
) {
1323 return &ctx
->key
.ec
;
1330 * \brief Encode an RSA private key (raw DER format).
1332 * This function encodes the provided key into the "raw" format specified
1333 * in PKCS#1 (RFC 8017, Appendix C, type `RSAPrivateKey`), with DER
1336 * The key elements are:
1338 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1340 * - `pk`: the public key (`n` and `e`)
1342 * - `d` (size: `dlen` bytes): the private exponent
1344 * The public key elements, and the private exponent `d`, can be
1345 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1346 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1348 * If `dest` is not `NULL`, then the encoded key is written at that
1349 * address, and the encoded length (in bytes) is returned. If `dest` is
1350 * `NULL`, then nothing is written, but the encoded length is still
1351 * computed and returned.
1353 * \param dest the destination buffer (or `NULL`).
1354 * \param sk the RSA private key.
1355 * \param pk the RSA public key.
1356 * \param d the RSA private exponent.
1357 * \param dlen the RSA private exponent length (in bytes).
1358 * \return the encoded key length (in bytes).
1360 size_t br_encode_rsa_raw_der(void *dest
, const br_rsa_private_key
*sk
,
1361 const br_rsa_public_key
*pk
, const void *d
, size_t dlen
);
1364 * \brief Encode an RSA private key (PKCS#8 DER format).
1366 * This function encodes the provided key into the PKCS#8 format
1367 * (RFC 5958, type `OneAsymmetricKey`). It wraps around the "raw DER"
1368 * format for the RSA key, as implemented by `br_encode_rsa_raw_der()`.
1370 * The key elements are:
1372 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1374 * - `pk`: the public key (`n` and `e`)
1376 * - `d` (size: `dlen` bytes): the private exponent
1378 * The public key elements, and the private exponent `d`, can be
1379 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1380 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1382 * If `dest` is not `NULL`, then the encoded key is written at that
1383 * address, and the encoded length (in bytes) is returned. If `dest` is
1384 * `NULL`, then nothing is written, but the encoded length is still
1385 * computed and returned.
1387 * \param dest the destination buffer (or `NULL`).
1388 * \param sk the RSA private key.
1389 * \param pk the RSA public key.
1390 * \param d the RSA private exponent.
1391 * \param dlen the RSA private exponent length (in bytes).
1392 * \return the encoded key length (in bytes).
1394 size_t br_encode_rsa_pkcs8_der(void *dest
, const br_rsa_private_key
*sk
,
1395 const br_rsa_public_key
*pk
, const void *d
, size_t dlen
);
1398 * \brief Encode an EC private key (raw DER format).
1400 * This function encodes the provided key into the "raw" format specified
1401 * in RFC 5915 (type `ECPrivateKey`), with DER encoding rules.
1403 * The private key is provided in `sk`, the public key being `pk`. If
1404 * `pk` is `NULL`, then the encoded key will not include the public key
1405 * in its `publicKey` field (which is nominally optional).
1407 * If `dest` is not `NULL`, then the encoded key is written at that
1408 * address, and the encoded length (in bytes) is returned. If `dest` is
1409 * `NULL`, then nothing is written, but the encoded length is still
1410 * computed and returned.
1412 * If the key cannot be encoded (e.g. because there is no known OBJECT
1413 * IDENTIFIER for the used curve), then 0 is returned.
1415 * \param dest the destination buffer (or `NULL`).
1416 * \param sk the EC private key.
1417 * \param pk the EC public key (or `NULL`).
1418 * \return the encoded key length (in bytes), or 0.
1420 size_t br_encode_ec_raw_der(void *dest
,
1421 const br_ec_private_key
*sk
, const br_ec_public_key
*pk
);
1424 * \brief Encode an EC private key (PKCS#8 DER format).
1426 * This function encodes the provided key into the PKCS#8 format
1427 * (RFC 5958, type `OneAsymmetricKey`). The curve is identified
1428 * by an OID provided as parameters to the `privateKeyAlgorithm`
1429 * field. The private key value (contents of the `privateKey` field)
1430 * contains the DER encoding of the `ECPrivateKey` type defined in
1431 * RFC 5915, without the `parameters` field (since they would be
1432 * redundant with the information in `privateKeyAlgorithm`).
1434 * The private key is provided in `sk`, the public key being `pk`. If
1435 * `pk` is not `NULL`, then the encoded public key is included in the
1436 * `publicKey` field of the private key value (but not in the `publicKey`
1437 * field of the PKCS#8 `OneAsymmetricKey` wrapper).
1439 * If `dest` is not `NULL`, then the encoded key is written at that
1440 * address, and the encoded length (in bytes) is returned. If `dest` is
1441 * `NULL`, then nothing is written, but the encoded length is still
1442 * computed and returned.
1444 * If the key cannot be encoded (e.g. because there is no known OBJECT
1445 * IDENTIFIER for the used curve), then 0 is returned.
1447 * \param dest the destination buffer (or `NULL`).
1448 * \param sk the EC private key.
1449 * \param pk the EC public key (or `NULL`).
1450 * \return the encoded key length (in bytes), or 0.
1452 size_t br_encode_ec_pkcs8_der(void *dest
,
1453 const br_ec_private_key
*sk
, const br_ec_public_key
*pk
);
1456 * \brief PEM banner for RSA private key (raw).
1458 #define BR_ENCODE_PEM_RSA_RAW "RSA PRIVATE KEY"
1461 * \brief PEM banner for EC private key (raw).
1463 #define BR_ENCODE_PEM_EC_RAW "EC PRIVATE KEY"
1466 * \brief PEM banner for an RSA or EC private key in PKCS#8 format.
1468 #define BR_ENCODE_PEM_PKCS8 "PRIVATE KEY"