BearSSL: bearssl_x509.h Source File

BearSSL

Loading...
Searching...
No Matches
bearssl_x509.h
Go to the documentation of this file.
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
36extern "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 */
368typedef 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 */
491extern 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 The "minimal" X.509 engine structure.
630 *
631 * The structure contents are opaque (they shall not be accessed directly),
632 * except for the first field (the vtable).
633 *
634 * The "minimal" engine performs a rudimentary but serviceable X.509 path
635 * validation.
636 */
637 typedef struct {
638 const br_x509_class *vtable;
639
640#ifndef BR_DOXYGEN_IGNORE
641 /* Structure for returning the EE public key. */
642 br_x509_pkey pkey;
643
644 /* CPU for the T0 virtual machine. */
645 struct {
646 uint32_t *dp;
647 uint32_t *rp;
648 const unsigned char *ip;
649 } cpu;
650 uint32_t dp_stack[32];
651 uint32_t rp_stack[32];
652 int err;
653
654 /* Server name to match with the SAN / CN of the EE certificate. */
655 const char *server_name;
656
657 /* Validated key usages. */
658 unsigned char key_usages;
659
660 /* Explicitly set date and time. */
661 uint32_t days, seconds;
662
663 /* Current certificate length (in bytes). Set to 0 when the
664 certificate has been fully processed. */
665 uint32_t cert_length;
666
667 /* Number of certificates processed so far in the current chain.
668 It is incremented at the end of the processing of a certificate,
669 so it is 0 for the EE. */
670 uint32_t num_certs;
671
672 /* Certificate data chunk. */
673 const unsigned char *hbuf;
674 size_t hlen;
675
676 /* The pad serves as destination for various operations. */
677 unsigned char pad[256];
678
679 /* Buffer for EE public key data. */
680 unsigned char ee_pkey_data[BR_X509_BUFSIZE_KEY];
681
682 /* Buffer for currently decoded public key. */
683 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
684
685 /* Signature type: signer key type, offset to the hash
686 function OID (in the T0 data block) and hash function
687 output length (TBS hash length). */
688 unsigned char cert_signer_key_type;
689 uint16_t cert_sig_hash_oid;
690 unsigned char cert_sig_hash_len;
691
692 /* Current/last certificate signature. */
693 unsigned char cert_sig[BR_X509_BUFSIZE_SIG];
694 uint16_t cert_sig_len;
695
696 /* Minimum RSA key length (difference in bytes from 128). */
697 int16_t min_rsa_size;
698
699 /* Configured trust anchors. */
700 const br_x509_trust_anchor *trust_anchors;
701 size_t trust_anchors_num;
702
703 /*
704 * Multi-hasher for the TBS.
705 */
706 unsigned char do_mhash;
707 br_multihash_context mhash;
708 unsigned char tbs_hash[64];
709
710 /*
711 * Simple hasher for the subject/issuer DN.
712 */
713 unsigned char do_dn_hash;
714 const br_hash_class *dn_hash_impl;
715 br_hash_compat_context dn_hash;
716 unsigned char current_dn_hash[64];
717 unsigned char next_dn_hash[64];
718 unsigned char saved_dn_hash[64];
719
720 /*
721 * Name elements to gather.
722 */
723 br_name_element *name_elts;
724 size_t num_name_elts;
725
726 /*
727 * Public key cryptography implementations (signature verification).
728 */
729 br_rsa_pkcs1_vrfy irsa;
730 br_ecdsa_vrfy iecdsa;
731 const br_ec_impl *iec;
732#endif
733
734} br_x509_minimal_context;
735
736/**
737 * \brief Class instance for the "minimal" X.509 engine.
738 */
739extern const br_x509_class br_x509_minimal_vtable;
740
741/**
742 * \brief Initialise a "minimal" X.509 engine.
743 *
744 * The `dn_hash_impl` parameter shall be a hash function internally used
745 * to match X.500 names (subject/issuer DN, and anchor names). Any standard
746 * hash function may be used, but a collision-resistant hash function is
747 * advised.
748 *
749 * After initialization, some implementations for signature verification
750 * (hash functions and signature algorithms) MUST be added.
751 *
752 * \param ctx context to initialise.
753 * \param dn_hash_impl hash function for DN comparisons.
754 * \param trust_anchors trust anchors.
755 * \param trust_anchors_num number of trust anchors.
756 */
757 void br_x509_minimal_init(br_x509_minimal_context *ctx,
758 const br_hash_class *dn_hash_impl,
759 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
760
761/**
762 * \brief Set a supported hash function in an X.509 "minimal" engine.
763 *
764 * Hash functions are used with signature verification algorithms.
765 * Once initialised (with `br_x509_minimal_init()`), the context must
766 * be configured with the hash functions it shall support for that
767 * purpose. The hash function identifier MUST be one of the standard
768 * hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,
769 * SHA-384 and SHA-512).
770 *
771 * If `impl` is `NULL`, this _removes_ support for the designated
772 * hash function.
773 *
774 * \param ctx validation context.
775 * \param id hash function identifier (from 1 to 6).
776 * \param impl hash function implementation (or `NULL`).
777 */
778static inline void
779br_x509_minimal_set_hash(br_x509_minimal_context *ctx,
780 int id, const br_hash_class *impl)
781{
782 br_multihash_setimpl(&ctx->mhash, id, impl);
783}
784
785/**
786 * \brief Set a RSA signature verification implementation in the X.509
787 * "minimal" engine.
788 *
789 * Once initialised (with `br_x509_minimal_init()`), the context must
790 * be configured with the signature verification implementations that
791 * it is supposed to support. If `irsa` is `0`, then the RSA support
792 * is disabled.
793 *
794 * \param ctx validation context.
795 * \param irsa RSA signature verification implementation (or `0`).
796 */
797static inline void
798br_x509_minimal_set_rsa(br_x509_minimal_context *ctx,
799 br_rsa_pkcs1_vrfy irsa)
800{
801 ctx->irsa = irsa;
802}
803
804/**
805 * \brief Set a ECDSA signature verification implementation in the X.509
806 * "minimal" engine.
807 *
808 * Once initialised (with `br_x509_minimal_init()`), the context must
809 * be configured with the signature verification implementations that
810 * it is supposed to support.
811 *
812 * If `iecdsa` is `0`, then this call disables ECDSA support; in that
813 * case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function
814 * that verifies ECDSA signatures with format "asn1", and it will use
815 * `iec` as underlying elliptic curve support.
816 *
817 * \param ctx validation context.
818 * \param iec elliptic curve implementation (or `NULL`).
819 * \param iecdsa ECDSA implementation (or `0`).
820 */
821static inline void
822br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx,
823 const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)
824{
825 ctx->iecdsa = iecdsa;
826 ctx->iec = iec;
827}
828
829/**
830 * \brief Initialise a "minimal" X.509 engine with default algorithms.
831 *
832 * This function performs the same job as `br_x509_minimal_init()`, but
833 * also sets implementations for RSA, ECDSA, and the standard hash
834 * functions.
835 *
836 * \param ctx context to initialise.
837 * \param trust_anchors trust anchors.
838 * \param trust_anchors_num number of trust anchors.
839 */
840 void br_x509_minimal_init_full(br_x509_minimal_context *ctx,
841 const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);
842
843/**
844 * \brief Set the validation time for the X.509 "minimal" engine.
845 *
846 * The validation time is set as two 32-bit integers, for days and
847 * seconds since a fixed epoch:
848 *
849 * - Days are counted in a proleptic Gregorian calendar since
850 * January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";
851 * it is also traditionally known as "1 BC".
852 *
853 * - Seconds are counted since midnight, from 0 to 86400 (a count of
854 * 86400 is possible only if a leap second happened).
855 *
856 * The validation date and time is understood in the UTC time zone.
857 *
858 * If the validation date and time are not explicitly set, but BearSSL
859 * was compiled with support for the system clock on the underlying
860 * platform, then the current time will automatically be used. Otherwise,
861 * not setting the validation date and time implies a validation
862 * failure (except in case of direct trust of the EE key).
863 *
864 * \param ctx validation context.
865 * \param days days since January 1st, 0 AD (Gregorian calendar).
866 * \param seconds seconds since midnight (0 to 86400).
867 */
868static inline void
869br_x509_minimal_set_time(br_x509_minimal_context *ctx,
870 uint32_t days, uint32_t seconds)
871{
872 ctx->days = days;
873 ctx->seconds = seconds;
874}
875
876/**
877 * \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"
878 * engine).
879 *
880 * The RSA key length is expressed in bytes. The default minimum key
881 * length is 128 bytes, corresponding to 1017 bits. RSA keys shorter
882 * than the configured length will be rejected, implying validation
883 * failure. This setting applies to keys extracted from certificates
884 * (both end-entity, and intermediate CA) but not to "CA" trust anchors.
885 *
886 * \param ctx validation context.
887 * \param byte_length minimum RSA key length, **in bytes** (not bits).
888 */
889static inline void
890br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
891{
892 ctx->min_rsa_size = (int16_t)(byte_length - 128);
893}
894
895/**
896 * \brief Set the name elements to gather.
897 *
898 * The provided array is linked in the context. The elements are
899 * gathered from the EE certificate. If the same element type is
900 * requested several times, then the relevant structures will be filled
901 * in the order the matching values are encountered in the certificate.
902 *
903 * \param ctx validation context.
904 * \param elts array of name element structures to fill.
905 * \param num_elts number of name element structures to fill.
906 */
907static inline void
908br_x509_minimal_set_name_elements(br_x509_minimal_context *ctx,
909 br_name_element *elts, size_t num_elts)
910{
911 ctx->name_elts = elts;
912 ctx->num_name_elts = num_elts;
913}
914
915/**
916 * \brief X.509 decoder context.
917 *
918 * This structure is _not_ for X.509 validation, but for extracting
919 * names and public keys from encoded certificates. Intended usage is
920 * to use (self-signed) certificates as trust anchors.
921 *
922 * Contents are opaque and shall not be accessed directly.
923 */
924 typedef struct {
925
926#ifndef BR_DOXYGEN_IGNORE
927 /* Structure for returning the public key. */
928 br_x509_pkey pkey;
929
930 /* CPU for the T0 virtual machine. */
931 struct {
932 uint32_t *dp;
933 uint32_t *rp;
934 const unsigned char *ip;
935 } cpu;
936 uint32_t dp_stack[32];
937 uint32_t rp_stack[32];
938 int err;
939
940 /* The pad serves as destination for various operations. */
941 unsigned char pad[256];
942
943 /* Flag set when decoding succeeds. */
944 unsigned char decoded;
945
946 /* Validity dates. */
947 uint32_t notbefore_days, notbefore_seconds;
948 uint32_t notafter_days, notafter_seconds;
949
950 /* The "CA" flag. This is set to true if the certificate contains
951 a Basic Constraints extension that asserts CA status. */
952 unsigned char isCA;
953
954 /* DN processing: the subject DN is extracted and pushed to the
955 provided callback. */
956 unsigned char copy_dn;
957 void *append_dn_ctx;
958 void (*append_dn)(void *ctx, const void *buf, size_t len);
959
960 /* Certificate data chunk. */
961 const unsigned char *hbuf;
962 size_t hlen;
963
964 /* Buffer for decoded public key. */
965 unsigned char pkey_data[BR_X509_BUFSIZE_KEY];
966
967 /* Type of key and hash function used in the certificate signature. */
968 unsigned char signer_key_type;
969 unsigned char signer_hash_id;
970#endif
971
972} br_x509_decoder_context;
973
974/**
975 * \brief Initialise an X.509 decoder context for processing a new
976 * certificate.
977 *
978 * The `append_dn()` callback (with opaque context `append_dn_ctx`)
979 * will be invoked to receive, chunk by chunk, the certificate's
980 * subject DN. If `append_dn` is `0` then the subject DN will be
981 * ignored.
982 *
983 * \param ctx X.509 decoder context to initialise.
984 * \param append_dn DN receiver callback (or `0`).
985 * \param append_dn_ctx context for the DN receiver callback.
986 */
987 void br_x509_decoder_init(br_x509_decoder_context *ctx,
988 void (*append_dn)(void *ctx, const void *buf, size_t len),
989 void *append_dn_ctx);
990
991/**
992 * \brief Push some certificate bytes into a decoder context.
993 *
994 * If `len` is non-zero, then that many bytes are pushed, from address
995 * `data`, into the provided decoder context.
996 *
997 * \param ctx X.509 decoder context.
998 * \param data certificate data chunk.
999 * \param len certificate data chunk length (in bytes).
1000 */
1001 void br_x509_decoder_push(br_x509_decoder_context *ctx,
1002 const void *data, size_t len);
1003
1004/**
1005 * \brief Obtain the decoded public key.
1006 *
1007 * Returned value is a pointer to a structure internal to the decoder
1008 * context; releasing or reusing the decoder context invalidates that
1009 * structure.
1010 *
1011 * If decoding was not finished, or failed, then `NULL` is returned.
1012 *
1013 * \param ctx X.509 decoder context.
1014 * \return the public key, or `NULL` on unfinished/error.
1015 */
1016static inline br_x509_pkey *
1017br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
1018{
1019 if (ctx->decoded && ctx->err == 0) {
1020 return &ctx->pkey;
1021 } else {
1022 return NULL;
1023 }
1024}
1025
1026/**
1027 * \brief Get decoder error status.
1028 *
1029 * If no error was reported yet but the certificate decoding is not
1030 * finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding
1031 * was successful, then 0 is returned.
1032 *
1033 * \param ctx X.509 decoder context.
1034 * \return 0 on successful decoding, or a non-zero error code.
1035 */
1036static inline int
1037br_x509_decoder_last_error(br_x509_decoder_context *ctx)
1038{
1039 if (ctx->err != 0) {
1040 return ctx->err;
1041 }
1042 if (!ctx->decoded) {
1043 return BR_ERR_X509_TRUNCATED;
1044 }
1045 return 0;
1046}
1047
1048/**
1049 * \brief Get the "isCA" flag from an X.509 decoder context.
1050 *
1051 * This flag is set if the decoded certificate claims to be a CA through
1052 * a Basic Constraints extension. This flag should not be read before
1053 * decoding completed successfully.
1054 *
1055 * \param ctx X.509 decoder context.
1056 * \return the "isCA" flag.
1057 */
1058static inline int
1059br_x509_decoder_isCA(br_x509_decoder_context *ctx)
1060{
1061 return ctx->isCA;
1062}
1063
1064/**
1065 * \brief Get the issuing CA key type (type of algorithm used to sign the
1066 * decoded certificate).
1067 *
1068 * This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned
1069 * if the signature type was not recognised.
1070 *
1071 * \param ctx X.509 decoder context.
1072 * \return the issuing CA key type.
1073 */
1074static inline int
1075br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
1076{
1077 return ctx->signer_key_type;
1078}
1079
1080/**
1081 * \brief Get the identifier for the hash function used to sign the decoded
1082 * certificate.
1083 *
1084 * This is 0 if the hash function was not recognised.
1085 *
1086 * \param ctx X.509 decoder context.
1087 * \return the signature hash function identifier.
1088 */
1089static inline int
1090br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
1091{
1092 return ctx->signer_hash_id;
1093}
1094
1095/**
1096 * \brief Type for an X.509 certificate (DER-encoded).
1097 */
1098 typedef struct {
1099 /** \brief The DER-encoded certificate data. */
1100 unsigned char *data;
1101 /** \brief The DER-encoded certificate length (in bytes). */
1102 size_t data_len;
1103} br_x509_certificate;
1104
1105/**
1106 * \brief Private key decoder context.
1107 *
1108 * The private key decoder recognises RSA and EC private keys, either in
1109 * their raw, DER-encoded format, or wrapped in an unencrypted PKCS#8
1110 * archive (again DER-encoded).
1111 *
1112 * Structure contents are opaque and shall not be accessed directly.
1113 */
1114 typedef struct {
1115#ifndef BR_DOXYGEN_IGNORE
1116 /* Structure for returning the private key. */
1117 union {
1118 br_rsa_private_key rsa;
1119 br_ec_private_key ec;
1120 } key;
1121
1122 /* CPU for the T0 virtual machine. */
1123 struct {
1124 uint32_t *dp;
1125 uint32_t *rp;
1126 const unsigned char *ip;
1127 } cpu;
1128 uint32_t dp_stack[32];
1129 uint32_t rp_stack[32];
1130 int err;
1131
1132 /* Private key data chunk. */
1133 const unsigned char *hbuf;
1134 size_t hlen;
1135
1136 /* The pad serves as destination for various operations. */
1137 unsigned char pad[256];
1138
1139 /* Decoded key type; 0 until decoding is complete. */
1140 unsigned char key_type;
1141
1142 /* Buffer for the private key elements. It shall be large enough
1143 to accommodate all elements for a RSA-4096 private key (roughly
1144 five 2048-bit integers, possibly a bit more). */
1145 unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];
1146#endif
1147} br_skey_decoder_context;
1148
1149/**
1150 * \brief Initialise a private key decoder context.
1151 *
1152 * \param ctx key decoder context to initialise.
1153 */
1154 void br_skey_decoder_init(br_skey_decoder_context *ctx);
1155
1156/**
1157 * \brief Push some data bytes into a private key decoder context.
1158 *
1159 * If `len` is non-zero, then that many data bytes, starting at address
1160 * `data`, are pushed into the decoder.
1161 *
1162 * \param ctx key decoder context.
1163 * \param data private key data chunk.
1164 * \param len private key data chunk length (in bytes).
1165 */
1166 void br_skey_decoder_push(br_skey_decoder_context *ctx,
1167 const void *data, size_t len);
1168
1169/**
1170 * \brief Get the decoding status for a private key.
1171 *
1172 * Decoding status is 0 on success, or a non-zero error code. If the
1173 * decoding is unfinished when this function is called, then the
1174 * status code `BR_ERR_X509_TRUNCATED` is returned.
1175 *
1176 * \param ctx key decoder context.
1177 * \return 0 on successful decoding, or a non-zero error code.
1178 */
1179static inline int
1180br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
1181{
1182 if (ctx->err != 0) {
1183 return ctx->err;
1184 }
1185 if (ctx->key_type == 0) {
1186 return BR_ERR_X509_TRUNCATED;
1187 }
1188 return 0;
1189}
1190
1191/**
1192 * \brief Get the decoded private key type.
1193 *
1194 * Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is
1195 * not finished or failed, then 0 is returned.
1196 *
1197 * \param ctx key decoder context.
1198 * \return decoded private key type, or 0.
1199 */
1200static inline int
1201br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
1202{
1203 if (ctx->err == 0) {
1204 return ctx->key_type;
1205 } else {
1206 return 0;
1207 }
1208}
1209
1210/**
1211 * \brief Get the decoded RSA private key.
1212 *
1213 * This function returns `NULL` if the decoding failed, or is not
1214 * finished, or the key is not RSA. The returned pointer references
1215 * structures within the context that can become invalid if the context
1216 * is reused or released.
1217 *
1218 * \param ctx key decoder context.
1219 * \return decoded RSA private key, or `NULL`.
1220 */
1221static inline const br_rsa_private_key *
1222br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
1223{
1224 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {
1225 return &ctx->key.rsa;
1226 } else {
1227 return NULL;
1228 }
1229}
1230
1231/**
1232 * \brief Get the decoded EC private key.
1233 *
1234 * This function returns `NULL` if the decoding failed, or is not
1235 * finished, or the key is not EC. The returned pointer references
1236 * structures within the context that can become invalid if the context
1237 * is reused or released.
1238 *
1239 * \param ctx key decoder context.
1240 * \return decoded EC private key, or `NULL`.
1241 */
1242static inline const br_ec_private_key *
1243br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
1244{
1245 if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {
1246 return &ctx->key.ec;
1247 } else {
1248 return NULL;
1249 }
1250}
1251
1252/**
1253 * \brief Encode an RSA private key (raw DER format).
1254 *
1255 * This function encodes the provided key into the "raw" format specified
1256 * in PKCS#1 (RFC 8017, Appendix C, type `RSAPrivateKey`), with DER
1257 * encoding rules.
1258 *
1259 * The key elements are:
1260 *
1261 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1262 *
1263 * - `pk`: the public key (`n` and `e`)
1264 *
1265 * - `d` (size: `dlen` bytes): the private exponent
1266 *
1267 * The public key elements, and the private exponent `d`, can be
1268 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1269 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1270 *
1271 * If `dest` is not `NULL`, then the encoded key is written at that
1272 * address, and the encoded length (in bytes) is returned. If `dest` is
1273 * `NULL`, then nothing is written, but the encoded length is still
1274 * computed and returned.
1275 *
1276 * \param dest the destination buffer (or `NULL`).
1277 * \param sk the RSA private key.
1278 * \param pk the RSA public key.
1279 * \param d the RSA private exponent.
1280 * \param dlen the RSA private exponent length (in bytes).
1281 * \return the encoded key length (in bytes).
1282 */
1283 size_t br_encode_rsa_raw_der(void *dest, const br_rsa_private_key *sk,
1284 const br_rsa_public_key *pk, const void *d, size_t dlen);
1285
1286/**
1287 * \brief Encode an RSA private key (PKCS#8 DER format).
1288 *
1289 * This function encodes the provided key into the PKCS#8 format
1290 * (RFC 5958, type `OneAsymmetricKey`). It wraps around the "raw DER"
1291 * format for the RSA key, as implemented by `br_encode_rsa_raw_der()`.
1292 *
1293 * The key elements are:
1294 *
1295 * - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)
1296 *
1297 * - `pk`: the public key (`n` and `e`)
1298 *
1299 * - `d` (size: `dlen` bytes): the private exponent
1300 *
1301 * The public key elements, and the private exponent `d`, can be
1302 * recomputed from the private key (see `br_rsa_compute_modulus()`,
1303 * `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).
1304 *
1305 * If `dest` is not `NULL`, then the encoded key is written at that
1306 * address, and the encoded length (in bytes) is returned. If `dest` is
1307 * `NULL`, then nothing is written, but the encoded length is still
1308 * computed and returned.
1309 *
1310 * \param dest the destination buffer (or `NULL`).
1311 * \param sk the RSA private key.
1312 * \param pk the RSA public key.
1313 * \param d the RSA private exponent.
1314 * \param dlen the RSA private exponent length (in bytes).
1315 * \return the encoded key length (in bytes).
1316 */
1317 size_t br_encode_rsa_pkcs8_der(void *dest, const br_rsa_private_key *sk,
1318 const br_rsa_public_key *pk, const void *d, size_t dlen);
1319
1320/**
1321 * \brief Encode an EC private key (raw DER format).
1322 *
1323 * This function encodes the provided key into the "raw" format specified
1324 * in RFC 5915 (type `ECPrivateKey`), with DER encoding rules.
1325 *
1326 * The private key is provided in `sk`, the public key being `pk`. If
1327 * `pk` is `NULL`, then the encoded key will not include the public key
1328 * in its `publicKey` field (which is nominally optional).
1329 *
1330 * If `dest` is not `NULL`, then the encoded key is written at that
1331 * address, and the encoded length (in bytes) is returned. If `dest` is
1332 * `NULL`, then nothing is written, but the encoded length is still
1333 * computed and returned.
1334 *
1335 * If the key cannot be encoded (e.g. because there is no known OBJECT
1336 * IDENTIFIER for the used curve), then 0 is returned.
1337 *
1338 * \param dest the destination buffer (or `NULL`).
1339 * \param sk the EC private key.
1340 * \param pk the EC public key (or `NULL`).
1341 * \return the encoded key length (in bytes), or 0.
1342 */
1343 size_t br_encode_ec_raw_der(void *dest,
1344 const br_ec_private_key *sk, const br_ec_public_key *pk);
1345
1346/**
1347 * \brief Encode an EC private key (PKCS#8 DER format).
1348 *
1349 * This function encodes the provided key into the PKCS#8 format
1350 * (RFC 5958, type `OneAsymmetricKey`). The curve is identified
1351 * by an OID provided as parameters to the `privateKeyAlgorithm`
1352 * field. The private key value (contents of the `privateKey` field)
1353 * contains the DER encoding of the `ECPrivateKey` type defined in
1354 * RFC 5915, without the `parameters` field (since they would be
1355 * redundant with the information in `privateKeyAlgorithm`).
1356 *
1357 * The private key is provided in `sk`, the public key being `pk`. If
1358 * `pk` is not `NULL`, then the encoded public key is included in the
1359 * `publicKey` field of the private key value (but not in the `publicKey`
1360 * field of the PKCS#8 `OneAsymmetricKey` wrapper).
1361 *
1362 * If `dest` is not `NULL`, then the encoded key is written at that
1363 * address, and the encoded length (in bytes) is returned. If `dest` is
1364 * `NULL`, then nothing is written, but the encoded length is still
1365 * computed and returned.
1366 *
1367 * If the key cannot be encoded (e.g. because there is no known OBJECT
1368 * IDENTIFIER for the used curve), then 0 is returned.
1369 *
1370 * \param dest the destination buffer (or `NULL`).
1371 * \param sk the EC private key.
1372 * \param pk the EC public key (or `NULL`).
1373 * \return the encoded key length (in bytes), or 0.
1374 */
1375 size_t br_encode_ec_pkcs8_der(void *dest,
1376 const br_ec_private_key *sk, const br_ec_public_key *pk);
1377
1378/**
1379 * \brief PEM banner for RSA private key (raw).
1380 */
1381#define BR_ENCODE_PEM_RSA_RAW "RSA PRIVATE KEY"
1382
1383/**
1384 * \brief PEM banner for EC private key (raw).
1385 */
1386#define BR_ENCODE_PEM_EC_RAW "EC PRIVATE KEY"
1387
1388/**
1389 * \brief PEM banner for an RSA or EC private key in PKCS#8 format.
1390 */
1391#define BR_ENCODE_PEM_PKCS8 "PRIVATE KEY"
1392
1393#ifdef __cplusplus
1394}
1395#endif
1396
1397#endif
bearssl_ec.h
br_ecdsa_vrfy
uint32_t(* br_ecdsa_vrfy)(const br_ec_impl *impl, const void *hash, size_t hash_len, const br_ec_public_key *pk, const void *sig, size_t sig_len)
Type for an ECDSA signature verification function.
Definition bearssl_ec.h:626
bearssl_hash.h
br_multihash_setimpl
static void br_multihash_setimpl(br_multihash_context *ctx, int id, const br_hash_class *impl)
Set a hash function implementation.
Definition bearssl_hash.h:1142
bearssl_rsa.h
br_rsa_pkcs1_vrfy
uint32_t(* br_rsa_pkcs1_vrfy)(const unsigned char *x, size_t xlen, const unsigned char *hash_oid, size_t hash_len, const br_rsa_public_key *pk, unsigned char *hash_out)
Type for a RSA signature verification engine (PKCS#1 v1.5).
Definition bearssl_rsa.h:278
br_x509_minimal_init
void br_x509_minimal_init(br_x509_minimal_context *ctx, const br_hash_class *dn_hash_impl, const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num)
Initialise a "minimal" X.509 engine.
br_x509_decoder_init
void br_x509_decoder_init(br_x509_decoder_context *ctx, void(*append_dn)(void *ctx, const void *buf, size_t len), void *append_dn_ctx)
Initialise an X.509 decoder context for processing a new certificate.
br_x509_minimal_set_ecdsa
static void br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx, const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)
Set a ECDSA signature verification implementation in the X.509 "minimal" engine.
Definition bearssl_x509.h:822
br_x509_minimal_set_rsa
static void br_x509_minimal_set_rsa(br_x509_minimal_context *ctx, br_rsa_pkcs1_vrfy irsa)
Set a RSA signature verification implementation in the X.509 "minimal" engine.
Definition bearssl_x509.h:798
br_x509_minimal_set_minrsa
static void br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)
Set the minimal acceptable length for RSA keys (X.509 "minimal" engine).
Definition bearssl_x509.h:890
BR_KEYTYPE_EC
#define BR_KEYTYPE_EC
Key type: algorithm is EC.
Definition bearssl_x509.h:286
br_x509_decoder_get_pkey
static br_x509_pkey * br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)
Obtain the decoded public key.
Definition bearssl_x509.h:1017
br_skey_decoder_init
void br_skey_decoder_init(br_skey_decoder_context *ctx)
Initialise a private key decoder context.
br_x509_decoder_isCA
static int br_x509_decoder_isCA(br_x509_decoder_context *ctx)
Get the "isCA" flag from an X.509 decoder context.
Definition bearssl_x509.h:1059
br_x509_decoder_get_signer_hash_id
static int br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)
Get the identifier for the hash function used to sign the decoded certificate.
Definition bearssl_x509.h:1090
br_skey_decoder_get_rsa
static const br_rsa_private_key * br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)
Get the decoded RSA private key.
Definition bearssl_x509.h:1222
br_x509_knownkey_init_ec
void br_x509_knownkey_init_ec(br_x509_knownkey_context *ctx, const br_ec_public_key *pk, unsigned usages)
Initialize a "known key" X.509 engine with a known EC public key.
br_x509_minimal_set_time
static void br_x509_minimal_set_time(br_x509_minimal_context *ctx, uint32_t days, uint32_t seconds)
Set the validation time for the X.509 "minimal" engine.
Definition bearssl_x509.h:869
br_x509_decoder_get_signer_key_type
static int br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)
Get the issuing CA key type (type of algorithm used to sign the decoded certificate).
Definition bearssl_x509.h:1075
BR_ERR_X509_TRUNCATED
#define BR_ERR_X509_TRUNCATED
X.509 status: truncated certificate.
Definition bearssl_x509.h:136
br_x509_decoder_push
void br_x509_decoder_push(br_x509_decoder_context *ctx, const void *data, size_t len)
Push some certificate bytes into a decoder context.
br_skey_decoder_key_type
static int br_skey_decoder_key_type(const br_skey_decoder_context *ctx)
Get the decoded private key type.
Definition bearssl_x509.h:1201
br_encode_ec_raw_der
size_t br_encode_ec_raw_der(void *dest, const br_ec_private_key *sk, const br_ec_public_key *pk)
Encode an EC private key (raw DER format).
br_x509_minimal_init_full
void br_x509_minimal_init_full(br_x509_minimal_context *ctx, const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num)
Initialise a "minimal" X.509 engine with default algorithms.
br_encode_rsa_pkcs8_der
size_t br_encode_rsa_pkcs8_der(void *dest, const br_rsa_private_key *sk, const br_rsa_public_key *pk, const void *d, size_t dlen)
Encode an RSA private key (PKCS#8 DER format).
br_x509_minimal_set_hash
static void br_x509_minimal_set_hash(br_x509_minimal_context *ctx, int id, const br_hash_class *impl)
Set a supported hash function in an X.509 "minimal" engine.
Definition bearssl_x509.h:779
br_skey_decoder_push
void br_skey_decoder_push(br_skey_decoder_context *ctx, const void *data, size_t len)
Push some data bytes into a private key decoder context.
br_skey_decoder_last_error
static int br_skey_decoder_last_error(const br_skey_decoder_context *ctx)
Get the decoding status for a private key.
Definition bearssl_x509.h:1180
br_x509_knownkey_vtable
const br_x509_class br_x509_knownkey_vtable
Class instance for the "known key" X.509 engine.
BR_KEYTYPE_RSA
#define BR_KEYTYPE_RSA
Key type: algorithm is RSA.
Definition bearssl_x509.h:284
br_x509_minimal_set_name_elements
static void br_x509_minimal_set_name_elements(br_x509_minimal_context *ctx, br_name_element *elts, size_t num_elts)
Set the name elements to gather.
Definition bearssl_x509.h:908
br_encode_rsa_raw_der
size_t br_encode_rsa_raw_der(void *dest, const br_rsa_private_key *sk, const br_rsa_public_key *pk, const void *d, size_t dlen)
Encode an RSA private key (raw DER format).
br_x509_decoder_last_error
static int br_x509_decoder_last_error(br_x509_decoder_context *ctx)
Get decoder error status.
Definition bearssl_x509.h:1037
br_encode_ec_pkcs8_der
size_t br_encode_ec_pkcs8_der(void *dest, const br_ec_private_key *sk, const br_ec_public_key *pk)
Encode an EC private key (PKCS#8 DER format).
br_x509_minimal_vtable
const br_x509_class br_x509_minimal_vtable
Class instance for the "minimal" X.509 engine.
br_skey_decoder_get_ec
static const br_ec_private_key * br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)
Get the decoded EC private key.
Definition bearssl_x509.h:1243
br_x509_knownkey_init_rsa
void br_x509_knownkey_init_rsa(br_x509_knownkey_context *ctx, const br_rsa_public_key *pk, unsigned usages)
Initialize a "known key" X.509 engine with a known RSA public key.
br_ec_impl
Type for an EC implementation.
Definition bearssl_ec.h:270
br_ec_private_key
Structure for an EC private key.
Definition bearssl_ec.h:258
br_ec_public_key
Structure for an EC public key.
Definition bearssl_ec.h:241
br_multihash_context
Multi-hasher context structure.
Definition bearssl_hash.h:1107
br_name_element
Type for receiving a name element.
Definition bearssl_x509.h:571
br_name_element::status
int status
Decoding status.
Definition bearssl_x509.h:624
br_name_element::len
size_t len
Length (in bytes) of the destination buffer.
Definition bearssl_x509.h:614
br_name_element::buf
char * buf
Destination buffer.
Definition bearssl_x509.h:607
br_name_element::oid
const unsigned char * oid
Element OID.
Definition bearssl_x509.h:602
br_rsa_private_key
RSA private key.
Definition bearssl_rsa.h:181
br_rsa_public_key
RSA public key.
Definition bearssl_rsa.h:161
br_skey_decoder_context
Private key decoder context.
Definition bearssl_x509.h:1114
br_x500_name
Distinguished Name (X.500) structure.
Definition bearssl_x509.h:245
br_x500_name::data
unsigned char * data
Encoded DN data.
Definition bearssl_x509.h:247
br_x500_name::len
size_t len
Encoded DN length (in bytes).
Definition bearssl_x509.h:249
br_x509_certificate
Type for an X.509 certificate (DER-encoded).
Definition bearssl_x509.h:1098
br_x509_certificate::data
unsigned char * data
The DER-encoded certificate data.
Definition bearssl_x509.h:1100
br_x509_certificate::data_len
size_t data_len
The DER-encoded certificate length (in bytes).
Definition bearssl_x509.h:1102
br_x509_class_
Class type for an X.509 engine.
Definition bearssl_x509.h:369
br_x509_class_::end_cert
void(* end_cert)(const br_x509_class **ctx)
Finish the current certificate.
Definition bearssl_x509.h:428
br_x509_class_::append
void(* append)(const br_x509_class **ctx, const unsigned char *buf, size_t len)
Receive some bytes for the current certificate.
Definition bearssl_x509.h:417
br_x509_class_::start_cert
void(* start_cert)(const br_x509_class **ctx, uint32_t length)
Start a new certificate.
Definition bearssl_x509.h:399
br_x509_class_::end_chain
unsigned(* end_chain)(const br_x509_class **ctx)
Finish the chain.
Definition bearssl_x509.h:441
br_x509_class_::context_size
size_t context_size
X.509 context size, in bytes.
Definition bearssl_x509.h:373
br_x509_class_::start_chain
void(* start_chain)(const br_x509_class **ctx, const char *server_name)
Start a new chain.
Definition bearssl_x509.h:390
br_x509_decoder_context
X.509 decoder context.
Definition bearssl_x509.h:924
br_x509_knownkey_context
The "known key" X.509 engine structure.
Definition bearssl_x509.h:479
br_x509_knownkey_context::vtable
const br_x509_class * vtable
Reference to the context vtable.
Definition bearssl_x509.h:481
br_x509_minimal_context
The "minimal" X.509 engine structure.
Definition bearssl_x509.h:637
br_x509_minimal_context::vtable
const br_x509_class * vtable
Definition bearssl_x509.h:638
br_x509_pkey
Aggregate structure for public keys.
Definition bearssl_x509.h:228
br_x509_pkey::ec
br_ec_public_key ec
EC public key.
Definition bearssl_x509.h:236
br_x509_pkey::rsa
br_rsa_public_key rsa
RSA public key.
Definition bearssl_x509.h:234
br_x509_pkey::key_type
unsigned char key_type
Key type: BR_KEYTYPE_RSA or BR_KEYTYPE_EC.
Definition bearssl_x509.h:230
br_x509_trust_anchor
Trust anchor structure.
Definition bearssl_x509.h:255
br_x509_trust_anchor::flags
unsigned flags
Anchor flags (e.g. BR_X509_TA_CA).
Definition bearssl_x509.h:259
br_x509_trust_anchor::pkey
br_x509_pkey pkey
Anchor public key.
Definition bearssl_x509.h:261
br_x509_trust_anchor::dn
br_x500_name dn
Encoded DN (X.500 name).
Definition bearssl_x509.h:257
br_hash_compat_context
Aggregate context for configurable hash function support.
Definition bearssl_hash.h:1077