1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-04-21 10:26:06 +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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
70 changed files with 18433 additions and 145 deletions

View File

@ -60,12 +60,12 @@ public:
std::unique_ptr<WiFiClient> create() override std::unique_ptr<WiFiClient> create() override
{ {
return std::unique_ptr<WiFiClient>(new WiFiClientSecure()); return std::unique_ptr<WiFiClient>(new axTLS::WiFiClientSecure());
} }
bool verify(WiFiClient& client, const char* host) override bool verify(WiFiClient& client, const char* host) override
{ {
auto wcs = static_cast<WiFiClientSecure&>(client); auto wcs = static_cast<axTLS::WiFiClientSecure&>(client);
return wcs.verify(_fingerprint.c_str(), host); return wcs.verify(_fingerprint.c_str(), host);
} }
@ -73,6 +73,34 @@ protected:
String _fingerprint; String _fingerprint;
}; };
class BearSSLTraits : public TransportTraits
{
public:
BearSSLTraits(const uint8_t fingerprint[20])
{
memcpy(_fingerprint, fingerprint, sizeof(_fingerprint));
}
std::unique_ptr<WiFiClient> create() override
{
BearSSL::WiFiClientSecure *client = new BearSSL::WiFiClientSecure();
client->setFingerprint(_fingerprint);
return std::unique_ptr<WiFiClient>(client);
}
bool verify(WiFiClient& client, const char* host) override
{
// No-op. BearSSL will not connect if the fingerprint doesn't match.
// So if you get to here you've already connected and it matched
(void) client;
(void) host;
return true;
}
protected:
uint8_t _fingerprint[20];
};
/** /**
* constructor * constructor
*/ */
@ -116,6 +144,24 @@ bool HTTPClient::begin(String url, String httpsFingerprint)
return true; return true;
} }
bool HTTPClient::begin(String url, const uint8_t httpsFingerprint[20])
{
_transportTraits.reset(nullptr);
_port = 443;
if (!beginInternal(url, "https")) {
return false;
}
_transportTraits = TransportTraitsPtr(new BearSSLTraits(httpsFingerprint));
DEBUG_HTTPCLIENT("[HTTP-Client][begin] BearSSL-httpsFingerprint:");
for (size_t i=0; i < 20; i++) {
DEBUG_HTTPCLIENT(" %02x", httpsFingerprint[i]);
}
DEBUG_HTTPCLIENT("\n");
return true;
}
/** /**
* parsing the url for all needed parameters * parsing the url for all needed parameters
* @param url String * @param url String
@ -213,6 +259,23 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, String httpsFinge
return true; return true;
} }
bool HTTPClient::begin(String host, uint16_t port, String uri, const uint8_t httpsFingerprint[20])
{
clear();
_host = host;
_port = port;
_uri = uri;
_transportTraits = TransportTraitsPtr(new BearSSLTraits(httpsFingerprint));
DEBUG_HTTPCLIENT("[HTTP-Client][begin] host: %s port: %d url: %s BearSSL-httpsFingerprint:", host.c_str(), port, uri.c_str());
for (size_t i=0; i < 20; i++) {
DEBUG_HTTPCLIENT(" %02x", httpsFingerprint[i]);
}
DEBUG_HTTPCLIENT("\n");
return true;
}
/** /**
* end * end
* called after the payload is handled * called after the payload is handled

View File

@ -133,10 +133,15 @@ public:
HTTPClient(); HTTPClient();
~HTTPClient(); ~HTTPClient();
// Plain HTTP connection, unencrypted
bool begin(String url); bool begin(String url);
bool begin(String url, String httpsFingerprint);
bool begin(String host, uint16_t port, String uri = "/"); bool begin(String host, uint16_t port, String uri = "/");
// Use axTLS for secure HTTPS connection
bool begin(String url, String httpsFingerprint);
bool begin(String host, uint16_t port, String uri, String httpsFingerprint); bool begin(String host, uint16_t port, String uri, String httpsFingerprint);
// Use BearSSL for secure HTTPS connection
bool begin(String url, const uint8_t httpsFingerprint[20]);
bool begin(String host, uint16_t port, String uri, const uint8_t httpsFingerprint[20]);
// deprecated, use the overload above instead // deprecated, use the overload above instead
bool begin(String host, uint16_t port, String uri, bool https, String httpsFingerprint) __attribute__ ((deprecated)); bool begin(String host, uint16_t port, String uri, bool https, String httpsFingerprint) __attribute__ ((deprecated));

View File

@ -0,0 +1,117 @@
/*
SecureBearSSLUpdater - SSL encrypted, password-protected firmware update
This example starts a HTTPS server on the ESP8266 to allow firmware updates
to be performed. All communication, including the username and password,
is encrypted via SSL. Be sure to update the SSID and PASSWORD before running
to allow connection to your WiFi network.
To upload through terminal you can use:
curl -u admin:admin -F "image=@firmware.bin" esp8266-webupdate.local/firmware
Adapted by Earle F. Philhower, III, from the SecureWebUpdater.ino example.
This example is released into the public domain.
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServerSecure.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
const char* host = "esp8266-webupdate";
const char* update_path = "/firmware";
const char* update_username = "admin";
const char* update_password = "admin";
const char* ssid = "........";
const char* password = "........";
BearSSL::ESP8266WebServerSecure httpServer(443);
ESP8266HTTPUpdateServer httpUpdater;
static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC
VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx
EDAOBgNVBAoMB1ByaXZhZG8xGjAYBgNVBAMMEXNlcnZlci56bGFiZWwuY29tMR8w
HQYJKoZIhvcNAQkBFhBlYXJsZUB6bGFiZWwuY29tMB4XDTE4MDMwNjA1NDg0NFoX
DTE5MDMwNjA1NDg0NFowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3Rh
dGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAPVKBwbZ+KDSl40YCDkP6y8Sv4iNGvEOZg8Y
X7sGvf/xZH7UiCBWPFIRpNmDSaZ3yjsmFqm6sLiYSGSdrBCFqdt9NTp2r7hga6Sj
oASSZY4B9pf+GblDy5m10KDx90BFKXdPMCLT+o76Nx9PpCvw13A848wHNG3bpBgI
t+w/vJCX3bkRn8yEYAU6GdMbYe7v446hX3kY5UmgeJFr9xz1kq6AzYrMt/UHhNzO
S+QckJaY0OGWvmTNspY3xCbbFtIDkCdBS8CZAw+itnofvnWWKQEXlt6otPh5njwy
+O1t/Q+Z7OMDYQaH02IQx3188/kW3FzOY32knER1uzjmRO+jhA8CAwEAATANBgkq
hkiG9w0BAQsFAAOCAQEAnDrROGRETB0woIcI1+acY1yRq4yAcH2/hdq2MoM+DCyM
E8CJaOznGR9ND0ImWpTZqomHOUkOBpvu7u315blQZcLbL1LfHJGRTCHVhvVrcyEb
fWTnRtAQdlirUm/obwXIitoz64VSbIVzcqqfg9C6ZREB9JbEX98/9Wp2gVY+31oC
JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m
+TGimzSdeWDvGBRWZHXczC2zD4aoE5vrl+GD2i++c6yjL/otHfYyUpzUfbI2hMAA
5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg==
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI
IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z
uUPLmbXQoPH3QEUpd08wItP6jvo3H0+kK/DXcDzjzAc0bdukGAi37D+8kJfduRGf
zIRgBToZ0xth7u/jjqFfeRjlSaB4kWv3HPWSroDNisy39QeE3M5L5ByQlpjQ4Za+
ZM2yljfEJtsW0gOQJ0FLwJkDD6K2eh++dZYpAReW3qi0+HmePDL47W39D5ns4wNh
BofTYhDHfXzz+RbcXM5jfaScRHW7OOZE76OEDwIDAQABAoIBAQDKov5NFbNFQNR8
djcM1O7Is6dRaqiwLeH4ZH1pZ3d9QnFwKanPdQ5eCj9yhfhJMrr5xEyCqT0nMn7T
yEIGYDXjontfsf8WxWkH2TjvrfWBrHOIOx4LJEvFzyLsYxiMmtZXvy6YByD+Dw2M
q2GH/24rRdI2klkozIOyazluTXU8yOsSGxHr/aOa9/sZISgLmaGOOuKI/3Zqjdhr
eHeSqoQFt3xXa8jw01YubQUDw/4cv9rk2ytTdAoQUimiKtgtjsggpP1LTq4xcuqN
d4jWhTcnorWpbD2cVLxrEbnSR3VuBCJEZv5axg5ZPxLEnlcId8vMtvTRb5nzzszn
geYUWDPhAoGBAPyKVNqqwQl44oIeiuRM2FYenMt4voVaz3ExJX2JysrG0jtCPv+Y
84R6Cv3nfITz3EZDWp5sW3OwoGr77lF7Tv9tD6BptEmgBeuca3SHIdhG2MR+tLyx
/tkIAarxQcTGsZaSqra3gXOJCMz9h2P5dxpdU+0yeMmOEnAqgQ8qtNBfAoGBAPim
RAtnrd0WSlCgqVGYFCvDh1kD5QTNbZc+1PcBHbVV45EmJ2fLXnlDeplIZJdYxmzu
DMOxZBYgfeLY9exje00eZJNSj/csjJQqiRftrbvYY7m5njX1kM5K8x4HlynQTDkg
rtKO0YZJxxmjRTbFGMegh1SLlFLRIMtehNhOgipRAoGBAPnEEpJGCS9GGLfaX0HW
YqwiEK8Il12q57mqgsq7ag7NPwWOymHesxHV5mMh/Dw+NyBi4xAGWRh9mtrUmeqK
iyICik773Gxo0RIqnPgd4jJWN3N3YWeynzulOIkJnSNx5BforOCTc3uCD2s2YB5X
jx1LKoNQxLeLRN8cmpIWicf/AoGBANjRSsZTKwV9WWIDJoHyxav/vPb+8WYFp8lZ
zaRxQbGM6nn4NiZI7OF62N3uhWB/1c7IqTK/bVHqFTuJCrCNcsgld3gLZ2QWYaMV
kCPgaj1BjHw4AmB0+EcajfKilcqtSroJ6MfMJ6IclVOizkjbByeTsE4lxDmPCDSt
/9MKanBxAoGAY9xo741Pn9WUxDyRplww606ccdNf/ksHWNc/Y2B5SPwxxSnIq8nO
j01SmsCUYVFAgZVOTiiycakjYLzxlc6p8BxSVqy6LlJqn95N8OXoQ+bkwUux/ekg
gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk=
-----END RSA PRIVATE KEY-----
)EOF";
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println("Booting Sketch...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
while(WiFi.waitForConnectResult() != WL_CONNECTED){
WiFi.begin(ssid, password);
Serial.println("WiFi failed, retrying.");
}
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
MDNS.begin(host);
httpServer.setRSACert(new BearSSLX509List(serverCert), new BearSSLPrivateKey(serverKey));
httpUpdater.setup(&httpServer, update_path, update_username, update_password);
httpServer.begin();
MDNS.addService("https", "tcp", 443);
Serial.printf("BearSSLUpdateServer ready!\nOpen https://%s.local%s in "\
"your browser and login with username '%s' and password "\
"'%s'\n", host, update_path, update_username, update_password);
}
void loop()
{
httpServer.handleClient();
}

View File

@ -0,0 +1,142 @@
/*
HelloServerBearSSL - Simple HTTPS server example
This example demonstrates a basic ESP8266WebServerSecure HTTPS server
that can serve "/" and "/inline" and generate detailed 404 (not found)
HTTP respoinses. Be sure to update the SSID and PASSWORD before running
to allow connection to your WiFi network.
Adapted by Earle F. Philhower, III, from the HelloServer.ino example.
This example is released into the public domain.
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServerSecure.h>
#include <ESP8266mDNS.h>
const char* ssid = "....";
const char* password = "....";
BearSSL::ESP8266WebServerSecure server(443);
static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC
VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx
EDAOBgNVBAoMB1ByaXZhZG8xGjAYBgNVBAMMEXNlcnZlci56bGFiZWwuY29tMR8w
HQYJKoZIhvcNAQkBFhBlYXJsZUB6bGFiZWwuY29tMB4XDTE4MDMwNjA1NDg0NFoX
DTE5MDMwNjA1NDg0NFowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3Rh
dGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAPVKBwbZ+KDSl40YCDkP6y8Sv4iNGvEOZg8Y
X7sGvf/xZH7UiCBWPFIRpNmDSaZ3yjsmFqm6sLiYSGSdrBCFqdt9NTp2r7hga6Sj
oASSZY4B9pf+GblDy5m10KDx90BFKXdPMCLT+o76Nx9PpCvw13A848wHNG3bpBgI
t+w/vJCX3bkRn8yEYAU6GdMbYe7v446hX3kY5UmgeJFr9xz1kq6AzYrMt/UHhNzO
S+QckJaY0OGWvmTNspY3xCbbFtIDkCdBS8CZAw+itnofvnWWKQEXlt6otPh5njwy
+O1t/Q+Z7OMDYQaH02IQx3188/kW3FzOY32knER1uzjmRO+jhA8CAwEAATANBgkq
hkiG9w0BAQsFAAOCAQEAnDrROGRETB0woIcI1+acY1yRq4yAcH2/hdq2MoM+DCyM
E8CJaOznGR9ND0ImWpTZqomHOUkOBpvu7u315blQZcLbL1LfHJGRTCHVhvVrcyEb
fWTnRtAQdlirUm/obwXIitoz64VSbIVzcqqfg9C6ZREB9JbEX98/9Wp2gVY+31oC
JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m
+TGimzSdeWDvGBRWZHXczC2zD4aoE5vrl+GD2i++c6yjL/otHfYyUpzUfbI2hMAA
5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg==
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI
IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z
uUPLmbXQoPH3QEUpd08wItP6jvo3H0+kK/DXcDzjzAc0bdukGAi37D+8kJfduRGf
zIRgBToZ0xth7u/jjqFfeRjlSaB4kWv3HPWSroDNisy39QeE3M5L5ByQlpjQ4Za+
ZM2yljfEJtsW0gOQJ0FLwJkDD6K2eh++dZYpAReW3qi0+HmePDL47W39D5ns4wNh
BofTYhDHfXzz+RbcXM5jfaScRHW7OOZE76OEDwIDAQABAoIBAQDKov5NFbNFQNR8
djcM1O7Is6dRaqiwLeH4ZH1pZ3d9QnFwKanPdQ5eCj9yhfhJMrr5xEyCqT0nMn7T
yEIGYDXjontfsf8WxWkH2TjvrfWBrHOIOx4LJEvFzyLsYxiMmtZXvy6YByD+Dw2M
q2GH/24rRdI2klkozIOyazluTXU8yOsSGxHr/aOa9/sZISgLmaGOOuKI/3Zqjdhr
eHeSqoQFt3xXa8jw01YubQUDw/4cv9rk2ytTdAoQUimiKtgtjsggpP1LTq4xcuqN
d4jWhTcnorWpbD2cVLxrEbnSR3VuBCJEZv5axg5ZPxLEnlcId8vMtvTRb5nzzszn
geYUWDPhAoGBAPyKVNqqwQl44oIeiuRM2FYenMt4voVaz3ExJX2JysrG0jtCPv+Y
84R6Cv3nfITz3EZDWp5sW3OwoGr77lF7Tv9tD6BptEmgBeuca3SHIdhG2MR+tLyx
/tkIAarxQcTGsZaSqra3gXOJCMz9h2P5dxpdU+0yeMmOEnAqgQ8qtNBfAoGBAPim
RAtnrd0WSlCgqVGYFCvDh1kD5QTNbZc+1PcBHbVV45EmJ2fLXnlDeplIZJdYxmzu
DMOxZBYgfeLY9exje00eZJNSj/csjJQqiRftrbvYY7m5njX1kM5K8x4HlynQTDkg
rtKO0YZJxxmjRTbFGMegh1SLlFLRIMtehNhOgipRAoGBAPnEEpJGCS9GGLfaX0HW
YqwiEK8Il12q57mqgsq7ag7NPwWOymHesxHV5mMh/Dw+NyBi4xAGWRh9mtrUmeqK
iyICik773Gxo0RIqnPgd4jJWN3N3YWeynzulOIkJnSNx5BforOCTc3uCD2s2YB5X
jx1LKoNQxLeLRN8cmpIWicf/AoGBANjRSsZTKwV9WWIDJoHyxav/vPb+8WYFp8lZ
zaRxQbGM6nn4NiZI7OF62N3uhWB/1c7IqTK/bVHqFTuJCrCNcsgld3gLZ2QWYaMV
kCPgaj1BjHw4AmB0+EcajfKilcqtSroJ6MfMJ6IclVOizkjbByeTsE4lxDmPCDSt
/9MKanBxAoGAY9xo741Pn9WUxDyRplww606ccdNf/ksHWNc/Y2B5SPwxxSnIq8nO
j01SmsCUYVFAgZVOTiiycakjYLzxlc6p8BxSVqy6LlJqn95N8OXoQ+bkwUux/ekg
gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk=
-----END RSA PRIVATE KEY-----
)EOF";
const int led = 13;
void handleRoot() {
digitalWrite(led, 1);
server.send(200, "text/plain", "Hello from esp8266 over HTTPS!");
digitalWrite(led, 0);
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup(void){
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.setRSACert(new BearSSLX509List(serverCert), new BearSSLPrivateKey(serverKey));
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTPS server started");
}
void loop(void){
server.handleClient();
}

View File

@ -19,43 +19,5 @@
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
#include "ESP8266WebServerSecureAxTLS.h"
#ifndef ESP8266WEBSERVERSECURE_H #include "ESP8266WebServerSecureBearSSL.h"
#define ESP8266WEBSERVERSECURE_H
#include <ESP8266WebServer.h>
#include <WiFiServerSecure.h>
class ESP8266WebServerSecure : public ESP8266WebServer
{
public:
ESP8266WebServerSecure(IPAddress addr, int port = 443);
ESP8266WebServerSecure(int port = 443);
virtual ~ESP8266WebServerSecure();
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
WiFiClient client() override { return _currentClientSecure; }
void begin() override;
void handleClient() override;
void close() override;
template<typename T>
size_t streamFile(T &file, const String& contentType) {
_streamFileCore(file.size(), file.name(), contentType);
return _currentClientSecure.write(file);
}
private:
size_t _currentClientWrite (const char *bytes, size_t len) override { return _currentClientSecure.write((const uint8_t *)bytes, len); }
size_t _currentClientWrite_P (PGM_P bytes, size_t len) override { return _currentClientSecure.write_P(bytes, len); }
protected:
WiFiServerSecure _serverSecure;
WiFiClientSecure _currentClientSecure;
};
#endif //ESP8266WEBSERVERSECURE_H

View File

@ -34,6 +34,8 @@
#define DEBUG_OUTPUT Serial #define DEBUG_OUTPUT Serial
#endif #endif
namespace axTLS {
ESP8266WebServerSecure::ESP8266WebServerSecure(IPAddress addr, int port) ESP8266WebServerSecure::ESP8266WebServerSecure(IPAddress addr, int port)
: _serverSecure(addr, port) : _serverSecure(addr, port)
{ {
@ -144,3 +146,4 @@ void ESP8266WebServerSecure::close() {
_serverSecure.close(); _serverSecure.close();
} }
};

View File

@ -0,0 +1,64 @@
/*
ESP8266WebServerSecure.h - Dead simple HTTPS web-server.
Supports only one simultaneous client, knows how to handle GET and POST.
Copyright (c) 2017 Earle F. Philhower, III. All rights reserved.
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 ESP8266WEBSERVERSECURE_H
#define ESP8266WEBSERVERSECURE_H
#include <ESP8266WebServer.h>
#include <WiFiServerSecure.h>
namespace axTLS {
class ESP8266WebServerSecure : public ESP8266WebServer
{
public:
ESP8266WebServerSecure(IPAddress addr, int port = 443);
ESP8266WebServerSecure(int port = 443);
virtual ~ESP8266WebServerSecure();
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
WiFiClient client() override { return _currentClientSecure; }
void begin() override;
void handleClient() override;
void close() override;
template<typename T>
size_t streamFile(T &file, const String& contentType) {
_streamFileCore(file.size(), file.name(), contentType);
return _currentClientSecure.write(file);
}
private:
size_t _currentClientWrite (const char *bytes, size_t len) override { return _currentClientSecure.write((const uint8_t *)bytes, len); }
size_t _currentClientWrite_P (PGM_P bytes, size_t len) override { return _currentClientSecure.write_P(bytes, len); }
protected:
WiFiServerSecure _serverSecure;
WiFiClientSecure _currentClientSecure;
};
};
#endif //ESP8266WEBSERVERSECURE_H

View File

@ -0,0 +1,165 @@
/*
ESP8266WebServerSecure.cpp - Dead simple HTTPS web-server.
Supports only one simultaneous client, knows how to handle GET and POST.
Copyright (c) 2017 Earle F. Philhower, III. All rights reserved.
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
Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)
*/
#include <Arduino.h>
#include <libb64/cencode.h>
#include "WiFiServer.h"
#include "WiFiClient.h"
#include "ESP8266WebServerSecureBearSSL.h"
//#define DEBUG_ESP_HTTP_SERVER
#ifdef DEBUG_ESP_PORT
#define DEBUG_OUTPUT DEBUG_ESP_PORT
#else
#define DEBUG_OUTPUT Serial
#endif
namespace BearSSL {
ESP8266WebServerSecure::ESP8266WebServerSecure(IPAddress addr, int port)
: _serverSecure(addr, port)
{
}
ESP8266WebServerSecure::ESP8266WebServerSecure(int port)
: _serverSecure(port)
{
}
void ESP8266WebServerSecure::setRSACert(const BearSSLX509List *chain, const BearSSLPrivateKey *sk)
{
_serverSecure.setRSACert(chain, sk);
}
void ESP8266WebServerSecure::setECCert(const BearSSLX509List *chain, unsigned cert_issuer_key_type, const BearSSLPrivateKey *sk)
{
_serverSecure.setECCert(chain, cert_issuer_key_type, sk);
}
void ESP8266WebServerSecure::setBufferSizes(int recv, int xmit)
{
_serverSecure.setBufferSizes(recv, xmit);
}
ESP8266WebServerSecure::~ESP8266WebServerSecure() {
// Nothing to do here.
// Base class's destructor will be called to clean up itself
}
// We need to basically cut-n-paste these from WebServer because of the problem
// of object slicing. The class uses assignment operators like "WiFiClient x=y;"
// When this happens, even if "y" is a WiFiClientSecure, the main class is
// already compiled down into code which will only copy the WiFiClient superclass
// and not the extra bits for our own class (since when it was compiled it needed
// to know the size of memory to allocate on the stack for this local variable
// there's not realy anything else it could do).
void ESP8266WebServerSecure::begin() {
_currentStatus = HC_NONE;
_serverSecure.begin();
if(!_headerKeysCount)
collectHeaders(0, 0);
}
void ESP8266WebServerSecure::handleClient() {
if (_currentStatus == HC_NONE) {
BearSSL::WiFiClientSecure client = _serverSecure.available();
if (!client) {
return;
}
#ifdef DEBUG_ESP_HTTP_SERVER
DEBUG_OUTPUT.println("New secure client");
#endif
_currentClientSecure = client;
_currentStatus = HC_WAIT_READ;
_statusChange = millis();
}
bool keepCurrentClient = false;
bool callYield = false;
if (_currentClientSecure.connected()) {
switch (_currentStatus) {
case HC_NONE:
// No-op to avoid C++ compiler warning
break;
case HC_WAIT_READ:
// Wait for data from client to become available
if (_currentClientSecure.available()) {
if (_parseRequest(_currentClientSecure)) {
_currentClientSecure.setTimeout(HTTP_MAX_SEND_WAIT);
_contentLength = CONTENT_LENGTH_NOT_SET;
_handleRequest();
if (_currentClientSecure.connected()) {
_currentStatus = HC_WAIT_CLOSE;
_statusChange = millis();
keepCurrentClient = true;
}
}
} else { // !_currentClient.available()
if (millis() - _statusChange <= HTTP_MAX_DATA_WAIT) {
keepCurrentClient = true;
}
callYield = true;
}
break;
case HC_WAIT_CLOSE:
// Wait for client to close the connection
if (millis() - _statusChange <= HTTP_MAX_CLOSE_WAIT) {
keepCurrentClient = true;
callYield = true;
}
}
}
if (!keepCurrentClient) {
_currentClientSecure = BearSSL::WiFiClientSecure();
_currentStatus = HC_NONE;
_currentUpload.reset();
}
if (callYield) {
yield();
}
}
void ESP8266WebServerSecure::close() {
_currentClientSecure.flush();
_currentClientSecure.stop();
_serverSecure.close();
}
void ESP8266WebServerSecure::setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) {
_serverSecure.setServerKeyAndCert_P(key, keyLen, cert, certLen);
}
void ESP8266WebServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen)
{
_serverSecure.setServerKeyAndCert(key, keyLen, cert, certLen);
}
};

