initial commit
* The `bearsslsys` crate is basically usable at this point. * The `bearssl` crate itself needs a lot work before being usable. The design needs heavy iterations, considerationg and love.main
commit
eca97f9f0b

@ 0,0 +1,4 @@


[output]


quiet = false


deny = ["warnings"]


informational_warnings = ["unmaintained", "unsound"]


@ 0,0 +1,2 @@


/target


/Cargo.lock


@ 0,0 +1 @@


max_width = 125


@ 0,0 +1,5 @@


[workspace]


members = [


"bearssl",


"bearsslsys",


]


@ 0,0 +1,32 @@


# Credits




Here we list the how other projects were utilized and their licenses.




## BearSSL




* Version 0.6's source code is extracted to be compiled in `build.rs` without Make for bundled builds.


 The [source tarball](https://bearssl.org/bearssl0.6.tar.gz) had the BLAKE3 hash `a34ab02f58c4c5155fef33404b961fe6afc931acfc5fd0c04993f3a88ba6269d`.




```


Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>




Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the


"Software"), to deal in the Software without restriction, including


without limitation the rights to use, copy, modify, merge, publish,


distribute, sublicense, and/or sell copies of the Software, and to


permit persons to whom the Software is furnished to do so, subject to


the following conditions:




The above copyright notice and this permission notice shall be


included in all copies or substantial portions of the Software.




THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF


MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND


NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS


BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN


ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN


CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE


SOFTWARE.


```


@ 0,0 +1,24 @@


[package]


name = "bearsslsys"


description = "FFI bindings to BearSSL"


version = "0.0.5pre.0"


authors = ["Aydin Mercan <aydin@mercan.dev>"]


license = "BSD3Clause"


readme = "README.md"


keywords = ["bearssl", "tls"]


edition = "2021"


rustversion = "1.63"




[badges]


maintenance = { status = "activelydeveloped" }




[dependencies]


libc = "0.2.132"




[builddependencies]


bindgen = "0.60.1"


cc = { version = "1.0.73", optional = true }




[features]


bundled = ["dep:cc"]


dontassumesize_tequalsuintptr_t = []


@ 0,0 +1,11 @@


Copyright 2022 Aydin Mercan <aydin@mercan.dev>




Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:




1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.




2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.




3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.




THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


@ 0,0 +1,29 @@


# `bearsslsys`




Rust bindings for BearSSL.




## Version




Currently BearSSL 0.6 and latest Rust stable is supported.




## Features




* `bundled`: Build and link statically BearSSL. Needs a working C compiler and autoenables some sensible flags for the build target.


* `dontassumesize_tequalsuintptr_t`: Use libc's `size_t` instead of `usize`. Should only needed when `sizeof(uintptr_t) != sizeof(size_t)`.




## Misc.




Once `core::ffi` types are stable, the bindings can and should be


dependencyfree for platforms where `dontassumesize_tequalsuintptr_t`


isn't required.




## License




This repository is licensed under the BSD3Clause. Please refer to `LICENSE` and


`CREDITS.md` for more details.




### Contribution




Unless you explicitly state otherwise, any contribution intentionally submitted


for inclusion in the work by you shall be licensed as above, without any


additional terms or conditions.


@ 0,0 +1,103 @@


use std::env;


use std::path::PathBuf;




#[cfg(not(feature = "bundled"))]


static HEADER_PATH: &str = "wrapper.h";




#[cfg(feature = "bundled")]


static HEADER_PATH: &str = "bundled/inc/bearssl.h";




#[cfg(not(feature = "bundled"))]


fn bearssl_handle_linkage() {


#[cfg(not(unix))]


panic!("linking dynamically is currently supported in only unix targets");




println!("cargo:rustclinksearch=/lib");


println!("cargo:rustclinksearch=/usr/lib");


println!("cargo:rustclinksearch=/usr/local/lib");


println!("cargo:rustclinklib=dylib=bearssl");


}




#[cfg(feature = "bundled")]


#[cfg(target_arch = "x86_64")]


fn build_configure_arch_specific(build: &mut cc::Build) {


let compiler = build.get_compiler();




build.define("BR_64", "1");




if compiler.is_like_gnu()  compiler.is_like_clang() {


build.define("BR_INT128", "1");


} else if compiler.is_like_msvc() {


build.define("BR_UMUL128", "1");


}




#[cfg(target_feature = "sse2")]


build.define("BR_SSE2", "1");




#[cfg(target_feature = "aes")]


build.define("BR_AES_X86NI", "1");


}




#[cfg(feature = "bundled")]


#[cfg(not(target_arch = "x86_64"))]


fn build_configure_arch_specific(build: &mut cc::Build) {


#[cfg(target_pointer_width = 64)]


build.define("BR_64", "1");


}




#[cfg(feature = "bundled")]


#[cfg(unix)]


fn build_configure_os_specific(build: &mut cc::Build) {


build.define("BR_USE_UNIX_TIME", "1").define("BR_USE_URANDOM", "1");


}




#[cfg(feature = "bundled")]


#[cfg(windows)]


fn build_configure_os_specific(build: &mut cc::Build) {


build.define("BR_USE_WIN32_RAND", "1").define("BR_USE_WIN32_TIME", "1");


}




#[cfg(feature = "bundled")]


fn bearssl_handle_linkage() {


let mut build = cc::Build::new();




build_configure_os_specific(&mut build);


build_configure_arch_specific(&mut build);




build


.include("bundled/inc")


.files(


std::fs::read_dir("bundled/src")


.expect("failed to get bundled source path")


.map(e e.expect("failed to read get file entry").path()),


)


.static_flag(true)


.compile("bearssl");




println!("cargo:lib_dir={}", env::var("OUT_DIR").unwrap());


println!("cargo:rustclinklib=static=bearssl");


}




fn main() {


bearssl_handle_linkage();




let bindings = bindgen::builder()


.use_core()


.ctypes_prefix("::libc")


.header(HEADER_PATH)


.default_macro_constant_type(bindgen::MacroTypeVariation::Signed)


.parse_callbacks(Box::new(bindgen::CargoCallbacks))


.allowlist_type("(brBR)_.*")


.allowlist_var("(brBR)_.*")


.allowlist_function("(brBR)_.*")


.blocklist_type("__.*_t")


.blocklist_type("size_t")


.generate()


.expect("Unable to generate bindings");




let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());




bindings


.write_to_file(out_path.join("bindings.rs"))


.expect("Couldn't write bindings!");


}


