1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-07-30 16:24:09 +03:00

Add BearSSL client and server, support true bidir, lower memory, modern SSL (#4273)

BearSSL (https://www.bearssl.org) is a TLS(SSL) library written by
Thomas Pornin that is optimized for lower-memory embedded systems
like the ESP8266. It supports a wide variety of modern ciphers and
is unique in that it doesn't perform any memory allocations during
operation (which is the unfortunate bane of the current axTLS).

BearSSL is also absolutely focused on security and by default performs
all its security checks on x.509 certificates during the connection
phase (but if you want to be insecure and dangerous, that's possible
too).

While it does support unidirectional SSL buffers, like axTLS,
as implemented the ESP8266 wrappers only support bidirectional
buffers. These bidirectional buffers avoid deadlocks in protocols
which don't have well separated receive and transmit periods.

This patch adds several classes which allow connecting to TLS servers
using this library in almost the same way as axTLS:
BearSSL::WiFiClientSecure - WiFiClient that supports TLS
BearSSL::WiFiServerSecure - WiFiServer supporting TLS and client certs

It also introduces objects for PEM/DER encoded keys and certificates:
BearSSLX509List - x.509 Certificate (list) for general use
BearSSLPrivateKey - RSA or EC private key
BearSSLPublicKey - RSA or EC public key (i.e. from a public website)

Finally, it adds a Certificate Authority store object which lets
BearSSL access a set of trusted CA certificates on SPIFFS to allow it
to verify the identity of any remote site on the Internet, without
requiring RAM except for the single matching certificate.
CertStoreSPIFFSBearSSL - Certificate store utility

Client certificates are supported for the BearSSL::WiFiClientSecure, and
what's more the BearSSL::WiFiServerSecure can also *require* remote clients
to have a trusted certificate signed by a specific CA (or yourself with
self-signing CAs).

Maximum Fragment Length Negotiation probing and usage are supported, but
be aware that most sites on the Internet don't support it yet.  When
available, you can reduce the memory footprint of the SSL client or server
dramatically (i.e. down to 2-8KB vs. the ~22KB required for a full 16K
receive fragment and 512b send fragment).  You can also manually set a
smaller fragment size and guarantee at your protocol level all data will
fit within it.

Examples are included to show the usage of these new features.

axTLS has been moved to its own namespace, "axtls".  A default "using"
clause allows existing apps to run using axTLS without any changes.

The BearSSL::WiFi{client,server}Secure implements the axTLS
client/server API which lets many end user applications take advantage
of BearSSL with few or no changes.

The BearSSL static library used presently is stored at
https://github.com/earlephilhower/bearssl-esp8266 and can be built
using the standard ESP8266 toolchain.
This commit is contained in:
Earle F. Philhower, III
2018-05-14 20:46:47 -07:00
committed by GitHub
parent bd87970aae
commit e3c970210f
70 changed files with 18433 additions and 145 deletions

View File

@ -0,0 +1,821 @@
/*
WiFiClientBearSSL- SSL client/server for esp8266 using BearSSL libraries
- Mostly compatible with Arduino WiFi shield library and standard
WiFiClient/ServerSecure (except for certificate handling).
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <memory>
#include <vector>
#include <bearssl/bearssl.h>
#include <pgmspace.h>
#include <stdlib.h>
#include <string.h>
#include <Arduino.h>
#include "BearSSLHelpers.h"
namespace brssl {
// Code here is pulled from brssl sources, with the copyright and license
// shown below. I've rewritten things using C++ semantics and removed
// custom VEC_* calls (std::vector to the rescue) and adjusted things to
// allow for long-running operation (i.e. some memory issues when DERs
// passed into the decoders). Bugs are most likely my fault.
// Original (c) message follows:
/*
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.
*/
class private_key {
public:
int key_type; /* BR_KEYTYPE_RSA or BR_KEYTYPE_EC */
union {
br_rsa_private_key rsa;
br_ec_private_key ec;
} key;
};
class public_key {
public:
int key_type; /* BR_KEYTYPE_RSA or BR_KEYTYPE_EC */
union {
br_rsa_public_key rsa;
br_ec_public_key ec;
} key;
};
class pem_object {
public:
char *name;
unsigned char *data;
size_t data_len;
};
// Forward definitions
void free_ta_contents(br_x509_trust_anchor *ta);
void free_public_key(public_key *pk);
void free_private_key(private_key *sk);
bool looks_like_DER(const unsigned char *buf, size_t len);
pem_object *decode_pem(const void *src, size_t len, size_t *num);
void free_pem_object_contents(pem_object *po);
// Used as callback multiple places to append a string to a vector
static void byte_vector_append(void *ctx, const void *buff, size_t len) {
std::vector<uint8_t> *vec = static_cast<std::vector<uint8_t>*>(ctx);
vec->reserve(vec->size() + len); // Allocate extra space all at once
for (size_t i = 0; i < len; i++) {
vec->push_back(((uint8_t*)buff)[i]);
}
}
static bool certificate_to_trust_anchor_inner(br_x509_trust_anchor *ta, const br_x509_certificate *xc) {
std::unique_ptr<br_x509_decoder_context> dc(new br_x509_decoder_context); // auto-delete on exit
std::vector<uint8_t> vdn;
br_x509_pkey *pk;
// Clear everything in the Trust Anchor
memset(ta, 0, sizeof(*ta));
br_x509_decoder_init(dc.get(), byte_vector_append, (void*)&vdn, 0, 0);
br_x509_decoder_push(dc.get(), xc->data, xc->data_len);
pk = br_x509_decoder_get_pkey(dc.get());
if (pk == nullptr) {
return false; // No key present, something broken in the cert!
}
// Copy the raw certificate data
ta->dn.data = (uint8_t*)malloc(vdn.size());
if (!ta->dn.data) {
return false; // OOM, but nothing yet allocated
}
memcpy(ta->dn.data, &vdn[0], vdn.size());
ta->dn.len = vdn.size();
ta->flags = 0;
if (br_x509_decoder_isCA(dc.get())) {
ta->flags |= BR_X509_TA_CA;
}
// Extract the public key
switch (pk->key_type) {
case BR_KEYTYPE_RSA:
ta->pkey.key_type = BR_KEYTYPE_RSA;
ta->pkey.key.rsa.n = (uint8_t*)malloc(pk->key.rsa.nlen);
ta->pkey.key.rsa.e = (uint8_t*)malloc(pk->key.rsa.elen);
if ((ta->pkey.key.rsa.n == nullptr) || (ta->pkey.key.rsa.e == nullptr)) {
free_ta_contents(ta); // OOM, so clean up
return false;
}
memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, pk->key.rsa.nlen);
ta->pkey.key.rsa.nlen = pk->key.rsa.nlen;
memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, pk->key.rsa.elen);
ta->pkey.key.rsa.elen = pk->key.rsa.elen;
return true;
case BR_KEYTYPE_EC:
ta->pkey.key_type = BR_KEYTYPE_EC;
ta->pkey.key.ec.curve = pk->key.ec.curve;
ta->pkey.key.ec.q = (uint8_t*)malloc(pk->key.ec.qlen);
if (ta->pkey.key.ec.q == nullptr) {
free_ta_contents(ta); // OOM, so clean up
return false;
}
memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen);
ta->pkey.key.ec.qlen = pk->key.ec.qlen;
return true;
default:
free_ta_contents(ta); // Unknown key type
return false;
}
// Should never get here, if so there was an unknown error
return false;
}
br_x509_trust_anchor *certificate_to_trust_anchor(const br_x509_certificate *xc) {
br_x509_trust_anchor *ta = (br_x509_trust_anchor*)malloc(sizeof(br_x509_trust_anchor));
if (!ta) {
return nullptr;
}
if (!certificate_to_trust_anchor_inner(ta, xc)) {
free(ta);
return nullptr;
}
return ta;
}
void free_ta_contents(br_x509_trust_anchor *ta) {
if (ta) {
free(ta->dn.data);
if (ta->pkey.key_type == BR_KEYTYPE_RSA) {
free(ta->pkey.key.rsa.n);
free(ta->pkey.key.rsa.e);
} else if (ta->pkey.key_type == BR_KEYTYPE_EC) {
free(ta->pkey.key.ec.q);
}
memset(ta, 0, sizeof(*ta));
}
}
// Checks if a bitstream looks like a valid DER(binary) encoding.
// Basically tries to verify the length of all included segments
// matches the length of the input buffer. Does not actually
// validate any contents.
bool looks_like_DER(const unsigned char *buff, size_t len) {
if (len < 2) {
return false;
}
if (pgm_read_byte(buff++) != 0x30) {
return false;
}
int fb = pgm_read_byte(buff++);
len -= 2;
if (fb < 0x80) {
return (size_t)fb == len;
} else if (fb == 0x80) {
return false;
} else {
fb -= 0x80;
if (len < (size_t)fb + 2) {
return false;
}
len -= (size_t)fb;
size_t dlen = 0;
while (fb -- > 0) {
if (dlen > (len >> 8)) {
return false;
}
dlen = (dlen << 8) + (size_t)pgm_read_byte(buff++);
}
return dlen == len;
}
}
void free_pem_object_contents(pem_object *po) {
if (po) {
free(po->name);
free(po->data);
}
}
// Converts a PEM (~=base64) source into a set of DER-encoded binary blobs.
// Each blob is named by the ---- BEGIN xxx ---- field, and multiple
// blobs may be returned.
pem_object *decode_pem(const void *src, size_t len, size_t *num) {
std::vector<pem_object> pem_list;
std::unique_ptr<br_pem_decoder_context> pc(new br_pem_decoder_context); // auto-delete on exit
if (!pc.get()) {
return nullptr;
}
pem_object po, *pos;
const unsigned char *buff;
std::vector<uint8_t> bv;
*num = 0;
br_pem_decoder_init(pc.get());
buff = (const unsigned char *)src;
po.name = nullptr;
po.data = nullptr;
po.data_len = 0;
bool inobj = false;
bool extra_nl = true;
while (len > 0) {
size_t tlen;
tlen = br_pem_decoder_push(pc.get(), buff, len);
buff += tlen;
len -= tlen;
switch (br_pem_decoder_event(pc.get())) {
case BR_PEM_BEGIN_OBJ:
po.name = strdup(br_pem_decoder_name(pc.get()));
br_pem_decoder_setdest(pc.get(), byte_vector_append, &bv);
inobj = true;
break;
case BR_PEM_END_OBJ:
if (inobj) {
// Stick data into the vector
po.data = (uint8_t*)malloc(bv.size());
if (po.data) {
memcpy(po.data, &bv[0], bv.size());
po.data_len = bv.size();
pem_list.push_back(po);
}
// Clean up state for next blob processing
bv.clear();
po.name = nullptr;
po.data = nullptr;
po.data_len = 0;
inobj = false;
}
break;
case BR_PEM_ERROR:
free(po.name);
for (size_t i = 0; i < pem_list.size(); i++) {
free_pem_object_contents(&pem_list[i]);
}
return nullptr;
default:
// Do nothing here, the parser is still working on things
break;
}
if (len == 0 && extra_nl) {
extra_nl = false;
buff = (const unsigned char *)"\n";
len = 1;
}
}
if (inobj) {
free(po.name);
for (size_t i = 0; i < pem_list.size(); i++) {
free_pem_object_contents(&pem_list[i]);
}
return nullptr;
}
pos = (pem_object*)malloc((1 + pem_list.size()) * sizeof(*pos));
if (pos) {
*num = pem_list.size();
pem_list.push_back(po); // Null-terminate list
memcpy(pos, &pem_list[0], pem_list.size() * sizeof(*pos));
}
return pos;
}
// Parse out DER or PEM encoded certificates from a binary buffer,
// potentially stored in PROGMEM.
br_x509_certificate *read_certificates(const char *buff, size_t len, size_t *num) {
std::vector<br_x509_certificate> cert_list;
pem_object *pos;
size_t u, num_pos;
br_x509_certificate *xcs;
br_x509_certificate dummy;
*num = 0;
if (looks_like_DER((const unsigned char *)buff, len)) {
xcs = (br_x509_certificate*)malloc(2 * sizeof(*xcs));
if (!xcs) {
return nullptr;
}
xcs[0].data = (uint8_t*)malloc(len);
if (!xcs[0].data) {
free(xcs);
return nullptr;
}
memcpy_P(xcs[0].data, buff, len);
xcs[0].data_len = len;
xcs[1].data = nullptr;
xcs[1].data_len = 0;
*num = 1;
return xcs;
}
pos = decode_pem(buff, len, &num_pos);
if (!pos) {
return nullptr;
}
for (u = 0; u < num_pos; u ++) {
if (!strcmp_P(pos[u].name, PSTR("CERTIFICATE")) || !strcmp_P(pos[u].name, PSTR("X509 CERTIFICATE"))) {
br_x509_certificate xc;
xc.data = pos[u].data;
xc.data_len = pos[u].data_len;
pos[u].data = nullptr; // Don't free the data we moved to the xc vector!
cert_list.push_back(xc);
}
}
for (u = 0; u < num_pos; u ++) {
free_pem_object_contents(&pos[u]);
}
free(pos);
if (cert_list.size() == 0) {
return nullptr;
}
*num = cert_list.size();
dummy.data = nullptr;
dummy.data_len = 0;
cert_list.push_back(dummy);
xcs = (br_x509_certificate*)malloc(cert_list.size() * sizeof(*xcs));
if (!xcs) {
for (size_t i = 0; i < cert_list.size(); i++) {
free(cert_list[i].data); // Clean up any captured data blobs
}
return nullptr;
}
memcpy(xcs, &cert_list[0], cert_list.size() * sizeof(br_x509_certificate));
// XCS now has [].data pointing to the previously allocated blobs, so don't
// want to free anything in cert_list[].
return xcs;
}
void free_certificates(br_x509_certificate *certs, size_t num) {
if (certs) {
for (size_t u = 0; u < num; u ++) {
free(certs[u].data);
}
free(certs);
}
}
static public_key *decode_public_key(const unsigned char *buff, size_t len) {
std::unique_ptr<br_pkey_decoder_context> dc(new br_pkey_decoder_context); // auto-delete on exit
if (!dc.get()) {
return nullptr;
}
public_key *pk = nullptr;
br_pkey_decoder_init(dc.get());
br_pkey_decoder_push(dc.get(), buff, len);
int err = br_pkey_decoder_last_error(dc.get());
if (err != 0) {
return nullptr;
}
const br_rsa_public_key *rk = nullptr;
const br_ec_public_key *ek = nullptr;
switch (br_pkey_decoder_key_type(dc.get())) {
case BR_KEYTYPE_RSA:
rk = br_pkey_decoder_get_rsa(dc.get());
pk = (public_key*)malloc(sizeof * pk);
if (!pk) {
return nullptr;
}
pk->key_type = BR_KEYTYPE_RSA;
pk->key.rsa.n = (uint8_t*)malloc(rk->nlen);
pk->key.rsa.e = (uint8_t*)malloc(rk->elen);
if (!pk->key.rsa.n || !pk->key.rsa.e) {
free(pk->key.rsa.n);
free(pk->key.rsa.e);
free(pk);
return nullptr;
}
memcpy(pk->key.rsa.n, rk->n, rk->nlen);
pk->key.rsa.nlen = rk->nlen;
memcpy(pk->key.rsa.e, rk->e, rk->elen);
pk->key.rsa.elen = rk->elen;
return pk;
case BR_KEYTYPE_EC:
ek = br_pkey_decoder_get_ec(dc.get());
pk = (public_key*)malloc(sizeof * pk);
if (!pk) {
return nullptr;
}
pk->key_type = BR_KEYTYPE_EC;
pk->key.ec.q = (uint8_t*)malloc(ek->qlen);
if (!pk->key.ec.q) {
free(pk);
return nullptr;
}
memcpy(pk->key.ec.q, ek->q, ek->qlen);
pk->key.ec.qlen = ek->qlen;
return pk;
default:
return nullptr;
}
}
void free_public_key(public_key *pk) {
if (pk) {
if (pk->key_type == BR_KEYTYPE_RSA) {
free(pk->key.rsa.n);
free(pk->key.rsa.e);
} else if (pk->key_type == BR_KEYTYPE_EC) {
free(pk->key.ec.q);
}
free(pk);
}
}
static private_key *decode_private_key(const unsigned char *buff, size_t len) {
std::unique_ptr<br_skey_decoder_context> dc(new br_skey_decoder_context); // auto-delete on exit
if (!dc.get()) {
return nullptr;
}
private_key *sk = nullptr;
br_skey_decoder_init(dc.get());
br_skey_decoder_push(dc.get(), buff, len);
int err = br_skey_decoder_last_error(dc.get());
if (err != 0) {
return nullptr;
}
const br_rsa_private_key *rk = nullptr;
const br_ec_private_key *ek = nullptr;
switch (br_skey_decoder_key_type(dc.get())) {
case BR_KEYTYPE_RSA:
rk = br_skey_decoder_get_rsa(dc.get());
sk = (private_key*)malloc(sizeof * sk);
if (!sk) {
return nullptr;
}
sk->key_type = BR_KEYTYPE_RSA;
sk->key.rsa.p = (uint8_t*)malloc(rk->plen);
sk->key.rsa.q = (uint8_t*)malloc(rk->qlen);
sk->key.rsa.dp = (uint8_t*)malloc(rk->dplen);
sk->key.rsa.dq = (uint8_t*)malloc(rk->dqlen);
sk->key.rsa.iq = (uint8_t*)malloc(rk->iqlen);
if (!sk->key.rsa.p || !sk->key.rsa.q || !sk->key.rsa.dp || !sk->key.rsa.dq || !sk->key.rsa.iq) {
free_private_key(sk);
return nullptr;
}
sk->key.rsa.n_bitlen = rk->n_bitlen;
memcpy(sk->key.rsa.p, rk->p, rk->plen);
sk->key.rsa.plen = rk->plen;
memcpy(sk->key.rsa.q, rk->q, rk->qlen);
sk->key.rsa.qlen = rk->qlen;
memcpy(sk->key.rsa.dp, rk->dp, rk->dplen);
sk->key.rsa.dplen = rk->dplen;
memcpy(sk->key.rsa.dq, rk->dq, rk->dqlen);
sk->key.rsa.dqlen = rk->dqlen;
memcpy(sk->key.rsa.iq, rk->iq, rk->iqlen);
sk->key.rsa.iqlen = rk->iqlen;
return sk;
case BR_KEYTYPE_EC:
ek = br_skey_decoder_get_ec(dc.get());
sk = (private_key*)malloc(sizeof * sk);
sk->key_type = BR_KEYTYPE_EC;
sk->key.ec.curve = ek->curve;
sk->key.ec.x = (uint8_t*)malloc(ek->xlen);
if (!sk->key.ec.x) {
free_private_key(sk);
return nullptr;
}
memcpy(sk->key.ec.x, ek->x, ek->xlen);
sk->key.ec.xlen = ek->xlen;
return sk;
default:
return nullptr;
}
}
void free_private_key(private_key *sk) {
if (sk) {
switch (sk->key_type) {
case BR_KEYTYPE_RSA:
free(sk->key.rsa.p);
free(sk->key.rsa.q);
free(sk->key.rsa.dp);
free(sk->key.rsa.dq);
free(sk->key.rsa.iq);
break;
case BR_KEYTYPE_EC:
free(sk->key.ec.x);
break;
default:
// Could be an uninitted key, no sub elements to free
break;
}
free(sk);
}
}
void free_pem_object(pem_object *pos) {
if (pos != nullptr) {
for (size_t u = 0; pos[u].name; u ++) {
free_pem_object_contents(&pos[u]);
}
free(pos);
}
}
private_key *read_private_key(const char *buff, size_t len) {
private_key *sk = nullptr;
pem_object *pos = nullptr;
if (looks_like_DER((const unsigned char*)buff, len)) {
sk = decode_private_key((const unsigned char*)buff, len);
return sk;
}
size_t num;
pos = decode_pem(buff, len, &num);
if (pos == nullptr) {
return nullptr; // PEM decode error
}
for (size_t u = 0; pos[u].name; u ++) {
const char *name = pos[u].name;
if (!strcmp_P(name, PSTR("RSA PRIVATE KEY")) || !strcmp_P(name, PSTR("EC PRIVATE KEY")) || !strcmp_P(name, PSTR("PRIVATE KEY"))) {
sk = decode_private_key(pos[u].data, pos[u].data_len);
free_pem_object(pos);
return sk;
}
}
// If we hit here, no match
free_pem_object(pos);
return nullptr;
}
public_key *read_public_key(const char *buff, size_t len) {
public_key *pk = nullptr;
pem_object *pos = nullptr;
if (looks_like_DER((const unsigned char*)buff, len)) {
pk = decode_public_key((const unsigned char*)buff, len);
return pk;
}
size_t num;
pos = decode_pem(buff, len, &num);
if (pos == nullptr) {
return nullptr; // PEM decode error
}
for (size_t u = 0; pos[u].name; u ++) {
const char *name = pos[u].name;
if (!strcmp_P(name, PSTR("RSA PUBLIC KEY")) || !strcmp_P(name, PSTR("EC PUBLIC KEY")) || !strcmp_P(name, PSTR("PUBLIC KEY"))) {
pk = decode_public_key(pos[u].data, pos[u].data_len);
free_pem_object(pos);
return pk;
}
}
// We hit here == no key found
free_pem_object(pos);
return pk;
}
};
// ----- Public Key -----
BearSSLPublicKey::BearSSLPublicKey() {
_key = nullptr;
}
BearSSLPublicKey::BearSSLPublicKey(const char *pemKey) {
_key = nullptr;
parse(pemKey);
}
BearSSLPublicKey::BearSSLPublicKey(const uint8_t *derKey, size_t derLen) {
_key = nullptr;
parse(derKey, derLen);
}
BearSSLPublicKey::~BearSSLPublicKey() {
if (_key) {
brssl::free_public_key(_key);
}
}
bool BearSSLPublicKey::parse(const char *pemKey) {
return parse((const uint8_t *)pemKey, strlen_P(pemKey));
}
bool BearSSLPublicKey::parse(const uint8_t *derKey, size_t derLen) {
if (_key) {
brssl::free_public_key(_key);
_key = nullptr;
}
_key = brssl::read_public_key((const char *)derKey, derLen);
return _key ? true : false;
}
bool BearSSLPublicKey::isRSA() const {
if (!_key || _key->key_type != BR_KEYTYPE_RSA) {
return false;
}
return true;
}
bool BearSSLPublicKey::isEC() const {
if (!_key || _key->key_type != BR_KEYTYPE_EC) {
return false;
}
return true;
}
const br_rsa_public_key *BearSSLPublicKey::getRSA() const {
if (!_key || _key->key_type != BR_KEYTYPE_RSA) {
return nullptr;
}
return &_key->key.rsa;
}
const br_ec_public_key *BearSSLPublicKey::getEC() const {
if (!_key || _key->key_type != BR_KEYTYPE_EC) {
return nullptr;
}
return &_key->key.ec;
}
// ----- Private Key -----
BearSSLPrivateKey::BearSSLPrivateKey() {
_key = nullptr;
}
BearSSLPrivateKey::BearSSLPrivateKey(const char *pemKey) {
_key = nullptr;
parse(pemKey);
}
BearSSLPrivateKey::BearSSLPrivateKey(const uint8_t *derKey, size_t derLen) {
_key = nullptr;
parse(derKey, derLen);
}
BearSSLPrivateKey::~BearSSLPrivateKey() {
if (_key) {
brssl::free_private_key(_key);
}
}
bool BearSSLPrivateKey::parse(const char *pemKey) {
return parse((const uint8_t *)pemKey, strlen_P(pemKey));
}
bool BearSSLPrivateKey::parse(const uint8_t *derKey, size_t derLen) {
if (_key) {
brssl::free_private_key(_key);
_key = nullptr;
}
_key = brssl::read_private_key((const char *)derKey, derLen);
return _key ? true : false;
}
bool BearSSLPrivateKey::isRSA() const {
if (!_key || _key->key_type != BR_KEYTYPE_RSA) {
return false;
}
return true;
}
bool BearSSLPrivateKey::isEC() const {
if (!_key || _key->key_type != BR_KEYTYPE_EC) {
return false;
}
return true;
}
const br_rsa_private_key *BearSSLPrivateKey::getRSA() const {
if (!_key || _key->key_type != BR_KEYTYPE_RSA) {
return nullptr;
}
return &_key->key.rsa;
}
const br_ec_private_key *BearSSLPrivateKey::getEC() const {
if (!_key || _key->key_type != BR_KEYTYPE_EC) {
return nullptr;
}
return &_key->key.ec;
}
BearSSLX509List::BearSSLX509List() {
_count = 0;
_cert = nullptr;
_ta = nullptr;
}
BearSSLX509List::BearSSLX509List(const char *pemCert) {
_count = 0;
_cert = nullptr;
_ta = nullptr;
append(pemCert);
}
BearSSLX509List::BearSSLX509List(const uint8_t *derCert, size_t derLen) {
_count = 0;
_cert = nullptr;
_ta = nullptr;
append(derCert, derLen);
}
BearSSLX509List::~BearSSLX509List() {
brssl::free_certificates(_cert, _count); // also frees cert
for (size_t i = 0; i < _count; i++) {
brssl::free_ta_contents(&_ta[i]);
}
free(_ta);
}
bool BearSSLX509List::append(const char *pemCert) {
return append((const uint8_t *)pemCert, strlen_P(pemCert));
}
bool BearSSLX509List::append(const uint8_t *derCert, size_t derLen) {
size_t numCerts;
br_x509_certificate *newCerts = brssl::read_certificates((const char *)derCert, derLen, &numCerts);
if (!newCerts) {
return false;
}
// Add in the certificates
br_x509_certificate *saveCert = _cert;
_cert = (br_x509_certificate*)realloc(_cert, (numCerts + _count) * sizeof(br_x509_certificate));
if (!_cert) {
free(newCerts);
_cert = saveCert;
return false;
}
memcpy(&_cert[_count], newCerts, numCerts * sizeof(br_x509_certificate));
free(newCerts);
// Build TAs for each certificate
br_x509_trust_anchor *saveTa = _ta;
_ta = (br_x509_trust_anchor*)realloc(_ta, (numCerts + _count) * sizeof(br_x509_trust_anchor));
if (!_ta) {
_ta = saveTa;
return false;
}
for (size_t i = 0; i < numCerts; i++) {
br_x509_trust_anchor *newTa = brssl::certificate_to_trust_anchor(&_cert[_count + i]);
if (newTa) {
_ta[_count + i ] = *newTa;
free(newTa);
} else {
return false; // OOM
}
}
_count += numCerts;
return true;
}

