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"
36 * X.509 Certificate Chain Processing
37 * ----------------------------------
39 * An X.509 processing engine receives an X.509 chain, chunk by chunk,
40 * as received from a SSL/TLS client or server (the client receives the
41 * server's certificate chain, and the server receives the client's
42 * certificate chain if it requested a client certificate). The chain
43 * is thus injected in the engine in SSL order (end-entity first).
45 * The engine's job is to return the public key to use for SSL/TLS.
46 * How exactly that key is obtained and verified is entirely up to the
51 * X.509 error codes are in the 32..63 range.
54 /* Validation was successful; this is not actually an error. */
55 #define BR_ERR_X509_OK 32
57 /* Invalid value in an ASN.1 structure. */
58 #define BR_ERR_X509_INVALID_VALUE 33
60 /* Truncated certificate. */
61 #define BR_ERR_X509_TRUNCATED 34
63 /* Empty certificate chain (no certificate at all). */
64 #define BR_ERR_X509_EMPTY_CHAIN 35
66 /* Decoding error: inner element extends beyond outer element size. */
67 #define BR_ERR_X509_INNER_TRUNC 36
69 /* Decoding error: unsupported tag class (application or private). */
70 #define BR_ERR_X509_BAD_TAG_CLASS 37
72 /* Decoding error: unsupported tag value. */
73 #define BR_ERR_X509_BAD_TAG_VALUE 38
75 /* Decoding error: indefinite length. */
76 #define BR_ERR_X509_INDEFINITE_LENGTH 39
78 /* Decoding error: extraneous element. */
79 #define BR_ERR_X509_EXTRA_ELEMENT 40
81 /* Decoding error: unexpected element. */
82 #define BR_ERR_X509_UNEXPECTED 41
84 /* Decoding error: expected constructed element, but is primitive. */
85 #define BR_ERR_X509_NOT_CONSTRUCTED 42
87 /* Decoding error: expected primitive element, but is constructed. */
88 #define BR_ERR_X509_NOT_PRIMITIVE 43
90 /* Decoding error: BIT STRING length is not multiple of 8. */
91 #define BR_ERR_X509_PARTIAL_BYTE 44
93 /* Decoding error: BOOLEAN value has invalid length. */
94 #define BR_ERR_X509_BAD_BOOLEAN 45
96 /* Decoding error: value is off-limits. */
97 #define BR_ERR_X509_OVERFLOW 46
99 /* Invalid distinguished name. */
100 #define BR_ERR_X509_BAD_DN 47
102 /* Invalid date/time representation. */
103 #define BR_ERR_X509_BAD_TIME 48
105 /* Certificate contains unsupported features that cannot be ignored. */
106 #define BR_ERR_X509_UNSUPPORTED 49
108 /* Key or signature size exceeds internal limits. */
109 #define BR_ERR_X509_LIMIT_EXCEEDED 50
111 /* Key type does not match that which was expected. */
112 #define BR_ERR_X509_WRONG_KEY_TYPE 51
114 /* Signature is invalid. */
115 #define BR_ERR_X509_BAD_SIGNATURE 52
117 /* Validation time is unknown. */
118 #define BR_ERR_X509_TIME_UNKNOWN 53
120 /* Certificate is expired or not yet valid. */
121 #define BR_ERR_X509_EXPIRED 54
123 /* Issuer/Subject DN mismatch in the chain. */
124 #define BR_ERR_X509_DN_MISMATCH 55
126 /* Expected server name was not found in the chain. */
127 #define BR_ERR_X509_BAD_SERVER_NAME 56
129 /* Unknown critical extension in certificate. */
130 #define BR_ERR_X509_CRITICAL_EXTENSION 57
132 /* Not a CA, or path length constraint violation */
133 #define BR_ERR_X509_NOT_CA 58
135 /* Key Usage extension prohibits intended usage. */
136 #define BR_ERR_X509_FORBIDDEN_KEY_USAGE 59
138 /* Public key found in certificate is too small. */
139 #define BR_ERR_X509_WEAK_PUBLIC_KEY 60
141 /* Chain could not be linked to a trust anchor. */
142 #define BR_ERR_X509_NOT_TRUSTED 62
145 * A structure to encode public keys.
148 unsigned char key_type
;
150 br_rsa_public_key rsa
;
156 * A trust anchor consists in:
164 /* unsigned char hashed_DN[64]; */
167 } br_x509_trust_anchor
;
169 /* Trust anchor flag: trust anchor is a CA and thus acceptable for
170 signing other certificates. Without this flag, the trust anchor
171 is only for direct trust (name and key match EE certificate). */
172 #define BR_X509_TA_CA 0x0001
175 * Key type: combination of a basic key type (low 4 bits) and some
178 * For a public key, the basic key type only is set.
180 * For an expected key type, the flags indicate the intended purpose(s)
181 * for the key; the basic key type may be set to 0 to indicate that any
182 * key type compatible with the indicated purpose is acceptable.
184 #define BR_KEYTYPE_RSA 1
185 #define BR_KEYTYPE_EC 2
187 #define BR_KEYTYPE_KEYX 0x10 /* key is for key exchange or encryption */
188 #define BR_KEYTYPE_SIGN 0x20 /* key is for verifying signatures */
191 * start_chain Called when a new chain is started. If 'server_name'
192 * is not NULL and non-empty, then it is a name that
193 * should be looked for in the EE certificate (in the
194 * SAN extension as dNSName, or in the subjectDN's CN
195 * if there is no SAN extension).
196 * The caller ensures that the provided 'server_name'
197 * pointer remains valid throughout validation.
199 * start_cert Begins a new certificate in the chain. The provided
200 * length is in bytes; this is the total certificate length.
202 * append Get some additional bytes for the current certificate.
204 * end_cert Ends the current certificate.
206 * end_chain Called at the end of the chain. Returned value is
207 * 0 on success, or a non-zero error code.
209 * get_pkey Returns the EE certificate public key.
211 * For a complete chain, start_chain() and end_chain() are always
212 * called. For each certificate, start_cert(), some append() calls, then
213 * end_cert() are called, in that order. There may be no append() call
214 * at all if the certificate is empty (which is not valid but may happen
215 * if the peer sends exactly that).
217 * get_pkey() shall return a pointer to a structure that is valid as
218 * long as a new chain is not started. This may be a sub-structure
219 * within the context for the engine. This function MAY return a valid
220 * pointer to a public key even in some cases of validation failure,
221 * depending on the validation engine.
223 typedef struct br_x509_class_ br_x509_class
;
224 struct br_x509_class_
{
226 void (*start_chain
)(const br_x509_class
**ctx
,
227 unsigned expected_key_type
,
228 const char *server_name
);
229 void (*start_cert
)(const br_x509_class
**ctx
, uint32_t length
);
230 void (*append
)(const br_x509_class
**ctx
,
231 const unsigned char *buf
, size_t len
);
232 void (*end_cert
)(const br_x509_class
**ctx
);
233 unsigned (*end_chain
)(const br_x509_class
**ctx
);
234 const br_x509_pkey
*(*get_pkey
)(const br_x509_class
*const *ctx
);
238 * The "known key" X.509 engine is a trivial engine that completely
239 * ignores the certificates, and instead reports an externally
240 * configured public key.
243 const br_x509_class
*vtable
;
245 } br_x509_knownkey_context
;
246 extern const br_x509_class br_x509_knownkey_vtable
;
249 * Initialize a "known key" X.509 engine with a known RSA public key.
250 * The provided pointers are linked in, not copied, so they must
251 * remain valid while the public key may be in usage (i.e. at least up
252 * to the end of the handshake -- and since there may be renegotiations,
253 * these buffers should stay until the connection is finished).
255 void br_x509_knownkey_init_rsa(br_x509_knownkey_context
*ctx
,
256 const br_rsa_public_key
*pk
);
259 * Initialize a "known key" X.509 engine with a known EC public key.
260 * The provided pointers are linked in, not copied, so they must
261 * remain valid while the public key may be in usage (i.e. at least up
262 * to the end of the handshake -- and since there may be renegotiations,
263 * these buffers should stay until the connection is finished).
265 void br_x509_knownkey_init_ec(br_x509_knownkey_context
*ctx
,
266 const br_ec_public_key
*pk
);
269 * The minimal X.509 engine has some state buffers which must be large
270 * enough to simultaneously accommodate:
271 * -- the public key extracted from the current certificate;
272 * -- the signature on the current certificate or on the previous
274 * -- the public key extracted from the EE certificate.
276 * We store public key elements in their raw unsigned big-endian
277 * encoding. We want to support up to RSA-4096 with a short (up to 64
278 * bits) public exponent, thus a buffer for a public key must have
279 * length at least 520 bytes. Similarly, a RSA-4096 signature has length
282 * Though RSA public exponents can formally be as large as the modulus
283 * (mathematically, even larger exponents would work, but PKCS#1 forbids
284 * them), exponents that do not fit on 32 bits are extremely rare,
285 * notably because some widespread implementation (e.g. Microsoft's
286 * CryptoAPI) don't support them. Moreover, large public exponent do not
287 * seem to imply any tangible security benefit, and they increase the
288 * cost of public key operations.
290 * EC public keys are shorter than RSA public keys; even with curve
291 * NIST P-521 (the largest curve we care to support), a public key is
292 * encoded over 133 bytes only.
294 #define BR_X509_BUFSIZE_KEY 520
295 #define BR_X509_BUFSIZE_SIG 512
298 * The "minimal" X.509 engine performs basic decoding of certificates and
303 * -- Basic Constraints extension
304 * -- Server name check against SAN extension
307 const br_x509_class
*vtable
;
309 /* Structure for returning the EE public key. */
312 /* CPU for the T0 virtual machine. */
316 const unsigned char *ip
;
318 uint32_t dp_stack
[32];
319 uint32_t rp_stack
[32];
322 /* Server name to match with the SAN / CN of the EE certificate. */
323 const char *server_name
;
325 /* Expected EE key type and usage. */
326 unsigned char expected_key_type
;
328 /* Explicitly set date and time. */
329 uint32_t days
, seconds
;
331 /* Current certificate length (in bytes). Set to 0 when the
332 certificate has been fully processed. */
333 uint32_t cert_length
;
335 /* Number of certificates processed so far in the current chain.
336 It is incremented at the end of the processing of a certificate,
337 so it is 0 for the EE. */
340 /* Certificate data chunk. */
341 const unsigned char *hbuf
;
344 /* The pad serves as destination for various operations. */
345 unsigned char pad
[256];
347 /* Buffer for EE public key data. */
348 unsigned char ee_pkey_data
[BR_X509_BUFSIZE_KEY
];
350 /* Buffer for currently decoded public key. */
351 unsigned char pkey_data
[BR_X509_BUFSIZE_KEY
];
353 /* Signature type: signer key type, offset to the hash
354 function OID (in the T0 data block) and hash function
355 output length (TBS hash length). */
356 unsigned char cert_signer_key_type
;
357 uint16_t cert_sig_hash_oid
;
358 unsigned char cert_sig_hash_len
;
360 /* Current/last certificate signature. */
361 unsigned char cert_sig
[BR_X509_BUFSIZE_SIG
];
362 uint16_t cert_sig_len
;
364 /* Minimum RSA key length (difference in bytes from 128). */
365 int16_t min_rsa_size
;
367 /* Configured trust anchors. */
368 const br_x509_trust_anchor
*trust_anchors
;
369 size_t trust_anchors_num
;
372 * Multi-hasher for the TBS.
374 unsigned char do_mhash
;
375 br_multihash_context mhash
;
376 unsigned char tbs_hash
[64];
379 * Simple hasher for the subject/issuer DN.
381 unsigned char do_dn_hash
;
382 const br_hash_class
*dn_hash_impl
;
383 br_hash_compat_context dn_hash
;
384 unsigned char current_dn_hash
[64];
385 unsigned char next_dn_hash
[64];
386 unsigned char saved_dn_hash
[64];
389 * Public key cryptography implementations (signature verification).
391 br_rsa_pkcs1_vrfy irsa
;
392 br_ecdsa_vrfy iecdsa
;
393 const br_ec_impl
*iec
;
395 } br_x509_minimal_context
;
396 extern const br_x509_class br_x509_minimal_vtable
;
399 * Initialize a "minimal" X.509 engine. Parameters are:
400 * -- context to initialize
401 * -- hash function to use for hashing normalized DN
402 * -- list of trust anchors
404 * After initialization, some hash function implementations for signature
405 * verification MUST be added.
407 void br_x509_minimal_init(br_x509_minimal_context
*ctx
,
408 const br_hash_class
*dn_hash_impl
,
409 const br_x509_trust_anchor
*trust_anchors
, size_t trust_anchors_num
);
412 * Set a hash function implementation, identified by ID, for purposes of
413 * verifying signatures on certificates. This must be called after
414 * br_x509_minimal_init().
417 br_x509_minimal_set_hash(br_x509_minimal_context
*ctx
,
418 int id
, const br_hash_class
*impl
)
420 br_multihash_setimpl(&ctx
->mhash
, id
, impl
);
424 * Set a RSA implementation, for purposes of verifying signatures on
425 * certificates. This must be called after br_x509_minimal_init().
428 br_x509_minimal_set_rsa(br_x509_minimal_context
*ctx
,
429 br_rsa_pkcs1_vrfy irsa
)
435 * Set an ECDSA implementation, for purposes of verifying signatures on
436 * certificates. This must be called after br_x509_minimal_init().
439 br_x509_minimal_set_ecdsa(br_x509_minimal_context
*ctx
,
440 const br_ec_impl
*iec
, br_ecdsa_vrfy iecdsa
)
442 ctx
->iecdsa
= iecdsa
;
447 * Set the validation time, normally to the current date and time.
448 * This consists in two 32-bit counts:
450 * -- Days are counted in a proleptic Gregorian calendar since
451 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
452 * it is also traditionally known as "1 BC".
454 * -- Seconds are counted since midnight, from 0 to 86400 (a count of
455 * 86400 is possible only if a leap second happened).
457 * If the validation date and time are not explicitly set, but BearSSL
458 * was compiled with support for the system clock on the underlying
459 * platform, then the current time will automatically be used. Otherwise,
460 * validation will fail (except in case of direct trust of the EE key).
463 br_x509_minimal_set_time(br_x509_minimal_context
*ctx
,
464 uint32_t days
, uint32_t seconds
)
467 ctx
->seconds
= seconds
;
471 * Set the minimal acceptable length for RSA keys, in bytes. Default
472 * is 128 bytes, which means RSA keys of 1017 bits or more. This setting
473 * applies to keys extracted from certificates (EE and intermediate CA).
474 * It does _not_ apply to "CA" trust anchors.
477 br_x509_minimal_set_minrsa(br_x509_minimal_context
*ctx
, int byte_length
)
479 ctx
->min_rsa_size
= (int16_t)(byte_length
- 128);
483 * An X.509 decoder context. This is not for X.509 validation, but for
484 * using certificates as trust anchors (e.g. self-signed certificates
489 /* Structure for returning the public key. */
492 /* CPU for the T0 virtual machine. */
496 const unsigned char *ip
;
498 uint32_t dp_stack
[32];
499 uint32_t rp_stack
[32];
502 /* The pad serves as destination for various operations. */
503 unsigned char pad
[256];
505 /* Flag set when decoding succeeds. */
506 unsigned char decoded
;
508 /* Validity dates. */
509 uint32_t notbefore_days
, notbefore_seconds
;
510 uint32_t notafter_days
, notafter_seconds
;
512 /* The "CA" flag. This is set to true if the certificate contains
513 a Basic Constraints extension that asserts CA status. */
516 /* DN processing: the subject DN is extracted and pushed to the
517 provided callback. */
518 unsigned char copy_dn
;
520 void (*append_dn
)(void *ctx
, const void *buf
, size_t len
);
522 /* Certificate data chunk. */
523 const unsigned char *hbuf
;
526 /* Buffer for decoded public key. */
527 unsigned char pkey_data
[BR_X509_BUFSIZE_KEY
];
529 /* Type of key and hash function used in the certificate signature. */
530 unsigned char signer_key_type
;
531 unsigned char signer_hash_id
;
533 } br_x509_decoder_context
;
536 * Initialise an X.509 decoder context for processing a new certificate.
538 void br_x509_decoder_init(br_x509_decoder_context
*ctx
,
539 void (*append_dn
)(void *ctx
, const void *buf
, size_t len
),
540 void *append_dn_ctx
);
543 * Push some certificate bytes into a decoder context.
545 void br_x509_decoder_push(br_x509_decoder_context
*ctx
,
546 const void *data
, size_t len
);
549 * Obtain the decoded public key. Returned value is a pointer to a
550 * structure internal to the decoder context; releasing or reusing the
551 * decoder context invalidates that structure.
553 * If decoding was not finished, or failed, then NULL is returned.
555 static inline br_x509_pkey
*
556 br_x509_decoder_get_pkey(br_x509_decoder_context
*ctx
)
558 if (ctx
->decoded
&& ctx
->err
== 0) {
566 * Get decoder error. If no error was reported yet but the certificate
567 * decoding is not finished, then the error code is BR_ERR_X509_TRUNCATED.
568 * If decoding was successful, then 0 is returned.
571 br_x509_decoder_last_error(br_x509_decoder_context
*ctx
)
577 return BR_ERR_X509_TRUNCATED
;
583 * Get the "isCA" flag from an X.509 decoder context. This flag is set
584 * if the decoded certificate claims to be a CA through a Basic
585 * Constraints extension.
588 br_x509_decoder_isCA(br_x509_decoder_context
*ctx
)
594 * Get the issuing CA key type (type of key used to sign the decoded
595 * certificate). This is BR_KEYTYPE_RSA or BR_KEYTYPE_EC. The value 0
596 * is returned if the signature type was not recognised.
599 br_x509_decoder_get_signer_key_type(br_x509_decoder_context
*ctx
)
601 return ctx
->signer_key_type
;
605 * Get the identifier for the hash function used to sign the decoded
606 * certificate. This is 0 if the hash function was not recognised.
609 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context
*ctx
)
611 return ctx
->signer_hash_id
;
615 * Type for an X.509 certificate (DER-encoded).
620 } br_x509_certificate
;
623 * Private key decoder context.
627 /* Structure for returning the private key. */
629 br_rsa_private_key rsa
;
630 br_ec_private_key ec
;
633 /* CPU for the T0 virtual machine. */
637 const unsigned char *ip
;
639 uint32_t dp_stack
[32];
640 uint32_t rp_stack
[32];
643 /* Private key data chunk. */
644 const unsigned char *hbuf
;
647 /* The pad serves as destination for various operations. */
648 unsigned char pad
[256];
650 /* Decoded key type; 0 until decoding is complete. */
651 unsigned char key_type
;
653 /* Buffer for the private key elements. It shall be large enough
654 to accommodate all elements for a RSA-4096 private key (roughly
655 five 2048-bit integers, possibly a bit more). */
656 unsigned char key_data
[3 * BR_X509_BUFSIZE_SIG
];
658 } br_skey_decoder_context
;
661 * Initialise a private key decoder context.
663 void br_skey_decoder_init(br_skey_decoder_context
*ctx
);
666 * Push some data bytes into a private key decoder context.
668 void br_skey_decoder_push(br_skey_decoder_context
*ctx
,
669 const void *data
, size_t len
);
672 * Get the decoding status for a private key. This is either 0 on success,
673 * or a non-zero error code.
676 br_skey_decoder_last_error(const br_skey_decoder_context
*ctx
)
681 if (ctx
->key_type
== 0) {
682 return BR_ERR_X509_TRUNCATED
;
688 * Get the decoded private key type. This is 0 if decoding is not finished
692 br_skey_decoder_key_type(const br_skey_decoder_context
*ctx
)
695 return ctx
->key_type
;
702 * Get the decoded RSA private key. This function returns NULL if the
703 * decoding failed, or is not finished, or the key is not RSA. The returned
704 * pointer references structures within the context that can become
705 * invalid if the context is reused or released.
707 static inline const br_rsa_private_key
*
708 br_skey_decoder_get_rsa(const br_skey_decoder_context
*ctx
)
710 if (ctx
->err
== 0 && ctx
->key_type
== BR_KEYTYPE_RSA
) {
711 return &ctx
->key
.rsa
;
718 * Get the decoded EC private key. This function returns NULL if the
719 * decoding failed, or is not finished, or the key is not EC. The returned
720 * pointer references structures within the context that can become
721 * invalid if the context is reused or released.
723 static inline const br_ec_private_key
*
724 br_skey_decoder_get_ec(const br_skey_decoder_context
*ctx
)
726 if (ctx
->err
== 0 && ctx
->key_type
== BR_KEYTYPE_EC
) {