@ 0,0 +1,170 @@


/*


* Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>


*


* Permission is hereby granted, free of charge, to any person obtaining


* a copy of this software and associated documentation files (the


* "Software"), to deal in the Software without restriction, including


* without limitation the rights to use, copy, modify, merge, publish,


* distribute, sublicense, and/or sell copies of the Software, and to


* permit persons to whom the Software is furnished to do so, subject to


* the following conditions:


*


* The above copyright notice and this permission notice shall be


* included in all copies or substantial portions of the Software.


*


* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF


* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND


* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS


* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN


* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN


* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE


* SOFTWARE.


*/




#ifndef BR_BEARSSL_H__


#define BR_BEARSSL_H__




#include <stddef.h>


#include <stdint.h>




/** \mainpage BearSSL API


*


* # API Layout


*


* The functions and structures defined by the BearSSL API are located


* in various header files:


*


*  Header file  Elements 


*  :  : 


*  bearssl_hash.h  Hash functions 


*  bearssl_hmac.h  HMAC 


*  bearssl_kdf.h  Key Derivation Functions 


*  bearssl_rand.h  Pseudorandom byte generators 


*  bearssl_prf.h  PRF implementations (for SSL/TLS) 


*  bearssl_block.h  Symmetric encryption 


*  bearssl_aead.h  AEAD algorithms (combined encryption + MAC) 


*  bearssl_rsa.h  RSA encryption and signatures 


*  bearssl_ec.h  Elliptic curves support (including ECDSA) 


*  bearssl_ssl.h  SSL/TLS engine interface 


*  bearssl_x509.h  X.509 certificate decoding and validation 


*  bearssl_pem.h  Base64/PEM decoding support functions 


*


* Applications using BearSSL are supposed to simply include `bearssl.h`


* as follows:


*


* #include <bearssl.h>


*


* The `bearssl.h` file itself includes all the other header files. It is


* possible to include specific header files, but it has no practical


* advantage for the application. The API is separated into separate


* header files only for documentation convenience.


*


*


* # Conventions


*


* ## MUST and SHALL


*


* In all descriptions, the usual "MUST", "SHALL", "MAY",... terminology


* is used. Failure to meet requirements expressed with a "MUST" or


* "SHALL" implies undefined behaviour, which means that segmentation


* faults, buffer overflows, and other similar adverse events, may occur.


*


* In general, BearSSL is not very forgiving of programming errors, and


* does not include much failsafes or error reporting when the problem


* does not arise from external transient conditions, and can be fixed


* only in the application code. This is done so in order to make the


* total code footprint lighter.


*


*


* ## `NULL` values


*


* Function parameters with a pointer type shall not be `NULL` unless


* explicitly authorised by the documentation. As an exception, when


* the pointer aims at a sequence of bytes and is accompanied with


* a length parameter, and the length is zero (meaning that there is


* no byte at all to retrieve), then the pointer may be `NULL` even if


* not explicitly allowed.


*


*


* ## Memory Allocation


*


* BearSSL does not perform dynamic memory allocation. This implies that


* for any functionality that requires a nontransient state, the caller


* is responsible for allocating the relevant context structure. Such


* allocation can be done in any appropriate area, including static data


* segments, the heap, and the stack, provided that proper alignment is


* respected. The header files define these context structures


* (including size and contents), so the C compiler should handle


* alignment automatically.


*


* Since there is no dynamic resource allocation, there is also nothing to


* release. When the calling code is done with a BearSSL feature, it


* may simple release the context structures it allocated itself, with


* no "close function" to call. If the context structures were allocated


* on the stack (as local variables), then even that release operation is


* implicit.


*


*


* ## Structure Contents


*


* Except when explicitly indicated, structure contents are opaque: they


* are included in the header files so that calling code may know the


* structure sizes and alignment requirements, but callers SHALL NOT


* access individual fields directly. For fields that are supposed to


* be read from or written to, the API defines accessor functions (the


* simplest of these accessor functions are defined as `static inline`


* functions, and the C compiler will optimise them away).


*


*


* # API Usage


*


* BearSSL usage for running a SSL/TLS client or server is described


* on the [BearSSL Web site](https://www.bearssl.org/api1.html). The


* BearSSL source archive also comes with sample code.


*/




#include "bearssl_hash.h"


#include "bearssl_hmac.h"


#include "bearssl_kdf.h"