View File

@ -0,0 +1,69 @@
/*
ESP8266WebServerSecure.h - Dead simple HTTPS web-server.
Supports only one simultaneous client, knows how to handle GET and POST.
Copyright (c) 2017 Earle F. Philhower, III. All rights reserved.
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 ESP8266WEBSERVERBEARSSL_H
#define ESP8266WEBSERVERBEARSSL_H
#include <ESP8266WebServer.h>
#include <BearSSLHelpers.h>
#include <WiFiServerSecureBearSSL.h>
namespace BearSSL {
class ESP8266WebServerSecure : public ESP8266WebServer
{
public:
ESP8266WebServerSecure(IPAddress addr, int port = 443);
ESP8266WebServerSecure(int port = 443);
virtual ~ESP8266WebServerSecure();
void setBufferSizes(int recv, int xmit);
void setRSACert(const BearSSLX509List *chain, const BearSSLPrivateKey *sk);
void setECCert(const BearSSLX509List *chain, unsigned cert_issuer_key_type, const BearSSLPrivateKey *sk);
WiFiClient client() override { return _currentClientSecure; }
void begin() override;
void handleClient() override;
void close() override;
template<typename T>
size_t streamFile(T &file, const String& contentType) {
_streamFileCore(file.size(), file.name(), contentType);
return _currentClientSecure.write(file);
}
// AXTLS Compatibility
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
private:
size_t _currentClientWrite (const char *bytes, size_t len) override { return _currentClientSecure.write((const uint8_t *)bytes, len); }
size_t _currentClientWrite_P (PGM_P bytes, size_t len) override { return _currentClientSecure.write_P(bytes, len); }
protected:
BearSSL::WiFiServerSecure _serverSecure;
BearSSL::WiFiClientSecure _currentClientSecure;
};
};
#endif //ESP8266WEBSERVERSECURE_H

View File

@ -0,0 +1,158 @@
// Demonstrate the CertStore object with WiFiClientBearSSL
//
// Before running, you must download the set of certs using
// the script "certs-from-mozilla.py" (no parameters)
// and then uploading the generated data directory to
// SPIFFS.
//
// Why would you need a CertStore?
//
// If you know the exact serve being connected to, or you
// are generating your own self-signed certificates and aren't
// allowing connections to HTTPS/TLS servers out of your
// control, then you do NOT want a CertStore. Hardcode the
// self-signing CA or the site's x.509 certificate directly.
//
// However, if you don't know what specific sites the system
// will be required to connect to and verify, a
// CertStore{SPIFFS,SD}BearSSL can allow you to select from
// 10s or 100s of CAs against which you can check the
// target's X.509, without taking any more RAM than a single
// certificate. This is the same way that standard browsers
// and operating systems use to verify SSL connections.
//
// About the chosen certs:
// The certificates are scraped from the Mozilla.org current
// list, but please don't take this as an endorsement or a
// requirement: it is up to YOU, the USER, to specify the
// certificate authorities you will use as trust bases.
//
// Mar 2018 by Earle F. Philhower, III
// Released to the public domain
#include <ESP8266WiFi.h>
#include <CertStoreSPIFFSBearSSL.h>
#include <time.h>
const char *ssid = "....";
const char *pass = "....";
// A single, global CertStore which can be used by all
// connections. Needs to stay live the entire time any of
// the WiFiClientBearSSLs are present.
CertStoreSPIFFSBearSSL certStore;
// Set time via NTP, as required for x.509 validation
void setClock() {
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print("Current time: ");
Serial.print(asctime(&timeinfo));
}
// Try and connect using a WiFiClientBearSSL to specified host:port and dump URL
void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) {
if (!path) {
path = "/";
}
Serial.printf("Trying: %s:443...", host);
client->connect(host, port);
if (!client->connected()) {
Serial.printf("*** Can't connect. ***\n-------\n");
return;
}
Serial.printf("Connected!\n-------\n");
client->write("GET ");
client->write(path);
client->write(" HTTP/1.0\r\nHost: ");
client->write(host);
client->write("\r\nUser-Agent: ESP8266\r\n");
client->write("\r\n");
uint32_t to = millis() + 5000;
if (client->connected()) {
do {
char tmp[32];
memset(tmp, 0, 32);
int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
yield();
if (rlen < 0) {
break;
}
// Only print out first line up to \r, then abort connection
char *nl = strchr(tmp, '\r');
if (nl) {
*nl = 0;
Serial.print(tmp);
break;
}
Serial.print(tmp);
} while (millis() < to);
}
client->stop();
Serial.printf("\n-------\n");
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
setClock(); // Required for X.509 validation
int numCerts = certStore.initCertStore();
Serial.printf("Number of CA certs read: %d\n", numCerts);
if (numCerts == 0) {
Serial.printf("No certs found. Did you run certs-from-mozill.py and upload the SPIFFS directory before running?\n");
return; // Can't connect to anything w/o certs!
}
BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure();
// Integrate the cert store with this connection
bear->setCertStore(&certStore);
Serial.printf("Attempting to fetch https://www.github.com/...\n");
fetchURL(bear, "www.github.com", 443, "/");
delete bear;
}
void loop() {
Serial.printf("\nPlease enter a website address (www.blah.com) to connect to: ");
String site;
do {
site = Serial.readString();
} while (site == "");
Serial.printf("https://%s/\n", site.c_str());
BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure();
// Integrate the cert store with this connection
bear->setCertStore(&certStore);
fetchURL(bear, site.c_str(), 443, "/");
delete bear;
}

View File

@ -0,0 +1,51 @@
#!/usr/bin/python
# This script pulls the list of Mozilla trusted certificate authorities
# from the web at the "mozurl" below, parses the file to grab the PEM
# for each cert, and then generates DER files in a new ./data directory
# Upload these to a SPIFFS filesystem and use the CertManager to parse
# and use them for your outgoing SSL connections.
#
# Script by Earle F. Philhower, III. Released to the public domain.
import csv
from os import mkdir
from subprocess import Popen, PIPE
import urllib2
try:
# for Python 2.x
from StringIO import StringIO
except ImportError:
# for Python 3.x
from io import StringIO
# Mozilla's URL for the CSV file with included PEM certs
mozurl = "https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReportPEMCSV"
# Load the manes[] and pems[] array from the URL
names = []
pems = []
response = urllib2.urlopen(mozurl)
csvData = response.read()
csvReader = csv.reader(StringIO(csvData))
for row in csvReader:
names.append(row[0]+":"+row[1]+":"+row[2])
pems.append(row[28])
del names[0] # Remove headers
del pems[0] # Remove headers
# Try and make ./data, skip if present
try:
os.mkdir("data")
except:
pass
# Process the text PEM using openssl into DER files
for i in range(0, len(pems)):
certName = "data/ca_%03d.der" % (i);
thisPem = pems[i].replace("'", "")
print names[i] + " -> " + certName
pipe = Popen(['openssl','x509','-inform','PEM','-outform','DER','-out', certName], shell = False, stdin = PIPE).stdin
pipe.write(thisPem)
pipe.close

View File

@ -0,0 +1,125 @@
// Shows how to use the Maximum Fragment Length option in
// BearSSL to reduce SSL memory needs.
//
// Mar 2018 by Earle F. Philhower, III
// Released to the public domain
#include <ESP8266WiFi.h>
const char *ssid = "....";
const char *pass = "....";
void fetch(BearSSL::WiFiClientSecure *client) {
client->write("GET / HTTP/1.0\r\nHost: tls.mbed.org\r\nUser-Agent: ESP8266\r\n\r\n");
client->flush();
uint32_t to = millis() + 5000;
do {
char tmp[32];
memset(tmp, 0, 32);
int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
yield();
if (rlen < 0) {
break;
}
Serial.print(tmp);
} while (millis() < to);
client->stop();
Serial.printf("\n-------\n");
}
int fetchNoMaxFragmentLength() {
int ret = ESP.getFreeHeap();
Serial.printf("\nConnecting to https://tls.mbed.org\n");
Serial.printf("No MFLN attempted\n");
BearSSL::WiFiClientSecure client;
client.setInsecure();
client.connect("tls.mbed.org", 443);
if (client.connected()) {
Serial.printf("Memory used: %d\n", ret - ESP.getFreeHeap());
ret -= ESP.getFreeHeap();
fetch(&client);
} else {
Serial.printf("Unable to connect\n");
}
return ret;
}
int fetchMaxFragmentLength() {
int ret = ESP.getFreeHeap();
// Servers which implement RFC6066's Maximum Fragment Length Negotiation
// can be configured to limit the size of TLS fragments they transmit.
// This lets small clients, like the ESP8266, use a smaller memory buffer
// on the receive end (all the way down to under 1KB). Unfortunately,
// as of March 2018, there are not many public HTTPS servers which
// implement this option. You can deploy your own HTTPS or MQTT server
// with MFLN enabled, of course.
//
// To determine if MFLN is supported by a server use the
// ::probeMaxFragmentLength() method before connecting, and if it
// returns true then you can use the ::setBufferSizes(rx, tx) to shrink
// the needed BearSSL memory while staying within protocol limits.
//
// If MFLN is not supported, you may still be able to mimimize the buffer
// sizes assuming you can ensure the server never transmits fragments larger
// than the size (i.e. by using HTTP GET RANGE methods, etc.).
BearSSL::WiFiClientSecure client;
client.setInsecure();
bool mfln = client.probeMaxFragmentLength("tls.mbed.org", 443, 1024);
Serial.printf("\nConnecting to https://tls.mbed.org\n");
Serial.printf("MFLN supported: %s\n", mfln ? "yes" : "no");
if (mfln) {
client.setBufferSizes(1024, 1024);
}
client.connect("tls.mbed.org", 443);
if (client.connected()) {
Serial.printf("Memory used: %d\n", ret - ESP.getFreeHeap());
ret -= ESP.getFreeHeap();
fetch(&client);
} else {
Serial.printf("Unable to connect\n");
}
return ret;
}
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.print(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
Serial.printf("\n\n\n\n\n");
yield();
int a = fetchNoMaxFragmentLength();
yield();
int b = fetchMaxFragmentLength();
yield();
Serial.printf("\n\n");
Serial.printf("Default SSL: %d bytes used\n", a);
Serial.printf("1024 byte MFLN SSL: %d bytes used\n", b);
}

View File

@ -0,0 +1,177 @@
/*
Demonstrate the usage of WiFiServerBearSSL.
By Earle F. Philhower, III
A simple HTTPS server is implemented with a self-signed
certificate for the ESP8266.
This is NOT the best way to implement a HTTPS website on the
ESP8266. Please see the ESP8266WebServerBearSSL example for
a much better way of doing this!
IMPORTANT NOTES ABOUT SSL CERTIFICATES
1. USE/GENERATE YOUR OWN CERTIFICATES
While a sample, self-signed certificate is included in this example,
it is ABSOLUTELY VITAL that you use your own SSL certificate in any
real-world deployment. Anyone with the certificate and key may be
able to decrypt your traffic, so your own keys should be kept in a
safe manner, not accessible on any public network.
2. HOW TO GENERATE YOUR OWN CERTIFICATE/KEY PAIR
It is easy to use OpenSSL to generate a self-signed certificate
openssl req -x509 -nodes -newkey rsa:2048 -keyout key.pem -out cert.pem -days 4096
You may also, of course, use a commercial, trusted SSL provider to
generate your certificate.
Included with this example are *SAMPLE* certs and keys. They are NOT
SECURE, since they're shared with all copies of the repo, so
DO NOT USE THE SAMPLE CERTS, KEYS, OR CAS IN YOUR OWN PROJECT!!!
Run this example and then try connecting to the server https://IP.
This example is released into the public domain.
*/
#include <ESP8266WiFi.h>
#include <time.h>
const char *ssid = "....";
const char *pass = "....";
// The HTTPS server
BearSSL::WiFiServerSecure server(443);
// The server's private key which must be kept secret
const char server_private_key[] PROGMEM = R"EOF(
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDJblrg47vF3qlE
NMRM7uG8QwE6v/AKpxOL+CLb/32s+dW9Psgf+oZKJgzGkYUoJdWpLitTmTZeykAs
Sq7Iax5Rq/mGqyAc7oJAUUAupfNRU0KwkD1XqtpQWEFoiqoIqZbOZ4CRX5q8z/MN
BH1aPVBMKaL33uwknkgJBzxwZJ2+uGKxRJt8+koj1CXgUCk5lEAEEG5kqE326MjN
O/c4gBqulBV8AIoq6/trY3apTS7FEOiN47qh1PVzoBm/oGVwXvoZAZOj7+gGGo91
sBC5oHJy5Y2BOcNB3opTNXQTiK3Z80b5wc3iQS+h83qAfHwhs6tfAW22WkAf+jtt
x8KdRWFNAgMBAAECggEAPd+jFL9/d1lc/zGCNuuN9YlTgFti/bKyo2UWOCOz1AVu
LVJyoLgQtggYFoqur1Vn2y7uaiB+/gD8U16hb7jPuGCuJjq8g4aUBfOvVmTtZ8a+
joPQA/TcWJ+zf8xQTJbjVwWeDYmje2oZC5+cbbK1zp9fiuoz+U+RawyI+TE+700i
ESCmsKFIHy2Ifruva8HgcPYIPpZ9zLxJj0Dii+WDs7zM9h2dzO4HfImSG/DPmgoV
ydo9IcrUE7KoMLa8Uo7u1b2h6BnTn7GfYiMSUsYcYR3CnpDBknBWjZMwrV0uqv9q
TbVc4QXt+c1q89HDg7BIJaOAzbCvJfgAfXUqZyqwQQKBgQD5ENFjicUzCqPw7fOy
Q5Z8GeUbIJ5urT1MheAq7SPd2kK8TsO3hUjNC0LLNSyKPs6gsYaIiObO3wDGeZZk
xeHBhrUVaz2nIjI7TrnCUpMDOrdxcPr4bc+ifV5YT4W3OFBWQ9chQEx3Nm3DbiX4
fpno34AiFrJF791JkTPFj9OIUQKBgQDPCgcae1pQr77q+GL5Q2tku3RrE4cWtExf
m8DzAb4Vxe3EhPz8bVr+71rqr/KqNfG1uKE3sT0fhB6VMTkHTOQU13jDrvpPUS3W
Vg8cVr5/+iiyF0xb+W8LQ+GVdR5xnMPSZHUtXyURvtzT4nnTAlAtN7lEytX9BzbX
xhltOOwGPQKBgA/Y/BnDSGLpCGlqGpl7J3YaB7PkLXCJYV8fHZZdpGyXWKu2r0lc
F7fEQanAZmcde/RJl2/UlisPkXMPhXxAAw9XTOph+nhJ+rw/VB6DNot8DvQO5kks
Y4vJQlmIJc/0q1fx1RxuhO8I7Y8D0TKwi4Z/wh1pKEq+6mul649kiWchAoGAWn8B
l9uvIHGRO9eSO23ytTcSrfL9Kzln4KqN7iom0hGP2kRe6F9MVP5+ePKrWSb3Hf0z
ysoX83ymeYPob352e32rda04EA9lv7giJrrrzbikrSNt5w3iMcRcCB4HTpW9Kmtq
pIhgBZ+tmpf1s/vg28LtoloeqtjKagpW9tzYnekCgYAZFZ84EGqS9SHw5LELgGY4
mQLMwbYZ6wBMA2PlqYi/17hoAVWz37mLDjtWDB4ir78QMoGbesQVtK9W/4vzmez4
ZLKlffdL5tCtA08Gq9aond1z83Xdnh1UjtwHIJvJPc/AoCFW1r5skv/G6acAk6I2
Zs0aiirNGTEymRX4rw26Qg==
-----END PRIVATE KEY-----
)EOF";
// The server's public certificate which must be shared
const char server_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDUTCCAjmgAwIBAgIJAOcfK7c3JQtnMA0GCSqGSIb3DQEBCwUAMD8xCzAJBgNV
BAYTAkFVMQ0wCwYDVQQIDAROb25lMQ0wCwYDVQQKDAROb25lMRIwEAYDVQQDDAlF
U1BTZXJ2ZXIwHhcNMTgwMzE0MTg1NTQ1WhcNMjkwNTMxMTg1NTQ1WjA/MQswCQYD
VQQGEwJBVTENMAsGA1UECAwETm9uZTENMAsGA1UECgwETm9uZTESMBAGA1UEAwwJ
RVNQU2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyW5a4OO7
xd6pRDTETO7hvEMBOr/wCqcTi/gi2/99rPnVvT7IH/qGSiYMxpGFKCXVqS4rU5k2
XspALEquyGseUav5hqsgHO6CQFFALqXzUVNCsJA9V6raUFhBaIqqCKmWzmeAkV+a
vM/zDQR9Wj1QTCmi997sJJ5ICQc8cGSdvrhisUSbfPpKI9Ql4FApOZRABBBuZKhN
9ujIzTv3OIAarpQVfACKKuv7a2N2qU0uxRDojeO6odT1c6AZv6BlcF76GQGTo+/o
BhqPdbAQuaBycuWNgTnDQd6KUzV0E4it2fNG+cHN4kEvofN6gHx8IbOrXwFttlpA
H/o7bcfCnUVhTQIDAQABo1AwTjAdBgNVHQ4EFgQUBEk8LqgV+sMjdl/gpP1OlcNW
14EwHwYDVR0jBBgwFoAUBEk8LqgV+sMjdl/gpP1OlcNW14EwDAYDVR0TBAUwAwEB
/zANBgkqhkiG9w0BAQsFAAOCAQEAO1IrqW21KfzrxKmtuDSHdH5YrC3iOhiF/kaK
xXbigdtw6KHW/pIhGiA3BY5u+d5eVuHTR5YSwIbbRvOjuoNBATAw/8f5mt5Wa+C3
PDpLNxDys561VbCW45RMQ0x5kybvDYi0D1R/grqZ18veuFSfE6QMJ/mzvr575fje
8r5Ou0IZOYYF8cyqG5rA4U7BYXEnH44VgwlpkF8pitPsnyUWaAYqE0KnZ0qw0Py4
HCkfGJNlNOOamnr6KakVlocwKY0SdxcLoXSs5ogTQvTSrAOjwcm1RA0hOCXr8f/f
UsQIIGpPVh1plR1vYNndDeBpRJSFkoJTkgAIrlFzSMwNebU0pg==
-----END CERTIFICATE-----
)EOF";
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Attach the server private cert/key combo
BearSSLX509List *serverCertList = new BearSSLX509List(server_cert);
BearSSLPrivateKey *serverPrivKey = new BearSSLPrivateKey(server_private_key);
server.setRSACert(serverCertList, serverPrivKey);
// Actually start accepting connections
server.begin();
}
static const char *HTTP_RES =
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Content-Length: 62\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"\r\n"
"<html>\r\n"
"<body>\r\n"
"<p>Hello from ESP8266!</p>\r\n"
"</body>\r\n"
"</html>\r\n";
void loop() {
BearSSL::WiFiClientSecure incoming = server.available();
if (!incoming) {
return;
}
Serial.println("Incoming connection...\n");
// Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here)
uint32_t timeout=millis() + 1000;
int lcwn = 0;
for (;;) {
unsigned char x=0;
if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) {
incoming.stop();
Serial.printf("Connection error, closed\n");
return;
} else if (!x) {
yield();
continue;
} else if (x == 0x0D) {
continue;
} else if (x == 0x0A) {
if (lcwn) {
break;
}
lcwn = 1;
} else
lcwn = 0;
}
incoming.write((uint8_t*)HTTP_RES, strlen(HTTP_RES));
incoming.flush();
incoming.stop();
Serial.printf("Connection closed.\n");
}

