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