#include "bearssl_rand.h"


#include "bearssl_prf.h"


#include "bearssl_block.h"


#include "bearssl_aead.h"


#include "bearssl_rsa.h"


#include "bearssl_ec.h"


#include "bearssl_ssl.h"


#include "bearssl_x509.h"


#include "bearssl_pem.h"




/** \brief Type for a configuration option.


*


* A "configuration option" is a value that is selected when the BearSSL


* library itself is compiled. Most options are boolean; their value is


* then either 1 (option is enabled) or 0 (option is disabled). Some


* values have other integer values. Option names correspond to macro


* names. Some of the options can be explicitly set in the internal


* `"config.h"` file.


*/


typedef struct {


/** \brief Configurable option name. */


const char *name;


/** \brief Configurable option value. */


long value;


} br_config_option;




/** \brief Get configuration report.


*


* This function returns compiled configuration options, each as a


* 'long' value. Names match internal macro names, in particular those


* that can be set in the `"config.h"` inner file. For boolean options,


* the numerical value is 1 if enabled, 0 if disabled. For maximum


* key sizes, values are expressed in bits.


*


* The returned array is terminated by an entry whose `name` is `NULL`.


*


* \return the configuration report.


*/


const br_config_option *br_get_config(void);




#endif

File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff

@ 0,0 +1,883 @@


/*


* Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>


*


* Permission is hereby granted, free of charge, to any person obtaining


* a copy of this software and associated documentation files (the


* "Software"), to deal in the Software without restriction, including


* without limitation the rights to use, copy, modify, merge, publish,


* distribute, sublicense, and/or sell copies of the Software, and to


* permit persons to whom the Software is furnished to do so, subject to


* the following conditions:


*


* The above copyright notice and this permission notice shall be


* included in all copies or substantial portions of the Software.


*


* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF


* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND


* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS


* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN


* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN


* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE


* SOFTWARE.


*/




#ifndef BR_BEARSSL_EC_H__


#define BR_BEARSSL_EC_H__




#include <stddef.h>


#include <stdint.h>




#include "bearssl_rand.h"




#ifdef __cplusplus


