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