/*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 BRSSL_H__25#define BRSSL_H__2627#ifndef _STANDALONE28#include <stdio.h>29#include <stdlib.h>30#include <string.h>31#include <stdint.h>3233#elif !defined(STAND_H)34#include <stand.h>35#endif3637#include "bearssl.h"3839/*40* malloc() wrapper:41* -- If len is 0, then NULL is returned.42* -- If len is non-zero, and allocation fails, then an error message is43* printed and the process exits with an error code.44*/45void *xmalloc(size_t len);4647/*48* free() wrapper, meant to release blocks allocated with xmalloc().49*/50void xfree(void *buf);5152/*53* Duplicate a character string into a newly allocated block.54*/55char *xstrdup(const void *src);5657/*58* Allocate a new block with the provided length, filled with a copy59* of exactly that many bytes starting at address 'src'.60*/61void *xblobdup(const void *src, size_t len);6263/*64* Duplicate a public key, into newly allocated blocks. The returned65* key must be later on released with xfreepkey().66*/67br_x509_pkey *xpkeydup(const br_x509_pkey *pk);6869/*70* Release a public key that was allocated with xpkeydup(). If pk is NULL,71* this function does nothing.72*/73void xfreepkey(br_x509_pkey *pk);7475/*76* Macros for growable arrays.77*/7879/*80* Make a structure type for a vector of 'type'.81*/82#define VECTOR(type) struct { \83type *buf; \84size_t ptr, len; \85}8687/*88* Constant initialiser for a vector.89*/90#define VEC_INIT { 0, 0, 0 }9192/*93* Clear a vector.94*/95#define VEC_CLEAR(vec) do { \96xfree((vec).buf); \97(vec).buf = NULL; \98(vec).ptr = 0; \99(vec).len = 0; \100} while (0)101102/*103* Clear a vector, first calling the provided function on each vector104* element.105*/106#define VEC_CLEAREXT(vec, fun) do { \107size_t vec_tmp; \108for (vec_tmp = 0; vec_tmp < (vec).ptr; vec_tmp ++) { \109(fun)(&(vec).buf[vec_tmp]); \110} \111VEC_CLEAR(vec); \112} while (0)113114/*115* Add a value at the end of a vector.116*/117#define VEC_ADD(vec, x) do { \118(vec).buf = vector_expand((vec).buf, sizeof *((vec).buf), \119&(vec).ptr, &(vec).len, 1); \120(vec).buf[(vec).ptr ++] = (x); \121} while (0)122123/*124* Add several values at the end of a vector.125*/126#define VEC_ADDMANY(vec, xp, num) do { \127size_t vec_num = (num); \128(vec).buf = vector_expand((vec).buf, sizeof *((vec).buf), \129&(vec).ptr, &(vec).len, vec_num); \130memcpy((vec).buf + (vec).ptr, \131(xp), vec_num * sizeof *((vec).buf)); \132(vec).ptr += vec_num; \133} while (0)134135/*136* Access a vector element by index. This is a lvalue, and can be modified.137*/138#define VEC_ELT(vec, idx) ((vec).buf[idx])139140/*141* Get current vector length.142*/143#define VEC_LEN(vec) ((vec).ptr)144145/*146* Copy all vector elements into a newly allocated block.147*/148#define VEC_TOARRAY(vec) xblobdup((vec).buf, sizeof *((vec).buf) * (vec).ptr)149150/*151* Internal function used to handle memory allocations for vectors.152*/153void *vector_expand(void *buf,154size_t esize, size_t *ptr, size_t *len, size_t extra);155156/*157* Type for a vector of bytes.158*/159typedef VECTOR(unsigned char) bvector;160161/*162* Compare two strings for equality; returned value is 1 if the strings163* are to be considered equal, 0 otherwise. Comparison is case-insensitive164* (ASCII letters only) and skips some characters (all whitespace, defined165* as ASCII codes 0 to 32 inclusive, and also '-', '_', '.', '/', '+' and166* ':').167*/168int eqstr(const char *s1, const char *s2);169170/*171* Convert a string to a positive integer (size_t). Returned value is172* (size_t)-1 on error. On error, an explicit error message is printed.173*/174size_t parse_size(const char *s);175176/*177* Structure for a known protocol version.178*/179typedef struct {180const char *name;181unsigned version;182const char *comment;183} protocol_version;184185/*186* Known protocol versions. Last element has a NULL name.187*/188extern const protocol_version protocol_versions[];189190/*191* Parse a version name. If the name is not recognized, then an error192* message is printed, and 0 is returned.193*/194unsigned parse_version(const char *name, size_t len);195196/*197* Type for a known hash function.198*/199typedef struct {200const char *name;201const br_hash_class *hclass;202const char *comment;203} hash_function;204205/*206* Known hash functions. Last element has a NULL name.207*/208extern const hash_function hash_functions[];209210/*211* Parse hash function names. This function expects a comma-separated212* list of names, and returns a bit mask corresponding to the matched213* names. If one of the name does not match, or the list is empty, then214* an error message is printed, and 0 is returned.215*/216unsigned parse_hash_functions(const char *arg);217218/*219* Get a curve name (by ID). If the curve ID is not known, this returns220* NULL.221*/222const char *get_curve_name(int id);223224/*225* Get a curve name (by ID). The name is written in the provided buffer226* (zero-terminated). If the curve ID is not known, the name is227* "unknown (***)" where "***" is the decimal value of the identifier.228* If the name does not fit in the provided buffer, then dst[0] is set229* to 0 (unless len is 0, in which case nothing is written), and -1 is230* returned. Otherwise, the name is written in dst[] (with a terminating231* 0), and this function returns 0.232*/233int get_curve_name_ext(int id, char *dst, size_t len);234235/*236* Type for a known cipher suite.237*/238typedef struct {239const char *name;240uint16_t suite;241unsigned req;242const char *comment;243} cipher_suite;244245/*246* Known cipher suites. Last element has a NULL name.247*/248extern const cipher_suite cipher_suites[];249250/*251* Flags for cipher suite requirements.252*/253#define REQ_TLS12 0x0001 /* suite needs TLS 1.2 */254#define REQ_SHA1 0x0002 /* suite needs SHA-1 */255#define REQ_SHA256 0x0004 /* suite needs SHA-256 */256#define REQ_SHA384 0x0008 /* suite needs SHA-384 */257#define REQ_AESCBC 0x0010 /* suite needs AES/CBC encryption */258#define REQ_AESGCM 0x0020 /* suite needs AES/GCM encryption */259#define REQ_AESCCM 0x0040 /* suite needs AES/CCM encryption */260#define REQ_CHAPOL 0x0080 /* suite needs ChaCha20+Poly1305 */261#define REQ_3DESCBC 0x0100 /* suite needs 3DES/CBC encryption */262#define REQ_RSAKEYX 0x0200 /* suite uses RSA key exchange */263#define REQ_ECDHE_RSA 0x0400 /* suite uses ECDHE_RSA key exchange */264#define REQ_ECDHE_ECDSA 0x0800 /* suite uses ECDHE_ECDSA key exchange */265#define REQ_ECDH 0x1000 /* suite uses static ECDH key exchange */266267/*268* Parse a list of cipher suite names. The names are comma-separated. If269* one of the name is not recognised, or the list is empty, then an270* appropriate error message is printed, and NULL is returned.271* The returned array is allocated with xmalloc() and must be released272* by the caller. That array is terminated with a dummy entry whose 'name'273* field is NULL. The number of entries (not counting the dummy entry)274* is also written into '*num'.275*/276cipher_suite *parse_suites(const char *arg, size_t *num);277278/*279* Get the name of a cipher suite. Returned value is NULL if the suite is280* not recognized.281*/282const char *get_suite_name(unsigned suite);283284/*285* Get the name of a cipher suite. The name is written in the provided286* buffer; if the suite is not recognised, then the name is287* "unknown (0x****)" where "****" is the hexadecimal value of the suite.288* If the name does not fit in the provided buffer, then dst[0] is set289* to 0 (unless len is 0, in which case nothing is written), and -1 is290* returned. Otherwise, the name is written in dst[] (with a terminating291* 0), and this function returns 0.292*/293int get_suite_name_ext(unsigned suite, char *dst, size_t len);294295/*296* Tell whether a cipher suite uses ECDHE key exchange.297*/298int uses_ecdhe(unsigned suite);299300/*301* Print out all known names (for protocol versions, cipher suites...).302*/303void list_names(void);304305/*306* Print out all known elliptic curve names.307*/308void list_curves(void);309310/*311* Get the symbolic name for an elliptic curve (by ID).312*/313const char *ec_curve_name(int curve);314315/*316* Get a curve by symbolic name. If the name is not recognized, -1 is317* returned.318*/319int get_curve_by_name(const char *str);320321/*322* Get the symbolic name for a hash function name (by ID).323*/324const char *hash_function_name(int id);325326/*327* Read a file completely. The returned block is allocated with xmalloc()328* and must be released by the caller.329* If the file cannot be found or read completely, or is empty, then an330* appropriate error message is written, and NULL is returned.331*/332unsigned char *read_file(const char *fname, size_t *len);333334/*335* Write a file completely. This returns 0 on success, -1 on error. On336* error, an appropriate error message is printed.337*/338int write_file(const char *fname, const void *data, size_t len);339340/*341* This function returns non-zero if the provided buffer "looks like"342* a DER-encoded ASN.1 object (criteria: it has the tag for a SEQUENCE343* with a definite length that matches the total object length).344*/345int looks_like_DER(const unsigned char *buf, size_t len);346347/*348* Type for a named blob (the 'name' is a normalised PEM header name).349*/350typedef struct {351char *name;352unsigned char *data;353size_t data_len;354} pem_object;355356/*357* Release the contents of a named blob (buffer and name).358*/359void free_pem_object_contents(pem_object *po);360361/*362* Decode a buffer as a PEM file, and return all objects. On error, NULL363* is returned and an error message is printed. Absence of any object364* is an error.365*366* The returned array is terminated by a dummy object whose 'name' is367* NULL. The number of objects (not counting the dummy terminator) is368* written in '*num'.369*/370pem_object *decode_pem(const void *src, size_t len, size_t *num);371372/*373* Get the certificate(s) from a file. This accepts both a single374* DER-encoded certificate, and a text file that contains375* PEM-encoded certificates (and possibly other objects, which are376* then ignored).377*378* On decoding error, or if the file turns out to contain no certificate379* at all, then an error message is printed and NULL is returned.380*381* The returned array, and all referenced buffers, are allocated with382* xmalloc() and must be released by the caller. The returned array383* ends with a dummy entry whose 'data' field is NULL.384* The number of decoded certificates (not counting the dummy entry)385* is written into '*num'.386*/387br_x509_certificate *read_certificates(const char *fname, size_t *num);388389/*390* Release certificates. This releases all certificate data arrays,391* and the whole array as well.392*/393void free_certificates(br_x509_certificate *certs, size_t num);394395/*396* Interpret a certificate as a trust anchor. The trust anchor is397* newly allocated with xmalloc() and the caller must release it.398* On decoding error, an error message is printed, and this function399* returns NULL.400*/401br_x509_trust_anchor *certificate_to_trust_anchor(br_x509_certificate *xc);402403/*404* Type for a vector of trust anchors.405*/406typedef VECTOR(br_x509_trust_anchor) anchor_list;407408/*409* Release contents for a trust anchor (assuming they were dynamically410* allocated with xmalloc()). The structure itself is NOT released.411*/412void free_ta_contents(br_x509_trust_anchor *ta);413414/*415* Decode certificates from a file and interpret them as trust anchors.416* The trust anchors are added to the provided list. The number of found417* anchors is returned; on error, 0 is returned (finding no anchor at418* all is considered an error). An appropriate error message is displayed.419*/420size_t read_trust_anchors(anchor_list *dst, const char *fname);421422/*423* Get the "signer key type" for the certificate (key type of the424* issuing CA). On error, this prints a message on stderr, and returns 0.425*/426int get_cert_signer_algo(br_x509_certificate *xc);427428/*429* Special "no anchor" X.509 validator that wraps around another X.509430* validator and turns "not trusted" error codes into success. This is431* by definition insecure, but convenient for debug purposes.432*/433typedef struct {434const br_x509_class *vtable;435const br_x509_class **inner;436} x509_noanchor_context;437extern const br_x509_class x509_noanchor_vtable;438439/*440* Initialise a "no anchor" X.509 validator.441*/442void x509_noanchor_init(x509_noanchor_context *xwc,443const br_x509_class **inner);444445/*446* Aggregate type for a private key.447*/448typedef struct {449int key_type; /* BR_KEYTYPE_RSA or BR_KEYTYPE_EC */450union {451br_rsa_private_key rsa;452br_ec_private_key ec;453} key;454} private_key;455456/*457* Decode a private key from a file. On error, this prints an error458* message and returns NULL.459*/460private_key *read_private_key(const char *fname);461462/*463* Free a private key.464*/465void free_private_key(private_key *sk);466467/*468* Get the encoded OID for a given hash function (to use with PKCS#1469* signatures). If the hash function ID is 0 (for MD5+SHA-1), or if470* the ID is not one of the SHA-* functions (SHA-1, SHA-224, SHA-256,471* SHA-384, SHA-512), then this function returns NULL.472*/473const unsigned char *get_hash_oid(int id);474475/*476* Get a hash implementation by ID. This returns NULL if the hash477* implementation is not available.478*/479const br_hash_class *get_hash_impl(int id);480481/*482* Find the symbolic name and the description for an error. If 'err' is483* recognised then the error symbolic name is returned; if 'comment' is484* not NULL then '*comment' is then set to a descriptive human-readable485* message. If the error code 'err' is not recognised, then '*comment' is486* untouched and this function returns NULL.487*/488const char *find_error_name(int err, const char **comment);489490/*491* Find the symbolic name for an algorithm implementation. Provided492* pointer should be a pointer to a vtable or to a function, where493* appropriate. If not recognised, then the string "UNKNOWN" is returned.494*495* If 'long_name' is non-zero, then the returned name recalls the496* algorithm type as well; otherwise, only the core implementation name497* is returned (e.g. the long name could be 'aes_big_cbcenc' while the498* short name is 'big').499*/500const char *get_algo_name(const void *algo, int long_name);501502/*503* Run a SSL engine, with a socket connected to the peer, and using504* stdin/stdout to exchange application data. The socket must be a505* non-blocking descriptor.506*507* To help with Win32 compatibility, the socket descriptor is provided508* as an "unsigned long" value.509*510* Returned value:511* 0 SSL connection closed successfully512* x > 0 SSL error "x"513* -1 early socket close514* -2 stdout was closed, or something failed badly515*/516int run_ssl_engine(br_ssl_engine_context *eng,517unsigned long fd, unsigned flags);518519#define RUN_ENGINE_VERBOSE 0x0001 /* enable verbose messages */520#define RUN_ENGINE_TRACE 0x0002 /* hex dump of records */521522/*523* Do the "client" command. Returned value is 0 on success, -1 on failure.524* Command-line arguments start _after_ the command name.525*/526int do_client(int argc, char *argv[]);527528/*529* Do the "server" command. Returned value is 0 on success, -1 on failure.530* Command-line arguments start _after_ the command name.531*/532int do_server(int argc, char *argv[]);533534/*535* Do the "verify" command. Returned value is 0 on success, -1 on failure.536* Command-line arguments start _after_ the command name.537*/538int do_verify(int argc, char *argv[]);539540/*541* Do the "skey" command. Returned value is 0 on success, -1 on failure.542* Command-line arguments start _after_ the command name.543*/544int do_skey(int argc, char *argv[]);545546/*547* Do the "ta" command. Returned value is 0 on success, -1 on failure.548* Command-line arguments start _after_ the command name.549*/550int do_ta(int argc, char *argv[]);551552/*553* Do the "chain" command. Returned value is 0 on success, -1 on failure.554* Command-line arguments start _after_ the command name.555*/556int do_chain(int argc, char *argv[]);557558/*559* Do the "twrch" command. Returned value is 0 on success, -1 on failure560* (processing or arguments), or a non-zero exit code. Command-line561* arguments start _after_ the command name.562*/563int do_twrch(int argc, char *argv[]);564565/*566* Do the "impl" command. Returned value is 0 on success, -1 on failure.567* Command-line arguments start _after_ the command name.568*/569int do_impl(int argc, char *argv[]);570571#endif572573574