extern "C" {


#endif




/** \file bearssl_ec.h


*


* # Elliptic Curves


*


* This file documents the EC implementations provided with BearSSL, and


* ECDSA.


*


* ## Elliptic Curve API


*


* Only "named curves" are supported. Each EC implementation supports


* one or several named curves, identified by symbolic identifiers.


* These identifiers are small integers, that correspond to the values


* registered by the


* [IANA](http://www.iana.org/assignments/tlsparameters/tlsparameters.xhtml#tlsparameters8).


*


* Since all currently defined elliptic curve identifiers are in the 0..31


* range, it is convenient to encode support of some curves in a 32bit


* word, such that bit x corresponds to curve of identifier x.


*


* An EC implementation is incarnated by a `br_ec_impl` instance, that


* offers the following fields:


*


*  `supported_curves`


*


* A 32bit word that documents the identifiers of the curves supported


* by this implementation.


*


*  `generator()`


*


* Callback method that returns a pointer to the conventional generator


* point for that curve.


*


*  `order()`


*


* Callback method that returns a pointer to the subgroup order for


* that curve. That value uses unsigned bigendian encoding.


*


*  `xoff()`


*


* Callback method that returns the offset and length of the X


* coordinate in an encoded point.


*


*  `mul()`


*


* Multiply a curve point with an integer.


*


*  `mulgen()`


*


* Multiply the curve generator with an integer. This may be faster


* than the generic `mul()`.


*


*  `muladd()`


*


* Multiply two curve points by two integers, and return the sum of


* the two products.


*


* All curve points are represented in uncompressed format. The `mul()`


* and `muladd()` methods take care to validate that the provided points


* are really part of the relevant curve subgroup.


*


* For all point multiplication functions, the following holds:


*


*  Functions validate that the provided points are valid members


* of the relevant curve subgroup. An error is reported if that is


* not the case.


*


*  Processing is constanttime, even if the point operands are not


* valid. This holds for both the source and resulting points, and


* the multipliers (integers). Only the byte length of the provided


* multiplier arrays (not their actual value length in bits) may


* leak through timingbased side channels.


*


*  The multipliers (integers) MUST be lower than the subgroup order.


* If this property is not met, then the result is indeterminate,


* but an error value is not ncessearily returned.


*


*


* ## ECDSA


*


* ECDSA signatures have two standard formats, called "raw" and "asn1".


* Internally, such a signature is a pair of modular integers `(r,s)`.


* The "raw" format is the concatenation of the unsigned bigendian


* encodings of these two integers, possibly leftpadded with zeros so


* that they have the same encoded length. The "asn1" format is the


* DER encoding of an ASN.1 structure that contains the two integer


* values:


*


* ECDSASignature ::= SEQUENCE {


* r INTEGER,


* s INTEGER


* }


*


* In general, in all of X.509 and SSL/TLS, the "asn1" format is used.


* BearSSL offers ECDSA implementations for both formats; conversion


* functions between the two formats are also provided. Conversion of a


* "raw" format signature into "asn1" may enlarge a signature by no more


* than 9 bytes for all supported curves; conversely, conversion of an


* "asn1" signature to "raw" may expand the signature but the "raw"


* length will never be more than twice the length of the "asn1" length


* (and usually it will be shorter).


*


* Note that for a given signature, the "raw" format is not fully


* deterministic, in that it does not enforce a minimal common length.


*/




/*


* Standard curve ID. These ID are equal to the assigned numerical


* identifiers assigned to these curves for TLS:


* http://www.iana.org/assignments/tlsparameters/tlsparameters.xhtml#tlsparameters8


*/




/** \brief Identifier for named curve sect163k1. */


#define BR_EC_sect163k1 1




/** \brief Identifier for named curve sect163r1. */


#define BR_EC_sect163r1 2




/** \brief Identifier for named curve sect163r2. */


#define BR_EC_sect163r2 3




/** \brief Identifier for named curve sect193r1. */


#define BR_EC_sect193r1 4




/** \brief Identifier for named curve sect193r2. */


#define BR_EC_sect193r2 5




/** \brief Identifier for named curve sect233k1. */


#define BR_EC_sect233k1 6




/** \brief Identifier for named curve sect233r1. */


#define BR_EC_sect233r1 7




/** \brief Identifier for named curve sect239k1. */


#define BR_EC_sect239k1 8




/** \brief Identifier for named curve sect283k1. */


#define BR_EC_sect283k1 9




/** \brief Identifier for named curve sect283r1. */


#define BR_EC_sect283r1 10




/** \brief Identifier for named curve sect409k1. */


#define BR_EC_sect409k1 11




/** \brief Identifier for named curve sect409r1. */


#define BR_EC_sect409r1 12




/** \brief Identifier for named curve sect571k1. */


#define BR_EC_sect571k1 13




/** \brief Identifier for named curve sect571r1. */


#define BR_EC_sect571r1 14




/** \brief Identifier for named curve secp160k1. */


#define BR_EC_secp160k1 15




/** \brief Identifier for named curve secp160r1. */


#define BR_EC_secp160r1 16




/** \brief Identifier for named curve secp160r2. */


#define BR_EC_secp160r2 17




/** \brief Identifier for named curve secp192k1. */


#define BR_EC_secp192k1 18




/** \brief Identifier for named curve secp192r1. */


#define BR_EC_secp192r1 19




/** \brief Identifier for named curve secp224k1. */


#define BR_EC_secp224k1 20




/** \brief Identifier for named curve secp224r1. */


#define BR_EC_secp224r1 21




/** \brief Identifier for named curve secp256k1. */


#define BR_EC_secp256k1 22




/** \brief Identifier for named curve secp256r1. */


#define BR_EC_secp256r1 23




/** \brief Identifier for named curve secp384r1. */


#define BR_EC_secp384r1 24




/** \brief Identifier for named curve secp521r1. */


#define BR_EC_secp521r1 25




/** \brief Identifier for named curve brainpoolP256r1. */


#define BR_EC_brainpoolP256r1 26




/** \brief Identifier for named curve brainpoolP384r1. */


#define BR_EC_brainpoolP384r1 27




/** \brief Identifier for named curve brainpoolP512r1. */


#define BR_EC_brainpoolP512r1 28




/** \brief Identifier for named curve Curve25519. */


#define BR_EC_curve25519 29




/** \brief Identifier for named curve Curve448. */


#define BR_EC_curve448 30




/**


* \brief Structure for an EC public key.


*/


typedef struct {


/** \brief Identifier for the curve used by this key. */


int curve;


/** \brief Public curve point (uncompressed format). */


unsigned char *q;


/** \brief Length of public curve point (in bytes). */


size_t qlen;


} br_ec_public_key;




/**


* \brief Structure for an EC private key.


*


* The private key is an integer modulo the curve subgroup order. The


* encoding below tolerates extra leading zeros. In general, it is


* recommended that the private key has the same length as the curve


* subgroup order.


*/


typedef struct {


/** \brief Identifier for the curve used by this key. */


int curve;


/** \brief Private key (integer, unsigned bigendian encoding). */


unsigned char *x;


/** \brief Private key length (in bytes). */


size_t xlen;


} br_ec_private_key;




/**


* \brief Type for an EC implementation.


*/


typedef struct {


/**


* \brief Supported curves.


*


* This word is a bitfield: bit `x` is set if the curve of ID `x`


* is supported. E.g. an implementation supporting both NIST P256


* (secp256r1, ID 23) and NIST P384 (secp384r1, ID 24) will have


* value `0x01800000` in this field.


*/


uint32_t supported_curves;




/**


* \brief Get the conventional generator.


*


* This function returns the conventional generator (encoded


* curve point) for the specified curve. This function MUST NOT


* be called if the curve is not supported.


*


* \param curve curve identifier.


* \param len receiver for the encoded generator length (in bytes).


* \return the encoded generator.


*/


const unsigned char *(*generator)(int curve, size_t *len);




/**


* \brief Get the subgroup order.


*


* This function returns the order of the subgroup generated by


* the conventional generator, for the specified curve. Unsigned


* bigendian encoding is used. This function MUST NOT be called


* if the curve is not supported.


*


* \param curve curve identifier.


* \param len receiver for the encoded order length (in bytes).


* \return the encoded order.


*/


const unsigned char *(*order)(int curve, size_t *len);




/**


* \brief Get the offset and length for the X coordinate.


*


* This function returns the offset and length (in bytes) of


* the X coordinate in an encoded nonzero point.


*


* \param curve curve identifier.


* \param len receiver for the X coordinate length (in bytes).


* \return the offset for the X coordinate (in bytes).


*/


size_t (*xoff)(int curve, size_t *len);




/**


* \brief Multiply a curve point by an integer.


*


* The source point is provided in array `G` (of size `Glen` bytes);


* the multiplication result is written over it. The multiplier


* `x` (of size `xlen` bytes) uses unsigned bigendian encoding.


*


* Rules:


*


*  The specified curve MUST be supported.


*


*  The source point must be a valid point on the relevant curve


* subgroup (and not the "point at infinity" either). If this is


* not the case, then this function returns an error (0).


*


*  The multiplier integer MUST be nonzero and less than the


* curve subgroup order. If this property does not hold, then


* the result is indeterminate and an error code is not


* guaranteed.


*


* Returned value is 1 on success, 0 on error. On error, the


* contents of `G` are indeterminate.


*


* \param G point to multiply.


* \param Glen length of the encoded point (in bytes).


* \param x multiplier (unsigned bigendian).


* \param xlen multiplier length (in bytes).


* \param curve curve identifier.


* \return 1 on success, 0 on error.


*/


uint32_t (*mul)(unsigned char *G, size_t Glen,


const unsigned char *x, size_t xlen, int curve);




/**


* \brief Multiply the generator by an integer.


*


* The multiplier MUST be nonzero and less than the curve


* subgroup order. Results are indeterminate if this property


* does not hold.


*


* \param R output buffer for the point.


* \param x multiplier (unsigned bigendian).


* \param xlen multiplier length (in bytes).


* \param curve curve identifier.


* \return encoded result point length (in bytes).


*/


size_t (*mulgen)(unsigned char *R,


const unsigned char *x, size_t xlen, int curve);




/**


* \brief Multiply two points by two integers and add the


* results.


*


* The point `x*A + y*B` is computed and written back in the `A`


* array.


*


* Rules:


*


*  The specified curve MUST be supported.


*


*  The source points (`A` and `B`) must be valid points on


* the relevant curve subgroup (and not the "point at


* infinity" either). If this is not the case, then this


* function returns an error (0).


*


*  If the `B` pointer is `NULL`, then the conventional


* subgroup generator is used. With some implementations,


* this may be faster than providing a pointer to the


* generator.


*


*  The multiplier integers (`x` and `y`) MUST be nonzero


* and less than the curve subgroup order. If either integer


* is zero, then an error is reported, but if one of them is


* not lower than the subgroup order, then the result is


* indeterminate and an error code is not guaranteed.


*


*  If the final result is the point at infinity, then an


* error is returned.


*


* Returned value is 1 on success, 0 on error. On error, the


* contents of `A` are indeterminate.


*


* \param A first point to multiply.


* \param B second point to multiply (`NULL` for the generator).


* \param len common length of the encoded points (in bytes).


* \param x multiplier for `A` (unsigned bigendian).


* \param xlen length of multiplier for `A` (in bytes).


* \param y multiplier for `A` (unsigned bigendian).


* \param ylen length of multiplier for `A` (in bytes).


* \param curve curve identifier.


* \return 1 on success, 0 on error.


*/


uint32_t (*muladd)(unsigned char *A, const unsigned char *B, size_t len,


const unsigned char *x, size_t xlen,


const unsigned char *y, size_t ylen, int curve);


} br_ec_impl;




/**


* \brief EC implementation "i31".


*


* This implementation internally uses generic code for modular integers,


* with a representation as sequences of 31bit words. It supports secp256r1,


* secp384r1 and secp521r1 (aka NIST curves P256, P384 and P521).


*/


extern const br_ec_impl br_ec_prime_i31;




/**


* \brief EC implementation "i15".


*


* This implementation internally uses generic code for modular integers,


* with a representation as sequences of 15bit words. It supports secp256r1,


* secp384r1 and secp521r1 (aka NIST curves P256, P384 and P521).


*/


extern const br_ec_impl br_ec_prime_i15;




/**


* \brief EC implementation "m15" for P256.


*


* This implementation uses specialised code for curve secp256r1 (also


* known as NIST P256), with optional Karatsuba decomposition, and fast


* modular reduction thanks to the field modulus special format. Only


* 32bit multiplications are used (with 32bit results, not 64bit).


*/


extern const br_ec_impl br_ec_p256_m15;




/**


* \brief EC implementation "m31" for P256.


*


* This implementation uses specialised code for curve secp256r1 (also


* known as NIST P256), relying on multiplications of 31bit values


* (MUL31).


*/


extern const br_ec_impl br_ec_p256_m31;




/**


* \brief EC implementation "i15" (generic code) for Curve25519.


*


* This implementation uses the generic code for modular integers (with


* 15bit words) to support Curve25519. Due to the specificities of the


* curve definition, the following applies:


*


*  `muladd()` is not implemented (the function returns 0 systematically).


*  `order()` returns 2^2551, since the point multiplication algorithm


* accepts any 32bit integer as input (it clears the top bit and low


* three bits systematically).


*/


extern const br_ec_impl br_ec_c25519_i15;




/**


* \brief EC implementation "i31" (generic code) for Curve25519.


*


* This implementation uses the generic code for modular integers (with


* 31bit words) to support Curve25519. Due to the specificities of the


* curve definition, the following applies:


*


*  `muladd()` is not implemented (the function returns 0 systematically).


*  `order()` returns 2^2551, since the point multiplication algorithm


* accepts any 32bit integer as input (it clears the top bit and low


* three bits systematically).


*/


extern const br_ec_impl br_ec_c25519_i31;




/**


* \brief EC implementation "m15" (specialised code) for Curve25519.


*


* This implementation uses custom code relying on multiplication of


* integers up to 15 bits. Due to the specificities of the curve


* definition, the following applies:


*


*  `muladd()` is not implemented (the function returns 0 systematically).


*  `order()` returns 2^2551, since the point multiplication algorithm


* accepts any 32bit integer as input (it clears the top bit and low


* three bits systematically).


*/


extern const br_ec_impl br_ec_c25519_m15;




/**


* \brief EC implementation "m31" (specialised code) for Curve25519.


*


* This implementation uses custom code relying on multiplication of


* integers up to 31 bits. Due to the specificities of the curve


* definition, the following applies:


*


*  `muladd()` is not implemented (the function returns 0 systematically).


*  `order()` returns 2^2551, since the point multiplication algorithm


* accepts any 32bit integer as input (it clears the top bit and low


* three bits systematically).


*/


extern const br_ec_impl br_ec_c25519_m31;




/**


* \brief Aggregate EC implementation "m15".


*


* This implementation is a wrapper for:


*


*  `br_ec_c25519_m15` for Curve25519


*  `br_ec_p256_m15` for NIST P256


*  `br_ec_prime_i15` for other curves (NIST P384 and NISTP512)


*/


extern const br_ec_impl br_ec_all_m15;




/**


* \brief Aggregate EC implementation "m31".


*


* This implementation is a wrapper for:


*


*  `br_ec_c25519_m31` for Curve25519


*  `br_ec_p256_m31` for NIST P256


*  `br_ec_prime_i31` for other curves (NIST P384 and NISTP512)


*/


extern const br_ec_impl br_ec_all_m31;




/**


* \brief Get the "default" EC implementation for the current system.


*


* This returns a pointer to the preferred implementation on the


* current system.


*


* \return the default EC implementation.


*/


const br_ec_impl *br_ec_get_default(void);




/**


* \brief Convert a signature from "raw" to "asn1".


*


* Conversion is done "in place" and the new length is returned.


* Conversion may enlarge the signature, but by no more than 9 bytes at


* most. On error, 0 is returned (error conditions include an odd raw


* signature length, or an oversized integer).


*


* \param sig signature to convert.


* \param sig_len signature length (in bytes).


* \return the new signature length, or 0 on error.


*/


size_t br_ecdsa_raw_to_asn1(void *sig, size_t sig_len);




/**


* \brief Convert a signature from "asn1" to "raw".


*


* Conversion is done "in place" and the new length is returned.


* Conversion may enlarge the signature, but the new signature length


* will be less than twice the source length at most. On error, 0 is


* returned (error conditions include an invalid ASN.1 structure or an


* oversized integer).


*


* \param sig signature to convert.


* \param sig_len signature length (in bytes).


* \return the new signature length, or 0 on error.


*/


size_t br_ecdsa_asn1_to_raw(void *sig, size_t sig_len);




/**


* \brief Type for an ECDSA signer function.


*


* A pointer to the EC implementation is provided. The hash value is


* assumed to have the length inferred from the designated hash function


* class.


*


* Signature is written in the buffer pointed to by `sig`, and the length


* (in bytes) is returned. On error, nothing is written in the buffer,


* and 0 is returned. This function returns 0 if the specified curve is


* not supported by the provided EC implementation.


*


* The signature format is either "raw" or "asn1", depending on the


* implementation; maximum length is predictable from the implemented


* curve:


*


*  curve  raw  asn1 


*  :  :  : 


*  NIST P256  64  72 


*  NIST P384  96  104 


*  NIST P521  132  139 


*


* \param impl EC implementation to use.


* \param hf hash function used to process the data.


* \param hash_value signed data (hashed).


* \param sk EC private key.


* \param sig destination buffer.


* \return the signature length (in bytes), or 0 on error.


*/


typedef size_t (*br_ecdsa_sign)(const br_ec_impl *impl,


const br_hash_class *hf, const void *hash_value,


const br_ec_private_key *sk, void *sig);




/**


* \brief Type for an ECDSA signature verification function.


*


* A pointer to the EC implementation is provided. The hashed value,


* computed over the purportedly signed data, is also provided with


* its length.


*


* The signature format is either "raw" or "asn1", depending on the


* implementation.


*


* Returned value is 1 on success (valid signature), 0 on error. This


* function returns 0 if the specified curve is not supported by the


* provided EC implementation.


*


* \param impl EC implementation to use.


* \param hash signed data (hashed).


* \param hash_len hash value length (in bytes).


* \param pk EC public key.


* \param sig signature.


* \param sig_len signature length (in bytes).


* \return 1 on success, 0 on error.


*/


typedef 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);




