Path: blob/main/contrib/bearssl/inc/bearssl_x509.h
39586 views
/*1* Copyright (c) 2016 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#ifndef BR_BEARSSL_X509_H__25#define BR_BEARSSL_X509_H__2627#include <stddef.h>28#include <stdint.h>2930#include "bearssl_ec.h"31#include "bearssl_hash.h"32#include "bearssl_rsa.h"3334#ifdef __cplusplus35extern "C" {36#endif3738/** \file bearssl_x509.h39*40* # X.509 Certificate Chain Processing41*42* An X.509 processing engine receives an X.509 chain, chunk by chunk,43* as received from a SSL/TLS client or server (the client receives the44* server's certificate chain, and the server receives the client's45* certificate chain if it requested a client certificate). The chain46* is thus injected in the engine in SSL order (end-entity first).47*48* The engine's job is to return the public key to use for SSL/TLS.49* How exactly that key is obtained and verified is entirely up to the50* engine.51*52* **The "known key" engine** returns a public key which is already known53* from out-of-band information (e.g. the client _remembers_ the key from54* a previous connection, as in the usual SSH model). This is the simplest55* engine since it simply ignores the chain, thereby avoiding the need56* for any decoding logic.57*58* **The "minimal" engine** implements minimal X.509 decoding and chain59* validation:60*61* - The provided chain should validate "as is". There is no attempt62* at reordering, skipping or downloading extra certificates.63*64* - X.509 v1, v2 and v3 certificates are supported.65*66* - Trust anchors are a DN and a public key. Each anchor is either a67* "CA" anchor, or a non-CA.68*69* - If the end-entity certificate matches a non-CA anchor (subject DN70* is equal to the non-CA name, and public key is also identical to71* the anchor key), then this is a _direct trust_ case and the72* remaining certificates are ignored.73*74* - Unless direct trust is applied, the chain must be verifiable up to75* a certificate whose issuer DN matches the DN from a "CA" trust anchor,76* and whose signature is verifiable against that anchor's public key.77* Subsequent certificates in the chain are ignored.78*79* - The engine verifies subject/issuer DN matching, and enforces80* processing of Basic Constraints and Key Usage extensions. The81* Authority Key Identifier, Subject Key Identifier, Issuer Alt Name,82* Subject Directory Attribute, CRL Distribution Points, Freshest CRL,83* Authority Info Access and Subject Info Access extensions are84* ignored. The Subject Alt Name is decoded for the end-entity85* certificate under some conditions (see below). Other extensions86* are ignored if non-critical, or imply chain rejection if critical.87*88* - The Subject Alt Name extension is parsed for names of type `dNSName`89* when decoding the end-entity certificate, and only if there is a90* server name to match. If there is no SAN extension, then the91* Common Name from the subjectDN is used. That name matching is92* case-insensitive and honours a single starting wildcard (i.e. if93* the name in the certificate starts with "`*.`" then this matches94* any word as first element). Note: this name matching is performed95* also in the "direct trust" model.96*97* - DN matching is byte-to-byte equality (a future version might98* include some limited processing for case-insensitive matching and99* whitespace normalisation).100*101* - Successful validation produces a public key type but also a set102* of allowed usages (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).103* The caller is responsible for checking that the key type and104* usages are compatible with the expected values (e.g. with the105* selected cipher suite, when the client validates the server's106* certificate).107*108* **Important caveats:**109*110* - The "minimal" engine does not check revocation status. The relevant111* extensions are ignored, and CRL or OCSP responses are not gathered112* or checked.113*114* - The "minimal" engine does not currently support Name Constraints115* (some basic functionality to handle sub-domains may be added in a116* later version).117*118* - The decoder is not "validating" in the sense that it won't reject119* some certificates with invalid field values when these fields are120* not actually processed.121*/122123/*124* X.509 error codes are in the 32..63 range.125*/126127/** \brief X.509 status: validation was successful; this is not actually128an error. */129#define BR_ERR_X509_OK 32130131/** \brief X.509 status: invalid value in an ASN.1 structure. */132#define BR_ERR_X509_INVALID_VALUE 33133134/** \brief X.509 status: truncated certificate. */135#define BR_ERR_X509_TRUNCATED 34136137/** \brief X.509 status: empty certificate chain (no certificate at all). */138#define BR_ERR_X509_EMPTY_CHAIN 35139140/** \brief X.509 status: decoding error: inner element extends beyond141outer element size. */142#define BR_ERR_X509_INNER_TRUNC 36143144/** \brief X.509 status: decoding error: unsupported tag class (application145or private). */146#define BR_ERR_X509_BAD_TAG_CLASS 37147148/** \brief X.509 status: decoding error: unsupported tag value. */149#define BR_ERR_X509_BAD_TAG_VALUE 38150151/** \brief X.509 status: decoding error: indefinite length. */152#define BR_ERR_X509_INDEFINITE_LENGTH 39153154/** \brief X.509 status: decoding error: extraneous element. */155#define BR_ERR_X509_EXTRA_ELEMENT 40156157/** \brief X.509 status: decoding error: unexpected element. */158#define BR_ERR_X509_UNEXPECTED 41159160/** \brief X.509 status: decoding error: expected constructed element, but161is primitive. */162#define BR_ERR_X509_NOT_CONSTRUCTED 42163164/** \brief X.509 status: decoding error: expected primitive element, but165is constructed. */166#define BR_ERR_X509_NOT_PRIMITIVE 43167168/** \brief X.509 status: decoding error: BIT STRING length is not multiple169of 8. */170#define BR_ERR_X509_PARTIAL_BYTE 44171172/** \brief X.509 status: decoding error: BOOLEAN value has invalid length. */173#define BR_ERR_X509_BAD_BOOLEAN 45174175/** \brief X.509 status: decoding error: value is off-limits. */176#define BR_ERR_X509_OVERFLOW 46177178/** \brief X.509 status: invalid distinguished name. */179#define BR_ERR_X509_BAD_DN 47180181/** \brief X.509 status: invalid date/time representation. */182#define BR_ERR_X509_BAD_TIME 48183184/** \brief X.509 status: certificate contains unsupported features that185cannot be ignored. */186#define BR_ERR_X509_UNSUPPORTED 49187188/** \brief X.509 status: key or signature size exceeds internal limits. */189#define BR_ERR_X509_LIMIT_EXCEEDED 50190191/** \brief X.509 status: key type does not match that which was expected. */192#define BR_ERR_X509_WRONG_KEY_TYPE 51193194/** \brief X.509 status: signature is invalid. */195#define BR_ERR_X509_BAD_SIGNATURE 52196197/** \brief X.509 status: validation time is unknown. */198#define BR_ERR_X509_TIME_UNKNOWN 53199200/** \brief X.509 status: certificate is expired or not yet valid. */201#define BR_ERR_X509_EXPIRED 54202203/** \brief X.509 status: issuer/subject DN mismatch in the chain. */204#define BR_ERR_X509_DN_MISMATCH 55205206/** \brief X.509 status: expected server name was not found in the chain. */207#define BR_ERR_X509_BAD_SERVER_NAME 56208209/** \brief X.509 status: unknown critical extension in certificate. */210#define BR_ERR_X509_CRITICAL_EXTENSION 57211212/** \brief X.509 status: not a CA, or path length constraint violation */213#define BR_ERR_X509_NOT_CA 58214215/** \brief X.509 status: Key Usage extension prohibits intended usage. */216#define BR_ERR_X509_FORBIDDEN_KEY_USAGE 59217218/** \brief X.509 status: public key found in certificate is too small. */219#define BR_ERR_X509_WEAK_PUBLIC_KEY 60220221/** \brief X.509 status: chain could not be linked to a trust anchor. */222#define BR_ERR_X509_NOT_TRUSTED 62223224/**225* \brief Aggregate structure for public keys.226*/227typedef struct {228/** \brief Key type: `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC` */229unsigned char key_type;230/** \brief Actual public key. */231union {232/** \brief RSA public key. */233br_rsa_public_key rsa;234/** \brief EC public key. */235br_ec_public_key ec;236} key;237} br_x509_pkey;238239/**240* \brief Distinguished Name (X.500) structure.241*242* The DN is DER-encoded.243*/244typedef struct {245/** \brief Encoded DN data. */246unsigned char *data;247/** \brief Encoded DN length (in bytes). */248size_t len;249} br_x500_name;250251/**252* \brief Trust anchor structure.253*/254typedef struct {255/** \brief Encoded DN (X.500 name). */256br_x500_name dn;257/** \brief Anchor flags (e.g. `BR_X509_TA_CA`). */258unsigned flags;259/** \brief Anchor public key. */260br_x509_pkey pkey;261} br_x509_trust_anchor;262263/**264* \brief Trust anchor flag: CA.265*266* A "CA" anchor is deemed fit to verify signatures on certificates.267* A "non-CA" anchor is accepted only for direct trust (server's268* certificate name and key match the anchor).269*/270#define BR_X509_TA_CA 0x0001271272/*273* Key type: combination of a basic key type (low 4 bits) and some274* optional flags.275*276* For a public key, the basic key type only is set.277*278* For an expected key type, the flags indicate the intended purpose(s)279* for the key; the basic key type may be set to 0 to indicate that any280* key type compatible with the indicated purpose is acceptable.281*/282/** \brief Key type: algorithm is RSA. */283#define BR_KEYTYPE_RSA 1284/** \brief Key type: algorithm is EC. */285#define BR_KEYTYPE_EC 2286287/**288* \brief Key type: usage is "key exchange".289*290* This value is combined (with bitwise OR) with the algorithm291* (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509292* validation engine that it should find a public key of that type,293* fit for key exchanges (e.g. `TLS_RSA_*` and `TLS_ECDH_*` cipher294* suites).295*/296#define BR_KEYTYPE_KEYX 0x10297298/**299* \brief Key type: usage is "signature".300*301* This value is combined (with bitwise OR) with the algorithm302* (`BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`) when informing the X.509303* validation engine that it should find a public key of that type,304* fit for signatures (e.g. `TLS_ECDHE_*` cipher suites).305*/306#define BR_KEYTYPE_SIGN 0x20307308/*309* start_chain Called when a new chain is started. If 'server_name'310* is not NULL and non-empty, then it is a name that311* should be looked for in the EE certificate (in the312* SAN extension as dNSName, or in the subjectDN's CN313* if there is no SAN extension).314* The caller ensures that the provided 'server_name'315* pointer remains valid throughout validation.316*317* start_cert Begins a new certificate in the chain. The provided318* length is in bytes; this is the total certificate length.319*320* append Get some additional bytes for the current certificate.321*322* end_cert Ends the current certificate.323*324* end_chain Called at the end of the chain. Returned value is325* 0 on success, or a non-zero error code.326*327* get_pkey Returns the EE certificate public key.328*329* For a complete chain, start_chain() and end_chain() are always330* called. For each certificate, start_cert(), some append() calls, then331* end_cert() are called, in that order. There may be no append() call332* at all if the certificate is empty (which is not valid but may happen333* if the peer sends exactly that).334*335* get_pkey() shall return a pointer to a structure that is valid as336* long as a new chain is not started. This may be a sub-structure337* within the context for the engine. This function MAY return a valid338* pointer to a public key even in some cases of validation failure,339* depending on the validation engine.340*/341342/**343* \brief Class type for an X.509 engine.344*345* A certificate chain validation uses a caller-allocated context, which346* contains the running state for that validation. Methods are called347* in due order:348*349* - `start_chain()` is called at the start of the validation.350* - Certificates are processed one by one, in SSL order (end-entity351* comes first). For each certificate, the following methods are352* called:353*354* - `start_cert()` at the beginning of the certificate.355* - `append()` is called zero, one or more times, to provide356* the certificate (possibly in chunks).357* - `end_cert()` at the end of the certificate.358*359* - `end_chain()` is called when the last certificate in the chain360* was processed.361* - `get_pkey()` is called after chain processing, if the chain362* validation was successful.363*364* A context structure may be reused; the `start_chain()` method shall365* ensure (re)initialisation.366*/367typedef struct br_x509_class_ br_x509_class;368struct br_x509_class_ {369/**370* \brief X.509 context size, in bytes.371*/372size_t context_size;373374/**375* \brief Start a new chain.376*377* This method shall set the vtable (first field) of the context378* structure.379*380* The `server_name`, if not `NULL`, will be considered as a381* fully qualified domain name, to be matched against the `dNSName`382* elements of the end-entity certificate's SAN extension (if there383* is no SAN, then the Common Name from the subjectDN will be used).384* If `server_name` is `NULL` then no such matching is performed.385*386* \param ctx validation context.387* \param server_name server name to match (or `NULL`).388*/389void (*start_chain)(const br_x509_class **ctx,390const char *server_name);391392/**393* \brief Start a new certificate.394*395* \param ctx validation context.396* \param length new certificate length (in bytes).397*/398void (*start_cert)(const br_x509_class **ctx, uint32_t length);399400/**401* \brief Receive some bytes for the current certificate.402*403* This function may be called several times in succession for404* a given certificate. The caller guarantees that for each405* call, `len` is not zero, and the sum of all chunk lengths406* for a certificate matches the total certificate length which407* was provided in the previous `start_cert()` call.408*409* If the new certificate is empty (no byte at all) then this410* function won't be called at all.411*412* \param ctx validation context.413* \param buf certificate data chunk.414* \param len certificate data chunk length (in bytes).415*/416void (*append)(const br_x509_class **ctx,417const unsigned char *buf, size_t len);418419/**420* \brief Finish the current certificate.421*422* This function is called when the end of the current certificate423* is reached.424*425* \param ctx validation context.426*/427void (*end_cert)(const br_x509_class **ctx);428429/**430* \brief Finish the chain.431*432* This function is called at the end of the chain. It shall433* return either 0 if the validation was successful, or a434* non-zero error code. The `BR_ERR_X509_*` constants are435* error codes, though other values may be possible.436*437* \param ctx validation context.438* \return 0 on success, or a non-zero error code.439*/440unsigned (*end_chain)(const br_x509_class **ctx);441442/**443* \brief Get the resulting end-entity public key.444*445* The decoded public key is returned. The returned pointer446* may be valid only as long as the context structure is447* unmodified, i.e. it may cease to be valid if the context448* is released or reused.449*450* This function _may_ return `NULL` if the validation failed.451* However, returning a public key does not mean that the452* validation was wholly successful; some engines may return453* a decoded public key even if the chain did not end on a454* trusted anchor.455*456* If validation succeeded and `usage` is not `NULL`, then457* `*usage` is filled with a combination of `BR_KEYTYPE_SIGN`458* and/or `BR_KEYTYPE_KEYX` that specifies the validated key459* usage types. It is the caller's responsibility to check460* that value against the intended use of the public key.461*462* \param ctx validation context.463* \return the end-entity public key, or `NULL`.464*/465const br_x509_pkey *(*get_pkey)(466const br_x509_class *const *ctx, unsigned *usages);467};468469/**470* \brief The "known key" X.509 engine structure.471*472* The structure contents are opaque (they shall not be accessed directly),473* except for the first field (the vtable).474*475* The "known key" engine returns an externally configured public key,476* and totally ignores the certificate contents.477*/478typedef struct {479/** \brief Reference to the context vtable. */480const br_x509_class *vtable;481#ifndef BR_DOXYGEN_IGNORE482br_x509_pkey pkey;483unsigned usages;484#endif485} br_x509_knownkey_context;486487/**488* \brief Class instance for the "known key" X.509 engine.489*/490extern const br_x509_class br_x509_knownkey_vtable;491492/**493* \brief Initialize a "known key" X.509 engine with a known RSA public key.494*495* The `usages` parameter indicates the allowed key usages for that key496* (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).497*498* The provided pointers are linked in, not copied, so they must remain499* valid while the public key may be in usage.500*501* \param ctx context to initialise.502* \param pk known public key.503* \param usages allowed key usages.504*/505void br_x509_knownkey_init_rsa(br_x509_knownkey_context *ctx,506const br_rsa_public_key *pk, unsigned usages);507508/**509* \brief Initialize a "known key" X.509 engine with a known EC public key.510*511* The `usages` parameter indicates the allowed key usages for that key512* (`BR_KEYTYPE_KEYX` and/or `BR_KEYTYPE_SIGN`).513*514* The provided pointers are linked in, not copied, so they must remain515* valid while the public key may be in usage.516*517* \param ctx context to initialise.518* \param pk known public key.519* \param usages allowed key usages.520*/521void br_x509_knownkey_init_ec(br_x509_knownkey_context *ctx,522const br_ec_public_key *pk, unsigned usages);523524#ifndef BR_DOXYGEN_IGNORE525/*526* The minimal X.509 engine has some state buffers which must be large527* enough to simultaneously accommodate:528* -- the public key extracted from the current certificate;529* -- the signature on the current certificate or on the previous530* certificate;531* -- the public key extracted from the EE certificate.532*533* We store public key elements in their raw unsigned big-endian534* encoding. We want to support up to RSA-4096 with a short (up to 64535* bits) public exponent, thus a buffer for a public key must have536* length at least 520 bytes. Similarly, a RSA-4096 signature has length537* 512 bytes.538*539* Though RSA public exponents can formally be as large as the modulus540* (mathematically, even larger exponents would work, but PKCS#1 forbids541* them), exponents that do not fit on 32 bits are extremely rare,542* notably because some widespread implementations (e.g. Microsoft's543* CryptoAPI) don't support them. Moreover, large public exponent do not544* seem to imply any tangible security benefit, and they increase the545* cost of public key operations. The X.509 "minimal" engine will tolerate546* public exponents of arbitrary size as long as the modulus and the547* exponent can fit together in the dedicated buffer.548*549* EC public keys are shorter than RSA public keys; even with curve550* NIST P-521 (the largest curve we care to support), a public key is551* encoded over 133 bytes only.552*/553#define BR_X509_BUFSIZE_KEY 520554#define BR_X509_BUFSIZE_SIG 512555#endif556557/**558* \brief Type for receiving a name element.559*560* An array of such structures can be provided to the X.509 decoding561* engines. If the specified elements are found in the certificate562* subject DN or the SAN extension, then the name contents are copied563* as zero-terminated strings into the buffer.564*565* The decoder converts TeletexString and BMPString to UTF8String, and566* ensures that the resulting string is zero-terminated. If the string567* does not fit in the provided buffer, then the copy is aborted and an568* error is reported.569*/570typedef struct {571/**572* \brief Element OID.573*574* For X.500 name elements (to be extracted from the subject DN),575* this is the encoded OID for the requested name element; the576* first byte shall contain the length of the DER-encoded OID577* value, followed by the OID value (for instance, OID 2.5.4.3,578* for id-at-commonName, will be `03 55 04 03`). This is579* equivalent to full DER encoding with the length but without580* the tag.581*582* For SAN name elements, the first byte (`oid[0]`) has value 0,583* followed by another byte that matches the expected GeneralName584* tag. Allowed second byte values are then:585*586* - 1: `rfc822Name`587*588* - 2: `dNSName`589*590* - 6: `uniformResourceIdentifier`591*592* - 0: `otherName`593*594* If first and second byte are 0, then this is a SAN element of595* type `otherName`; the `oid[]` array should then contain, right596* after the two bytes of value 0, an encoded OID (with the same597* conventions as for X.500 name elements). If a match is found598* for that OID, then the corresponding name element will be599* extracted, as long as it is a supported string type.600*/601const unsigned char *oid;602603/**604* \brief Destination buffer.605*/606char *buf;607608/**609* \brief Length (in bytes) of the destination buffer.610*611* The buffer MUST NOT be smaller than 1 byte.612*/613size_t len;614615/**616* \brief Decoding status.617*618* Status is 0 if the name element was not found, 1 if it was619* found and decoded, or -1 on error. Error conditions include620* an unrecognised encoding, an invalid encoding, or a string621* too large for the destination buffer.622*/623int status;624625} br_name_element;626627/**628* \brief Callback for validity date checks.629*630* The function receives as parameter an arbitrary user-provided context,631* and the notBefore and notAfter dates specified in an X.509 certificate,632* both expressed as a number of days and a number of seconds:633*634* - Days are counted in a proleptic Gregorian calendar since635* January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";636* it is also traditionally known as "1 BC".637*638* - Seconds are counted since midnight, from 0 to 86400 (a count of639* 86400 is possible only if a leap second happened).640*641* Each date and time is understood in the UTC time zone. The "Unix642* Epoch" (January 1st, 1970, 00:00 UTC) corresponds to days=719528 and643* seconds=0; the "Windows Epoch" (January 1st, 1601, 00:00 UTC) is644* days=584754, seconds=0.645*646* This function must return -1 if the current date is strictly before647* the "notBefore" time, or +1 if the current date is strictly after the648* "notAfter" time. If neither condition holds, then the function returns649* 0, which means that the current date falls within the validity range of650* the certificate. If the function returns a value distinct from -1, 0651* and +1, then this is interpreted as an unavailability of the current652* time, which normally ends the validation process with a653* `BR_ERR_X509_TIME_UNKNOWN` error.654*655* During path validation, this callback will be invoked for each656* considered X.509 certificate. Validation fails if any of the calls657* returns a non-zero value.658*659* The context value is an abritrary pointer set by the caller when660* configuring this callback.661*662* \param tctx context pointer.663* \param not_before_days notBefore date (days since Jan 1st, 0 AD).664* \param not_before_seconds notBefore time (seconds, at most 86400).665* \param not_after_days notAfter date (days since Jan 1st, 0 AD).666* \param not_after_seconds notAfter time (seconds, at most 86400).667* \return -1, 0 or +1.668*/669typedef int (*br_x509_time_check)(void *tctx,670uint32_t not_before_days, uint32_t not_before_seconds,671uint32_t not_after_days, uint32_t not_after_seconds);672673/**674* \brief The "minimal" X.509 engine structure.675*676* The structure contents are opaque (they shall not be accessed directly),677* except for the first field (the vtable).678*679* The "minimal" engine performs a rudimentary but serviceable X.509 path680* validation.681*/682typedef struct {683const br_x509_class *vtable;684685#ifndef BR_DOXYGEN_IGNORE686/* Structure for returning the EE public key. */687br_x509_pkey pkey;688689/* CPU for the T0 virtual machine. */690struct {691uint32_t *dp;692uint32_t *rp;693const unsigned char *ip;694} cpu;695uint32_t dp_stack[31];696uint32_t rp_stack[31];697int err;698699/* Server name to match with the SAN / CN of the EE certificate. */700const char *server_name;701702/* Validated key usages. */703unsigned char key_usages;704705/* Explicitly set date and time. */706uint32_t days, seconds;707708/* Current certificate length (in bytes). Set to 0 when the709certificate has been fully processed. */710uint32_t cert_length;711712/* Number of certificates processed so far in the current chain.713It is incremented at the end of the processing of a certificate,714so it is 0 for the EE. */715uint32_t num_certs;716717/* Certificate data chunk. */718const unsigned char *hbuf;719size_t hlen;720721/* The pad serves as destination for various operations. */722unsigned char pad[256];723724/* Buffer for EE public key data. */725unsigned char ee_pkey_data[BR_X509_BUFSIZE_KEY];726727/* Buffer for currently decoded public key. */728unsigned char pkey_data[BR_X509_BUFSIZE_KEY];729730/* Signature type: signer key type, offset to the hash731function OID (in the T0 data block) and hash function732output length (TBS hash length). */733unsigned char cert_signer_key_type;734uint16_t cert_sig_hash_oid;735unsigned char cert_sig_hash_len;736737/* Current/last certificate signature. */738unsigned char cert_sig[BR_X509_BUFSIZE_SIG];739uint16_t cert_sig_len;740741/* Minimum RSA key length (difference in bytes from 128). */742int16_t min_rsa_size;743744/* Configured trust anchors. */745const br_x509_trust_anchor *trust_anchors;746size_t trust_anchors_num;747748/*749* Multi-hasher for the TBS.750*/751unsigned char do_mhash;752br_multihash_context mhash;753unsigned char tbs_hash[64];754755/*756* Simple hasher for the subject/issuer DN.757*/758unsigned char do_dn_hash;759const br_hash_class *dn_hash_impl;760br_hash_compat_context dn_hash;761unsigned char current_dn_hash[64];762unsigned char next_dn_hash[64];763unsigned char saved_dn_hash[64];764765/*766* Name elements to gather.767*/768br_name_element *name_elts;769size_t num_name_elts;770771/*772* Callback function (and context) to get the current date.773*/774void *itime_ctx;775br_x509_time_check itime;776777/*778* Public key cryptography implementations (signature verification).779*/780br_rsa_pkcs1_vrfy irsa;781br_ecdsa_vrfy iecdsa;782const br_ec_impl *iec;783#endif784785} br_x509_minimal_context;786787/**788* \brief Class instance for the "minimal" X.509 engine.789*/790extern const br_x509_class br_x509_minimal_vtable;791792/**793* \brief Initialise a "minimal" X.509 engine.794*795* The `dn_hash_impl` parameter shall be a hash function internally used796* to match X.500 names (subject/issuer DN, and anchor names). Any standard797* hash function may be used, but a collision-resistant hash function is798* advised.799*800* After initialization, some implementations for signature verification801* (hash functions and signature algorithms) MUST be added.802*803* \param ctx context to initialise.804* \param dn_hash_impl hash function for DN comparisons.805* \param trust_anchors trust anchors.806* \param trust_anchors_num number of trust anchors.807*/808void br_x509_minimal_init(br_x509_minimal_context *ctx,809const br_hash_class *dn_hash_impl,810const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);811812/**813* \brief Set a supported hash function in an X.509 "minimal" engine.814*815* Hash functions are used with signature verification algorithms.816* Once initialised (with `br_x509_minimal_init()`), the context must817* be configured with the hash functions it shall support for that818* purpose. The hash function identifier MUST be one of the standard819* hash function identifiers (1 to 6, for MD5, SHA-1, SHA-224, SHA-256,820* SHA-384 and SHA-512).821*822* If `impl` is `NULL`, this _removes_ support for the designated823* hash function.824*825* \param ctx validation context.826* \param id hash function identifier (from 1 to 6).827* \param impl hash function implementation (or `NULL`).828*/829static inline void830br_x509_minimal_set_hash(br_x509_minimal_context *ctx,831int id, const br_hash_class *impl)832{833br_multihash_setimpl(&ctx->mhash, id, impl);834}835836/**837* \brief Set a RSA signature verification implementation in the X.509838* "minimal" engine.839*840* Once initialised (with `br_x509_minimal_init()`), the context must841* be configured with the signature verification implementations that842* it is supposed to support. If `irsa` is `0`, then the RSA support843* is disabled.844*845* \param ctx validation context.846* \param irsa RSA signature verification implementation (or `0`).847*/848static inline void849br_x509_minimal_set_rsa(br_x509_minimal_context *ctx,850br_rsa_pkcs1_vrfy irsa)851{852ctx->irsa = irsa;853}854855/**856* \brief Set a ECDSA signature verification implementation in the X.509857* "minimal" engine.858*859* Once initialised (with `br_x509_minimal_init()`), the context must860* be configured with the signature verification implementations that861* it is supposed to support.862*863* If `iecdsa` is `0`, then this call disables ECDSA support; in that864* case, `iec` may be `NULL`. Otherwise, `iecdsa` MUST point to a function865* that verifies ECDSA signatures with format "asn1", and it will use866* `iec` as underlying elliptic curve support.867*868* \param ctx validation context.869* \param iec elliptic curve implementation (or `NULL`).870* \param iecdsa ECDSA implementation (or `0`).871*/872static inline void873br_x509_minimal_set_ecdsa(br_x509_minimal_context *ctx,874const br_ec_impl *iec, br_ecdsa_vrfy iecdsa)875{876ctx->iecdsa = iecdsa;877ctx->iec = iec;878}879880/**881* \brief Initialise a "minimal" X.509 engine with default algorithms.882*883* This function performs the same job as `br_x509_minimal_init()`, but884* also sets implementations for RSA, ECDSA, and the standard hash885* functions.886*887* \param ctx context to initialise.888* \param trust_anchors trust anchors.889* \param trust_anchors_num number of trust anchors.890*/891void br_x509_minimal_init_full(br_x509_minimal_context *ctx,892const br_x509_trust_anchor *trust_anchors, size_t trust_anchors_num);893894/**895* \brief Set the validation time for the X.509 "minimal" engine.896*897* The validation time is set as two 32-bit integers, for days and898* seconds since a fixed epoch:899*900* - Days are counted in a proleptic Gregorian calendar since901* January 1st, 0 AD. Year "0 AD" is the one that preceded "1 AD";902* it is also traditionally known as "1 BC".903*904* - Seconds are counted since midnight, from 0 to 86400 (a count of905* 86400 is possible only if a leap second happened).906*907* The validation date and time is understood in the UTC time zone. The908* "Unix Epoch" (January 1st, 1970, 00:00 UTC) corresponds to days=719528909* and seconds=0; the "Windows Epoch" (January 1st, 1601, 00:00 UTC) is910* days=584754, seconds=0.911*912* If the validation date and time are not explicitly set, but BearSSL913* was compiled with support for the system clock on the underlying914* platform, then the current time will automatically be used. Otherwise,915* not setting the validation date and time implies a validation916* failure (except in case of direct trust of the EE key).917*918* \param ctx validation context.919* \param days days since January 1st, 0 AD (Gregorian calendar).920* \param seconds seconds since midnight (0 to 86400).921*/922static inline void923br_x509_minimal_set_time(br_x509_minimal_context *ctx,924uint32_t days, uint32_t seconds)925{926ctx->days = days;927ctx->seconds = seconds;928ctx->itime = 0;929}930931/**932* \brief Set the validity range callback function for the X.509933* "minimal" engine.934*935* The provided function will be invoked to check whether the validation936* date is within the validity range for a given X.509 certificate; a937* call will be issued for each considered certificate. The provided938* context pointer (itime_ctx) will be passed as first parameter to the939* callback.940*941* \param tctx context for callback invocation.942* \param cb callback function.943*/944static inline void945br_x509_minimal_set_time_callback(br_x509_minimal_context *ctx,946void *itime_ctx, br_x509_time_check itime)947{948ctx->itime_ctx = itime_ctx;949ctx->itime = itime;950}951952/**953* \brief Set the minimal acceptable length for RSA keys (X.509 "minimal"954* engine).955*956* The RSA key length is expressed in bytes. The default minimum key957* length is 128 bytes, corresponding to 1017 bits. RSA keys shorter958* than the configured length will be rejected, implying validation959* failure. This setting applies to keys extracted from certificates960* (both end-entity, and intermediate CA) but not to "CA" trust anchors.961*962* \param ctx validation context.963* \param byte_length minimum RSA key length, **in bytes** (not bits).964*/965static inline void966br_x509_minimal_set_minrsa(br_x509_minimal_context *ctx, int byte_length)967{968ctx->min_rsa_size = (int16_t)(byte_length - 128);969}970971/**972* \brief Set the name elements to gather.973*974* The provided array is linked in the context. The elements are975* gathered from the EE certificate. If the same element type is976* requested several times, then the relevant structures will be filled977* in the order the matching values are encountered in the certificate.978*979* \param ctx validation context.980* \param elts array of name element structures to fill.981* \param num_elts number of name element structures to fill.982*/983static inline void984br_x509_minimal_set_name_elements(br_x509_minimal_context *ctx,985br_name_element *elts, size_t num_elts)986{987ctx->name_elts = elts;988ctx->num_name_elts = num_elts;989}990991/**992* \brief X.509 decoder context.993*994* This structure is _not_ for X.509 validation, but for extracting995* names and public keys from encoded certificates. Intended usage is996* to use (self-signed) certificates as trust anchors.997*998* Contents are opaque and shall not be accessed directly.999*/1000typedef struct {10011002#ifndef BR_DOXYGEN_IGNORE1003/* Structure for returning the public key. */1004br_x509_pkey pkey;10051006/* CPU for the T0 virtual machine. */1007struct {1008uint32_t *dp;1009uint32_t *rp;1010const unsigned char *ip;1011} cpu;1012uint32_t dp_stack[32];1013uint32_t rp_stack[32];1014int err;10151016/* The pad serves as destination for various operations. */1017unsigned char pad[256];10181019/* Flag set when decoding succeeds. */1020unsigned char decoded;10211022/* Validity dates. */1023uint32_t notbefore_days, notbefore_seconds;1024uint32_t notafter_days, notafter_seconds;10251026/* The "CA" flag. This is set to true if the certificate contains1027a Basic Constraints extension that asserts CA status. */1028unsigned char isCA;10291030/* DN processing: the subject DN is extracted and pushed to the1031provided callback. */1032unsigned char copy_dn;1033void *append_dn_ctx;1034void (*append_dn)(void *ctx, const void *buf, size_t len);10351036/* Certificate data chunk. */1037const unsigned char *hbuf;1038size_t hlen;10391040/* Buffer for decoded public key. */1041unsigned char pkey_data[BR_X509_BUFSIZE_KEY];10421043/* Type of key and hash function used in the certificate signature. */1044unsigned char signer_key_type;1045unsigned char signer_hash_id;1046#endif10471048} br_x509_decoder_context;10491050/**1051* \brief Initialise an X.509 decoder context for processing a new1052* certificate.1053*1054* The `append_dn()` callback (with opaque context `append_dn_ctx`)1055* will be invoked to receive, chunk by chunk, the certificate's1056* subject DN. If `append_dn` is `0` then the subject DN will be1057* ignored.1058*1059* \param ctx X.509 decoder context to initialise.1060* \param append_dn DN receiver callback (or `0`).1061* \param append_dn_ctx context for the DN receiver callback.1062*/1063void br_x509_decoder_init(br_x509_decoder_context *ctx,1064void (*append_dn)(void *ctx, const void *buf, size_t len),1065void *append_dn_ctx);10661067/**1068* \brief Push some certificate bytes into a decoder context.1069*1070* If `len` is non-zero, then that many bytes are pushed, from address1071* `data`, into the provided decoder context.1072*1073* \param ctx X.509 decoder context.1074* \param data certificate data chunk.1075* \param len certificate data chunk length (in bytes).1076*/1077void br_x509_decoder_push(br_x509_decoder_context *ctx,1078const void *data, size_t len);10791080/**1081* \brief Obtain the decoded public key.1082*1083* Returned value is a pointer to a structure internal to the decoder1084* context; releasing or reusing the decoder context invalidates that1085* structure.1086*1087* If decoding was not finished, or failed, then `NULL` is returned.1088*1089* \param ctx X.509 decoder context.1090* \return the public key, or `NULL` on unfinished/error.1091*/1092static inline br_x509_pkey *1093br_x509_decoder_get_pkey(br_x509_decoder_context *ctx)1094{1095if (ctx->decoded && ctx->err == 0) {1096return &ctx->pkey;1097} else {1098return NULL;1099}1100}11011102/**1103* \brief Get decoder error status.1104*1105* If no error was reported yet but the certificate decoding is not1106* finished, then the error code is `BR_ERR_X509_TRUNCATED`. If decoding1107* was successful, then 0 is returned.1108*1109* \param ctx X.509 decoder context.1110* \return 0 on successful decoding, or a non-zero error code.1111*/1112static inline int1113br_x509_decoder_last_error(br_x509_decoder_context *ctx)1114{1115if (ctx->err != 0) {1116return ctx->err;1117}1118if (!ctx->decoded) {1119return BR_ERR_X509_TRUNCATED;1120}1121return 0;1122}11231124/**1125* \brief Get the "isCA" flag from an X.509 decoder context.1126*1127* This flag is set if the decoded certificate claims to be a CA through1128* a Basic Constraints extension. This flag should not be read before1129* decoding completed successfully.1130*1131* \param ctx X.509 decoder context.1132* \return the "isCA" flag.1133*/1134static inline int1135br_x509_decoder_isCA(br_x509_decoder_context *ctx)1136{1137return ctx->isCA;1138}11391140/**1141* \brief Get the issuing CA key type (type of algorithm used to sign the1142* decoded certificate).1143*1144* This is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. The value 0 is returned1145* if the signature type was not recognised.1146*1147* \param ctx X.509 decoder context.1148* \return the issuing CA key type.1149*/1150static inline int1151br_x509_decoder_get_signer_key_type(br_x509_decoder_context *ctx)1152{1153return ctx->signer_key_type;1154}11551156/**1157* \brief Get the identifier for the hash function used to sign the decoded1158* certificate.1159*1160* This is 0 if the hash function was not recognised.1161*1162* \param ctx X.509 decoder context.1163* \return the signature hash function identifier.1164*/1165static inline int1166br_x509_decoder_get_signer_hash_id(br_x509_decoder_context *ctx)1167{1168return ctx->signer_hash_id;1169}11701171/**1172* \brief Type for an X.509 certificate (DER-encoded).1173*/1174typedef struct {1175/** \brief The DER-encoded certificate data. */1176unsigned char *data;1177/** \brief The DER-encoded certificate length (in bytes). */1178size_t data_len;1179} br_x509_certificate;11801181/**1182* \brief Private key decoder context.1183*1184* The private key decoder recognises RSA and EC private keys, either in1185* their raw, DER-encoded format, or wrapped in an unencrypted PKCS#81186* archive (again DER-encoded).1187*1188* Structure contents are opaque and shall not be accessed directly.1189*/1190typedef struct {1191#ifndef BR_DOXYGEN_IGNORE1192/* Structure for returning the private key. */1193union {1194br_rsa_private_key rsa;1195br_ec_private_key ec;1196} key;11971198/* CPU for the T0 virtual machine. */1199struct {1200uint32_t *dp;1201uint32_t *rp;1202const unsigned char *ip;1203} cpu;1204uint32_t dp_stack[32];1205uint32_t rp_stack[32];1206int err;12071208/* Private key data chunk. */1209const unsigned char *hbuf;1210size_t hlen;12111212/* The pad serves as destination for various operations. */1213unsigned char pad[256];12141215/* Decoded key type; 0 until decoding is complete. */1216unsigned char key_type;12171218/* Buffer for the private key elements. It shall be large enough1219to accommodate all elements for a RSA-4096 private key (roughly1220five 2048-bit integers, possibly a bit more). */1221unsigned char key_data[3 * BR_X509_BUFSIZE_SIG];1222#endif1223} br_skey_decoder_context;12241225/**1226* \brief Initialise a private key decoder context.1227*1228* \param ctx key decoder context to initialise.1229*/1230void br_skey_decoder_init(br_skey_decoder_context *ctx);12311232/**1233* \brief Push some data bytes into a private key decoder context.1234*1235* If `len` is non-zero, then that many data bytes, starting at address1236* `data`, are pushed into the decoder.1237*1238* \param ctx key decoder context.1239* \param data private key data chunk.1240* \param len private key data chunk length (in bytes).1241*/1242void br_skey_decoder_push(br_skey_decoder_context *ctx,1243const void *data, size_t len);12441245/**1246* \brief Get the decoding status for a private key.1247*1248* Decoding status is 0 on success, or a non-zero error code. If the1249* decoding is unfinished when this function is called, then the1250* status code `BR_ERR_X509_TRUNCATED` is returned.1251*1252* \param ctx key decoder context.1253* \return 0 on successful decoding, or a non-zero error code.1254*/1255static inline int1256br_skey_decoder_last_error(const br_skey_decoder_context *ctx)1257{1258if (ctx->err != 0) {1259return ctx->err;1260}1261if (ctx->key_type == 0) {1262return BR_ERR_X509_TRUNCATED;1263}1264return 0;1265}12661267/**1268* \brief Get the decoded private key type.1269*1270* Private key type is `BR_KEYTYPE_RSA` or `BR_KEYTYPE_EC`. If decoding is1271* not finished or failed, then 0 is returned.1272*1273* \param ctx key decoder context.1274* \return decoded private key type, or 0.1275*/1276static inline int1277br_skey_decoder_key_type(const br_skey_decoder_context *ctx)1278{1279if (ctx->err == 0) {1280return ctx->key_type;1281} else {1282return 0;1283}1284}12851286/**1287* \brief Get the decoded RSA private key.1288*1289* This function returns `NULL` if the decoding failed, or is not1290* finished, or the key is not RSA. The returned pointer references1291* structures within the context that can become invalid if the context1292* is reused or released.1293*1294* \param ctx key decoder context.1295* \return decoded RSA private key, or `NULL`.1296*/1297static inline const br_rsa_private_key *1298br_skey_decoder_get_rsa(const br_skey_decoder_context *ctx)1299{1300if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_RSA) {1301return &ctx->key.rsa;1302} else {1303return NULL;1304}1305}13061307/**1308* \brief Get the decoded EC private key.1309*1310* This function returns `NULL` if the decoding failed, or is not1311* finished, or the key is not EC. The returned pointer references1312* structures within the context that can become invalid if the context1313* is reused or released.1314*1315* \param ctx key decoder context.1316* \return decoded EC private key, or `NULL`.1317*/1318static inline const br_ec_private_key *1319br_skey_decoder_get_ec(const br_skey_decoder_context *ctx)1320{1321if (ctx->err == 0 && ctx->key_type == BR_KEYTYPE_EC) {1322return &ctx->key.ec;1323} else {1324return NULL;1325}1326}13271328/**1329* \brief Encode an RSA private key (raw DER format).1330*1331* This function encodes the provided key into the "raw" format specified1332* in PKCS#1 (RFC 8017, Appendix C, type `RSAPrivateKey`), with DER1333* encoding rules.1334*1335* The key elements are:1336*1337* - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)1338*1339* - `pk`: the public key (`n` and `e`)1340*1341* - `d` (size: `dlen` bytes): the private exponent1342*1343* The public key elements, and the private exponent `d`, can be1344* recomputed from the private key (see `br_rsa_compute_modulus()`,1345* `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).1346*1347* If `dest` is not `NULL`, then the encoded key is written at that1348* address, and the encoded length (in bytes) is returned. If `dest` is1349* `NULL`, then nothing is written, but the encoded length is still1350* computed and returned.1351*1352* \param dest the destination buffer (or `NULL`).1353* \param sk the RSA private key.1354* \param pk the RSA public key.1355* \param d the RSA private exponent.1356* \param dlen the RSA private exponent length (in bytes).1357* \return the encoded key length (in bytes).1358*/1359size_t br_encode_rsa_raw_der(void *dest, const br_rsa_private_key *sk,1360const br_rsa_public_key *pk, const void *d, size_t dlen);13611362/**1363* \brief Encode an RSA private key (PKCS#8 DER format).1364*1365* This function encodes the provided key into the PKCS#8 format1366* (RFC 5958, type `OneAsymmetricKey`). It wraps around the "raw DER"1367* format for the RSA key, as implemented by `br_encode_rsa_raw_der()`.1368*1369* The key elements are:1370*1371* - `sk`: the private key (`p`, `q`, `dp`, `dq` and `iq`)1372*1373* - `pk`: the public key (`n` and `e`)1374*1375* - `d` (size: `dlen` bytes): the private exponent1376*1377* The public key elements, and the private exponent `d`, can be1378* recomputed from the private key (see `br_rsa_compute_modulus()`,1379* `br_rsa_compute_pubexp()` and `br_rsa_compute_privexp()`).1380*1381* If `dest` is not `NULL`, then the encoded key is written at that1382* address, and the encoded length (in bytes) is returned. If `dest` is1383* `NULL`, then nothing is written, but the encoded length is still1384* computed and returned.1385*1386* \param dest the destination buffer (or `NULL`).1387* \param sk the RSA private key.1388* \param pk the RSA public key.1389* \param d the RSA private exponent.1390* \param dlen the RSA private exponent length (in bytes).1391* \return the encoded key length (in bytes).1392*/1393size_t br_encode_rsa_pkcs8_der(void *dest, const br_rsa_private_key *sk,1394const br_rsa_public_key *pk, const void *d, size_t dlen);13951396/**1397* \brief Encode an EC private key (raw DER format).1398*1399* This function encodes the provided key into the "raw" format specified1400* in RFC 5915 (type `ECPrivateKey`), with DER encoding rules.1401*1402* The private key is provided in `sk`, the public key being `pk`. If1403* `pk` is `NULL`, then the encoded key will not include the public key1404* in its `publicKey` field (which is nominally optional).1405*1406* If `dest` is not `NULL`, then the encoded key is written at that1407* address, and the encoded length (in bytes) is returned. If `dest` is1408* `NULL`, then nothing is written, but the encoded length is still1409* computed and returned.1410*1411* If the key cannot be encoded (e.g. because there is no known OBJECT1412* IDENTIFIER for the used curve), then 0 is returned.1413*1414* \param dest the destination buffer (or `NULL`).1415* \param sk the EC private key.1416* \param pk the EC public key (or `NULL`).1417* \return the encoded key length (in bytes), or 0.1418*/1419size_t br_encode_ec_raw_der(void *dest,1420const br_ec_private_key *sk, const br_ec_public_key *pk);14211422/**1423* \brief Encode an EC private key (PKCS#8 DER format).1424*1425* This function encodes the provided key into the PKCS#8 format1426* (RFC 5958, type `OneAsymmetricKey`). The curve is identified1427* by an OID provided as parameters to the `privateKeyAlgorithm`1428* field. The private key value (contents of the `privateKey` field)1429* contains the DER encoding of the `ECPrivateKey` type defined in1430* RFC 5915, without the `parameters` field (since they would be1431* redundant with the information in `privateKeyAlgorithm`).1432*1433* The private key is provided in `sk`, the public key being `pk`. If1434* `pk` is not `NULL`, then the encoded public key is included in the1435* `publicKey` field of the private key value (but not in the `publicKey`1436* field of the PKCS#8 `OneAsymmetricKey` wrapper).1437*1438* If `dest` is not `NULL`, then the encoded key is written at that1439* address, and the encoded length (in bytes) is returned. If `dest` is1440* `NULL`, then nothing is written, but the encoded length is still1441* computed and returned.1442*1443* If the key cannot be encoded (e.g. because there is no known OBJECT1444* IDENTIFIER for the used curve), then 0 is returned.1445*1446* \param dest the destination buffer (or `NULL`).1447* \param sk the EC private key.1448* \param pk the EC public key (or `NULL`).1449* \return the encoded key length (in bytes), or 0.1450*/1451size_t br_encode_ec_pkcs8_der(void *dest,1452const br_ec_private_key *sk, const br_ec_public_key *pk);14531454/**1455* \brief PEM banner for RSA private key (raw).1456*/1457#define BR_ENCODE_PEM_RSA_RAW "RSA PRIVATE KEY"14581459/**1460* \brief PEM banner for EC private key (raw).1461*/1462#define BR_ENCODE_PEM_EC_RAW "EC PRIVATE KEY"14631464/**1465* \brief PEM banner for an RSA or EC private key in PKCS#8 format.1466*/1467#define BR_ENCODE_PEM_PKCS8 "PRIVATE KEY"14681469#ifdef __cplusplus1470}1471#endif14721473#endif147414751476