View File

@ -0,0 +1,122 @@
/*
WiFiClientBearSSL- SSL client/server for esp8266 using BearSSL libraries
- Mostly compatible with Arduino WiFi shield library and standard
WiFiClient/ServerSecure (except for certificate handling).
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BEARSSLHELPERS_H
#define _BEARSSLHELPERS_H
#include <bearssl/bearssl.h>
// Internal opaque structures, not needed by user applications
namespace brssl {
class public_key;
class private_key;
};
// Holds either a single public RSA or EC key for use when BearSSL wants a pubkey.
// Copies all associated data so no need to keep input PEM/DER keys.
// All inputs can be either in RAM or PROGMEM.
class BearSSLPublicKey {
public:
BearSSLPublicKey();
BearSSLPublicKey(const char *pemKey);
BearSSLPublicKey(const uint8_t *derKey, size_t derLen);
~BearSSLPublicKey();
bool parse(const char *pemKey);
bool parse(const uint8_t *derKey, size_t derLen);
// Accessors for internal use, not needed by apps
bool isRSA() const;
bool isEC() const;
const br_rsa_public_key *getRSA() const;
const br_ec_public_key *getEC() const;
// Disable the copy constructor, we're pointer based
BearSSLPublicKey(const BearSSLPublicKey& that) = delete;
private:
brssl::public_key *_key;
};
// Holds either a single private RSA or EC key for use when BearSSL wants a secretkey.
// Copies all associated data so no need to keep input PEM/DER keys.
// All inputs can be either in RAM or PROGMEM.
class BearSSLPrivateKey {
public:
BearSSLPrivateKey();
BearSSLPrivateKey(const char *pemKey);
BearSSLPrivateKey(const uint8_t *derKey, size_t derLen);
~BearSSLPrivateKey();
bool parse(const char *pemKey);
bool parse(const uint8_t *derKey, size_t derLen);
// Accessors for internal use, not needed by apps
bool isRSA() const;
bool isEC() const;
const br_rsa_private_key *getRSA() const;
const br_ec_private_key *getEC() const;
// Disable the copy constructor, we're pointer based
BearSSLPrivateKey(const BearSSLPrivateKey& that) = delete;
private:
brssl::private_key *_key;
};
// Holds one or more X.509 certificates and associated trust anchors for
// use whenever BearSSL needs a cert or TA. May want to have multiple
// certs for things like a series of trusted CAs (but check the CertStore class
// for a more memory efficient way).
// Copies all associated data so no need to keep input PEM/DER certs.
// All inputs can be either in RAM or PROGMEM.
class BearSSLX509List {
public:
BearSSLX509List();
BearSSLX509List(const char *pemCert);
BearSSLX509List(const uint8_t *derCert, size_t derLen);
~BearSSLX509List();
bool append(const char *pemCert);
bool append(const uint8_t *derCert, size_t derLen);
// Accessors
size_t getCount() const {
return _count;
}
const br_x509_certificate *getX509Certs() const {
return _cert;
}
const br_x509_trust_anchor *getTrustAnchors() const {
return _ta;
}
// Disable the copy constructor, we're pointer based
BearSSLX509List(const BearSSLX509List& that) = delete;
private:
size_t _count;
br_x509_certificate *_cert;
br_x509_trust_anchor *_ta;
};
#endif

View File

@ -0,0 +1,141 @@
/*
CertStoreBearSSL.cpp - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CertStoreBearSSL.h"
#include <memory>
extern "C" {
// Callbacks for the x509 decoder
static void dn_append(void *ctx, const void *buf, size_t len) {
br_sha256_context *sha1 = (br_sha256_context*)ctx;
br_sha256_update(sha1, buf, len);
}
static void dn_append_null(void *ctx, const void *buf, size_t len) {
(void) ctx;
(void) buf;
(void) len;
}
}
CertStoreBearSSL::CertInfo CertStoreBearSSL::preprocessCert(const char *fname, const void *raw, size_t sz) {
CertStoreBearSSL::CertInfo ci;
// Clear the CertInfo
memset(&ci, 0, sizeof(ci));
// Process it using SHA256, same as the hashed_dn
br_x509_decoder_context *ctx = new br_x509_decoder_context;
br_sha256_context *sha256 = new br_sha256_context;
br_sha256_init(sha256);
br_x509_decoder_init(ctx, dn_append, sha256, nullptr, nullptr);
br_x509_decoder_push(ctx, (const void*)raw, sz);
// Copy result to structure
br_sha256_out(sha256, &ci.sha256);
strcpy(ci.fname, fname);
// Clean up allocated memory
delete sha256;
delete ctx;
// Return result
return ci;
}
br_x509_trust_anchor *CertStoreBearSSL::makeTrustAnchor(const void *der, size_t der_len, const CertInfo *ci) {
// std::unique_ptr will free dc when we exit scope, automatically
std::unique_ptr<br_x509_decoder_context> dc(new br_x509_decoder_context);
br_x509_decoder_init(dc.get(), dn_append_null, nullptr, nullptr, nullptr);
br_x509_decoder_push(dc.get(), der, der_len);
br_x509_pkey *pk = br_x509_decoder_get_pkey(dc.get());
if (!pk) {
return nullptr;
}
br_x509_trust_anchor *ta = (br_x509_trust_anchor*)malloc(sizeof(br_x509_trust_anchor));
if (!ta) {
return nullptr;
}
memset(ta, 0, sizeof(*ta));
ta->dn.data = (uint8_t*)malloc(sizeof(ci->sha256));
if (!ta->dn.data) {
free(ta);
return nullptr;
}
memcpy(ta->dn.data, ci->sha256, sizeof(ci->sha256));
ta->dn.len = sizeof(ci->sha256);
ta->flags = 0;
if (br_x509_decoder_isCA(dc.get())) {
ta->flags |= BR_X509_TA_CA;
}
switch (pk->key_type) {
case BR_KEYTYPE_RSA:
ta->pkey.key_type = BR_KEYTYPE_RSA;
ta->pkey.key.rsa.n = (uint8_t*)malloc(pk->key.rsa.nlen);
if (!ta->pkey.key.rsa.n) {
free(ta->dn.data);
free(ta);
return nullptr;
}
memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, pk->key.rsa.nlen);
ta->pkey.key.rsa.nlen = pk->key.rsa.nlen;
ta->pkey.key.rsa.e = (uint8_t*)malloc(pk->key.rsa.elen);
if (!ta->pkey.key.rsa.e) {
free(ta->pkey.key.rsa.n);
free(ta->dn.data);
free(ta);
return nullptr;
}
memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, pk->key.rsa.elen);
ta->pkey.key.rsa.elen = pk->key.rsa.elen;
return ta;
case BR_KEYTYPE_EC:
ta->pkey.key_type = BR_KEYTYPE_EC;
ta->pkey.key.ec.curve = pk->key.ec.curve;
ta->pkey.key.ec.q = (uint8_t*)malloc(pk->key.ec.qlen);
if (!ta->pkey.key.ec.q) {
free(ta->dn.data);
free(ta);
return nullptr;
}
memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen);
ta->pkey.key.ec.qlen = pk->key.ec.qlen;
return ta;
default:
free(ta->dn.data);
free(ta);
return nullptr;
}
}
void CertStoreBearSSL::freeTrustAnchor(const br_x509_trust_anchor *ta) {
switch (ta->pkey.key_type) {
case BR_KEYTYPE_RSA:
free(ta->pkey.key.rsa.e);
free(ta->pkey.key.rsa.n);
break;
case BR_KEYTYPE_EC:
free(ta->pkey.key.ec.q);
break;
}
free(ta->dn.data);
free((void*)ta);
}

View File

@ -0,0 +1,61 @@
/*
CertStoreBearSSL.h - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CERTSTORE_BEARSSL_H
#define _CERTSTORE_BEARSSL_H
#include <Arduino.h>
#include <bearssl/bearssl.h>
// Virtual base class for the certificate stores, which allow use
// of a large set of certificates stored on SPIFFS of SD card to
// be dynamically used when validating a X509 certificate
// Templates for child classes not possible due to the difference in SD
// and FS in terms of directory parsing and interating. Dir doesn't
// exist in SD, everything is a file (which might support get-next-entry()
// or not).
// This class should not be instantiated directly, only via its children.
class CertStoreBearSSL {
public:
CertStoreBearSSL() {}
virtual ~CertStoreBearSSL() {}
// Preprocess the certs from the flash, returns number parsed
virtual int initCertStore(const char *dir) = 0;
// Installs the cert store into the X509 decoder (normally via static function callbacks)
virtual void installCertStore(br_x509_minimal_context *ctx) = 0;
protected:
// The binary format of the pre-computed file
class CertInfo {
public:
uint8_t sha256[32];
char fname[64];
};
CertInfo preprocessCert(const char *fname, const void *raw, size_t sz);
static br_x509_trust_anchor *makeTrustAnchor(const void *der, size_t der_len, const CertInfo *ci);
static void freeTrustAnchor(const br_x509_trust_anchor *ta);
};
#endif

View File

@ -0,0 +1,141 @@
/*
CertStoreSDBearSSL.cpp - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <SD.h>
#include "CertStoreSDBearSSL.h"
CertStoreSDBearSSL::CertStoreSDBearSSL() : CertStoreBearSSL() {
path = "";
}
CertStoreSDBearSSL::~CertStoreSDBearSSL() {
}
CertStoreBearSSL::CertInfo CertStoreSDBearSSL::preprocessCert(File *f) {
CertStoreBearSSL::CertInfo ci;
memset(&ci, 0, sizeof(ci));
// Load the DER into RAM temporarially
if (!f) {
return ci;
}
int sz = f->size();
uint8_t *buf = new uint8_t[sz];
if (!buf) {
return ci;
}
f->read(buf, sz);
ci = CertStoreBearSSL::preprocessCert(f->name(), buf, sz);
delete buf;
return ci;
}
int CertStoreSDBearSSL::initCertStore(const char *subdir) {
int count = 0;
// We want path to have a leading slash and a trailing one
path = subdir;
if (path[0] != '/') {
path = "/" + path;
}
if (!path.endsWith("/")) {
path += "/";
}
String tblName = path + "ca_tbl.bin";
File tbl = SD.open(tblName, FILE_WRITE);
if (!tbl) {
return 0;
}
File d = SD.open(path);
while (true) {
File nextFile = d.openNextFile();
if (!nextFile) {
break;
}
if (!strstr(nextFile.name(), ".der")) {
continue;
}
CertStoreBearSSL::CertInfo ci = preprocessCert(&nextFile);
nextFile.close();
tbl.write((uint8_t*)&ci, sizeof(ci));
count++;
}
tbl.close();
return count;
}
void CertStoreSDBearSSL::installCertStore(br_x509_minimal_context *ctx) {
br_x509_minimal_set_dynamic(ctx, (void*)this, findHashedTA, freeHashedTA);
}
const br_x509_trust_anchor *CertStoreSDBearSSL::findHashedTA(void *ctx, void *hashed_dn, size_t len) {
CertStoreSDBearSSL *cs = static_cast<CertStoreSDBearSSL*>(ctx);
CertInfo ci;
String tblName = cs->path + "ca_tbl.bin";
if (len != sizeof(ci.sha256) || !SD.exists(tblName)) {
return nullptr;
}
File f = SD.open(tblName, FILE_READ);
if (!f) {
return nullptr;
}
while (f.read((uint8_t*)&ci, sizeof(ci)) == sizeof(ci)) {
if (!memcmp(ci.sha256, hashed_dn, sizeof(ci.sha256))) {
// This could be the one!
f.close();
File d = SD.open(ci.fname, FILE_READ);
if (!d) {
return nullptr;
}
size_t der_len = d.size();
uint8_t *der = (uint8_t*)malloc(der_len);
if (!der) {
d.close();
return nullptr;
}
if (d.read(der, der_len) != (int)der_len) {
d.close();
free(der);
return nullptr;
}
d.close();
br_x509_trust_anchor *ta = CertStoreBearSSL::makeTrustAnchor(der, der_len, &ci);
free(der);
return ta;
}
}
f.close();
return nullptr;
}
void CertStoreSDBearSSL::freeHashedTA(void *ctx, const br_x509_trust_anchor *ta) {
(void) ctx; // not needed
CertStoreBearSSL::freeTrustAnchor(ta);
}

View File

@ -0,0 +1,47 @@
/*
CertStoreSDBearSSL.h - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CERTSTORESD_BEARSSL_H
#define _CERTSTORESD_BEARSSL_H
#include "CertStoreBearSSL.h"
class File;
// SD cert store can be in a subdirectory as there are fewer limits
// Note that SD.begin() MUST be called before doing initCertStore because
// there are different options for the CS and other pins you need to
// specify it in your own code.
class CertStoreSDBearSSL : public CertStoreBearSSL {
public:
CertStoreSDBearSSL();
virtual ~CertStoreSDBearSSL();
virtual int initCertStore(const char *dir = "/") override;
virtual void installCertStore(br_x509_minimal_context *ctx) override;
private:
String path;
CertInfo preprocessCert(File *f);
// These need to be static as they are callbacks from BearSSL C code
static const br_x509_trust_anchor *findHashedTA(void *ctx, void *hashed_dn, size_t len);
static void freeHashedTA(void *ctx, const br_x509_trust_anchor *ta);
};
#endif

View File

@ -0,0 +1,125 @@
/*
CertStoreSPIFFSBearSSL.cpp - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CertStoreSPIFFSBearSSL.h"
#include <FS.h>
CertStoreSPIFFSBearSSL::CertStoreSPIFFSBearSSL() : CertStoreBearSSL() {
}
CertStoreSPIFFSBearSSL::~CertStoreSPIFFSBearSSL() {
}
CertStoreBearSSL::CertInfo CertStoreSPIFFSBearSSL::preprocessCert(const char *fname) {
CertStoreBearSSL::CertInfo ci;
memset(&ci, 0, sizeof(ci));
// Load the DER into RAM temporarially
File f = SPIFFS.open(fname, "r");
if (!f) {
return ci;
}
int sz = f.size();
uint8_t *buf = new uint8_t[sz];
if (!buf) {
f.close();
return ci;
}
f.read(buf, sz);
f.close();
ci = CertStoreBearSSL::preprocessCert(fname, buf, sz);
delete[] buf;
return ci;
}
int CertStoreSPIFFSBearSSL::initCertStore(const char *subdir) {
(void) subdir; // ignored prefix, not enough space in filenames
int count = 0;
SPIFFS.begin();
File tbl = SPIFFS.open("/ca_tbl.bin", "w");
if (!tbl) {
return 0;
}
Dir d = SPIFFS.openDir("");
while (d.next()) {
if (!strstr(d.fileName().c_str(), ".der")) {
continue;
}
CertStoreBearSSL::CertInfo ci = preprocessCert(d.fileName().c_str());
tbl.write((uint8_t*)&ci, sizeof(ci));
count++;
}
tbl.close();
return count;
}
void CertStoreSPIFFSBearSSL::installCertStore(br_x509_minimal_context *ctx) {
br_x509_minimal_set_dynamic(ctx, /* no context needed */nullptr, findHashedTA, freeHashedTA);
}
const br_x509_trust_anchor *CertStoreSPIFFSBearSSL::findHashedTA(void *ctx, void *hashed_dn, size_t len) {
(void) ctx; // not needed
CertInfo ci;
if (len != sizeof(ci.sha256) || !SPIFFS.exists("/ca_tbl.bin")) {
return nullptr;
}
File f = SPIFFS.open("/ca_tbl.bin", "r");
if (!f) {
return nullptr;
}
while (f.read((uint8_t*)&ci, sizeof(ci)) == sizeof(ci)) {
if (!memcmp(ci.sha256, hashed_dn, sizeof(ci.sha256))) {
// This could be the one!
f.close();
File d = SPIFFS.open(ci.fname, "r");
if (!d) {
return nullptr;
}
size_t der_len = d.size();
uint8_t *der = (uint8_t*)malloc(der_len);
if (!der) {
d.close();
return nullptr;
}
if (d.read(der, der_len) != der_len) {
d.close();
free(der);
return nullptr;
}
d.close();
br_x509_trust_anchor *ta = CertStoreBearSSL::makeTrustAnchor(der, der_len, &ci);
free(der);
return ta;
}
}
f.close();
return nullptr;
}
void CertStoreSPIFFSBearSSL::freeHashedTA(void *ctx, const br_x509_trust_anchor *ta) {
(void) ctx; // not needed
CertStoreBearSSL::freeTrustAnchor(ta);
}