/**


* \brief ECDSA signature generator, "i31" implementation, "asn1" format.


*


* \see br_ecdsa_sign()


*


* \param impl EC implementation to use.


* \param hf hash function used to process the data.


* \param hash_value signed data (hashed).


* \param sk EC private key.


* \param sig destination buffer.


* \return the signature length (in bytes), or 0 on error.


*/


size_t br_ecdsa_i31_sign_asn1(const br_ec_impl *impl,


const br_hash_class *hf, const void *hash_value,


const br_ec_private_key *sk, void *sig);




/**


* \brief ECDSA signature generator, "i31" implementation, "raw" format.


*


* \see br_ecdsa_sign()


*


* \param impl EC implementation to use.


* \param hf hash function used to process the data.


* \param hash_value signed data (hashed).


* \param sk EC private key.


* \param sig destination buffer.


* \return the signature length (in bytes), or 0 on error.


*/


size_t br_ecdsa_i31_sign_raw(const br_ec_impl *impl,


const br_hash_class *hf, const void *hash_value,


const br_ec_private_key *sk, void *sig);




/**


* \brief ECDSA signature verifier, "i31" implementation, "asn1" format.


*


* \see br_ecdsa_vrfy()


*


* \param impl EC implementation to use.


* \param hash signed data (hashed).


* \param hash_len hash value length (in bytes).


* \param pk EC public key.


* \param sig signature.


* \param sig_len signature length (in bytes).


* \return 1 on success, 0 on error.


*/