View File

@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDUTCCAjmgAwIBAgIJAOcfK7c3JQtnMA0GCSqGSIb3DQEBCwUAMD8xCzAJBgNV
BAYTAkFVMQ0wCwYDVQQIDAROb25lMQ0wCwYDVQQKDAROb25lMRIwEAYDVQQDDAlF
U1BTZXJ2ZXIwHhcNMTgwMzE0MTg1NTQ1WhcNMjkwNTMxMTg1NTQ1WjA/MQswCQYD
VQQGEwJBVTENMAsGA1UECAwETm9uZTENMAsGA1UECgwETm9uZTESMBAGA1UEAwwJ
RVNQU2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyW5a4OO7
xd6pRDTETO7hvEMBOr/wCqcTi/gi2/99rPnVvT7IH/qGSiYMxpGFKCXVqS4rU5k2
XspALEquyGseUav5hqsgHO6CQFFALqXzUVNCsJA9V6raUFhBaIqqCKmWzmeAkV+a
vM/zDQR9Wj1QTCmi997sJJ5ICQc8cGSdvrhisUSbfPpKI9Ql4FApOZRABBBuZKhN
9ujIzTv3OIAarpQVfACKKuv7a2N2qU0uxRDojeO6odT1c6AZv6BlcF76GQGTo+/o
BhqPdbAQuaBycuWNgTnDQd6KUzV0E4it2fNG+cHN4kEvofN6gHx8IbOrXwFttlpA
H/o7bcfCnUVhTQIDAQABo1AwTjAdBgNVHQ4EFgQUBEk8LqgV+sMjdl/gpP1OlcNW
14EwHwYDVR0jBBgwFoAUBEk8LqgV+sMjdl/gpP1OlcNW14EwDAYDVR0TBAUwAwEB
/zANBgkqhkiG9w0BAQsFAAOCAQEAO1IrqW21KfzrxKmtuDSHdH5YrC3iOhiF/kaK
xXbigdtw6KHW/pIhGiA3BY5u+d5eVuHTR5YSwIbbRvOjuoNBATAw/8f5mt5Wa+C3
PDpLNxDys561VbCW45RMQ0x5kybvDYi0D1R/grqZ18veuFSfE6QMJ/mzvr575fje
8r5Ou0IZOYYF8cyqG5rA4U7BYXEnH44VgwlpkF8pitPsnyUWaAYqE0KnZ0qw0Py4
HCkfGJNlNOOamnr6KakVlocwKY0SdxcLoXSs5ogTQvTSrAOjwcm1RA0hOCXr8f/f
UsQIIGpPVh1plR1vYNndDeBpRJSFkoJTkgAIrlFzSMwNebU0pg==
-----END CERTIFICATE-----

View File

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDJblrg47vF3qlE
NMRM7uG8QwE6v/AKpxOL+CLb/32s+dW9Psgf+oZKJgzGkYUoJdWpLitTmTZeykAs
Sq7Iax5Rq/mGqyAc7oJAUUAupfNRU0KwkD1XqtpQWEFoiqoIqZbOZ4CRX5q8z/MN
BH1aPVBMKaL33uwknkgJBzxwZJ2+uGKxRJt8+koj1CXgUCk5lEAEEG5kqE326MjN
O/c4gBqulBV8AIoq6/trY3apTS7FEOiN47qh1PVzoBm/oGVwXvoZAZOj7+gGGo91
sBC5oHJy5Y2BOcNB3opTNXQTiK3Z80b5wc3iQS+h83qAfHwhs6tfAW22WkAf+jtt
x8KdRWFNAgMBAAECggEAPd+jFL9/d1lc/zGCNuuN9YlTgFti/bKyo2UWOCOz1AVu
LVJyoLgQtggYFoqur1Vn2y7uaiB+/gD8U16hb7jPuGCuJjq8g4aUBfOvVmTtZ8a+
joPQA/TcWJ+zf8xQTJbjVwWeDYmje2oZC5+cbbK1zp9fiuoz+U+RawyI+TE+700i
ESCmsKFIHy2Ifruva8HgcPYIPpZ9zLxJj0Dii+WDs7zM9h2dzO4HfImSG/DPmgoV
ydo9IcrUE7KoMLa8Uo7u1b2h6BnTn7GfYiMSUsYcYR3CnpDBknBWjZMwrV0uqv9q
TbVc4QXt+c1q89HDg7BIJaOAzbCvJfgAfXUqZyqwQQKBgQD5ENFjicUzCqPw7fOy
Q5Z8GeUbIJ5urT1MheAq7SPd2kK8TsO3hUjNC0LLNSyKPs6gsYaIiObO3wDGeZZk
xeHBhrUVaz2nIjI7TrnCUpMDOrdxcPr4bc+ifV5YT4W3OFBWQ9chQEx3Nm3DbiX4
fpno34AiFrJF791JkTPFj9OIUQKBgQDPCgcae1pQr77q+GL5Q2tku3RrE4cWtExf
m8DzAb4Vxe3EhPz8bVr+71rqr/KqNfG1uKE3sT0fhB6VMTkHTOQU13jDrvpPUS3W
Vg8cVr5/+iiyF0xb+W8LQ+GVdR5xnMPSZHUtXyURvtzT4nnTAlAtN7lEytX9BzbX
xhltOOwGPQKBgA/Y/BnDSGLpCGlqGpl7J3YaB7PkLXCJYV8fHZZdpGyXWKu2r0lc
F7fEQanAZmcde/RJl2/UlisPkXMPhXxAAw9XTOph+nhJ+rw/VB6DNot8DvQO5kks
Y4vJQlmIJc/0q1fx1RxuhO8I7Y8D0TKwi4Z/wh1pKEq+6mul649kiWchAoGAWn8B
l9uvIHGRO9eSO23ytTcSrfL9Kzln4KqN7iom0hGP2kRe6F9MVP5+ePKrWSb3Hf0z
ysoX83ymeYPob352e32rda04EA9lv7giJrrrzbikrSNt5w3iMcRcCB4HTpW9Kmtq
pIhgBZ+tmpf1s/vg28LtoloeqtjKagpW9tzYnekCgYAZFZ84EGqS9SHw5LELgGY4
mQLMwbYZ6wBMA2PlqYi/17hoAVWz37mLDjtWDB4ir78QMoGbesQVtK9W/4vzmez4
ZLKlffdL5tCtA08Gq9aond1z83Xdnh1UjtwHIJvJPc/AoCFW1r5skv/G6acAk6I2
Zs0aiirNGTEymRX4rw26Qg==
-----END PRIVATE KEY-----

View File

