mirror of
https://github.com/esp8266/Arduino.git
synced 2025-07-27 18:02:17 +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:
committed by
GitHub
parent
bd87970aae
commit
e3c970210f
@ -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;
|
||||
}
|
||||
|
51
libraries/ESP8266WiFi/examples/BearSSL_CertStore/certs-from-mozilla.py
Executable file
51
libraries/ESP8266WiFi/examples/BearSSL_CertStore/certs-from-mozilla.py
Executable 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
|
||||
|
@ -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);
|
||||
}
|
177
libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino
Normal file
177
libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino
Normal 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
|
||||
Sq7Iax5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KBgA/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");
|
||||
}
|
20
libraries/ESP8266WiFi/examples/BearSSL_Server/cert.pem
Normal file
20
libraries/ESP8266WiFi/examples/BearSSL_Server/cert.pem
Normal 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-----
|
28
libraries/ESP8266WiFi/examples/BearSSL_Server/key.pem
Normal file
28
libraries/ESP8266WiFi/examples/BearSSL_Server/key.pem
Normal 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/TcW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PlqYi/17hoAVWz37mLDjtWDB4ir78QMoGbesQVtK9W/4vzmez4
|
||||
ZLKlffdL5tCtA08Gq9aond1z83Xdnh1UjtwHIJvJPc/AoCFW1r5skv/G6acAk6I2
|
||||
Zs0aiirNGTEymRX4rw26Qg==
|
||||
-----END PRIVATE KEY-----
|
@ -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++YUh8NrbXwE83xVsDqcB3F76xcXNKFD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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");
|
||||
}
|
@ -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
|
@ -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-----
|
@ -0,0 +1 @@
|
||||
A25EB184B01D7FBB
|
@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEAxsa4qU/tlzN4YTcnn/I/ffsijOPc8QRcwClKzasIZNFEye4u
|
||||
Thl+LGZWFIFb8X8Dc+xmmBaWlPJbqtphgFKStparDdduHSW1ud6Y1FVKxljo3UwC
|
||||
MrYm76Q/j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2LcWlcgt4EEojJRxukljcFerkjVndz1
|
||||
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-----
|
@ -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
|
@ -0,0 +1,17 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICyTCCAbECCQCiXrGEsB1/uzANBgkqhkiG9w0BAQsFADAhMQswCQYDVQQGEwJV
|
||||
UzESMBAGA1UEAwwJMTI3LjAuMC4zMB4XDTE4MDMxNDA0MjIwNloXDTI5MDIyNDA0
|
||||
MjIwNlowLDEWMBQGA1UECgwNTXkgQ2xpZW50IE9yZzESMBAGA1UEAwwJMTI3LjAu
|
||||
MC4yMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5MW88nCi2tUrf/Tq
|
||||
5w+5IvuqTAusaN4eelwS69sd9yXfM/DEgipw7o4t340oGdLVA4b7h1Qwxttw62ki
|
||||
Z5VecXosg7xbJSjbB4LLLcmv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
||||
+4EmQ6Vmls87ObCMsHFFdBKJoz13+HemWRHn0Y57BgdvVakWV9Fu6Q9Mytv1fi6Z
|
||||
uY3TLSixKARUoE//xTzFMShJcsaEZZjZaOP7BqG3s8KfDqs1U0sKnUCo5FwfO3sU
|
||||
04vFAoGALjVG6v0IpvPFZcJBN8wUuu9cLduyCnUiFsMYgfglXDSkynRS51/7Fxqf
|
||||
q0ROTeHrKem3iiJ62j7U3tNni2awczWCgTlUjSQzBQo6Cu1UA52M3/XyqVNmfx/g
|
||||
04dVpDrqFscdIasQcL1UddiwcT2a63RjriBaTETvjegoNVu1XR4=
|
||||
-----END RSA PRIVATE KEY-----
|
@ -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-----
|
@ -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
|
@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDTzCCAjcCCQDPXvMRYOpeuDANBgkqhkiG9w0BAQsFADCBpjESMBAGA1UEAwwJ
|
||||
MTI3LjAuMC4xMQswCQYDVQQGEwJVUzElMCMGA1UECgwcTXkgT3duIENlcnRpZmlj
|
||||
YXRlIEF1dGhvcml0eTEUMBIGA1UECAwLQXJkdWlub0xhbmQxFTATBgNVBAcMDEFy
|
||||
ZHVpbm9WaWxsZTEVMBMGA1UECgwMRVNQODI2NlVzZXJzMRgwFgYDVQQLDA9FU1A4
|
||||
MjY2LUFyZHVpbm8wHhcNMTgwMzE0MDQwMDAwWhcNMjkwMjI0MDQwMDAwWjAsMRYw
|
||||
FAYDVQQKDA1NeSBTZXJ2ZXIgT3JnMRIwEAYDVQQDDAkxMjcuMC4wLjMwggEiMA0G
|
||||
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCxE1VO+o/75hSHw2ttfATzfFWwOpwH
|
||||
cXvrFxc0oUMRF9V3Y/8u/IOi8JyhC1PRQJGA9zFGnz3gS48f9G7pnYu7zmxX/+Lt
|
||||
x7bu1zZZEVJ+6GVHEc8slYfFOXUIR9en+jCQQJD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qNirGKN2XspwmTqEjzbhv0KLt4F
|
||||
X4GyWOoU0nFksXiLIFpOaQWSwWG7KJWrfGJ9kWXR0Xxsfl5QLoDCuNCsn3t4d43T
|
||||
K7phlwKBgHDzF+50+/Wez3YHCy2a/HgSbHCpLQjkknvgwkOh1z7YitYBUm72HP8Z
|
||||
Ge6b4wEfNuBdlZll/y9BQQOZJLFvJTE5t51X9klrkGrOb+Ftwr7eI/H5xgcadI52
|
||||
tPYglR5fjuRF/wnt3oX9JlQ2RtSbs+3naXH8JoherHaqNn8UpH0t
|
||||
-----END RSA PRIVATE KEY-----
|
@ -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
|
||||
}
|
@ -19,6 +19,12 @@ WiFiServerSecure KEYWORD1
|
||||
WiFiUDP KEYWORD1
|
||||
WiFiClientSecure KEYWORD1
|
||||
ESP8266WiFiMulti KEYWORD1
|
||||
BearSSLX509List KEYWORD1
|
||||
BearSSLPrivateKey KEYWORD1
|
||||
BearSSLPublicKey KEYWORD1
|
||||
CertStoreSPIFFSBearSSL KEYWORD1
|
||||
CertStoreSDBearSSL KEYWORD1
|
||||
|
||||
#######################################
|
||||
# Methods and Functions (KEYWORD2)
|
||||
#######################################
|
||||
@ -157,6 +163,28 @@ localPort KEYWORD2
|
||||
stopAll 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)
|
||||
#######################################
|
||||
|
821
libraries/ESP8266WiFi/src/BearSSLHelpers.cpp
Normal file
821
libraries/ESP8266WiFi/src/BearSSLHelpers.cpp
Normal 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;
|
||||
}
|
122
libraries/ESP8266WiFi/src/BearSSLHelpers.h
Normal file
122
libraries/ESP8266WiFi/src/BearSSLHelpers.h
Normal 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
|
141
libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp
Normal file
141
libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp
Normal 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);
|
||||
}
|
61
libraries/ESP8266WiFi/src/CertStoreBearSSL.h
Normal file
61
libraries/ESP8266WiFi/src/CertStoreBearSSL.h
Normal 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
|
||||
|
141
libraries/ESP8266WiFi/src/CertStoreSDBearSSL.cpp
Normal file
141
libraries/ESP8266WiFi/src/CertStoreSDBearSSL.cpp
Normal 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);
|
||||
}
|
47
libraries/ESP8266WiFi/src/CertStoreSDBearSSL.h
Normal file
47
libraries/ESP8266WiFi/src/CertStoreSDBearSSL.h
Normal 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
|
125
libraries/ESP8266WiFi/src/CertStoreSPIFFSBearSSL.cpp
Normal file
125
libraries/ESP8266WiFi/src/CertStoreSPIFFSBearSSL.cpp
Normal 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);
|
||||
}
|
43
libraries/ESP8266WiFi/src/CertStoreSPIFFSBearSSL.h
Normal file
43
libraries/ESP8266WiFi/src/CertStoreSPIFFSBearSSL.h
Normal 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
|
||||
|
@ -40,6 +40,8 @@ extern "C" {
|
||||
#include "WiFiServer.h"
|
||||
#include "WiFiServerSecure.h"
|
||||
#include "WiFiClientSecure.h"
|
||||
#include "BearSSLHelpers.h"
|
||||
#include "CertStoreBearSSL.h"
|
||||
|
||||
#ifdef DEBUG_ESP_WIFI
|
||||
#ifdef DEBUG_ESP_PORT
|
||||
|
@ -20,77 +20,8 @@
|
||||
|
||||
*/
|
||||
|
||||
#ifndef wificlientsecure_h
|
||||
#define wificlientsecure_h
|
||||
#include "WiFiClient.h"
|
||||
#include "include/ssl.h"
|
||||
#include "WiFiClientSecureAxTLS.h"
|
||||
#include "WiFiClientSecureBearSSL.h"
|
||||
|
||||
|
||||
class SSLContext;
|
||||
|
||||
class WiFiClientSecure : public WiFiClient {
|
||||
public:
|
||||
WiFiClientSecure();
|
||||
~WiFiClientSecure() override;
|
||||
|
||||
int connect(IPAddress ip, uint16_t port) override;
|
||||
int connect(const String host, uint16_t port) override;
|
||||
int connect(const char* name, uint16_t port) override;
|
||||
|
||||
bool verify(const char* fingerprint, const char* domain_name);
|
||||
bool verifyCertChain(const char* domain_name);
|
||||
|
||||
uint8_t connected() override;
|
||||
size_t write(const uint8_t *buf, size_t size) override;
|
||||
size_t write_P(PGM_P buf, size_t size) override;
|
||||
size_t write(Stream& stream); // Note this is not virtual
|
||||
int read(uint8_t *buf, size_t size) override;
|
||||
int available() override;
|
||||
int read() override;
|
||||
int peek() override;
|
||||
size_t peekBytes(uint8_t *buffer, size_t length) override;
|
||||
void stop() override;
|
||||
|
||||
bool setCACert(const uint8_t* pk, size_t size);
|
||||
bool setCertificate(const uint8_t* pk, size_t size);
|
||||
bool setPrivateKey(const uint8_t* pk, size_t size);
|
||||
|
||||
bool setCACert_P(PGM_VOID_P pk, size_t size);
|
||||
bool setCertificate_P(PGM_VOID_P pk, size_t size);
|
||||
bool setPrivateKey_P(PGM_VOID_P pk, size_t size);
|
||||
|
||||
bool loadCACert(Stream& stream, size_t size);
|
||||
bool loadCertificate(Stream& stream, size_t size);
|
||||
bool loadPrivateKey(Stream& stream, size_t size);
|
||||
|
||||
void allowSelfSignedCerts();
|
||||
|
||||
template<typename TFile>
|
||||
bool loadCertificate(TFile& file) {
|
||||
return loadCertificate(file, file.size());
|
||||
}
|
||||
|
||||
template<typename TFile>
|
||||
bool loadPrivateKey(TFile& file) {
|
||||
return loadPrivateKey(file, file.size());
|
||||
}
|
||||
|
||||
template<typename TFile>
|
||||
bool loadCACert(TFile& file) {
|
||||
return loadCACert(file, file.size());
|
||||
}
|
||||
|
||||
friend class WiFiServerSecure; // Needs access to custom constructor below
|
||||
protected:
|
||||
// Only called by WiFiServerSecure
|
||||
WiFiClientSecure(ClientContext* client, bool usePMEM, const uint8_t *rsakey, int rsakeyLen, const uint8_t *cert, int certLen);
|
||||
|
||||
protected:
|
||||
void _initSSLContext();
|
||||
int _connectSSL(const char* hostName);
|
||||
bool _verifyDN(const char* name);
|
||||
|
||||
std::shared_ptr<SSLContext> _ssl = nullptr;
|
||||
};
|
||||
|
||||
#endif //wificlientsecure_h
|
||||
using namespace axTLS;
|
||||
// using namespace BearSSL;
|
||||
|
@ -51,6 +51,8 @@ extern "C"
|
||||
#define SSL_DEBUG_OPTS 0
|
||||
#endif
|
||||
|
||||
namespace axTLS {
|
||||
|
||||
|
||||
typedef struct BufferItem
|
||||
{
|
||||
@ -905,3 +907,5 @@ extern "C" void __ax_wdt_feed()
|
||||
optimistic_yield(10000);
|
||||
}
|
||||
extern "C" void ax_wdt_feed() __attribute__ ((weak, alias("__ax_wdt_feed")));
|
||||
|
||||
};
|
100
libraries/ESP8266WiFi/src/WiFiClientSecureAxTLS.h
Normal file
100
libraries/ESP8266WiFi/src/WiFiClientSecureAxTLS.h
Normal 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
|
1289
libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp
Normal file
1289
libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp
Normal file
File diff suppressed because it is too large
Load Diff
215
libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.h
Normal file
215
libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.h
Normal 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
|
@ -17,27 +17,5 @@
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef wifiserversecure_h
|
||||
#define wifiserversecure_h
|
||||
|
||||
#include "WiFiServer.h"
|
||||
class WiFiClientSecure;
|
||||
|
||||
class WiFiServerSecure : public WiFiServer {
|
||||
public:
|
||||
WiFiServerSecure(IPAddress addr, uint16_t port);
|
||||
WiFiServerSecure(uint16_t port);
|
||||
void setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
|
||||
void setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen);
|
||||
virtual ~WiFiServerSecure() {}
|
||||
WiFiClientSecure available(uint8_t* status = NULL);
|
||||
private:
|
||||
bool usePMEM = false;
|
||||
const uint8_t *rsakey = nullptr;
|
||||
int rsakeyLen = 0;
|
||||
const uint8_t *cert = nullptr;
|
||||
int certLen = 0;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
#include "WiFiServerSecureAxTLS.h"
|
||||
#include "WiFiServerSecureBearSSL.h"
|
||||
|
@ -36,6 +36,9 @@ extern "C" {
|
||||
#include "include/ClientContext.h"
|
||||
#include "WiFiServerSecure.h"
|
||||
|
||||
|
||||
namespace axTLS {
|
||||
|
||||
WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port)
|
||||
{
|
||||
}
|
||||
@ -77,3 +80,4 @@ WiFiClientSecure WiFiServerSecure::available(uint8_t* status)
|
||||
return WiFiClientSecure();
|
||||
}
|
||||
|
||||
};
|
48
libraries/ESP8266WiFi/src/WiFiServerSecureAxTLS.h
Normal file
48
libraries/ESP8266WiFi/src/WiFiServerSecureAxTLS.h
Normal 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
|
||||
|
119
libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp
Normal file
119
libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp
Normal 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);
|
||||
}
|
||||
|
||||
|
||||
};
|
76
libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.h
Normal file
76
libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.h
Normal 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
|
Reference in New Issue
Block a user