uint32_t br_ecdsa_i31_vrfy_asn1(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);




/**


* \brief ECDSA signature verifier, "i31" implementation, "raw" format.


*


* \see br_ecdsa_vrfy()


*


* \param impl EC implementation to use.


* \param hash signed data (hashed).


* \param hash_len hash value length (in bytes).


* \param pk EC public key.


* \param sig signature.


* \param sig_len signature length (in bytes).


* \return 1 on success, 0 on error.


*/


uint32_t br_ecdsa_i31_vrfy_raw(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);




/**


* \brief ECDSA signature generator, "i15" implementation, "asn1" format.


*


* \see br_ecdsa_sign()


*


* \param impl EC implementation to use.


* \param hf hash function used to process the data.


* \param hash_value signed data (hashed).


* \param sk EC private key.


* \param sig destination buffer.


* \return the signature length (in bytes), or 0 on error.


*/


size_t br_ecdsa_i15_sign_asn1(const br_ec_impl *impl,


const br_hash_class *hf, const void *hash_value,


const br_ec_private_key *sk, void *sig);




/**


* \brief ECDSA signature generator, "i15" implementation, "raw" format.


*


* \see br_ecdsa_sign()


*


* \param impl EC implementation to use.


* \param hf hash function used to process the data.


* \param hash_value signed data (hashed).


* \param sk EC private key.


* \param sig destination buffer.


* \return the signature length (in bytes), or 0 on error.


*/