@ -0,0 +1,257 @@
/*
Demonstrate the usage of client certificate validation
for WiFiServerBearSSL.
By Earle F. Philhower, III
TLS servers can require that a client present it with an X.509
certificate signed by a trusted authority. Clients which try
and connect without a x.509 key, or with an x.509 key not signed
by the trusted authority (which could be a self-signing CA)
can not connect.
This example uses a predefined CA and any number of client
certificates. Clients will need both their X.509 cert and their
private key, both of which are generated in the signing process.
To run this example:
1. Generate a private certificate-authority certificate and key:
openssl genrsa -out ca_key.pem 2048
openssl req -x509 -new -nodes -key ca_key.pem -days 4096 -config ca.conf -out ca_cer.pem
KEEP ca_key.pem ABSOLUTELY SECURE, WITH IT ANYONE CAN MAKE CERTS
SIGNED BY YOU!
DO NOT UPLOAD ca_key.pem TO THE ESP8266, IT'S NOT NEEDED (SEE BELOW)!
ca_cer.pem is the Public X.509 certificate for your signing authority
and can(must) be shared and included in the server as the trust root.
2. Generate a private server certificate and key pair (using the
self-signed CA or any other CA you'd like)
openssl genrsa -out server_key.pem 2048
openssl req -out server_req.csr -key server_key.pem -new -config server.conf
openssl x509 -req -in server_req.csr -out server_cer.pem -sha256 -CAcreateserial -days 4000 -CA ca_cer.pem -CAkey ca_key.pem
KEEP server_key.pem SECURE, IT IS YOUR SERVER'S PRIVATE KEY.
THIS WILL BE STORED IN THE SERVER ALONE. CLIENTS DO NOT NEED IT!
server_cer.pem *CAN* BE SHARED WITH CLIENTS, OR THE CLIENTS CAN SIMPLY
USE YOUR SELF-SIGNED CA_CER.PEM
3. Generate any number of private client certificate/key pairs (using the
private CA above)
openssl genrsa -out client1_key.pem 2048
openssl req -out client1_req.csr -key client1_key.pem -new -config client.conf
openssl x509 -req -in client1_req.csr -out client1_cer.pem -sha256 -CAcreateserial -days 4000 -CA ca_cer.pem -CAkey ca_key.pem
Every client should have its own unique certificate generated and
a copy of that specific client's private key.
DO NOT SHARE THE PRIVATE KEY GENERATED ABOVE!
Included with this example are *SAMPLE* certs and keys. They are NOT
SECURE, since they're shared with all copies of the repo, so
DO NOT USE THE SAMPLE CERTS, KEYS, OR CAS IN YOUR OWN PROJECT!!!
Run this example and then try connecting to the server IP:4433.
If you don't specify the client cert and key on the WGET command
line, you will not get connected.
ex: wget --quiet --O - --no-check-certificate --certificate=client1_cer.pem --private-key=client1_key.pem https://esp.ip.add.ress/
This example is released into the public domain.
*/
#include <ESP8266WiFi.h>
#include <time.h>
const char *ssid = "....";
const char *pass = "....";
// The server which will require a client cert signed by the trusted CA
BearSSL::WiFiServerSecure server(443);
// The hardcoded certificate authority for this example.
// Don't use it on your own apps!!!!!
const char ca_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIC1TCCAb2gAwIBAgIJAMPt1Ms37+hLMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV
BAYTAlVTMRIwEAYDVQQDDAkxMjcuMC4wLjMwHhcNMTgwMzE0MDQyMTU0WhcNMjkw
NTMxMDQyMTU0WjAhMQswCQYDVQQGEwJVUzESMBAGA1UEAwwJMTI3LjAuMC4zMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsa4qU/tlzN4YTcnn/I/ffsi
jOPc8QRcwClKzasIZNFEye4uThl+LGZWFIFb8X8Dc+xmmBaWlPJbqtphgFKStpar
DdduHSW1ud6Y1FVKxljo3UwCMrYm76Q/jNzXJvGs6Z1MDNsVZzGJaoqit2H2Hkvk
y+7kk3YbEDlcyVsLOw0zCKL4cd2DSNDyhIZxWo2a8Qn5IdjWAYtsTnW6MvLk/ya4
abNeRfSZwi+r37rqi9CIs++NpL5ynqkKKEMrbeLactWgHbWrZeaMyLpuUEL2GF+w
MRaAwaj7ERwT5gFJRqYwj6bbfIdx5PC7h7ucbyp272MbrDa6WNBCMwQO222t4wID
AQABoxAwDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCmXfrC42nW
IpL3JDkB8YlB2QUvD9JdMp98xxo33+xE69Gov0e6984F1Gluao0p6sS7KF+q3YLS
4hjnzuGzF9GJMimIB7NMQ20yXKfKpmKJ7YugMaKTDWDhHn5679mKVbLSQxHCUMEe
tEnMT93/UaDbWBjV6zu876q5vjPMYgDHODqO295ySaA71UkijaCn6UwKUT49286T
V9ZtzgabNGHXfklHgUPWoShyze+G3g29I1BR0qABoJI63zaNu8ua42v5g1RldxsW
X8yKI14mFOGxuvcygG8L2xxysW7Zq+9g+O7gW0Pm6RDYnUQmIwY83h1KFCtYCJdS
2PgozwkkUNyP
-----END CERTIFICATE-----
)EOF";
// The server's private key which must be kept secret
const char server_private_key[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAsRNVTvqP++YUh8NrbXwE83xVsDqcB3F76xcXNKFDERfVd2P/
LvyDovCcoQtT0UCRgPcxRp894EuPH/Ru6Z2Lu85sV//i7ce27tc2WRFSfuhlRxHP
LJWHxTl1CEfXp/owkECQ4MB3pw6Ekc16iTEPiezTG+T+mQ/BkiIwcIK6CMlpR9DI
eYUTqv0f9NrUfAjdBrqlEO2gpgFvLFrkDEU2ntAIc4aPOP7yDOym/xzfy6TiG8Wo
7nlh6M97xTZGfbEPCH9rZDjo5istym1HzF5P+COq+OTSPscjFGXoi978o6hZwa7i
zxorg4h5a5lGnshRu2Gl+Ybfa14OwnIrv/yCswIDAQABAoIBAHxwgbsHCriTcEoY
Yx6F0VTrQ6ydA5mXfuYvS/eIfIE+pp1IgMScYEXZobjrJPQg1CA1l0NyFSHS97oV
JPy34sMQxcLx6KABgeVHCMJ/EeJtnv7a3SUP0GIhhsVS95Lsl8RIG4hWub+EzFVK
eZqAB9N9wr4Pp3wZPodbz37B38rb1QPyMFmQOLlHjKTOmoxsXhL2ot+R3+aLYSur
oPO1kQo7/d0UAZoy8h9OQN4a2EXvawh4O2EvFGbc5X/yXwAdEQ4NPp9VZhkNIRkV
+XZ3FcIqEVOploKtRF/tVBTz3g61/lFz21L9PMmV5y8tvSafr2SpJugGVmp2rrVQ
VNyGlIECgYEA10JSI5gmeCU3zK6kvOfBp54hY/5dDrSUpjKkMxpmm7WZQ6Il/k7A
hMcLeMzHiriT7WhRIXF8AOr2MoEkHkH3DhVNN4ccieVZx2SE5P5mVkItZGLrrpfU
dysR/ARAI1HYegGUiKacZtf9SrRavU0m7fOVOiYwbFRhjyX+MyuteYkCgYEA0pbz
4ZosetScP68uZx1sGlTfkcqLl7i15DHk3gnj6jKlfhvC2MjeLMhNDtKeUAuY7rLQ
guZ0CCghWAv0Glh5eYdfIiPhgqFfX4P5F3Om4zQHVPYj8xHfHG4ZP7dKQTndrO1Q
fLdGDTQLVXabAUSp2YGrijC8J9idSW1pYClvF1sCgYEAjkDn41nzYkbGP1/Swnwu
AEWCL4Czoro32jVxScxSrugt5wJLNWp508VukWBTJhugtq3Pn9hNaJXeKbYqVkyl
pgrxwpZph7+nuxt0r5hnrO2C7eppcjIoWLB/7BorAKxf8REGReBFT7nBTBMwPBW2
el4U6h6+tXh2GJG1Eb/1nnECgYAydVb0THOx7rWNkNUGggc/++why61M6kYy6j2T
cj05BW+f2tkCBoctpcTI83BZb53yO8g4RS2yMqNirGKN2XspwmTqEjzbhv0KLt4F
X4GyWOoU0nFksXiLIFpOaQWSwWG7KJWrfGJ9kWXR0Xxsfl5QLoDCuNCsn3t4d43T
K7phlwKBgHDzF+50+/Wez3YHCy2a/HgSbHCpLQjkknvgwkOh1z7YitYBUm72HP8Z
Ge6b4wEfNuBdlZll/y9BQQOZJLFvJTE5t51X9klrkGrOb+Ftwr7eI/H5xgcadI52
tPYglR5fjuRF/wnt3oX9JlQ2RtSbs+3naXH8JoherHaqNn8UpH0t
-----END RSA PRIVATE KEY-----
)EOF";
// The server's public certificate which must be shared
const char server_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDTzCCAjcCCQDPXvMRYOpeuDANBgkqhkiG9w0BAQsFADCBpjESMBAGA1UEAwwJ
MTI3LjAuMC4xMQswCQYDVQQGEwJVUzElMCMGA1UECgwcTXkgT3duIENlcnRpZmlj
YXRlIEF1dGhvcml0eTEUMBIGA1UECAwLQXJkdWlub0xhbmQxFTATBgNVBAcMDEFy
ZHVpbm9WaWxsZTEVMBMGA1UECgwMRVNQODI2NlVzZXJzMRgwFgYDVQQLDA9FU1A4
MjY2LUFyZHVpbm8wHhcNMTgwMzE0MDQwMDAwWhcNMjkwMjI0MDQwMDAwWjAsMRYw
FAYDVQQKDA1NeSBTZXJ2ZXIgT3JnMRIwEAYDVQQDDAkxMjcuMC4wLjMwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCxE1VO+o/75hSHw2ttfATzfFWwOpwH
cXvrFxc0oUMRF9V3Y/8u/IOi8JyhC1PRQJGA9zFGnz3gS48f9G7pnYu7zmxX/+Lt
x7bu1zZZEVJ+6GVHEc8slYfFOXUIR9en+jCQQJDgwHenDoSRzXqJMQ+J7NMb5P6Z
D8GSIjBwgroIyWlH0Mh5hROq/R/02tR8CN0GuqUQ7aCmAW8sWuQMRTae0Ahzho84
/vIM7Kb/HN/LpOIbxajueWHoz3vFNkZ9sQ8If2tkOOjmKy3KbUfMXk/4I6r45NI+
xyMUZeiL3vyjqFnBruLPGiuDiHlrmUaeyFG7YaX5ht9rXg7Cciu//IKzAgMBAAEw
DQYJKoZIhvcNAQELBQADggEBAEnG+FNyNCOkBvzHiUpHHpScxZqM2f+XDcewJgeS
L6HkYEDIZZDNnd5gduSvkHpdJtWgsvJ7dJZL40w7Ba5sxpZHPIgKJGl9hzMkG+aA
z5GMkjys9h2xpQZx9KL3q7G6A+C0bll7ODZlwBtY07CFMykT4Mp2oMRrQKRucMSV
AB1mKujLAnMRKJ3NM89RQJH4GYiRps9y/HvM5lh7EIK/J0/nEZeJxY5hJngskPKb
oPPdmkR97kaQnll4KNsC3owVlHVU2fMftgYkgQLzyeWgzcNa39AF3B6JlcOzNyQY
seoK24dHmt6tWmn/sbxX7Aa6TL/4mVlFoOgcaTJyVaY/BrY=
-----END CERTIFICATE-----
)EOF";
// Note there are no client certificates required here in the server.
// That is because all clients will send a certificate that can be
// proven to be signed by the public CA certificate included at the
// head of the app.
// Set time via NTP, as required for x.509 validation
void setClock()
{
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print("Current time: ");
Serial.print(asctime(&timeinfo));
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
setClock(); // Required for X.509 validation
// Attach the server private cert/key combo
BearSSLX509List *serverCertList = new BearSSLX509List(server_cert);
BearSSLPrivateKey *serverPrivKey = new BearSSLPrivateKey(server_private_key);
server.setRSACert(serverCertList, serverPrivKey);
// Require a certificate validated by the trusted CA
BearSSLX509List *serverTrustedCA = new BearSSLX509List(ca_cert);
server.setClientTrustAnchor(serverTrustedCA);
// Actually start accepting connections
server.begin();
}
static const char *HTTP_RES =
"HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Content-Length: 59\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"\r\n"
"<html>\r\n"
"<body>\r\n"
"<p>Hello my friend!</p>\r\n"
"</body>\r\n"
"</html>\r\n";
void loop() {
BearSSL::WiFiClientSecure incoming = server.available();
if (!incoming) {
return;
}
Serial.println("Incoming connection...\n");
// Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here)
uint32_t timeout=millis() + 1000;
int lcwn = 0;
for (;;) {
unsigned char x=0;
if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) {
incoming.stop();
Serial.printf("Connection error, closed\n");
return;
} else if (!x) {
yield();
continue;
} else if (x == 0x0D) {
continue;
} else if (x == 0x0A) {
if (lcwn) {
break;
}
lcwn = 1;
} else
lcwn = 0;
}
incoming.write((uint8_t*)HTTP_RES, strlen(HTTP_RES));
incoming.flush();
incoming.stop();
Serial.printf("Connection closed.\n");
}

View File

@ -0,0 +1,12 @@
[ req ]
prompt = no
default_bits = 2048
distinguished_name = req_dn
x509_extensions = v3_req
[ req_dn ]
C = US
CN = 127.0.0.3
[v3_req]
basicConstraints=CA:TRUE

View File

@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC1TCCAb2gAwIBAgIJAMPt1Ms37+hLMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV
BAYTAlVTMRIwEAYDVQQDDAkxMjcuMC4wLjMwHhcNMTgwMzE0MDQyMTU0WhcNMjkw
NTMxMDQyMTU0WjAhMQswCQYDVQQGEwJVUzESMBAGA1UEAwwJMTI3LjAuMC4zMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsa4qU/tlzN4YTcnn/I/ffsi
jOPc8QRcwClKzasIZNFEye4uThl+LGZWFIFb8X8Dc+xmmBaWlPJbqtphgFKStpar
DdduHSW1ud6Y1FVKxljo3UwCMrYm76Q/jNzXJvGs6Z1MDNsVZzGJaoqit2H2Hkvk
y+7kk3YbEDlcyVsLOw0zCKL4cd2DSNDyhIZxWo2a8Qn5IdjWAYtsTnW6MvLk/ya4
abNeRfSZwi+r37rqi9CIs++NpL5ynqkKKEMrbeLactWgHbWrZeaMyLpuUEL2GF+w
MRaAwaj7ERwT5gFJRqYwj6bbfIdx5PC7h7ucbyp272MbrDa6WNBCMwQO222t4wID
AQABoxAwDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCmXfrC42nW
IpL3JDkB8YlB2QUvD9JdMp98xxo33+xE69Gov0e6984F1Gluao0p6sS7KF+q3YLS
4hjnzuGzF9GJMimIB7NMQ20yXKfKpmKJ7YugMaKTDWDhHn5679mKVbLSQxHCUMEe
tEnMT93/UaDbWBjV6zu876q5vjPMYgDHODqO295ySaA71UkijaCn6UwKUT49286T
V9ZtzgabNGHXfklHgUPWoShyze+G3g29I1BR0qABoJI63zaNu8ua42v5g1RldxsW
X8yKI14mFOGxuvcygG8L2xxysW7Zq+9g+O7gW0Pm6RDYnUQmIwY83h1KFCtYCJdS
2PgozwkkUNyP
-----END CERTIFICATE-----

View File

@ -0,0 +1 @@
A25EB184B01D7FBB

View File

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxsa4qU/tlzN4YTcnn/I/ffsijOPc8QRcwClKzasIZNFEye4u
Thl+LGZWFIFb8X8Dc+xmmBaWlPJbqtphgFKStparDdduHSW1ud6Y1FVKxljo3UwC
MrYm76Q/jNzXJvGs6Z1MDNsVZzGJaoqit2H2Hkvky+7kk3YbEDlcyVsLOw0zCKL4
cd2DSNDyhIZxWo2a8Qn5IdjWAYtsTnW6MvLk/ya4abNeRfSZwi+r37rqi9CIs++N
pL5ynqkKKEMrbeLactWgHbWrZeaMyLpuUEL2GF+wMRaAwaj7ERwT5gFJRqYwj6bb
fIdx5PC7h7ucbyp272MbrDa6WNBCMwQO222t4wIDAQABAoIBABP6hzblRLEMyE2l
GIN3+q+z3R4iDOPgl13tCIqxZQ+VBP/yw46v+0GFK6O1+MLGDFfLa+hfZNUlotcC
Sgh2xC476IdknrmpP6Gl4OB+jhxvdUBA0nu8WR9+97A1xh4w7jswxyMHphgQH4qo
0n/yBaW35RAmO60iksfHrC7EytUtahZkWq13xZsN8VNEn3dS/M54XEEQp+BLXZEh
WTd4sm5ddK58NZwLvkn0zaMyH38tllF7sezxZxWz+q4yCOB1/Xw0BC3e7dqBLtaC
PHrxWedph9sF+HXyDoXXp6S6IfSlXnCwMl0e3xBppIY9BYDnVwZpGxfUAMg26RyH
w5UEmPECgYEA51v0bxjZ/3boOH44glEFfmcJCLacoeQud+DZEMWFxmkApEVn9211
t1G+N8rnHBiAhi9bDhi3Qs9fvOxXBhqaLw1xV8KGNY8bKiKoUu8y1aeHWPbgmzYp
sfrX70mhgHUgJt4i6xzW5esTmXl3ZAqPWxzECavmoLbHnssouPb5YckCgYEA2/Jj
LPlP4XN8b4NpOhYlHmMEIwD7utIct5/7ydjtucUQAHqJ+EQ20R4MCHc9zTvjeyZ9
H/Rdxo+L0pwpbqSr0JTxOqQ1GzqstT9jVYNs+tRIQoeskd+Ags34sDJwPIbGUPfz
rBOfcHLwGfAMMBQzk5zT8frAZQV/8H7ejpCxyEsCgYBIptOnX4J1en2J3/kW0yKK
gwiPN+kP3XvKIU2Iur47hBWzgCgZxsHEg2LcWlcgt4EEojJRxukljcFerkjVndz1
EZ+aE3fZscqx/JgnEv4/oZAbG8uEcgm93iuY9OJGWIF0MyV79150bNGGzGH1hGto
DSxybQzLQxqEfv+WtdeyIQKBgQDPc8GjS8vSQ9EchQAdL4H3NUFTmrvULBW2BInC
in8+9uXu7aVwqzZg60xCN+XszA31vAnMt/ozLHWfQne5ykvcQn985iDI/ACmO5F/
uKRzuQIm7j0QoZRey9NCrXA7RouLFzOYHDIIKADbFhUIzCURl5w44l/RaOyRc7iL
E2L8HQKBgQC8WK5nT2QYtimzuwQrvSWkWyVu8/z/U8AKTusCV71uL9A6OBiUzJO3
/3Befn+qt9Nm1ZHqTsJWXIE8LPblhCkvYraq9cJ+KIymWtFVMeR99DN/yTofdyxX
Uw58Z3i5HDK4AzJhBzvk14REw5xOZZLsWAqoMHTCM/T+hVqhD+cjAw==
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,8 @@
[ req ]
prompt = no
default_bits = 2048
distinguished_name = req_dn
[ req_dn ]
O = My Client Org
CN = 127.0.0.2

View File

@ -0,0 +1,17 @@
-----BEGIN CERTIFICATE-----
MIICyTCCAbECCQCiXrGEsB1/uzANBgkqhkiG9w0BAQsFADAhMQswCQYDVQQGEwJV
UzESMBAGA1UEAwwJMTI3LjAuMC4zMB4XDTE4MDMxNDA0MjIwNloXDTI5MDIyNDA0
MjIwNlowLDEWMBQGA1UECgwNTXkgQ2xpZW50IE9yZzESMBAGA1UEAwwJMTI3LjAu
MC4yMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5MW88nCi2tUrf/Tq
5w+5IvuqTAusaN4eelwS69sd9yXfM/DEgipw7o4t340oGdLVA4b7h1Qwxttw62ki
Z5VecXosg7xbJSjbB4LLLcmvC0pYvCactMWI+k4Na6VA1cS+hMsgnd37Shzo3Gyz
2AxrpMrcANsIaLD+o9Ji/00XmbvA/dKW/sG6vK5rWjNV0JE9WVjAW+eek8doIjh5
mOKVR7zVeR1cr8wTp48e6LX9oJsv9nfACyIyMGCFp8qa+zQEBNKevohEl9OOi9Vh
H50UU6UEo0ZGAzWF8fp+T4ltTFxr/T0PXn5J2Kk2Wl5Zt5XLt0cDBlrMDpz24ZAQ
go/CDwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQA/6HqENDo5gsxWQIyC+fRFEUIy
cJ2lOlGxrf83oc1I5V10A8r6aOcwNoYlMq1Upcu2oAk2Kf5X9pq6EbM7BXuBESm4
TYYPawv3lHeiX8uX3iUReasDLBTbj4WycteSjI4JUVPvZv8ILznKkKLr2tGV19ha
UfFu/cc3iazMt0jMORd6gznWxkbgY9Qr3V4VNReD0ZUa0s9ANOjnKRIXymRicCRy
HNwSXsj/sQR1lbnI1pkyGlTZaigADlqIsH+XJjYuVxdUge5Cz1+D9kcjF9PjF4V1
u/lw6sR50qc2k5rC1WK4QLlgoknd5+ZrRiHlZXrJdcj9KnWdh4aGa3jwJpOW
-----END CERTIFICATE-----