View File

@ -0,0 +1,43 @@
/*
CertStoreSPIFFSBearSSL.h - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CERTSTORESPIFFS_BEARSSL_H
#define _CERTSTORESPIFFS_BEARSSL_H
#include "CertStoreBearSSL.h"
#include <FS.h>
// SPIFFS cert stores stored in root directory due to filename length limits
class CertStoreSPIFFSBearSSL : public CertStoreBearSSL {
public:
CertStoreSPIFFSBearSSL();
virtual ~CertStoreSPIFFSBearSSL();
virtual int initCertStore(const char *dir = "") override; // ignores dir
virtual void installCertStore(br_x509_minimal_context *ctx) override;
private:
CertInfo preprocessCert(const char *fname);
// These need to be static as they are callbacks from BearSSL C code
static const br_x509_trust_anchor *findHashedTA(void *ctx, void *hashed_dn, size_t len);
static void freeHashedTA(void *ctx, const br_x509_trust_anchor *ta);
};
#endif

View File

@ -40,6 +40,8 @@ extern "C" {
#include "WiFiServer.h"
#include "WiFiServerSecure.h"
#include "WiFiClientSecure.h"
#include "BearSSLHelpers.h"
#include "CertStoreBearSSL.h"
#ifdef DEBUG_ESP_WIFI
#ifdef DEBUG_ESP_PORT

View File

@ -20,77 +20,8 @@
*/
#ifndef wificlientsecure_h
#define wificlientsecure_h
#include "WiFiClient.h"
#include "include/ssl.h"
#include "WiFiClientSecureAxTLS.h"
#include "WiFiClientSecureBearSSL.h"
class SSLContext;
class WiFiClientSecure : public WiFiClient {
public:
WiFiClientSecure();
~WiFiClientSecure() override;
int connect(IPAddress ip, uint16_t port) override;
int connect(const String host, uint16_t port) override;
int connect(const char* name, uint16_t port) override;
bool verify(const char* fingerprint, const char* domain_name);
bool verifyCertChain(const char* domain_name);
uint8_t connected() override;
size_t write(const uint8_t *buf, size_t size) override;
size_t write_P(PGM_P buf, size_t size) override;
size_t write(Stream& stream); // Note this is not virtual
int read(uint8_t *buf, size_t size) override;
int available() override;
int read() override;
int peek() override;
size_t peekBytes(uint8_t *buffer, size_t length) override;
void stop() override;
bool setCACert(const uint8_t* pk, size_t size);
bool setCertificate(const uint8_t* pk, size_t size);
bool setPrivateKey(const uint8_t* pk, size_t size);
bool setCACert_P(PGM_VOID_P pk, size_t size);
bool setCertificate_P(PGM_VOID_P pk, size_t size);
bool setPrivateKey_P(PGM_VOID_P pk, size_t size);
bool loadCACert(Stream& stream, size_t size);
bool loadCertificate(Stream& stream, size_t size);
bool loadPrivateKey(Stream& stream, size_t size);
void allowSelfSignedCerts();
template<typename TFile>
bool loadCertificate(TFile& file) {
return loadCertificate(file, file.size());
}
template<typename TFile>
bool loadPrivateKey(TFile& file) {
return loadPrivateKey(file, file.size());
}
template<typename TFile>
bool loadCACert(TFile& file) {
return loadCACert(file, file.size());
}
friend class WiFiServerSecure; // Needs access to custom constructor below
protected:
// Only called by WiFiServerSecure
WiFiClientSecure(ClientContext* client, bool usePMEM, const uint8_t *rsakey, int rsakeyLen, const uint8_t *cert, int certLen);
protected:
void _initSSLContext();
int _connectSSL(const char* hostName);
bool _verifyDN(const char* name);
std::shared_ptr<SSLContext> _ssl = nullptr;
};
#endif //wificlientsecure_h
using namespace axTLS;
// using namespace BearSSL;