size_t br_ecdsa_i15_sign_raw(const br_ec_impl *impl,


const br_hash_class *hf, const void *hash_value,


const br_ec_private_key *sk, void *sig);




/**


* \brief ECDSA signature verifier, "i15" implementation, "asn1" format.


*


* \see br_ecdsa_vrfy()


*


* \param impl EC implementation to use.


* \param hash signed data (hashed).


* \param hash_len hash value length (in bytes).


* \param pk EC public key.


* \param sig signature.


* \param sig_len signature length (in bytes).


* \return 1 on success, 0 on error.


*/


uint32_t br_ecdsa_i15_vrfy_asn1(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);




/**


* \brief ECDSA signature verifier, "i15" implementation, "raw" format.


*


* \see br_ecdsa_vrfy()


*


* \param impl EC implementation to use.


* \param hash signed data (hashed).


* \param hash_len hash value length (in bytes).


* \param pk EC public key.


* \param sig signature.


* \param sig_len signature length (in bytes).


* \return 1 on success, 0 on error.


*/


uint32_t br_ecdsa_i15_vrfy_raw(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);




/**


* \brief Get "default" ECDSA implementation (signer, asn1 format).


*


* This returns the preferred implementation of ECDSA signature generation


* ("asn1" output format) on the current system.


*


* \return the default implementation.


*/


br_ecdsa_sign br_ecdsa_sign_asn1_get_default(void);




/**


* \brief Get "default" ECDSA implementation (signer, raw format).


*


* This returns the preferred implementation of ECDSA signature generation


* ("raw" output format) on the current system.


*


* \return the default implementation.


*/


br_ecdsa_sign br_ecdsa_sign_raw_get_default(void);




/**


* \brief Get "default" ECDSA implementation (verifier, asn1 format).


*


* This returns the preferred implementation of ECDSA signature verification


* ("asn1" output format) on the current system.


*


* \return the default implementation.


*/


br_ecdsa_vrfy br_ecdsa_vrfy_asn1_get_default(void);




/**


* \brief Get "default" ECDSA implementation (verifier, raw format).


*


* This returns the preferred implementation of ECDSA signature verification


* ("raw" output format) on the current system.


*


* \return the default implementation.


*/


br_ecdsa_vrfy br_ecdsa_vrfy_raw_get_default(void);




/**


* \brief Maximum size for EC private key element buffer.


*


* This is the largest number of bytes that `br_ec_keygen()` may need or


* ever return.


*/


#define BR_EC_KBUF_PRIV_MAX_SIZE 72




/**


* \brief Maximum size for EC public key element buffer.


*


* This is the largest number of bytes that `br_ec_compute_public()` may


* need or ever return.


*/


#define BR_EC_KBUF_PUB_MAX_SIZE 145