View File

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEA5MW88nCi2tUrf/Tq5w+5IvuqTAusaN4eelwS69sd9yXfM/DE
gipw7o4t340oGdLVA4b7h1Qwxttw62kiZ5VecXosg7xbJSjbB4LLLcmvC0pYvCac
tMWI+k4Na6VA1cS+hMsgnd37Shzo3Gyz2AxrpMrcANsIaLD+o9Ji/00XmbvA/dKW
/sG6vK5rWjNV0JE9WVjAW+eek8doIjh5mOKVR7zVeR1cr8wTp48e6LX9oJsv9nfA
CyIyMGCFp8qa+zQEBNKevohEl9OOi9VhH50UU6UEo0ZGAzWF8fp+T4ltTFxr/T0P
Xn5J2Kk2Wl5Zt5XLt0cDBlrMDpz24ZAQgo/CDwIDAQABAoIBAAb5eE8z2+MsCI14
HAk7U3ubjI+Q84qm6ur0D6edIIa+YtWki3kkbhj3wLJGDWjsIo5e+SAhEvOdEQ48
QE5EIYL4JI9HmMfDPRo3hJY6xdlkRNxHmRNxykFHS+VyPk3GF8DYqH/nmpeh1f+S
WNFHX6jAfoCQLOt0Ke84pMf/w65uGixdVcXgHRA/n4gKbS84a7nZEl5NqT02wrrA
BRY6pRvcsvFHaf4VEPKXpRE5UxXGMJwtyYfl9Mukszepi6g/Hk2WI499tdgDzM55
hWLRlW7ZzMILz4aP1LYt7iolKPAEst2rZdSgumIwznZUymIevlo95iYjazX9TWFv
K9LKoeECgYEA9Mj569wGYATBSD1SQzPRMQybDpBgoz+T2tfeqaas2aHcUIUK2v8c
iR5xe3soFOPTaaQBtUgo3S016SR2OLo9xY0ag71mrJZj+zuY+bPO1YMi+qh0/s5E
ZRGMzhAzTmX/5jYQmu6W5ZIAETELMZ4E8p9hW/yG+1oT4Z0csXfP4BkCgYEA70D0
Ef7e2os/76X7T2PpcLfA/4VPLS/QIbm57eVuc1GX5U7/YXdnqE4Z1pFhR+yJdId0
iqx9NxTpqxK8QTkswZSeltLXnvWxlZWjsW+GdhwzrLjjA8OAuZqk/uiNVVTavl0M
vjxTJWAiRU3PF9bLeFvF059HuflnFOqwtiyEWGcCgYBOWMUlKJchxGPYq0fZGoyq
Fk7KqotDtOWt9cneoupP/e52Fx8SWPTZLlVEIHcDuKfB+CxTyXTK1d2bcYAlR/bd
c/w4jjZ+puP5VWnxAgwBaqeXcrN/mqVpc+SNT8IcJalyFXvbGuJROBmtZvUePGV5
Amo29ux9JqeWXqMAakiugQKBgB50MB0SSh+bVfoVMJX8a7xzR1e/CkMAMQf58ha7
+4EmQ6Vmls87ObCMsHFFdBKJoz13+HemWRHn0Y57BgdvVakWV9Fu6Q9Mytv1fi6Z
uY3TLSixKARUoE//xTzFMShJcsaEZZjZaOP7BqG3s8KfDqs1U0sKnUCo5FwfO3sU
04vFAoGALjVG6v0IpvPFZcJBN8wUuu9cLduyCnUiFsMYgfglXDSkynRS51/7Fxqf
q0ROTeHrKem3iiJ62j7U3tNni2awczWCgTlUjSQzBQo6Cu1UA52M3/XyqVNmfx/g
04dVpDrqFscdIasQcL1UddiwcT2a63RjriBaTETvjegoNVu1XR4=
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,16 @@
-----BEGIN CERTIFICATE REQUEST-----
MIICcTCCAVkCAQAwLDEWMBQGA1UECgwNTXkgQ2xpZW50IE9yZzESMBAGA1UEAwwJ
MTI3LjAuMC4yMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5MW88nCi
2tUrf/Tq5w+5IvuqTAusaN4eelwS69sd9yXfM/DEgipw7o4t340oGdLVA4b7h1Qw
xttw62kiZ5VecXosg7xbJSjbB4LLLcmvC0pYvCactMWI+k4Na6VA1cS+hMsgnd37
Shzo3Gyz2AxrpMrcANsIaLD+o9Ji/00XmbvA/dKW/sG6vK5rWjNV0JE9WVjAW+ee
k8doIjh5mOKVR7zVeR1cr8wTp48e6LX9oJsv9nfACyIyMGCFp8qa+zQEBNKevohE
l9OOi9VhH50UU6UEo0ZGAzWF8fp+T4ltTFxr/T0PXn5J2Kk2Wl5Zt5XLt0cDBlrM
Dpz24ZAQgo/CDwIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAFLPF8/g9IMgQZvk
ZXvgPPPUAvANX3e0mcivjZD1BoqQ7CHeBqDpaaqH6i0qZrRQI6oli69IeQczkrXh
onhzLvCVoWmS1FH9JyWozRO6LeePEtV0jzxBDxHAd3pmlqTwLEpm0LfpBMkMe0Cb
r+3bOvAqW4ILkdSJ5FiAqlubu4+ezSLQTS/EJ+BzLkhuVuERqXFo/tW5KqviYbTL
XbvoLRVydNOUVZ+ts9YAtYLsqGoB6Rax6IzoLz5BXe5edw3FAEuotAJaLgWkBh/A
283zzb0pIUiZdF+8n61Fg4qFMZYYps4Fll4FXTn4mIzsfbJpkPXYGGuKvla46svH
tpAv/so=
-----END CERTIFICATE REQUEST-----

View File

@ -0,0 +1,8 @@
[ req ]
prompt = no
default_bits = 2048
distinguished_name = req_dn
[ req_dn ]
O = My Server Org
CN = 127.0.0.3

View File

@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDTzCCAjcCCQDPXvMRYOpeuDANBgkqhkiG9w0BAQsFADCBpjESMBAGA1UEAwwJ
MTI3LjAuMC4xMQswCQYDVQQGEwJVUzElMCMGA1UECgwcTXkgT3duIENlcnRpZmlj
YXRlIEF1dGhvcml0eTEUMBIGA1UECAwLQXJkdWlub0xhbmQxFTATBgNVBAcMDEFy
ZHVpbm9WaWxsZTEVMBMGA1UECgwMRVNQODI2NlVzZXJzMRgwFgYDVQQLDA9FU1A4
MjY2LUFyZHVpbm8wHhcNMTgwMzE0MDQwMDAwWhcNMjkwMjI0MDQwMDAwWjAsMRYw
FAYDVQQKDA1NeSBTZXJ2ZXIgT3JnMRIwEAYDVQQDDAkxMjcuMC4wLjMwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCxE1VO+o/75hSHw2ttfATzfFWwOpwH
cXvrFxc0oUMRF9V3Y/8u/IOi8JyhC1PRQJGA9zFGnz3gS48f9G7pnYu7zmxX/+Lt
x7bu1zZZEVJ+6GVHEc8slYfFOXUIR9en+jCQQJDgwHenDoSRzXqJMQ+J7NMb5P6Z
D8GSIjBwgroIyWlH0Mh5hROq/R/02tR8CN0GuqUQ7aCmAW8sWuQMRTae0Ahzho84
/vIM7Kb/HN/LpOIbxajueWHoz3vFNkZ9sQ8If2tkOOjmKy3KbUfMXk/4I6r45NI+
xyMUZeiL3vyjqFnBruLPGiuDiHlrmUaeyFG7YaX5ht9rXg7Cciu//IKzAgMBAAEw
DQYJKoZIhvcNAQELBQADggEBAEnG+FNyNCOkBvzHiUpHHpScxZqM2f+XDcewJgeS
L6HkYEDIZZDNnd5gduSvkHpdJtWgsvJ7dJZL40w7Ba5sxpZHPIgKJGl9hzMkG+aA
z5GMkjys9h2xpQZx9KL3q7G6A+C0bll7ODZlwBtY07CFMykT4Mp2oMRrQKRucMSV
AB1mKujLAnMRKJ3NM89RQJH4GYiRps9y/HvM5lh7EIK/J0/nEZeJxY5hJngskPKb
oPPdmkR97kaQnll4KNsC3owVlHVU2fMftgYkgQLzyeWgzcNa39AF3B6JlcOzNyQY
seoK24dHmt6tWmn/sbxX7Aa6TL/4mVlFoOgcaTJyVaY/BrY=
-----END CERTIFICATE-----

View File

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAsRNVTvqP++YUh8NrbXwE83xVsDqcB3F76xcXNKFDERfVd2P/
LvyDovCcoQtT0UCRgPcxRp894EuPH/Ru6Z2Lu85sV//i7ce27tc2WRFSfuhlRxHP
LJWHxTl1CEfXp/owkECQ4MB3pw6Ekc16iTEPiezTG+T+mQ/BkiIwcIK6CMlpR9DI
eYUTqv0f9NrUfAjdBrqlEO2gpgFvLFrkDEU2ntAIc4aPOP7yDOym/xzfy6TiG8Wo
7nlh6M97xTZGfbEPCH9rZDjo5istym1HzF5P+COq+OTSPscjFGXoi978o6hZwa7i
zxorg4h5a5lGnshRu2Gl+Ybfa14OwnIrv/yCswIDAQABAoIBAHxwgbsHCriTcEoY
Yx6F0VTrQ6ydA5mXfuYvS/eIfIE+pp1IgMScYEXZobjrJPQg1CA1l0NyFSHS97oV
JPy34sMQxcLx6KABgeVHCMJ/EeJtnv7a3SUP0GIhhsVS95Lsl8RIG4hWub+EzFVK
eZqAB9N9wr4Pp3wZPodbz37B38rb1QPyMFmQOLlHjKTOmoxsXhL2ot+R3+aLYSur
oPO1kQo7/d0UAZoy8h9OQN4a2EXvawh4O2EvFGbc5X/yXwAdEQ4NPp9VZhkNIRkV
+XZ3FcIqEVOploKtRF/tVBTz3g61/lFz21L9PMmV5y8tvSafr2SpJugGVmp2rrVQ
VNyGlIECgYEA10JSI5gmeCU3zK6kvOfBp54hY/5dDrSUpjKkMxpmm7WZQ6Il/k7A
hMcLeMzHiriT7WhRIXF8AOr2MoEkHkH3DhVNN4ccieVZx2SE5P5mVkItZGLrrpfU
dysR/ARAI1HYegGUiKacZtf9SrRavU0m7fOVOiYwbFRhjyX+MyuteYkCgYEA0pbz
4ZosetScP68uZx1sGlTfkcqLl7i15DHk3gnj6jKlfhvC2MjeLMhNDtKeUAuY7rLQ
guZ0CCghWAv0Glh5eYdfIiPhgqFfX4P5F3Om4zQHVPYj8xHfHG4ZP7dKQTndrO1Q
fLdGDTQLVXabAUSp2YGrijC8J9idSW1pYClvF1sCgYEAjkDn41nzYkbGP1/Swnwu
AEWCL4Czoro32jVxScxSrugt5wJLNWp508VukWBTJhugtq3Pn9hNaJXeKbYqVkyl
pgrxwpZph7+nuxt0r5hnrO2C7eppcjIoWLB/7BorAKxf8REGReBFT7nBTBMwPBW2
el4U6h6+tXh2GJG1Eb/1nnECgYAydVb0THOx7rWNkNUGggc/++why61M6kYy6j2T
cj05BW+f2tkCBoctpcTI83BZb53yO8g4RS2yMqNirGKN2XspwmTqEjzbhv0KLt4F
X4GyWOoU0nFksXiLIFpOaQWSwWG7KJWrfGJ9kWXR0Xxsfl5QLoDCuNCsn3t4d43T
K7phlwKBgHDzF+50+/Wez3YHCy2a/HgSbHCpLQjkknvgwkOh1z7YitYBUm72HP8Z
Ge6b4wEfNuBdlZll/y9BQQOZJLFvJTE5t51X9klrkGrOb+Ftwr7eI/H5xgcadI52
tPYglR5fjuRF/wnt3oX9JlQ2RtSbs+3naXH8JoherHaqNn8UpH0t
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,228 @@
// Example of the different modes of the X.509 validation options
// in the WiFiClientBearSSL object
//
// Mar 2018 by Earle F. Philhower, III
// Released to the public domain
#include <ESP8266WiFi.h>
#include <time.h>
const char *ssid = "....";
const char *pass = "....";
const char * host = "api.github.com";
const uint16_t port = 443;
const char * path = "/";
// Set time via NTP, as required for x.509 validation
void setClock() {
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print("Current time: ");
Serial.print(asctime(&timeinfo));
}
// Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response
void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) {
if (!path) {
path = "/";
}
Serial.printf("Trying: %s:443...", host);
client->connect(host, port);
if (!client->connected()) {
Serial.printf("*** Can't connect. ***\n-------\n");
return;
}
Serial.printf("Connected!\n-------\n");
client->write("GET ");
client->write(path);
client->write(" HTTP/1.0\r\nHost: ");
client->write(host);
client->write("\r\nUser-Agent: ESP8266\r\n");
client->write("\r\n");
uint32_t to = millis() + 5000;
if (client->connected()) {
do {
char tmp[32];
memset(tmp, 0, 32);
int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
yield();
if (rlen < 0) {
break;
}
// Only print out first line up to \r, then abort connection
char *nl = strchr(tmp, '\r');
if (nl) {
*nl = 0;
Serial.print(tmp);
break;
}
Serial.print(tmp);
} while (millis() < to);
}
client->stop();
Serial.printf("\n-------\n\n");
}
void fetchNoConfig() {
Serial.printf(R"EOF(
If there are no CAs or insecure options specified, BearSSL will not connect.
Expect the following call to fail as none have been configured.
)EOF");
BearSSL::WiFiClientSecure client;
fetchURL(&client, host, port, path);
}
void fetchInsecure() {
Serial.printf(R"EOF(
This is absolutely *insecure*, but you can tell BearSSL not to check the
certificate of the server. In this mode it will accept ANY certificate,
which is subject to man-in-the-middle (MITM) attacks.
)EOF");
BearSSL::WiFiClientSecure client;
client.setInsecure();
fetchURL(&client, host, port, path);
}
void fetchFingerprint() {
Serial.printf(R"EOF(
The SHA-1 fingerprint of an X.509 certificate can be used to validate it
instead of the while certificate. This is not nearly as secure as real
X.509 validation, but is better than nothing.
)EOF");
BearSSL::WiFiClientSecure client;
const uint8_t fp[20] = {0x35, 0x85, 0x74, 0xEF, 0x67, 0x35, 0xA7, 0xCE, 0x40, 0x69, 0x50, 0xF3, 0xC0, 0xF6, 0x80, 0xCF, 0x80, 0x3B, 0x2E, 0x19};
client.setFingerprint(fp);
fetchURL(&client, host, port, path);
}
void fetchSelfSigned() {
Serial.printf(R"EOF(
It is also possible to accept *any* self-signed certificate. This is
absolutely insecure as anyone can make a self-signed certificate.
)EOF");
BearSSL::WiFiClientSecure client;
Serial.printf("First, try and connect to a badssl.com self-signed website (will fail):\n");
fetchURL(&client, "self-signed.badssl.com", 443, "/");
Serial.printf("Now we'll enable self-signed certs (will pass)\n");
client.allowSelfSignedCerts();
fetchURL(&client, "self-signed.badssl.com", 443, "/");
}
void fetchKnownKey() {
Serial.printf(R"EOF(
The server certificate can be completely ignored and its public key
hardcoded in your application. This should be secure as the public key
needs to be paired with the private key of the site, which is obviously
private and not shared. A MITM without the private key would not be
able to establish communications.
)EOF");
// Extracted by: openssl x509 -pubkey -noout -in servercert.pem
static const char pubkey[] PROGMEM = R"KEY(
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqcCPMEktuxLoDAxdHQgI
95FweH4Fa6+LslU2qmmUBF+pu4ZOUvpIQxVU5wqdWaxZauxG1nYUTrAWdPb1n0um
gLsGE7WYXJnQPJewIK4Qhua0LsrirIdHkcwHQ83NEYj+lswhg0fUQURt06Uta5ak
LovDdJPLqTuTS/nshOa76hR0ouWnrqucLL1szcvX/obB+Nsbmr58Mrg8prQfRoK6
ibzlZysV88qPcCpc57lq6QBKQ2F9WgQMssQigXfTNm8lAAQ+L6gCZngd4KfHYPSJ
YA07oFWmuSOalgh00Wh8PUjuRGrcNxWpmgfALQHHFYgoDcD+a8+GoJk+GdJd3ong
ZQIDAQAB
-----END PUBLIC KEY-----
)KEY";
BearSSL::WiFiClientSecure client;
BearSSLPublicKey key(pubkey);
client.setKnownKey(&key);
fetchURL(&client, host, port, path);
}
void fetchCertAuthority() {
static const char digicert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL
MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug
RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm
+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW
PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM
xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB
Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3
hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg
EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF
MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA
FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec
nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z
eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF
hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2
Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep
+OkuE6N36B9K
-----END CERTIFICATE-----
)EOF";
Serial.printf(R"EOF(
A specific certification authority can be passed in and used to validate
a chain of certificates from a given server. These will be validated
using BearSSL's rules, which do NOT include certificate revocation lists.
A specific server's certificate, or your own self-signed root certificate
can also be used. ESP8266 time needs to be valid for checks to pass as
BearSSL does verify the notValidBefore/After fields.
)EOF");
BearSSL::WiFiClientSecure client;
BearSSLX509List cert(digicert);
client.setTrustAnchors(&cert);
Serial.printf("Try validating without setting the time (should fail)\n");
fetchURL(&client, host, port, path);
Serial.printf("Try again after setting NTP time (should pass)\n");
setClock();
fetchURL(&client, host, port, path);
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
fetchNoConfig();
fetchInsecure();
fetchFingerprint();
fetchSelfSigned();
fetchKnownKey();
fetchCertAuthority();
}
void loop() {
// Nothing to do here
}

View File

@ -19,6 +19,12 @@ WiFiServerSecure KEYWORD1
WiFiUDP KEYWORD1 WiFiUDP KEYWORD1
WiFiClientSecure KEYWORD1 WiFiClientSecure KEYWORD1
ESP8266WiFiMulti KEYWORD1 ESP8266WiFiMulti KEYWORD1
BearSSLX509List KEYWORD1
BearSSLPrivateKey KEYWORD1
BearSSLPublicKey KEYWORD1
CertStoreSPIFFSBearSSL KEYWORD1
CertStoreSDBearSSL KEYWORD1
####################################### #######################################
# Methods and Functions (KEYWORD2) # Methods and Functions (KEYWORD2)
####################################### #######################################
@ -157,6 +163,28 @@ localPort KEYWORD2
stopAll KEYWORD2 stopAll KEYWORD2
stopAllExcept KEYWORD2 stopAllExcept KEYWORD2
#WiFiClientBearSSL
setInsecure KEYWORD2
setKnownKey KEYWORD2
setFingerprint KEYWORD2
allowSelfSignedCerts KEYWORD2
setTrustAnchors KEYWORD2
setX509Time KEYWORD2
setClientRSACert KEYWORD2
setClientECCert KEYWORD2
setBufferSizes KEYWORD2
getLastSSLError KEYWORD2
setCertStore KEYWORD2
probeMaxFragmentLength KEYWORD2
#WiFiServerBearSSL
setRSACert KEYWORD2
setECCert KEYWORD2
setClientTrustAnchor KEYWORD2
#CertStoreBearSSL
initCertStore KEYWORD2
####################################### #######################################
# Constants (LITERAL1) # Constants (LITERAL1)
####################################### #######################################

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 "WiFiServer.h"
#include "WiFiServerSecure.h" #include "WiFiServerSecure.h"
#include "WiFiClientSecure.h" #include "WiFiClientSecure.h"
#include "BearSSLHelpers.h"
#include "CertStoreBearSSL.h"
#ifdef DEBUG_ESP_WIFI #ifdef DEBUG_ESP_WIFI
#ifdef DEBUG_ESP_PORT #ifdef DEBUG_ESP_PORT

View File