View File

@ -51,6 +51,8 @@ extern "C"
#define SSL_DEBUG_OPTS 0
#endif
namespace axTLS {
typedef struct BufferItem
{
@ -905,3 +907,5 @@ extern "C" void __ax_wdt_feed()
optimistic_yield(10000);
}
extern "C" void ax_wdt_feed() __attribute__ ((weak, alias("__ax_wdt_feed")));
};

View File

@ -0,0 +1,100 @@
/*
WiFiClientSecure.h - Variant of WiFiClient with TLS support
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wificlientsecure_h
#define wificlientsecure_h
#include "WiFiClient.h"
#include "include/ssl.h"
namespace axTLS {
class SSLContext;
class WiFiClientSecure : public WiFiClient {
public:
WiFiClientSecure();
~WiFiClientSecure() override;
int connect(IPAddress ip, uint16_t port) override;
int connect(const String host, uint16_t port) override;
int connect(const char* name, uint16_t port) override;
bool verify(const char* fingerprint, const char* domain_name);
bool verifyCertChain(const char* domain_name);
uint8_t connected() override;
size_t write(const uint8_t *buf, size_t size) override;
size_t write_P(PGM_P buf, size_t size) override;
size_t write(Stream& stream); // Note this is not virtual
int read(uint8_t *buf, size_t size) override;
int available() override;
int read() override;
int peek() override;
size_t peekBytes(uint8_t *buffer, size_t length) override;
void stop() override;
bool setCACert(const uint8_t* pk, size_t size);
bool setCertificate(const uint8_t* pk, size_t size);
bool setPrivateKey(const uint8_t* pk, size_t size);
bool setCACert_P(PGM_VOID_P pk, size_t size);
bool setCertificate_P(PGM_VOID_P pk, size_t size);
bool setPrivateKey_P(PGM_VOID_P pk, size_t size);
bool loadCACert(Stream& stream, size_t size);
bool loadCertificate(Stream& stream, size_t size);
bool loadPrivateKey(Stream& stream, size_t size);
void allowSelfSignedCerts();
template<typename TFile>
bool loadCertificate(TFile& file) {
return loadCertificate(file, file.size());
}
template<typename TFile>
bool loadPrivateKey(TFile& file) {
return loadPrivateKey(file, file.size());
}
template<typename TFile>
bool loadCACert(TFile& file) {
return loadCACert(file, file.size());
}
friend class WiFiServerSecure; // Needs access to custom constructor below
protected:
// Only called by WiFiServerSecure
WiFiClientSecure(ClientContext* client, bool usePMEM, const uint8_t *rsakey, int rsakeyLen, const uint8_t *cert, int certLen);
protected:
void _initSSLContext();
int _connectSSL(const char* hostName);
bool _verifyDN(const char* name);
std::shared_ptr<SSLContext> _ssl = nullptr;
};
};
#endif //wificlientsecure_h

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,215 @@
/*
WiFiClientBearSSL- SSL client/server for esp8266 using BearSSL libraries
- Mostly compatible with Arduino WiFi shield library and standard
WiFiClient/ServerSecure (except for certificate handling).
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wificlientbearssl_h
#define wificlientbearssl_h
#include "WiFiClient.h"
#include <bearssl/bearssl.h>
#include "BearSSLHelpers.h"
#include "CertStoreBearSSL.h"
namespace BearSSL {
class WiFiClientSecure : public WiFiClient {
public:
WiFiClientSecure();
~WiFiClientSecure() override;
int connect(IPAddress ip, uint16_t port) override;
int connect(const String host, uint16_t port) override;
int connect(const char* name, uint16_t port) override;
uint8_t connected() override;
size_t write(const uint8_t *buf, size_t size) override;
size_t write_P(PGM_P buf, size_t size) override;
size_t write(const char *buf) {
return write((const uint8_t*)buf, strlen(buf));
}
size_t write_P(const char *buf) {
return write_P((PGM_P)buf, strlen_P(buf));
}
size_t write(Stream& stream); // Note this is not virtual
int read(uint8_t *buf, size_t size) override;
int available() override;
int read() override;
int peek() override;
size_t peekBytes(uint8_t *buffer, size_t length) override;
void stop() override;
void flush() override;
// Don't validate the chain, just accept whatever is given. VERY INSECURE!
void setInsecure() {
_use_insecure = true;
}
// Assume a given public key, don't validate or use cert info at all
void setKnownKey(const BearSSLPublicKey *pk, unsigned usages = BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN) {
_knownkey = pk;
_knownkey_usages = usages;
}
// Only check SHA1 fingerprint of certificate
void setFingerprint(const uint8_t fingerprint[20]) {
_use_fingerprint = true;
memcpy_P(_fingerprint, fingerprint, 20);
}
// Accept any certificate that's self-signed
void allowSelfSignedCerts() {
_use_self_signed = true;
}
// Install certificates of trusted CAs or specific site
void setTrustAnchors(const BearSSLX509List *ta) {
_ta = ta;
}
// In cases when NTP is not used, app must set a time manually to check cert validity
void setX509Time(time_t now) {
_now = now;
}
// Install a client certificate for this connection, in case the server requires it (i.e. MQTT)
void setClientRSACert(const BearSSLX509List *cert, const BearSSLPrivateKey *sk);
void setClientECCert(const BearSSLX509List *cert, const BearSSLPrivateKey *sk,
unsigned allowed_usages, unsigned cert_issuer_key_type);
// Sets the requested buffer size for transmit and receive
void setBufferSizes(int recv, int xmit);
// Return an error code and possibly a text string in a passed-in buffer with last SSL failure
int getLastSSLError(char *dest = NULL, size_t len = 0);
// Attach a preconfigured certificate store
void setCertStore(CertStoreBearSSL *certStore) {
_certStore = certStore;
}
// Check for Maximum Fragment Length support for given len
static bool probeMaxFragmentLength(IPAddress ip, uint16_t port, uint16_t len);
static bool probeMaxFragmentLength(const char *hostname, uint16_t port, uint16_t len);
static bool probeMaxFragmentLength(const String host, uint16_t port, uint16_t len);
// AXTLS compatbile wrappers
bool verify(const char* fingerprint, const char* domain_name) { (void) fingerprint; (void) domain_name; return false; } // Can't handle this case, need app code changes
bool verifyCertChain(const char* domain_name) { (void)domain_name; return connected(); } // If we're connected, the cert passed validation during handshake
bool setCACert(const uint8_t* pk, size_t size);
bool setCertificate(const uint8_t* pk, size_t size);
bool setPrivateKey(const uint8_t* pk, size_t size);
bool setCACert_P(PGM_VOID_P pk, size_t size) { return setCACert((const uint8_t *)pk, size); }
bool setCertificate_P(PGM_VOID_P pk, size_t size) { return setCertificate((const uint8_t *)pk, size); }
bool setPrivateKey_P(PGM_VOID_P pk, size_t size) { return setPrivateKey((const uint8_t *)pk, size); }
bool loadCACert(Stream& stream, size_t size);
bool loadCertificate(Stream& stream, size_t size);
bool loadPrivateKey(Stream& stream, size_t size);
template<typename TFile>
bool loadCertificate(TFile& file) {
return loadCertificate(file, file.size());
}
template<typename TFile>
bool loadPrivateKey(TFile& file) {
return loadPrivateKey(file, file.size());
}
template<typename TFile>
bool loadCACert(TFile& file) {
return loadCACert(file, file.size());
}
private:
void _clear();
void _clearAuthenticationSettings();
// Only one of the following two should ever be != nullptr!
std::shared_ptr<br_ssl_client_context> _sc;
std::shared_ptr<br_ssl_server_context> _sc_svr;
inline bool ctx_present() {
return (_sc != nullptr) || (_sc_svr != nullptr);
}
br_ssl_engine_context *_eng; // &_sc->eng, to allow for client or server contexts
std::shared_ptr<br_x509_minimal_context> _x509_minimal;
std::shared_ptr<struct br_x509_insecure_context> _x509_insecure;
std::shared_ptr<br_x509_knownkey_context> _x509_knownkey;
std::shared_ptr<unsigned char> _iobuf_in;
std::shared_ptr<unsigned char> _iobuf_out;
time_t _now;
const BearSSLX509List *_ta;
CertStoreBearSSL *_certStore;
int _iobuf_in_size;
int _iobuf_out_size;
bool _handshake_done;
bool _oom_err;
bool _use_insecure;
bool _use_fingerprint;
uint8_t _fingerprint[20];
bool _use_self_signed;
const BearSSLPublicKey *_knownkey;
unsigned _knownkey_usages;
unsigned char *_recvapp_buf;
size_t _recvapp_len;
bool _clientConnected(); // Is the underlying socket alive?
bool _connectSSL(const char *hostName); // Do initial SSL handshake
void _freeSSL();
int _run_until(unsigned target, bool blocking = true);
size_t _write(const uint8_t *buf, size_t size, bool pmem);
bool _wait_for_handshake(); // Sets and return the _handshake_done after connecting
// Optional client certificate
const BearSSLX509List *_chain;
const BearSSLPrivateKey *_sk;
unsigned _allowed_usages;
unsigned _cert_issuer_key_type;
// Methods for handling server.available() call which returns a client connection.
friend class WiFiServerSecure; // Server needs to access these constructors
WiFiClientSecure(ClientContext *client, const BearSSLX509List *chain, unsigned cert_issuer_key_type,
const BearSSLPrivateKey *sk, int iobuf_in_size, int iobuf_out_size, const BearSSLX509List *client_CA_ta);
WiFiClientSecure(ClientContext* client, const BearSSLX509List *chain, const BearSSLPrivateKey *sk,
int iobuf_in_size, int iobuf_out_size, const BearSSLX509List *client_CA_ta);
// RSA keyed server
bool _connectSSLServerRSA(const BearSSLX509List *chain, const BearSSLPrivateKey *sk, const BearSSLX509List *client_CA_ta);
// EC keyed server
bool _connectSSLServerEC(const BearSSLX509List *chain, unsigned cert_issuer_key_type, const BearSSLPrivateKey *sk,
const BearSSLX509List *client_CA_ta);
// X.509 validators differ from server to client
bool _installClientX509Validator(); // Set up X509 validator for a client conn.
bool _installServerX509Validator(const BearSSLX509List *client_CA_ta); // Setup X509 client cert validation, if supplied
uint8_t *_streamLoad(Stream& stream, size_t size);
// AXTLS compatible mode needs to delete the stored certs and keys on destruction
bool _deleteChainKeyTA;
private:
// Single memory buffer used for BearSSL auxilliary stack, insead of growing main Arduino stack for all apps
static std::shared_ptr<uint8_t> _bearssl_stack;
// The local copy, only used to enable a reference count
std::shared_ptr<uint8_t> _local_bearssl_stack;
};
};
#endif

View File

@ -17,27 +17,5 @@
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wifiserversecure_h
#define wifiserversecure_h
#include "WiFiServer.h"
class WiFiClientSecure;
class WiFiServerSecure : public WiFiServer {
public:
WiFiServerSecure(IPAddress addr, uint16_t port);
WiFiServerSecure(uint16_t port);
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
virtual ~WiFiServerSecure() {}
WiFiClientSecure available(uint8_t* status = NULL);
private:
bool usePMEM = false;
const uint8_t *rsakey = nullptr;
int rsakeyLen = 0;
const uint8_t *cert = nullptr;
int certLen = 0;
};
#endif
#include "WiFiServerSecureAxTLS.h"
#include "WiFiServerSecureBearSSL.h"

View File

@ -36,6 +36,9 @@ extern "C" {
#include "include/ClientContext.h"
#include "WiFiServerSecure.h"
namespace axTLS {
WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port)
{
}
@ -77,3 +80,4 @@ WiFiClientSecure WiFiServerSecure::available(uint8_t* status)
return WiFiClientSecure();
}
};

View File

@ -0,0 +1,48 @@
/*
WiFiServerSecure.h - Library for Arduino ESP8266
Copyright (c) 2017 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wifiserversecure_h
#define wifiserversecure_h
#include "WiFiServer.h"
namespace axTLS {
class WiFiClientSecure;
class WiFiServerSecure : public WiFiServer {
public:
WiFiServerSecure(IPAddress addr, uint16_t port);
WiFiServerSecure(uint16_t port);
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
virtual ~WiFiServerSecure() {}
WiFiClientSecure available(uint8_t* status = NULL);
private:
bool usePMEM = false;
const uint8_t *rsakey = nullptr;
int rsakeyLen = 0;
const uint8_t *cert = nullptr;
int certLen = 0;
};
};
#endif

View File

@ -0,0 +1,119 @@
/*
WiFiServerBearSSL.cpp - SSL server for esp8266, mostly compatible
with Arduino WiFi shield library
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define LWIP_INTERNAL
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
}
#include "debug.h"
#include "ESP8266WiFi.h"
#include "WiFiClient.h"
#include "WiFiServer.h"
#include "lwip/opt.h"
#include "lwip/tcp.h"
#include "lwip/inet.h"
#include "include/ClientContext.h"
#include "WiFiServerSecureBearSSL.h"
namespace BearSSL {
// Only need to call the standard server constructor
WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port) {
}
// Only need to call the standard server constructor
WiFiServerSecure::WiFiServerSecure(uint16_t port) : WiFiServer(port) {
}
// Destructor only checks if we need to delete compatibilty cert/key
WiFiServerSecure::~WiFiServerSecure() {
if (_deleteChainAndKey) {
delete _chain;
delete _sk;
}
}
// Specify a RSA-signed certificate and key for the server. Only copies the pointer, the
// caller needs to preserve this chain and key for the life of the object.
void WiFiServerSecure::setRSACert(const BearSSLX509List *chain, const BearSSLPrivateKey *sk) {
_chain = chain;
_sk = sk;
}
// Specify a EC-signed certificate and key for the server. Only copies the pointer, the
// caller needs to preserve this chain and key for the life of the object.
void WiFiServerSecure::setECCert(const BearSSLX509List *chain, unsigned cert_issuer_key_type, const BearSSLPrivateKey *sk) {
_chain = chain;
_cert_issuer_key_type = cert_issuer_key_type;
_sk = sk;
}
// Return a client if there's an available connection waiting. If one is returned,
// then any validation (i.e. client cert checking) will have succeeded.
WiFiClientSecure WiFiServerSecure::available(uint8_t* status) {
(void) status; // Unused
if (_unclaimed) {
if (_sk && _sk->isRSA()) {
WiFiClientSecure result(_unclaimed, _chain, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta);
_unclaimed = _unclaimed->next();
result.setNoDelay(_noDelay);
DEBUGV("WS:av\r\n");
return result;
} else if (_sk && _sk->isEC()) {
WiFiClientSecure result(_unclaimed, _chain, _cert_issuer_key_type, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta);
_unclaimed = _unclaimed->next();
result.setNoDelay(_noDelay);
DEBUGV("WS:av\r\n");
return result;
} else {
// No key was defined, so we can't actually accept and attempt accept() and SSL handshake.
DEBUGV("WS:nokey\r\n");
}
}
// Something weird, return a no-op object
optimistic_yield(1000);
return WiFiClientSecure();
}
void WiFiServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) {
BearSSLX509List *chain = new BearSSLX509List(cert, certLen);
BearSSLPrivateKey *sk = new BearSSLPrivateKey(key, keyLen);
if (!chain || !key) {
// OOM, fail gracefully
delete chain;
delete sk;
return;
}
_deleteChainAndKey = true;
setRSACert(chain, sk);
}
void WiFiServerSecure::setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) {
setServerKeyAndCert(key, keyLen, cert, certLen);
}
};

View File

@ -0,0 +1,76 @@
/*
WiFiServerBearSSL.h - Library for Arduino ESP8266
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef wifiserverbearssl_h
#define wifiserverbearssl_h
#include "WiFiServer.h"
#include "WiFiClientSecureBearSSL.h"
#include "BearSSLHelpers.h"
#include <bearssl/bearssl.h>
namespace BearSSL {
class WiFiClientSecure;
class WiFiServerSecure : public WiFiServer {
public:
WiFiServerSecure(IPAddress addr, uint16_t port);
WiFiServerSecure(uint16_t port);
virtual ~WiFiServerSecure();
// Override the default buffer sizes, if you know what you're doing...
void setBufferSizes(int recv, int xmit) {
_iobuf_in_size = recv;
_iobuf_out_size = xmit;
}
// Set the server's RSA key and x509 certificate (required, pick one).
// Caller needs to preserve the chain and key throughout the life of the server.
void setRSACert(const BearSSLX509List *chain, const BearSSLPrivateKey *sk);
// Set the server's EC key and x509 certificate (required, pick one)
// Caller needs to preserve the chain and key throughout the life of the server.
void setECCert(const BearSSLX509List *chain, unsigned cert_issuer_key_type, const BearSSLPrivateKey *sk);
// Require client certificates validated against the passed in x509 trust anchor
// Caller needs to preserve the cert throughout the life of the server.
void setClientTrustAnchor(const BearSSLX509List *client_CA_ta) {
_client_CA_ta = client_CA_ta;
}
// If awaiting connection available and authenticated (i.e. client cert), return it.
WiFiClientSecure available(uint8_t* status = NULL);
// Compatibility with axTLS interface
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
private:
const BearSSLX509List *_chain = nullptr;
unsigned _cert_issuer_key_type = 0;
const BearSSLPrivateKey *_sk = nullptr;
int _iobuf_in_size = BR_SSL_BUFSIZE_INPUT;
int _iobuf_out_size = 837;
const BearSSLX509List *_client_CA_ta = nullptr;
bool _deleteChainAndKey = false;
};
};
#endif