/**


* \brief Generate a new EC private key.


*


* If the specified `curve` is not supported by the elliptic curve


* implementation (`impl`), then this function returns zero.


*


* The `sk` structure fields are set to the new private key data. In


* particular, `sk.x` is made to point to the provided key buffer (`kbuf`),


* in which the actual private key data is written. That buffer is assumed


* to be large enough. The `BR_EC_KBUF_PRIV_MAX_SIZE` defines the maximum


* size for all supported curves.


*


* The number of bytes used in `kbuf` is returned. If `kbuf` is `NULL`, then


* the private key is not actually generated, and `sk` may also be `NULL`;


* the minimum length for `kbuf` is still computed and returned.


*


* If `sk` is `NULL` but `kbuf` is not `NULL`, then the private key is


* still generated and stored in `kbuf`.


*


* \param rng_ctx source PRNG context (already initialized).


* \param impl the elliptic curve implementation.


* \param sk the private key structure to fill, or `NULL`.


* \param kbuf the key element buffer, or `NULL`.


* \param curve the curve identifier.


* \return the key data length (in bytes), or zero.


*/


size_t br_ec_keygen(const br_prng_class **rng_ctx,


const br_ec_impl *impl, br_ec_private_key *sk,


void *kbuf, int curve);




/**


* \brief Compute EC public key from EC private key.


*


* This function uses the provided elliptic curve implementation (`impl`)


* to compute the public key corresponding to the private key held in `sk`.


* The public key point is written into `kbuf`, which is then linked from


* the `*pk` structure. The size of the public key point, i.e. the number


* of bytes used in `kbuf`, is returned.


*


* If `kbuf` is `NULL`, then the public key point is NOT computed, and


* the public key structure `*pk` is unmodified (`pk` may be `NULL` in


* that case). The size of the public key point is still returned.


*


* If `pk` is `NULL` but `kbuf` is not `NULL`, then the public key


* point is computed and stored in `kbuf`, and its size is returned.


*


* If the curve used by the private key is not supported by the curve


* implementation, then this function returns zero.


*


* The private key MUST be valid. An offrange private key value is not


* necessarily detected, and leads to unpredictable results.


*


* \param impl the elliptic curve implementation.


* \param pk the public key structure to fill (or `NULL`).


* \param kbuf the public key point buffer (or `NULL`).


* \param sk the source private key.


* \return the public key point length (in bytes), or zero.


*/


size_t br_ec_compute_pub(const br_ec_impl *impl, br_ec_public_key *pk,


void *kbuf, const br_ec_private_key *sk);




#ifdef __cplusplus


}


#endif




#endif

File diff suppressed because it is too large
Load Diff

@ 0,0 +1,241 @@


/*


* Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>


*


* Permission is hereby granted, free of charge, to any person obtaining


* a copy of this software and associated documentation files (the


* "Software"), to deal in the Software without restriction, including


* without limitation the rights to use, copy, modify, merge, publish,


* distribute, sublicense, and/or sell copies of the Software, and to


* permit persons to whom the Software is furnished to do so, subject to


* the following conditions:


*


* The above copyright notice and this permission notice shall be


* included in all copies or substantial portions of the Software.


*


* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF


* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND


* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS


* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN


* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN


* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE


* SOFTWARE.


*/




#ifndef BR_BEARSSL_HMAC_H__


#define BR_BEARSSL_HMAC_H__




#include <stddef.h>


#include <stdint.h>




#include "bearssl_hash.h"




#ifdef __cplusplus


extern "C" {


#endif




/** \file bearssl_hmac.h


*


* # HMAC


*


* HMAC is initialized with a key and an underlying hash function; it


* then fills a "key context". That context contains the processed


* key.


*


* With the key context, a HMAC context can be initialized to process


* the input bytes and obtain the MAC output. The key context is not


* modified during that process, and can be reused.


*


* IMPORTANT: HMAC shall be used only with functions that have the


* following properties:


*


*  hash output size does not exceed 64 bytes;


*  hash internal state size does not exceed 64 bytes;


*  internal block length is a power of 2 between 16 and 256 bytes.


*/




/**


* \brief HMAC key context.


*


* The HMAC key context is initialised with a hash function implementation


* and a secret key. Contents are opaque (callers should not access them


* directly). The caller is responsible for allocating the context where


* appropriate. Context initialisation and usage incurs no dynamic


* allocation, so there is no release function.


*/


typedef struct {


#ifndef BR_DOXYGEN_IGNORE


const br_hash_class *dig_vtable;


unsigned char ksi[64], kso[64];


#endif


} br_hmac_key_context;




/**


* \brief HMAC key context initialisation.


*


* Initialise the key context with the provided key, using the hash function


* identified by `digest_vtable`. This supports arbitrary key lengths.


*


* \param kc HMAC key context to initialise.


* \param digest_vtable pointer to the hash function implementation vtable.


* \param key pointer to the HMAC secret key.


* \param key_len HMAC secret key length (in bytes).


*/


void br_hmac_key_init(br_hmac_key_context *kc,


const br_hash_class *digest_vtable, const void *key, size_t key_len);




/*


* \brief Get the underlying hash function.


*


* This function returns a pointer to the implementation vtable of the


* hash function used for this HMAC key context.


*


* \param kc HMAC key context.


* \return the hash function implementation.


*/


static inline const br_hash_class *br_hmac_key_get_digest(


const br_hmac_key_context *kc)


{


return kc>dig_vtable;


}




/**


* \brief HMAC computation context.


*


* The HMAC computation context maintains the state for a single HMAC


* computation. It is modified as input bytes are injected. The context


* is callerallocated and has no release function since it does not


* dynamically allocate external resources. Its contents are opaque.


*/


typedef struct {


#ifndef BR_DOXYGEN_IGNORE


br_hash_compat_context dig;


unsigned char kso[64] 