@ -20,77 +20,8 @@
*/ */
#ifndef wificlientsecure_h #include "WiFiClientSecureAxTLS.h"
#define wificlientsecure_h #include "WiFiClientSecureBearSSL.h"
#include "WiFiClient.h"
#include "include/ssl.h"
using namespace axTLS;
class SSLContext; // using 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;
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

View File

@ -51,6 +51,8 @@ extern "C"
#define SSL_DEBUG_OPTS 0 #define SSL_DEBUG_OPTS 0
#endif #endif
namespace axTLS {
typedef struct BufferItem typedef struct BufferItem
{ {
@ -905,3 +907,5 @@ extern "C" void __ax_wdt_feed()
optimistic_yield(10000); optimistic_yield(10000);
} }
extern "C" void ax_wdt_feed() __attribute__ ((weak, alias("__ax_wdt_feed"))); 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 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
#ifndef wifiserversecure_h #include "WiFiServerSecureAxTLS.h"
#define wifiserversecure_h #include "WiFiServerSecureBearSSL.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

View File

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

View File

@ -65,6 +65,14 @@ HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& curr
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
} }
HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& currentVersion,
const uint8_t httpsFingerprint[20])
{
HTTPClient http;
http.begin(url, httpsFingerprint);
return handleUpdate(http, currentVersion, false);
}
HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint) HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint)
{ {
HTTPClient http; HTTPClient http;
@ -72,6 +80,13 @@ HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String
return handleUpdate(http, currentVersion, true); return handleUpdate(http, currentVersion, true);
} }
HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const uint8_t httpsFingerprint[20])
{
HTTPClient http;
http.begin(url, httpsFingerprint);
return handleUpdate(http, currentVersion, true);
}
HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion) HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion)
{ {
HTTPClient http; HTTPClient http;
@ -98,13 +113,21 @@ HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, co
http.begin(host, port, uri); http.begin(host, port, uri);
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
} }
HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& url, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const String& httpsFingerprint) const String& currentVersion, const String& httpsFingerprint)
{ {
HTTPClient http; HTTPClient http;
http.begin(host, port, url, httpsFingerprint); http.begin(host, port, url, httpsFingerprint);
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
}
HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const uint8_t httpsFingerprint[20])
{
HTTPClient http;
http.begin(host, port, url, httpsFingerprint);
return handleUpdate(http, currentVersion, false);
} }
/** /**

View File

@ -78,6 +78,8 @@ public:
t_httpUpdate_return update(const String& url, const String& currentVersion = ""); t_httpUpdate_return update(const String& url, const String& currentVersion = "");
t_httpUpdate_return update(const String& url, const String& currentVersion, t_httpUpdate_return update(const String& url, const String& currentVersion,
const String& httpsFingerprint); const String& httpsFingerprint);
t_httpUpdate_return update(const String& url, const String& currentVersion,
const uint8_t httpsFingerprint[20]); // BearSSL
// This function is deprecated, use one of the overloads below along with rebootOnUpdate // This function is deprecated, use one of the overloads below along with rebootOnUpdate
t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion, t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
@ -87,12 +89,15 @@ public:
const String& currentVersion = ""); const String& currentVersion = "");
t_httpUpdate_return update(const String& host, uint16_t port, const String& url, t_httpUpdate_return update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const String& httpsFingerprint); const String& currentVersion, const String& httpsFingerprint);
t_httpUpdate_return update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const uint8_t httpsFingerprint[20]); // BearSSL
// This function is deprecated, use rebootOnUpdate and the next one instead // This function is deprecated, use rebootOnUpdate and the next one instead
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = ""); t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = "");
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint); t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint);
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const uint8_t httpsFingerprint[20]); // BearSSL
int getLastError(void); int getLastError(void);

View File

@ -40,7 +40,7 @@ compiler.S.flags=-c -g -x assembler-with-cpp -MMD -mlongcalls
compiler.c.elf.flags=-g {compiler.warning_flags} -Os -nostdlib -Wl,--no-check-sections -u app_entry {build.float} -Wl,-static "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" "-L{compiler.libc.path}/lib" "-T{build.flash_ld}" -Wl,--gc-sections -Wl,-wrap,system_restart_local -Wl,-wrap,spi_flash_read compiler.c.elf.flags=-g {compiler.warning_flags} -Os -nostdlib -Wl,--no-check-sections -u app_entry {build.float} -Wl,-static "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" "-L{compiler.libc.path}/lib" "-T{build.flash_ld}" -Wl,--gc-sections -Wl,-wrap,system_restart_local -Wl,-wrap,spi_flash_read
compiler.c.elf.cmd=xtensa-lx106-elf-gcc compiler.c.elf.cmd=xtensa-lx106-elf-gcc
compiler.c.elf.libs=-lhal -lphy -lpp -lnet80211 {build.lwip_lib} -lwpa -lcrypto -lmain -lwps -laxtls -lespnow -lsmartconfig -lairkiss -lwpa2 -lstdc++ -lm -lc -lgcc compiler.c.elf.libs=-lhal -lphy -lpp -lnet80211 {build.lwip_lib} -lwpa -lcrypto -lmain -lwps -lbearssl -laxtls -lespnow -lsmartconfig -lairkiss -lwpa2 -lstdc++ -lm -lc -lgcc
compiler.cpp.cmd=xtensa-lx106-elf-g++ compiler.cpp.cmd=xtensa-lx106-elf-g++
compiler.cpp.flags=-c {compiler.warning_flags} -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections compiler.cpp.flags=-c {compiler.warning_flags} -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections

View File

@ -40,7 +40,7 @@ function build_sketches()
local build_arg=$3 local build_arg=$3
local build_dir=build.tmp local build_dir=build.tmp
mkdir -p $build_dir mkdir -p $build_dir
local build_cmd="python tools/build.py -b generic -v -w all -k -p $PWD/$build_dir $build_arg " local build_cmd="python tools/build.py -b generic -v -w all -s 4M1M -v -k -p $PWD/$build_dir $build_arg "
local sketches=$(find $srcpath -name *.ino) local sketches=$(find $srcpath -name *.ino)
print_size_info >size.log print_size_info >size.log
export ARDUINO_IDE_PATH=$arduino export ARDUINO_IDE_PATH=$arduino
@ -145,7 +145,7 @@ function build_boards()
function install_platformio() function install_platformio()
{ {
pip install --user -U https://github.com/platformio/platformio/archive/develop.zip pip install --user -U https://github.com/platformio/platformio/archive/develop.zip
platformio platform install https://github.com/platformio/platform-espressif8266.git#feature/stage platformio platform install "https://github.com/platformio/platform-espressif8266.git#feature/stage"
sed -i 's/https:\/\/github\.com\/esp8266\/Arduino\.git/*/' ~/.platformio/platforms/espressif8266/platform.json sed -i 's/https:\/\/github\.com\/esp8266\/Arduino\.git/*/' ~/.platformio/platforms/espressif8266/platform.json
ln -s $TRAVIS_BUILD_DIR ~/.platformio/packages/framework-arduinoespressif8266 ln -s $TRAVIS_BUILD_DIR ~/.platformio/packages/framework-arduinoespressif8266
# Install dependencies: # Install dependencies:
@ -243,7 +243,7 @@ if [ "$BUILD_TYPE" = "build" ]; then
elif [ "$BUILD_TYPE" = "platformio" ]; then elif [ "$BUILD_TYPE" = "platformio" ]; then
# PlatformIO # PlatformIO
install_platformio install_platformio
build_sketches_with_platformio $TRAVIS_BUILD_DIR/libraries "--board nodemcuv2 --verbose" build_sketches_with_platformio $TRAVIS_BUILD_DIR/libraries "--board nodemcuv2 --project-option=lib_ldf_mode=deep+ --verbose"
elif [ "$BUILD_TYPE" = "docs" ]; then elif [ "$BUILD_TYPE" = "docs" ]; then
# Build documentation using Sphinx # Build documentation using Sphinx
cd $TRAVIS_BUILD_DIR/doc cd $TRAVIS_BUILD_DIR/doc

View File

@ -78,7 +78,7 @@ env.Append(
LIBS=[ LIBS=[
"hal", "phy", "pp", "net80211", "wpa", "crypto", "main", "hal", "phy", "pp", "net80211", "wpa", "crypto", "main",
"wps", "axtls", "espnow", "smartconfig", "airkiss", "wpa2", "wps", "bearssl", "axtls", "espnow", "smartconfig", "airkiss", "wpa2",
"stdc++", "m", "c", "gcc" "stdc++", "m", "c", "gcc"
], ],

View File

@ -0,0 +1,169 @@
/*
* 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_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 non-transient 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_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"
#include "bearssl_port.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

View File

@ -0,0 +1,804 @@
/*
* 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>
#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/tls-parameters/tls-parameters.xhtml#tls-parameters-8).
*
* Since all currently defined elliptic curve identifiers are in the 0..31
* range, it is convenient to encode support of some curves in a 32-bit
* 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 32-bit 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 big-endian 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 constant-time, 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 timing-based 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 big-endian
* encodings of these two integers, possibly left-padded 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/tls-parameters/tls-parameters.xhtml#tls-parameters-8
*/
/** \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 big-endian 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 P-256
* (secp256r1, ID 23) and NIST P-384 (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
* big-endian 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 non-zero 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 big-endian 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 non-zero 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 big-endian).
* \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 non-zero 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 big-endian).
* \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 non-zero
* 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 big-endian).
* \param xlen length of multiplier for `A` (in bytes).
* \param y multiplier for `A` (unsigned big-endian).
* \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 31-bit words. It supports secp256r1,
* secp384r1 and secp521r1 (aka NIST curves P-256, P-384 and P-521).
*/
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 15-bit words. It supports secp256r1,
* secp384r1 and secp521r1 (aka NIST curves P-256, P-384 and P-521).
*/
extern const br_ec_impl br_ec_prime_i15;
/**
* \brief EC implementation "m15" for P-256.
*
* This implementation uses specialised code for curve secp256r1 (also
* known as NIST P-256), with optional Karatsuba decomposition, and fast
* modular reduction thanks to the field modulus special format. Only
* 32-bit multiplications are used (with 32-bit results, not 64-bit).
*/
extern const br_ec_impl br_ec_p256_m15;
/**
* \brief EC implementation "m31" for P-256.
*
* This implementation uses specialised code for curve secp256r1 (also
* known as NIST P-256), relying on multiplications of 31-bit 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
* 15-bit 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^255-1, since the point multiplication algorithm
* accepts any 32-bit 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
* 31-bit 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^255-1, since the point multiplication algorithm
* accepts any 32-bit 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^255-1, since the point multiplication algorithm
* accepts any 32-bit 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^255-1, since the point multiplication algorithm
* accepts any 32-bit 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 P-256
* - `br_ec_prime_i15` for other curves (NIST P-384 and NIST-P512)
*/
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 P-256
* - `br_ec_prime_i31` for other curves (NIST P-384 and NIST-P512)
*/
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 P-256 | 64 | 72 |
* | NIST P-384 | 96 | 104 |
* | NIST P-521 | 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);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,211 @@
/*
* 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 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 caller-allocated 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];
size_t out_len;
#endif
} br_hmac_context;
/**
* \brief HMAC computation initialisation.
*
* Initialise a HMAC context with a key context. The key context is
* unmodified. Relevant data from the key context is immediately copied;
* the key context can thus be independently reused, modified or released
* without impacting this HMAC computation.
*
* An explicit output length can be specified; the actual output length
* will be the minimum of that value and the natural HMAC output length.
* If `out_len` is 0, then the natural HMAC output length is selected. The
* "natural output length" is the output length of the underlying hash
* function.
*
* \param ctx HMAC context to initialise.
* \param kc HMAC key context (already initialised with the key).
* \param out_len HMAC output length (0 to select "natural length").
*/
void br_hmac_init(br_hmac_context *ctx,
const br_hmac_key_context *kc, size_t out_len);
/**
* \brief Get the HMAC output size.
*
* The HMAC output size is the number of bytes that will actually be
* produced with `br_hmac_out()` with the provided context. This function
* MUST NOT be called on a non-initialised HMAC computation context.
* The returned value is the minimum of the HMAC natural length (output
* size of the underlying hash function) and the `out_len` parameter which
* was used with the last `br_hmac_init()` call on that context (if the
* initialisation `out_len` parameter was 0, then this function will
* return the HMAC natural length).
*
* \param ctx the (already initialised) HMAC computation context.
* \return the HMAC actual output size.
*/
static inline size_t
br_hmac_size(br_hmac_context *ctx)
{
return ctx->out_len;
}
/**
* \brief Inject some bytes in HMAC.
*
* The provided `len` bytes are injected as extra input in the HMAC
* computation incarnated by the `ctx` HMAC context. It is acceptable
* that `len` is zero, in which case `data` is ignored (and may be
* `NULL`) and this function does nothing.
*/
void br_hmac_update(br_hmac_context *ctx, const void *data, size_t len);
/**
* \brief Compute the HMAC output.
*
* The destination buffer MUST be large enough to accomodate the result;
* its length is at most the "natural length" of HMAC (i.e. the output
* length of the underlying hash function). The context is NOT modified;
* further bytes may be processed. Thus, "partial HMAC" values can be
* efficiently obtained.
*
* Returned value is the output length (in bytes).
*
* \param ctx HMAC computation context.
* \param out destination buffer for the HMAC output.
* \return the produced value length (in bytes).
*/
size_t br_hmac_out(const br_hmac_context *ctx, void *out);
/**
* \brief Constant-time HMAC computation.
*
* This function compute the HMAC output in constant time. Some extra
* input bytes are processed, then the output is computed. The extra
* input consists in the `len` bytes pointed to by `data`. The `len`
* parameter must lie between `min_len` and `max_len` (inclusive);
* `max_len` bytes are actually read from `data`. Computing time (and
* memory access pattern) will not depend upon the data byte contents or
* the value of `len`.
*
* The output is written in the `out` buffer, that MUST be large enough
* to receive it.
*
* The difference `max_len - min_len` MUST be less than 2<sup>30</sup>
* (i.e. about one gigabyte).
*
* This function computes the output properly only if the underlying
* hash function uses MD padding (i.e. MD5, SHA-1, SHA-224, SHA-256,
* SHA-384 or SHA-512).
*
* The provided context is NOT modified.
*
* \param ctx the (already initialised) HMAC computation context.
* \param data the extra input bytes.
* \param len the extra input length (in bytes).
* \param min_len minimum extra input length (in bytes).
* \param max_len maximum extra input length (in bytes).
* \param out destination buffer for the HMAC output.
* \return the produced value length (in bytes).
*/
size_t br_hmac_outCT(const br_hmac_context *ctx,
const void *data, size_t len, size_t min_len, size_t max_len,
void *out);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,243 @@
/*
* 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_PEM_H__
#define BR_BEARSSL_PEM_H__
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \file bearssl_pem.h
*
* # PEM Support
*
* PEM is a traditional encoding layer use to store binary objects (in
* particular X.509 certificates, and private keys) in text files. While
* the acronym comes from an old, defunct standard ("Privacy Enhanced
* Mail"), the format has been reused, with some variations, by many
* systems, and is a _de facto_ standard, even though it is not, actually,
* specified in all clarity anywhere.
*
* ## Format Details
*
* BearSSL contains a generic, streamed PEM decoder, which handles the
* following format:
*
* - The input source (a sequence of bytes) is assumed to be the
* encoding of a text file in an ASCII-compatible charset. This
* includes ISO-8859-1, Windows-1252, and UTF-8 encodings. Each
* line ends on a newline character (U+000A LINE FEED). The
* U+000D CARRIAGE RETURN characters are ignored, so the code
* accepts both Windows-style and Unix-style line endings.
*
* - Each object begins with a banner that occurs at the start of
* a line; the first banner characters are "`-----BEGIN `" (five
* dashes, the word "BEGIN", and a space). The banner matching is
* not case-sensitive.
*
* - The _object name_ consists in the characters that follow the
* banner start sequence, up to the end of the line, but without
* trailing dashes (in "normal" PEM, there are five trailing
* dashes, but this implementation is not picky about these dashes).
* The BearSSL decoder normalises the name characters to uppercase
* (for ASCII letters only) and accepts names up to 127 characters.
*
* - The object ends with a banner that again occurs at the start of
* a line, and starts with "`-----END `" (again case-insensitive).
*
* - Between that start and end banner, only Base64 data shall occur.
* Base64 converts each sequence of three bytes into four
* characters; the four characters are ASCII letters, digits, "`+`"
* or "`-`" signs, and one or two "`=`" signs may occur in the last
* quartet. Whitespace is ignored (whitespace is any ASCII character
* of code 32 or less, so control characters are whitespace) and
* lines may have arbitrary length; the only restriction is that the
* four characters of a quartet must appear on the same line (no
* line break inside a quartet).
*
* - A single file may contain more than one PEM object. Bytes that
* occur between objects are ignored.
*
*
* ## PEM Decoder API
*
* The PEM decoder offers a state-machine API. The caller allocates a
* decoder context, then injects source bytes. Source bytes are pushed
* with `br_pem_decoder_push()`. The decoder stops accepting bytes when
* it reaches an "event", which is either the start of an object, the
* end of an object, or a decoding error within an object.
*
* The `br_pem_decoder_event()` function is used to obtain the current
* event; it also clears it, thus allowing the decoder to accept more
* bytes. When a object start event is raised, the decoder context
* offers the found object name (normalised to ASCII uppercase).
*
* When an object is reached, the caller must set an appropriate callback
* function, which will receive (by chunks) the decoded object data.
*
* Since the decoder context makes no dynamic allocation, it requires
* no explicit deallocation.
*/
/**
* \brief PEM decoder context.
*
* Contents are opaque (they should not be accessed directly).
*/
typedef struct {
#ifndef BR_DOXYGEN_IGNORE
/* CPU for the T0 virtual machine. */
struct {
uint32_t *dp;
uint32_t *rp;
const unsigned char *ip;
} cpu;
uint32_t dp_stack[32];
uint32_t rp_stack[32];
int err;
const unsigned char *hbuf;
size_t hlen;
void (*dest)(void *dest_ctx, const void *src, size_t len);
void *dest_ctx;
unsigned char event;
char name[128];
unsigned char buf[255];
size_t ptr;
#endif
} br_pem_decoder_context;
/**
* \brief Initialise a PEM decoder structure.
*
* \param ctx decoder context to initialise.
*/
void br_pem_decoder_init(br_pem_decoder_context *ctx);
/**
* \brief Push some bytes into the decoder.
*
* Returned value is the number of bytes actually consumed; this may be
* less than the number of provided bytes if an event is raised. When an
* event is raised, it must be read (with `br_pem_decoder_event()`);
* until the event is read, this function will return 0.
*
* \param ctx decoder context.
* \param data new data bytes.
* \param len number of new data bytes.
* \return the number of bytes actually received (may be less than `len`).
*/
size_t br_pem_decoder_push(br_pem_decoder_context *ctx,
const void *data, size_t len);
/**
* \brief Set the receiver for decoded data.
*
* When an object is entered, the provided function (with opaque context
* pointer) will be called repeatedly with successive chunks of decoded
* data for that object. If `dest` is set to 0, then decoded data is
* simply ignored. The receiver can be set at any time, but, in practice,
* it should be called immediately after receiving a "start of object"
* event.
*
* \param ctx decoder context.
* \param dest callback for receiving decoded data.
* \param dest_ctx opaque context pointer for the `dest` callback.
*/
static inline void
br_pem_decoder_setdest(br_pem_decoder_context *ctx,
void (*dest)(void *dest_ctx, const void *src, size_t len),
void *dest_ctx)
{
ctx->dest = dest;
ctx->dest_ctx = dest_ctx;
}
/**
* \brief Get the last event.
*
* If an event was raised, then this function returns the event value, and
* also clears it, thereby allowing the decoder to proceed. If no event
* was raised since the last call to `br_pem_decoder_event()`, then this
* function returns 0.
*
* \param ctx decoder context.
* \return the raised event, or 0.
*/
int br_pem_decoder_event(br_pem_decoder_context *ctx);
/**
* \brief Event: start of object.
*
* This event is raised when the start of a new object has been detected.
* The object name (normalised to uppercase) can be accessed with
* `br_pem_decoder_name()`.
*/
#define BR_PEM_BEGIN_OBJ 1
/**
* \brief Event: end of object.
*
* This event is raised when the end of the current object is reached
* (normally, i.e. with no decoding error).
*/
#define BR_PEM_END_OBJ 2
/**
* \brief Event: decoding error.
*
* This event is raised when decoding fails within an object.
* This formally closes the current object and brings the decoder back
* to the "out of any object" state. The offending line in the source
* is consumed.
*/
#define BR_PEM_ERROR 3
/**
* \brief Get the name of the encountered object.
*
* The encountered object name is defined only when the "start of object"
* event is raised. That name is normalised to uppercase (for ASCII letters
* only) and does not include trailing dashes.
*
* \param ctx decoder context.
* \return the current object name.
*/
static inline const char *
br_pem_decoder_name(br_pem_decoder_context *ctx)
{
return ctx->name;
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,20 @@
#ifndef _bearssl_port_h
#define _bearssl_port_h
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
extern void br_esp8266_stack_proxy_init(uint8_t *space, uint16_t size);
extern size_t br_esp8266_stack_proxy_max();
extern size_t br_esp8266_stack_proxy_usage();
extern void br_esp8266_stack_proxy_deinit();
#ifdef __cplusplus
};
#endif
#endif

