Optimised code for encoding/decoding integers when the underlying architecture has...
[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 Initialise a "minimal" X.509 engine with default algorithms.
827 *
828 * This function performs the same job as `br_x509_minimal_init()`, but
829 * also sets implementations for RSA, ECDSA, and the standard hash
830 * functions.
831 *
832 * \param ctx context to initialise.
833 * \param trust_anchors trust anchors.
834 * \param trust_anchors_num number of trust anchors.
835 */
836 void br_x509_minimal_init_full(br_x509_minimal_context *ctx,
837 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
838
839 /**
840 * \brief Set the validation time for the X.509 "minimal" engine.
841 *
842 * The validation time is set as two 32-bit integers, for days and
843 * seconds since a fixed epoch:
844 *
845 * - Days are counted in a proleptic Gregorian calendar since
846 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
847 * it is also traditionally known as "1 BC".
848 *
849 * - Seconds are counted since midnight, from 0 to 86400 (a count of
850 * 86400 is possible only if a leap second happened).
851 *
852 * The validation date and time is understood in the UTC time zone.
853 *
854 * If the validation date and time are not explicitly set, but BearSSL
855 * was compiled with support for the system clock on the underlying
856 * platform, then the current time will automatically be used. Otherwise,
857 * not setting the validation date and time implies a validation
858 * failure (except in case of direct trust of the EE key).
859 *
860 * \param ctx validation context.
861 * \param days days since January 1st, 0 AD (Gregorian calendar).
862 * \param seconds seconds since midnight (0 to 86400).
863 */
864 static inline void
865 br_x509_minimal_set_time(br_x509_minimal_context *ctx,
866 uint32_t days, uint32_t seconds)
867 {
868 ctx->days = days;
869 ctx->seconds = seconds;
870 }
871
872 /**
873 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
874 * engine).
875 *
876 * The RSA key length is expressed in bytes. The default minimum key
877 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
878 * than the configured length will be rejected, implying validation
879 * failure. This setting applies to keys extracted from certificates
880 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
881 *
882 * \param ctx validation context.
883 * \param byte_length minimum RSA key length, **in bytes** (not bits).
884 */
885 static inline void
886 br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
887 {
888 ctx->min_rsa_size = (int16_t)(byte_length - 128);
889 }
890
891 /**
892 * \brief Set the name elements to gather.
893 *
894 * The provided array is linked in the context. The elements are
895 * gathered from the EE certificate. If the same element type is
896 * requested several times, then the relevant structures will be filled
897 * in the order the matching values are encountered in the certificate.
898 *
899 * \param ctx validation context.
900 * \param elts array of name element structures to fill.
901 * \param num_elts number of name element structures to fill.
902 */
903 static inline void
904 br_x509_minimal_set_name_elements(br_x509_minimal_context *ctx,
905 br_name_element *elts, size_t num_elts)
906 {
907 ctx->name_elts = elts;
908 ctx->num_name_elts = num_elts;
909 }
910
911 /**
912 * \brief X.509 decoder context.
913 *
914 * This structure is _not_ for X.509 validation, but for extracting
915 * names and public keys from encoded certificates. Intended usage is
916 * to use (self-signed) certificates as trust anchors.
917 *
918 * Contents are opaque and shall not be accessed directly.
919 */
920 typedef struct {
921
922 #ifndef BR_DOXYGEN_IGNORE
923 /* Structure for returning the public key. */
924 br_x509_pkey pkey;
925
926 /* CPU for the T0 virtual machine. */
927 struct {
928 uint32_t *dp;
929 uint32_t *rp;
930 const unsigned char *ip;
931 } cpu;
932 uint32_t dp_stack[32];
933 uint32_t rp_stack[32];
934 int err;
935
936 /* The pad serves as destination for various operations. */
937 unsigned char pad[256];
938
939 /* Flag set when decoding succeeds. */
940 unsigned char decoded;
941
942 /* Validity dates. */
943 uint32_t notbefore_days, notbefore_seconds;
944 uint32_t notafter_days, notafter_seconds;
945
946 /* The "CA" flag. This is set to true if the certificate contains
947 a Basic Constraints extension that asserts CA status. */
948 unsigned char isCA;
949
950 /* DN processing: the subject DN is extracted and pushed to the
951 provided callback. */
952 unsigned char copy_dn;
953 void *append_dn_ctx;
954 void (*append_dn)(void *ctx, const void *buf, size_t len);
955
956 /* Certificate data chunk. */
957 const unsigned char *hbuf;
958 size_t hlen;
959
960 /* Buffer for decoded public key. */
961 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
962
963 /* Type of key and hash function used in the certificate signature. */
964 unsigned char signer_key_type;
965 unsigned char signer_hash_id;
966 #endif
967
968 } br_x509_decoder_context;
969
970 /**
971 * \brief Initialise an X.509 decoder context for processing a new
972 * certificate.
973 *
974 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
975 * will be invoked to receive, chunk by chunk, the certificate's
976 * subject DN. If `append_dn` is `0` then the subject DN will be
977 * ignored.
978 *
979 * \param ctx X.509 decoder context to initialise.
980 * \param append_dn DN receiver callback (or `0`).
981 * \param append_dn_ctx context for the DN receiver callback.
982 */
983 void br_x509_decoder_init(br_x509_decoder_context *ctx,
984 void (*append_dn)(void *ctx, const void *buf, size_t len),
985 void *append_dn_ctx);
986
987 /**
988 * \brief Push some certificate bytes into a decoder context.
989 *
990 * If `len` is non-zero, then that many bytes are pushed, from address
991 * `data`, into the provided decoder context.
992 *
993 * \param ctx X.509 decoder context.
994 * \param data certificate data chunk.
995 * \param len certificate data chunk length (in bytes).
996 */
997 void br_x509_decoder_push(br_x509_decoder_context *ctx,
998 const void *data, size_t len);
999
1000 /**
1001 * \brief Obtain the decoded public key.
1002 *
1003 * Returned value is a pointer to a structure internal to the decoder
1004 * context; releasing or reusing the decoder context invalidates that
1005 * structure.
1006 *
1007 * If decoding was not finished, or failed, then `NULL` is returned.
1008 *
1009 * \param ctx X.509 decoder context.
1010 * \return the public key, or `NULL` on unfinished/error.
1011 */
1012 static inline br_x509_pkey *
1013 br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
1014 {
1015 if (ctx->decoded && ctx->err == 0) {
1016 return &ctx->pkey;
1017 } else {
1018 return NULL;
1019 }
1020 }
1021
1022 /**
1023 * \brief Get decoder error status.
1024 *
1025 * If no error was reported yet but the certificate decoding is not
1026 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
1027 * was successful, then 0 is returned.
1028 *
1029 * \param ctx X.509 decoder context.
1030 * \return 0 on successful decoding, or a non-zero error code.
1031 */
1032 static inline int
1033 br_x509_decoder_last_error(br_x509_decoder_context *ctx)
1034 {
1035 if (ctx->err != 0) {
1036 return ctx->err;
1037 }
1038 if (!ctx->decoded) {
1039 return BR_ERR_X509_TRUNCATED;
1040 }
1041 return 0;
1042 }
1043
1044 /**
1045 * \brief Get the "isCA" flag from an X.509 decoder context.
1046 *
1047 * This flag is set if the decoded certificate claims to be a CA through
1048 * a Basic Constraints extension. This flag should not be read before
1049 * decoding completed successfully.
1050 *
1051 * \param ctx X.509 decoder context.
1052 * \return the "isCA" flag.
1053 */
1054 static inline int
1055 br_x509_decoder_isCA(br_x509_decoder_context *ctx)
1056 {
1057 return ctx->isCA;
1058 }
1059
1060 /**
1061 * \brief Get the issuing CA key type (type of algorithm used to sign the
1062 * decoded certificate).
1063 *
1064 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
1065 * if the signature type was not recognised.
1066 *
1067 * \param ctx X.509 decoder context.
1068 * \return the issuing CA key type.
1069 */
1070 static inline int
1071 br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
1072 {
1073 return ctx->signer_key_type;
1074 }
1075
1076 /**
1077 * \brief Get the identifier for the hash function used to sign the decoded
1078 * certificate.
1079 *
1080 * This is 0 if the hash function was not recognised.
1081 *
1082 * \param ctx X.509 decoder context.
1083 * \return the signature hash function identifier.
1084 */
1085 static inline int
1086 br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
1087 {
1088 return ctx->signer_hash_id;
1089 }
1090
1091 /**
1092 * \brief Type for an X.509 certificate (DER-encoded).
1093 */
1094 typedef struct {
1095 /** \brief The DER-encoded certificate data. */
1096 unsigned char *data;
1097 /** \brief The DER-encoded certificate length (in bytes). */
1098 size_t data_len;
1099 } br_x509_certificate;
1100
1101 /**
1102 * \brief Private key decoder context.
1103 *
1104 * The private key decoder recognises RSA and EC private keys, either in
1105 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
1106 * archive (again DER-encoded).
1107 *
1108 * Structure contents are opaque and shall not be accessed directly.
1109 */
1110 typedef struct {
1111 #ifndef BR_DOXYGEN_IGNORE
1112 /* Structure for returning the private key. */
1113 union {
1114 br_rsa_private_key rsa;
1115 br_ec_private_key ec;
1116 } key;
1117
1118 /* CPU for the T0 virtual machine. */
1119 struct {
1120 uint32_t *dp;
1121 uint32_t *rp;
1122 const unsigned char *ip;
1123 } cpu;
1124 uint32_t dp_stack[32];
1125 uint32_t rp_stack[32];
1126 int err;
1127
1128 /* Private key data chunk. */
1129 const unsigned char *hbuf;
1130 size_t hlen;
1131
1132 /* The pad serves as destination for various operations. */
1133 unsigned char pad[256];
1134
1135 /* Decoded key type; 0 until decoding is complete. */
1136 unsigned char key_type;
1137
1138 /* Buffer for the private key elements. It shall be large enough
1139 to accommodate all elements for a RSA-4096 private key (roughly
1140 five 2048-bit integers, possibly a bit more). */
1141 unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];
1142 #endif
1143 } br_skey_decoder_context;
1144
1145 /**
1146 * \brief Initialise a private key decoder context.
1147 *
1148 * \param ctx key decoder context to initialise.
1149 */
1150 void br_skey_decoder_init(br_skey_decoder_context *ctx);
1151
1152 /**
1153 * \brief Push some data bytes into a private key decoder context.
1154 *
1155 * If `len` is non-zero, then that many data bytes, starting at address
1156 * `data`, are pushed into the decoder.
1157 *
1158 * \param ctx key decoder context.
1159 * \param data private key data chunk.
1160 * \param len private key data chunk length (in bytes).
1161 */
1162 void br_skey_decoder_push(br_skey_decoder_context *ctx,
1163 const void *data, size_t len);
1164
1165 /**
1166 * \brief Get the decoding status for a private key.
1167 *
1168 * Decoding status is 0 on success, or a non-zero error code. If the
1169 * decoding is unfinished when this function is called, then the
1170 * status code `BR_ERR_X509_TRUNCATED` is returned.
1171 *
1172 * \param ctx key decoder context.
1173 * \return 0 on successful decoding, or a non-zero error code.
1174 */
1175 static inline int
1176 br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
1177 {
1178 if (ctx->err != 0) {
1179 return ctx->err;
1180 }
1181 if (ctx->key_type == 0) {
1182 return BR_ERR_X509_TRUNCATED;
1183 }
1184 return 0;
1185 }
1186
1187 /**
1188 * \brief Get the decoded private key type.
1189 *
1190 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1191 * not finished or failed, then 0 is returned.
1192 *
1193 * \param ctx key decoder context.
1194 * \return decoded private key type, or 0.
1195 */
1196 static inline int
1197 br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
1198 {
1199 if (ctx->err == 0) {
1200 return ctx->key_type;
1201 } else {
1202 return 0;
1203 }
1204 }
1205
1206 /**
1207 * \brief Get the decoded RSA private key.
1208 *
1209 * This function returns `NULL` if the decoding failed, or is not
1210 * finished, or the key is not RSA. The returned pointer references
1211 * structures within the context that can become invalid if the context
1212 * is reused or released.
1213 *
1214 * \param ctx key decoder context.
1215 * \return decoded RSA private key, or `NULL`.
1216 */
1217 static inline const br_rsa_private_key *
1218 br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
1219 {
1220 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {
1221 return &ctx->key.rsa;
1222 } else {
1223 return NULL;
1224 }
1225 }
1226
1227 /**
1228 * \brief Get the decoded EC private key.
1229 *
1230 * This function returns `NULL` if the decoding failed, or is not
1231 * finished, or the key is not EC. The returned pointer references
1232 * structures within the context that can become invalid if the context
1233 * is reused or released.
1234 *
1235 * \param ctx key decoder context.
1236 * \return decoded EC private key, or `NULL`.
1237 */
1238 static inline const br_ec_private_key *
1239 br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
1240 {
1241 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {
1242 return &ctx->key.ec;
1243 } else {
1244 return NULL;
1245 }
1246 }
1247
1248 #endif