View File

@ -0,0 +1,150 @@
/*
* 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_PRF_H__
#define BR_BEARSSL_PRF_H__
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \file bearssl_prf.h
*
* # The TLS PRF
*
* The "PRF" is the pseudorandom function used internally during the
* SSL/TLS handshake, notably to expand negociated shared secrets into
* the symmetric encryption keys that will be used to process the
* application data.
*
* TLS 1.0 and 1.1 define a PRF that is based on both MD5 and SHA-1. This
* is implemented by the `br_tls10_prf()` function.
*
* TLS 1.2 redefines the PRF, using an explicit hash function. The
* `br_tls12_sha256_prf()` and `br_tls12_sha384_prf()` functions apply that
* PRF with, respectively, SHA-256 and SHA-384. Most standard cipher suites
* rely on the SHA-256 based PRF, but some use SHA-384.
*
* The PRF always uses as input three parameters: a "secret" (some
* bytes), a "label" (ASCII string), and a "seed" (again some bytes). An
* arbitrary output length can be produced. The "seed" is provided as an
* arbitrary number of binary chunks, that gets internally concatenated.
*/
/**
* \brief Type for a seed chunk.
*
* Each chunk may have an arbitrary length, and may be empty (no byte at
* all). If the chunk length is zero, then the pointer to the chunk data
* may be `NULL`.
*/
typedef struct {
/**
* \brief Pointer to the chunk data.
*/
const void *data;
/**
* \brief Chunk length (in bytes).
*/
size_t len;
} br_tls_prf_seed_chunk;
/**
* \brief PRF implementation for TLS 1.0 and 1.1.
*
* This PRF is the one specified by TLS 1.0 and 1.1. It internally uses
* MD5 and SHA-1.
*
* \param dst destination buffer.
* \param len output length (in bytes).
* \param secret secret value (key) for this computation.
* \param secret_len length of "secret" (in bytes).
* \param label PRF label (zero-terminated ASCII string).
* \param seed_num number of seed chunks.
* \param seed seed chnks for this computation (usually non-secret).
*/
void br_tls10_prf(void *dst, size_t len,
const void *secret, size_t secret_len, const char *label,
size_t seed_num, const br_tls_prf_seed_chunk *seed);
/**
* \brief PRF implementation for TLS 1.2, with SHA-256.
*
* This PRF is the one specified by TLS 1.2, when the underlying hash
* function is SHA-256.
*
* \param dst destination buffer.
* \param len output length (in bytes).
* \param secret secret value (key) for this computation.
* \param secret_len length of "secret" (in bytes).
* \param label PRF label (zero-terminated ASCII string).
* \param seed_num number of seed chunks.
* \param seed seed chnks for this computation (usually non-secret).
*/
void br_tls12_sha256_prf(void *dst, size_t len,
const void *secret, size_t secret_len, const char *label,
size_t seed_num, const br_tls_prf_seed_chunk *seed);
/**
* \brief PRF implementation for TLS 1.2, with SHA-384.
*
* This PRF is the one specified by TLS 1.2, when the underlying hash
* function is SHA-384.
*
* \param dst destination buffer.
* \param len output length (in bytes).
* \param secret secret value (key) for this computation.
* \param secret_len length of "secret" (in bytes).
* \param label PRF label (zero-terminated ASCII string).
* \param seed_num number of seed chunks.
* \param seed seed chnks for this computation (usually non-secret).
*/
void br_tls12_sha384_prf(void *dst, size_t len,
const void *secret, size_t secret_len, const char *label,
size_t seed_num, const br_tls_prf_seed_chunk *seed);
/**
* brief A convenient type name for a PRF implementation.
*
* \param dst destination buffer.
* \param len output length (in bytes).
* \param secret secret value (key) for this computation.
* \param secret_len length of "secret" (in bytes).
* \param label PRF label (zero-terminated ASCII string).
* \param seed_num number of seed chunks.
* \param seed seed chnks for this computation (usually non-secret).
*/
typedef void (*br_tls_prf_impl)(void *dst, size_t len,
const void *secret, size_t secret_len, const char *label,
size_t seed_num, const br_tls_prf_seed_chunk *seed);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,295 @@
/*
* 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_RAND_H__
#define BR_BEARSSL_RAND_H__
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \file bearssl_rand.h
*
* # Pseudo-Random Generators
*
* A PRNG is a state-based engine that outputs pseudo-random bytes on
* demand. It is initialized with an initial seed, and additional seed
* bytes can be added afterwards. Bytes produced depend on the seeds and
* also on the exact sequence of calls (including sizes requested for
* each call).
*
*
* ## Procedural and OOP API
*
* For the PRNG of name "`xxx`", two API are provided. The _procedural_
* API defined a context structure `br_xxx_context` and three functions:
*
* - `br_xxx_init()`
*
* Initialise the context with an initial seed.
*
* - `br_xxx_generate()`
*
* Produce some pseudo-random bytes.
*
* - `br_xxx_update()`
*
* Inject some additional seed.
*
* The initialisation function sets the first context field (`vtable`)
* to a pointer to the vtable that supports the OOP API. The OOP API
* provides access to the same functions through function pointers,
* named `init()`, `generate()` and `update()`.
*
* Note that the context initialisation method may accept additional
* parameters, provided as a 'const void *' pointer at API level. These
* additional parameters depend on the implemented PRNG.
*
*
* ## HMAC_DRBG
*
* HMAC_DRBG is defined in [NIST SP 800-90A Revision
* 1](http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf).
* It uses HMAC repeatedly, over some configurable underlying hash
* function. In BearSSL, it is implemented under the "`hmac_drbg`" name.
* The "extra parameters" pointer for context initialisation should be
* set to a pointer to the vtable for the underlying hash function (e.g.
* pointer to `br_sha256_vtable` to use HMAC_DRBG with SHA-256).
*
* According to the NIST standard, each request shall produce up to
* 2<sup>19</sup> bits (i.e. 64 kB of data); moreover, the context shall
* be reseeded at least once every 2<sup>48</sup> requests. This
* implementation does not maintain the reseed counter (the threshold is
* too high to be reached in practice) and does not object to producing
* more than 64 kB in a single request; thus, the code cannot fail,
* which corresponds to the fact that the API has no room for error
* codes. However, this implies that requesting more than 64 kB in one
* `generate()` request, or making more than 2<sup>48</sup> requests
* without reseeding, is formally out of NIST specification. There is
* no currently known security penalty for exceeding the NIST limits,
* and, in any case, HMAC_DRBG usage in implementing SSL/TLS always
* stays much below these thresholds.
*/
/**
* \brief Class type for PRNG implementations.
*
* A `br_prng_class` instance references the methods implementing a PRNG.
* Constant instances of this structure are defined for each implemented
* PRNG. Such instances are also called "vtables".
*/
typedef struct br_prng_class_ br_prng_class;
struct br_prng_class_ {
/**
* \brief Size (in bytes) of the context structure appropriate for
* running this PRNG.
*/
size_t context_size;
/**
* \brief Initialisation method.
*
* The context to initialise is provided as a pointer to its
* first field (the vtable pointer); this function sets that
* first field to a pointer to the vtable.
*
* The extra parameters depend on the implementation; each
* implementation defines what kind of extra parameters it
* expects (if any).
*
* Requirements on the initial seed depend on the implemented
* PRNG.
*
* \param ctx PRNG context to initialise.
* \param params extra parameters for the PRNG.
* \param seed initial seed.
* \param seed_len initial seed length (in bytes).
*/
void (*init)(const br_prng_class **ctx, const void *params,
const void *seed, size_t seed_len);
/**
* \brief Random bytes generation.
*
* This method produces `len` pseudorandom bytes, in the `out`
* buffer. The context is updated accordingly.
*
* \param ctx PRNG context.
* \param out output buffer.
* \param len number of pseudorandom bytes to produce.
*/
void (*generate)(const br_prng_class **ctx, void *out, size_t len);
/**
* \brief Inject additional seed bytes.
*
* The provided seed bytes are added into the PRNG internal
* entropy pool.
*
* \param ctx PRNG context.
* \param seed additional seed.
* \param seed_len additional seed length (in bytes).
*/
void (*update)(const br_prng_class **ctx,
const void *seed, size_t seed_len);
};
/**
* \brief Context for HMAC_DRBG.
*
* The context contents are opaque, except the first field, which
* supports OOP.
*/
typedef struct {
/**
* \brief Pointer to the vtable.
*
* This field is set with the initialisation method/function.
*/
const br_prng_class *vtable;
#ifndef BR_DOXYGEN_IGNORE
unsigned char K[64];
unsigned char V[64];
const br_hash_class *digest_class;
#endif
} br_hmac_drbg_context;
/**
* \brief Statically allocated, constant vtable for HMAC_DRBG.
*/
extern const br_prng_class br_hmac_drbg_vtable;
/**
* \brief HMAC_DRBG initialisation.
*
* The context to initialise is provided as a pointer to its first field
* (the vtable pointer); this function sets that first field to a
* pointer to the vtable.
*
* The `seed` value is what is called, in NIST terminology, the
* concatenation of the "seed", "nonce" and "personalization string", in
* that order.
*
* The `digest_class` parameter defines the underlying hash function.
* Formally, the NIST standard specifies that the hash function shall
* be only SHA-1 or one of the SHA-2 functions. This implementation also
* works with any other implemented hash function (such as MD5), but
* this is non-standard and therefore not recommended.
*
* \param ctx HMAC_DRBG context to initialise.
* \param digest_class vtable for the underlying hash function.
* \param seed initial seed.
* \param seed_len initial seed length (in bytes).
*/
void br_hmac_drbg_init(br_hmac_drbg_context *ctx,
const br_hash_class *digest_class, const void *seed, size_t seed_len);
/**
* \brief Random bytes generation with HMAC_DRBG.
*
* This method produces `len` pseudorandom bytes, in the `out`
* buffer. The context is updated accordingly. Formally, requesting
* more than 65536 bytes in one request falls out of specification
* limits (but it won't fail).
*
* \param ctx HMAC_DRBG context.
* \param out output buffer.
* \param len number of pseudorandom bytes to produce.
*/
void br_hmac_drbg_generate(br_hmac_drbg_context *ctx, void *out, size_t len);
/**
* \brief Inject additional seed bytes in HMAC_DRBG.
*
* The provided seed bytes are added into the HMAC_DRBG internal
* entropy pool. The process does not _replace_ existing entropy,
* thus pushing non-random bytes (i.e. bytes which are known to the
* attackers) does not degrade the overall quality of generated bytes.
*
* \param ctx HMAC_DRBG context.
* \param seed additional seed.
* \param seed_len additional seed length (in bytes).
*/
void br_hmac_drbg_update(br_hmac_drbg_context *ctx,
const void *seed, size_t seed_len);
/**
* \brief Get the hash function implementation used by a given instance of
* HMAC_DRBG.
*
* This calls MUST NOT be performed on a context which was not
* previously initialised.
*
* \param ctx HMAC_DRBG context.
* \return the hash function vtable.
*/
static inline const br_hash_class *
br_hmac_drbg_get_hash(const br_hmac_drbg_context *ctx)
{
return ctx->digest_class;
}
/**
* \brief Type for a provider of entropy seeds.
*
* A "seeder" is a function that is able to obtain random values from
* some source and inject them as entropy seed in a PRNG. A seeder
* shall guarantee that the total entropy of the injected seed is large
* enough to seed a PRNG for purposes of cryptographic key generation
* (i.e. at least 128 bits).
*
* A seeder may report a failure to obtain adequate entropy. Seeders
* shall endeavour to fix themselves transient errors by trying again;
* thus, callers may consider reported errors as permanent.
*
* \param ctx PRNG context to seed.
* \return 1 on success, 0 on error.
*/
typedef int (*br_prng_seeder)(const br_prng_class **ctx);
/**
* \brief Get a seeder backed by the operating system or hardware.
*
* Get a seeder that feeds on RNG facilities provided by the current
* operating system or hardware. If no such facility is known, then 0
* is returned.
*
* If `name` is not `NULL`, then `*name` is set to a symbolic string
* that identifies the seeder implemention. If no seeder is returned
* and `name` is not `NULL`, then `*name` is set to a pointer to the
* constant string `"none"`.
*
* \param name receiver for seeder name, or `NULL`.
* \return the system seeder, if available, or 0.
*/
br_prng_seeder br_prng_seeder_system(const char **name);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,743 @@
/*
* 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_RSA_H__
#define BR_BEARSSL_RSA_H__
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \file bearssl_rsa.h
*
* # RSA
*
* This file documents the RSA implementations provided with BearSSL.
* Note that the SSL engine accesses these implementations through a
* configurable API, so it is possible to, for instance, run a SSL
* server which uses a RSA engine which is not based on this code.
*
* ## Key Elements
*
* RSA public and private keys consist in lists of big integers. All
* such integers are represented with big-endian unsigned notation:
* first byte is the most significant, and the value is positive (so
* there is no dedicated "sign bit"). Public and private key structures
* thus contain, for each such integer, a pointer to the first value byte
* (`unsigned char *`), and a length (`size_t`) which is the number of
* relevant bytes. As a general rule, minimal-length encoding is not
* enforced: values may have extra leading bytes of value 0.
*
* RSA public keys consist in two integers:
*
* - the modulus (`n`);
* - the public exponent (`e`).
*
* RSA private keys, as defined in
* [PKCS#1](https://tools.ietf.org/html/rfc3447), contain eight integers:
*
* - the modulus (`n`);
* - the public exponent (`e`);
* - the private exponent (`d`);
* - the first prime factor (`p`);
* - the second prime factor (`q`);
* - the first reduced exponent (`dp`, which is `d` modulo `p-1`);
* - the second reduced exponent (`dq`, which is `d` modulo `q-1`);
* - the CRT coefficient (`iq`, the inverse of `q` modulo `p`).
*
* However, the implementations defined in BearSSL use only five of
* these integers: `p`, `q`, `dp`, `dq` and `iq`.
*
* ## Security Features and Limitations
*
* The implementations contained in BearSSL have the following limitations
* and features:
*
* - They are constant-time. This means that the execution time and
* memory access pattern may depend on the _lengths_ of the private
* key components, but not on their value, nor on the value of
* the operand. Note that this property is not achieved through
* random masking, but "true" constant-time code.
*
* - They support only private keys with two prime factors. RSA private
* key with three or more prime factors are nominally supported, but
* rarely used; they may offer faster operations, at the expense of
* more code and potentially a reduction in security if there are
* "too many" prime factors.
*
* - The public exponent may have arbitrary length. Of course, it is
* a good idea to keep public exponents small, so that public key
* operations are fast; but, contrary to some widely deployed
* implementations, BearSSL has no problem with public exponent
* longer than 32 bits.
*
* - The two prime factors of the modulus need not have the same length
* (but severely imbalanced factor lengths might reduce security).
* Similarly, there is no requirement that the first factor (`p`)
* be greater than the second factor (`q`).
*
* - Prime factors and modulus must be smaller than a compile-time limit.
* This is made necessary by the use of fixed-size stack buffers, and
* the limit has been adjusted to keep stack usage under 2 kB for the
* RSA operations. Currently, the maximum modulus size is 4096 bits,
* and the maximum prime factor size is 2080 bits.
*
* - The RSA functions themselves do not enforce lower size limits,
* except that which is absolutely necessary for the operation to
* mathematically make sense (e.g. a PKCS#1 v1.5 signature with
* SHA-1 requires a modulus of at least 361 bits). It is up to users
* of this code to enforce size limitations when appropriate (e.g.
* the X.509 validation engine, by default, rejects RSA keys of
* less than 1017 bits).
*
* - Within the size constraints expressed above, arbitrary bit lengths
* are supported. There is no requirement that prime factors or
* modulus have a size multiple of 8 or 16.
*
* - When verifying PKCS#1 v1.5 signatures, both variants of the hash
* function identifying header (with and without the ASN.1 NULL) are
* supported. When producing such signatures, the variant with the
* ASN.1 NULL is used.
*
* ## Implementations
*
* Three RSA implementations are included:
*
* - The **i32** implementation internally represents big integers
* as arrays of 32-bit integers. It is perfunctory and portable,
* but not very efficient.
*
* - The **i31** implementation uses 32-bit integers, each containing
* 31 bits worth of integer data. The i31 implementation is somewhat
* faster than the i32 implementation (the reduced integer size makes
* carry propagation easier) for a similar code footprint, but uses
* very slightly larger stack buffers (about 4% bigger).
*
* - The **i62** implementation is similar to the i31 implementation,
* except that it internally leverages the 64x64->128 multiplication
* opcode. This implementation is available only on architectures
* where such an opcode exists. It is much faster than i31.
*
* - The **i15** implementation uses 16-bit integers, each containing
* 15 bits worth of integer data. Multiplication results fit on
* 32 bits, so this won't use the "widening" multiplication routine
* on ARM Cortex M0/M0+, for much better performance and constant-time
* execution.
*/
/**
* \brief RSA public key.
*
* The structure references the modulus and the public exponent. Both
* integers use unsigned big-endian representation; extra leading bytes
* of value 0 are allowed.
*/
typedef struct {
/** \brief Modulus. */
unsigned char *n;
/** \brief Modulus length (in bytes). */
size_t nlen;
/** \brief Public exponent. */
unsigned char *e;
/** \brief Public exponent length (in bytes). */
size_t elen;
} br_rsa_public_key;
/**
* \brief RSA private key.
*
* The structure references the primvate factors, reduced private
* exponents, and CRT coefficient. It also contains the bit length of
* the modulus. The big integers use unsigned big-endian representation;
* extra leading bytes of value 0 are allowed. However, the modulus bit
* length (`n_bitlen`) MUST be exact.
*/
typedef struct {
/** \brief Modulus bit length (in bits, exact value). */
uint32_t n_bitlen;
/** \brief First prime factor. */
unsigned char *p;
/** \brief First prime factor length (in bytes). */
size_t plen;
/** \brief Second prime factor. */
unsigned char *q;
/** \brief Second prime factor length (in bytes). */
size_t qlen;
/** \brief First reduced private exponent. */
unsigned char *dp;
/** \brief First reduced private exponent length (in bytes). */
size_t dplen;
/** \brief Second reduced private exponent. */
unsigned char *dq;
/** \brief Second reduced private exponent length (in bytes). */
size_t dqlen;
/** \brief CRT coefficient. */
unsigned char *iq;
/** \brief CRT coefficient length (in bytes). */
size_t iqlen;
} br_rsa_private_key;
/**
* \brief Type for a RSA public key engine.
*
* The public key engine performs the modular exponentiation of the
* provided value with the public exponent. The value is modified in
* place.
*
* The value length (`xlen`) is verified to have _exactly_ the same
* length as the modulus (actual modulus length, without extra leading
* zeros in the modulus representation in memory). If the length does
* not match, then this function returns 0 and `x[]` is unmodified.
*
* It `xlen` is correct, then `x[]` is modified. Returned value is 1
* on success, 0 on error. Error conditions include an oversized `x[]`
* (the array has the same length as the modulus, but the numerical value
* is not lower than the modulus) and an invalid modulus (e.g. an even
* integer). If an error is reported, then the new contents of `x[]` are
* unspecified.
*
* \param x operand to exponentiate.
* \param xlen length of the operand (in bytes).
* \param pk RSA public key.
* \return 1 on success, 0 on error.
*/
typedef uint32_t (*br_rsa_public)(unsigned char *x, size_t xlen,
const br_rsa_public_key *pk);
/**
* \brief Type for a RSA signature verification engine (PKCS#1 v1.5).
*
* Parameters are:
*
* - The signature itself. The provided array is NOT modified.
*
* - The encoded OID for the hash function. The provided array must begin
* with a single byte that contains the length of the OID value (in
* bytes), followed by exactly that many bytes. This parameter may
* also be `NULL`, in which case the raw hash value should be used
* with the PKCS#1 v1.5 "type 1" padding (as used in SSL/TLS up
* to TLS-1.1, with a 36-byte hash value).
*
* - The hash output length, in bytes.
*
* - The public key.
*
* - An output buffer for the hash value. The caller must still compare
* it with the hash of the data over which the signature is computed.
*
* **Constraints:**
*
* - Hash length MUST be no more than 64 bytes.
*
* - OID value length MUST be no more than 32 bytes (i.e. `hash_oid[0]`
* must have a value in the 0..32 range, inclusive).
*
* This function verifies that the signature length (`xlen`) matches the
* modulus length (this function returns 0 on mismatch). If the modulus
* size exceeds the maximum supported RSA size, then the function also
* returns 0.
*
* Returned value is 1 on success, 0 on error.
*
* Implementations of this type need not be constant-time.
*
* \param x signature buffer.
* \param xlen signature length (in bytes).
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash_len expected hash value length (in bytes).
* \param pk RSA public key.
* \param hash_out output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
typedef uint32_t (*br_rsa_pkcs1_vrfy)(const unsigned char *x, size_t xlen,
const unsigned char *hash_oid, size_t hash_len,
const br_rsa_public_key *pk, unsigned char *hash_out);
/**
* \brief Type for a RSA private key engine.
*
* The `x[]` buffer is modified in place, and its length is inferred from
* the modulus length (`x[]` is assumed to have a length of
* `(sk->n_bitlen+7)/8` bytes).
*
* Returned value is 1 on success, 0 on error.
*
* \param x operand to exponentiate.
* \param sk RSA private key.
* \return 1 on success, 0 on error.
*/
typedef uint32_t (*br_rsa_private)(unsigned char *x,
const br_rsa_private_key *sk);
/**
* \brief Type for a RSA signature generation engine (PKCS#1 v1.5).
*
* Parameters are:
*
* - The encoded OID for the hash function. The provided array must begin
* with a single byte that contains the length of the OID value (in
* bytes), followed by exactly that many bytes. This parameter may
* also be `NULL`, in which case the raw hash value should be used
* with the PKCS#1 v1.5 "type 1" padding (as used in SSL/TLS up
* to TLS-1.1, with a 36-byte hash value).
*
* - The hash value computes over the data to sign (its length is
* expressed in bytes).
*
* - The RSA private key.
*
* - The output buffer, that receives the signature.
*
* Returned value is 1 on success, 0 on error. Error conditions include
* a too small modulus for the provided hash OID and value, or some
* invalid key parameters. The signature length is exactly
* `(sk->n_bitlen+7)/8` bytes.
*
* This function is expected to be constant-time with regards to the
* private key bytes (lengths of the modulus and the individual factors
* may leak, though) and to the hashed data.
*
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash hash value.
* \param hash_len hash value length (in bytes).
* \param sk RSA private key.
* \param x output buffer for the signature value.
* \return 1 on success, 0 on error.
*/
typedef uint32_t (*br_rsa_pkcs1_sign)(const unsigned char *hash_oid,
const unsigned char *hash, size_t hash_len,
const br_rsa_private_key *sk, unsigned char *x);
/**
* \brief Encoded OID for SHA-1 (in RSA PKCS#1 signatures).
*/
#define BR_HASH_OID_SHA1 \
((const unsigned char *)"\x05\x2B\x0E\x03\x02\x1A")
/**
* \brief Encoded OID for SHA-224 (in RSA PKCS#1 signatures).
*/
#define BR_HASH_OID_SHA224 \
((const unsigned char *)"\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04")
/**
* \brief Encoded OID for SHA-256 (in RSA PKCS#1 signatures).
*/
#define BR_HASH_OID_SHA256 \
((const unsigned char *)"\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01")
/**
* \brief Encoded OID for SHA-384 (in RSA PKCS#1 signatures).
*/
#define BR_HASH_OID_SHA384 \
((const unsigned char *)"\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02")
/**
* \brief Encoded OID for SHA-512 (in RSA PKCS#1 signatures).
*/
#define BR_HASH_OID_SHA512 \
((const unsigned char *)"\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03")
/*
* RSA "i32" engine. Integers are internally represented as arrays of
* 32-bit integers, and the core multiplication primitive is the
* 32x32->64 multiplication.
*/
/**
* \brief RSA public key engine "i32".
*
* \see br_rsa_public
*
* \param x operand to exponentiate.
* \param xlen length of the operand (in bytes).
* \param pk RSA public key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i32_public(unsigned char *x, size_t xlen,
const br_rsa_public_key *pk);
/**
* \brief RSA signature verification engine "i32".
*
* \see br_rsa_pkcs1_vrfy
*
* \param x signature buffer.
* \param xlen signature length (in bytes).
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash_len expected hash value length (in bytes).
* \param pk RSA public key.
* \param hash_out output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i32_pkcs1_vrfy(const unsigned char *x, size_t xlen,
const unsigned char *hash_oid, size_t hash_len,
const br_rsa_public_key *pk, unsigned char *hash_out);
/**
* \brief RSA private key engine "i32".
*
* \see br_rsa_private
*
* \param x operand to exponentiate.
* \param sk RSA private key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i32_private(unsigned char *x,
const br_rsa_private_key *sk);
/**
* \brief RSA signature generation engine "i32".
*
* \see br_rsa_pkcs1_sign
*
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash hash value.
* \param hash_len hash value length (in bytes).
* \param sk RSA private key.
* \param x output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i32_pkcs1_sign(const unsigned char *hash_oid,
const unsigned char *hash, size_t hash_len,
const br_rsa_private_key *sk, unsigned char *x);
/*
* RSA "i31" engine. Similar to i32, but only 31 bits are used per 32-bit
* word. This uses slightly more stack space (about 4% more) and code
* space, but it quite faster.
*/
/**
* \brief RSA public key engine "i31".
*
* \see br_rsa_public
*
* \param x operand to exponentiate.
* \param xlen length of the operand (in bytes).
* \param pk RSA public key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i31_public(unsigned char *x, size_t xlen,
const br_rsa_public_key *pk);
/**
* \brief RSA signature verification engine "i31".
*
* \see br_rsa_pkcs1_vrfy
*
* \param x signature buffer.
* \param xlen signature length (in bytes).
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash_len expected hash value length (in bytes).
* \param pk RSA public key.
* \param hash_out output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i31_pkcs1_vrfy(const unsigned char *x, size_t xlen,
const unsigned char *hash_oid, size_t hash_len,
const br_rsa_public_key *pk, unsigned char *hash_out);
/**
* \brief RSA private key engine "i31".
*
* \see br_rsa_private
*
* \param x operand to exponentiate.
* \param sk RSA private key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i31_private(unsigned char *x,
const br_rsa_private_key *sk);
/**
* \brief RSA signature generation engine "i31".
*
* \see br_rsa_pkcs1_sign
*
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash hash value.
* \param hash_len hash value length (in bytes).
* \param sk RSA private key.
* \param x output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i31_pkcs1_sign(const unsigned char *hash_oid,
const unsigned char *hash, size_t hash_len,
const br_rsa_private_key *sk, unsigned char *x);
/*
* RSA "i62" engine. Similar to i31, but internal multiplication use
* 64x64->128 multiplications. This is available only on architecture
* that offer such an opcode.
*/
/**
* \brief RSA public key engine "i62".
*
* This function is defined only on architecture that offer a 64x64->128
* opcode. Use `br_rsa_i62_public_get()` to dynamically obtain a pointer
* to that functiom.
*
* \see br_rsa_public
*
* \param x operand to exponentiate.
* \param xlen length of the operand (in bytes).
* \param pk RSA public key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i62_public(unsigned char *x, size_t xlen,
const br_rsa_public_key *pk);
/**
* \brief RSA signature verification engine "i62".
*
* This function is defined only on architecture that offer a 64x64->128
* opcode. Use `br_rsa_i62_pkcs1_vrfy_get()` to dynamically obtain a pointer
* to that functiom.
*
* \see br_rsa_pkcs1_vrfy
*
* \param x signature buffer.
* \param xlen signature length (in bytes).
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash_len expected hash value length (in bytes).
* \param pk RSA public key.
* \param hash_out output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i62_pkcs1_vrfy(const unsigned char *x, size_t xlen,
const unsigned char *hash_oid, size_t hash_len,
const br_rsa_public_key *pk, unsigned char *hash_out);
/**
* \brief RSA private key engine "i62".
*
* This function is defined only on architecture that offer a 64x64->128
* opcode. Use `br_rsa_i62_private_get()` to dynamically obtain a pointer
* to that functiom.
*
* \see br_rsa_private
*
* \param x operand to exponentiate.
* \param sk RSA private key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i62_private(unsigned char *x,
const br_rsa_private_key *sk);
/**
* \brief RSA signature generation engine "i62".
*
* This function is defined only on architecture that offer a 64x64->128
* opcode. Use `br_rsa_i62_pkcs1_sign_get()` to dynamically obtain a pointer
* to that functiom.
*
* \see br_rsa_pkcs1_sign
*
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash hash value.
* \param hash_len hash value length (in bytes).
* \param sk RSA private key.
* \param x output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i62_pkcs1_sign(const unsigned char *hash_oid,
const unsigned char *hash, size_t hash_len,
const br_rsa_private_key *sk, unsigned char *x);
/**
* \brief Get the RSA "i62" implementation (public key operations),
* if available.
*
* \return the implementation, or 0.
*/
br_rsa_public br_rsa_i62_public_get(void);
/**
* \brief Get the RSA "i62" implementation (PKCS#1 signature verification),
* if available.
*
* \return the implementation, or 0.
*/
br_rsa_pkcs1_vrfy br_rsa_i62_pkcs1_vrfy_get(void);
/**
* \brief Get the RSA "i62" implementation (private key operations),
* if available.
*
* \return the implementation, or 0.
*/
br_rsa_private br_rsa_i62_private_get(void);
/**
* \brief Get the RSA "i62" implementation (PKCS#1 signature generation),
* if available.
*
* \return the implementation, or 0.
*/
br_rsa_pkcs1_sign br_rsa_i62_pkcs1_sign_get(void);
/*
* RSA "i15" engine. Integers are represented as 15-bit integers, so
* the code uses only 32-bit multiplication (no 64-bit result), which
* is vastly faster (and constant-time) on the ARM Cortex M0/M0+.
*/
/**
* \brief RSA public key engine "i15".
*
* \see br_rsa_public
*
* \param x operand to exponentiate.
* \param xlen length of the operand (in bytes).
* \param pk RSA public key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i15_public(unsigned char *x, size_t xlen,
const br_rsa_public_key *pk);
/**
* \brief RSA signature verification engine "i15".
*
* \see br_rsa_pkcs1_vrfy
*
* \param x signature buffer.
* \param xlen signature length (in bytes).
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash_len expected hash value length (in bytes).
* \param pk RSA public key.
* \param hash_out output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i15_pkcs1_vrfy(const unsigned char *x, size_t xlen,
const unsigned char *hash_oid, size_t hash_len,
const br_rsa_public_key *pk, unsigned char *hash_out);
/**
* \brief RSA private key engine "i15".
*
* \see br_rsa_private
*
* \param x operand to exponentiate.
* \param sk RSA private key.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i15_private(unsigned char *x,
const br_rsa_private_key *sk);
/**
* \brief RSA signature generation engine "i15".
*
* \see br_rsa_pkcs1_sign
*
* \param hash_oid encoded hash algorithm OID (or `NULL`).
* \param hash hash value.
* \param hash_len hash value length (in bytes).
* \param sk RSA private key.
* \param x output buffer for the hash value.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_i15_pkcs1_sign(const unsigned char *hash_oid,
const unsigned char *hash, size_t hash_len,
const br_rsa_private_key *sk, unsigned char *x);
/**
* \brief Get "default" RSA implementation (public-key operations).
*
* This returns the preferred implementation of RSA (public-key operations)
* on the current system.
*
* \return the default implementation.
*/
br_rsa_public br_rsa_public_get_default(void);
/**
* \brief Get "default" RSA implementation (private-key operations).
*
* This returns the preferred implementation of RSA (private-key operations)
* on the current system.
*
* \return the default implementation.
*/
br_rsa_private br_rsa_private_get_default(void);
/**
* \brief Get "default" RSA implementation (PKCS#1 signature verification).
*
* This returns the preferred implementation of RSA (signature verification)
* on the current system.
*
* \return the default implementation.
*/
br_rsa_pkcs1_vrfy br_rsa_pkcs1_vrfy_get_default(void);
/**
* \brief Get "default" RSA implementation (PKCS#1 signature generation).
*
* This returns the preferred implementation of RSA (signature generation)
* on the current system.
*
* \return the default implementation.
*/
br_rsa_pkcs1_sign br_rsa_pkcs1_sign_get_default(void);
/**
* \brief RSA decryption helper, for SSL/TLS.
*
* This function performs the RSA decryption for a RSA-based key exchange
* in a SSL/TLS server. The provided RSA engine is used. The `data`
* parameter points to the value to decrypt, of length `len` bytes. On
* success, the 48-byte pre-master secret is copied into `data`, starting
* at the first byte of that buffer; on error, the contents of `data`
* become indeterminate.
*
* This function first checks that the provided value length (`len`) is
* not lower than 59 bytes, and matches the RSA modulus length; if neither
* of this property is met, then this function returns 0 and the buffer
* is unmodified.
*
* Otherwise, decryption and then padding verification are performed, both
* in constant-time. A decryption error, or a bad padding, or an
* incorrect decrypted value length are reported with a returned value of
* 0; on success, 1 is returned. The caller (SSL server engine) is supposed
* to proceed with a random pre-master secret in case of error.
*
* \param core RSA private key engine.
* \param sk RSA private key.
* \param data input/output buffer.
* \param len length (in bytes) of the data to decrypt.
* \return 1 on success, 0 on error.
*/
uint32_t br_rsa_ssl_decrypt(br_rsa_private core, const br_rsa_private_key *sk,
unsigned char *data, size_t len);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -112,6 +112,7 @@ SECTIONS
*liblwip_src.a:(.literal .text .literal.* .text.*) *liblwip_src.a:(.literal .text .literal.* .text.*)
*liblwip2.a:(.literal .text .literal.* .text.*) *liblwip2.a:(.literal .text .literal.* .text.*)
*liblwip2_1460.a:(.literal .text .literal.* .text.*) *liblwip2_1460.a:(.literal .text .literal.* .text.*)
*libbearssl.a:(.literal .text .literal.* .text.*)
*libaxtls.a:(.literal .text .literal.* .text.*) *libaxtls.a:(.literal .text .literal.* .text.*)
*libat.a:(.literal.* .text.*) *libat.a:(.literal.* .text.*)
*libcrypto.a:(.literal.* .text.*) *libcrypto.a:(.literal.* .text.*)

BIN
tools/sdk/lib/libbearssl.a Normal file

Binary file not shown.