mirror of
https://github.com/esp8266/Arduino.git
synced 2025-04-19 23:22:16 +03:00
Add cryptographically signed update support (#5213)
Using a pluggable architecture, allow updates delivered via the Update class to be verified as signed by a certificate. By using plugins, avoid pulling either axTLS or BearSSL into normal builds. A signature is appended to a binary image, followed by the size of the signature as a 32-bit int. The updater takes a verification function and checks this signature using whatever method it chooses, and if it fails the update is not applied. A SHA256 hash class is presently implemented for the signing hash (since MD5 is a busted algorithm). A BearSSLPublicKey based verifier is implemented for RSA keys. The application only needs the Public Key, while to sign you can use OpenSSL and your private key (which should never leave your control or be deployed on any endpoints). An example using automatic signing is included. Update the docs to show the signing steps and how to use it in the automatic and manual modes. Also remove one debugging line from the signing tool. Saves ~600 bytes when in debug mode by moving strings to PMEM Windows can't run the signing script, nor does it normally have OpenSSL installed. When trying to build an automatically signed binary, warn and don't run the python.
This commit is contained in:
parent
e5d50a6e4b
commit
d8acfffdb0
@ -6,6 +6,18 @@
|
||||
|
||||
//#define DEBUG_UPDATER Serial
|
||||
|
||||
#include <Updater_Signing.h>
|
||||
#ifndef ARDUINO_SIGNING
|
||||
#define ARDUINO_SIGNING 0
|
||||
#endif
|
||||
|
||||
#if ARDUINO_SIGNING
|
||||
#include "../../libraries/ESP8266WiFi/src/BearSSLHelpers.h"
|
||||
static BearSSL::PublicKey signPubKey(signing_pubkey);
|
||||
static BearSSL::HashSHA256 hash;
|
||||
static BearSSL::SigningVerifier sign(&signPubKey);
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
#include "c_types.h"
|
||||
#include "spi_flash.h"
|
||||
@ -23,7 +35,12 @@ UpdaterClass::UpdaterClass()
|
||||
, _startAddress(0)
|
||||
, _currentAddress(0)
|
||||
, _command(U_FLASH)
|
||||
, _hash(nullptr)
|
||||
, _verify(nullptr)
|
||||
{
|
||||
#if ARDUINO_SIGNING
|
||||
installSignature(&hash, &sign);
|
||||
#endif
|
||||
}
|
||||
|
||||
void UpdaterClass::_reset() {
|
||||
@ -96,9 +113,9 @@ bool UpdaterClass::begin(size_t size, int command, int ledPin, uint8_t ledOn) {
|
||||
updateStartAddress = (updateEndAddress > roundedSize)? (updateEndAddress - roundedSize) : 0;
|
||||
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08zX (%zd)\n", roundedSize, roundedSize);
|
||||
DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08zX (%zd)\n", updateEndAddress, updateEndAddress);
|
||||
DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08zX (%zd)\n", currentSketchSize, currentSketchSize);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] roundedSize: 0x%08zX (%zd)\n"), roundedSize, roundedSize);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] updateEndAddress: 0x%08zX (%zd)\n"), updateEndAddress, updateEndAddress);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] currentSketchSize: 0x%08zX (%zd)\n"), currentSketchSize, currentSketchSize);
|
||||
#endif
|
||||
|
||||
//make sure that the size of both sketches is less than the total space (updateEndAddress)
|
||||
@ -131,12 +148,14 @@ bool UpdaterClass::begin(size_t size, int command, int ledPin, uint8_t ledOn) {
|
||||
_command = command;
|
||||
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress);
|
||||
DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress);
|
||||
DEBUG_UPDATER.printf("[begin] _size: 0x%08zX (%zd)\n", _size, _size);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] _startAddress: 0x%08X (%d)\n"), _startAddress, _startAddress);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] _currentAddress: 0x%08X (%d)\n"), _currentAddress, _currentAddress);
|
||||
DEBUG_UPDATER.printf_P(PSTR("[begin] _size: 0x%08zX (%zd)\n"), _size, _size);
|
||||
#endif
|
||||
|
||||
if (!_verify) {
|
||||
_md5.begin();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -159,7 +178,7 @@ bool UpdaterClass::end(bool evenIfRemaining){
|
||||
|
||||
if(hasError() || (!isFinished() && !evenIfRemaining)){
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("premature end: res:%u, pos:%zu/%zu\n", getError(), progress(), _size);
|
||||
DEBUG_UPDATER.printf_P(PSTR("premature end: res:%u, pos:%zu/%zu\n"), getError(), progress(), _size);
|
||||
#endif
|
||||
|
||||
_reset();
|
||||
@ -173,15 +192,68 @@ bool UpdaterClass::end(bool evenIfRemaining){
|
||||
_size = progress();
|
||||
}
|
||||
|
||||
uint32_t sigLen = 0;
|
||||
if (_verify) {
|
||||
ESP.flashRead(_startAddress + _size - sizeof(uint32_t), &sigLen, sizeof(uint32_t));
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf_P(PSTR("[Updater] sigLen: %d\n"), sigLen);
|
||||
#endif
|
||||
if (sigLen != _verify->length()) {
|
||||
_setError(UPDATE_ERROR_SIGN);
|
||||
_reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
int binSize = _size - sigLen - sizeof(uint32_t) /* The siglen word */;
|
||||
_hash->begin();
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf_P(PSTR("[Updater] Adjusted binsize: %d\n"), binSize);
|
||||
#endif
|
||||
// Calculate the MD5 and hash using proper size
|
||||
uint8_t buff[128];
|
||||
for(int i = 0; i < binSize; i += sizeof(buff)) {
|
||||
ESP.flashRead(_startAddress + i, (uint32_t *)buff, sizeof(buff));
|
||||
size_t read = std::min((int)sizeof(buff), binSize - i);
|
||||
_hash->add(buff, read);
|
||||
}
|
||||
_hash->end();
|
||||
#ifdef DEBUG_UPDATER
|
||||
unsigned char *ret = (unsigned char *)_hash->hash();
|
||||
DEBUG_UPDATER.printf_P(PSTR("[Updater] Computed Hash:"));
|
||||
for (int i=0; i<_hash->len(); i++) DEBUG_UPDATER.printf(" %02x", ret[i]);
|
||||
DEBUG_UPDATER.printf("\n");
|
||||
#endif
|
||||
uint8_t *sig = (uint8_t*)malloc(sigLen);
|
||||
if (!sig) {
|
||||
_setError(UPDATE_ERROR_SIGN);
|
||||
_reset();
|
||||
return false;
|
||||
}
|
||||
ESP.flashRead(_startAddress + binSize, (uint32_t *)sig, sigLen);
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf_P(PSTR("[Updater] Received Signature:"));
|
||||
for (size_t i=0; i<sigLen; i++) {
|
||||
DEBUG_UPDATER.printf(" %02x", sig[i]);
|
||||
}
|
||||
DEBUG_UPDATER.printf("\n");
|
||||
#endif
|
||||
if (!_verify->verify(_hash, (void *)sig, sigLen)) {
|
||||
_setError(UPDATE_ERROR_SIGN);
|
||||
_reset();
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf_P(PSTR("[Updater] Signature matches\n"));
|
||||
#endif
|
||||
} else if (_target_md5.length()) {
|
||||
_md5.calculate();
|
||||
if(_target_md5.length()) {
|
||||
if(strcasecmp(_target_md5.c_str(), _md5.toString().c_str()) != 0){
|
||||
if (strcasecmp(_target_md5.c_str(), _md5.toString().c_str())) {
|
||||
_setError(UPDATE_ERROR_MD5);
|
||||
_reset();
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUG_UPDATER
|
||||
else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str());
|
||||
else DEBUG_UPDATER.printf_P(PSTR("MD5 Success: %s\n"), _target_md5.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
@ -199,10 +271,10 @@ bool UpdaterClass::end(bool evenIfRemaining){
|
||||
eboot_command_write(&ebcmd);
|
||||
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08zX\n", _startAddress, _size);
|
||||
DEBUG_UPDATER.printf_P(PSTR("Staged: address:0x%08X, size:0x%08zX\n"), _startAddress, _size);
|
||||
}
|
||||
else if (_command == U_SPIFFS) {
|
||||
DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08zX\n", _startAddress, _size);
|
||||
DEBUG_UPDATER.printf_P(PSTR("SPIFFS: address:0x%08X, size:0x%08zX\n"), _startAddress, _size);
|
||||
#endif
|
||||
}
|
||||
|
||||
@ -229,12 +301,12 @@ bool UpdaterClass::_writeBuffer(){
|
||||
if (_currentAddress == _startAddress + FLASH_MODE_PAGE) {
|
||||
flashMode = ESP.getFlashChipMode();
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("Header: 0x%1X %1X %1X %1X\n", _buffer[0], _buffer[1], _buffer[2], _buffer[3]);
|
||||
DEBUG_UPDATER.printf_P(PSTR("Header: 0x%1X %1X %1X %1X\n"), _buffer[0], _buffer[1], _buffer[2], _buffer[3]);
|
||||
#endif
|
||||
bufferFlashMode = ESP.magicFlashChipMode(_buffer[FLASH_MODE_OFFSET]);
|
||||
if (bufferFlashMode != flashMode) {
|
||||
#ifdef DEBUG_UPDATER
|
||||
DEBUG_UPDATER.printf("Set flash mode from 0x%1X to 0x%1X\n", bufferFlashMode, flashMode);
|
||||
DEBUG_UPDATER.printf_P(PSTR("Set flash mode from 0x%1X to 0x%1X\n"), bufferFlashMode, flashMode);
|
||||
#endif
|
||||
|
||||
_buffer[FLASH_MODE_OFFSET] = flashMode;
|
||||
@ -262,7 +334,9 @@ bool UpdaterClass::_writeBuffer(){
|
||||
_setError(UPDATE_ERROR_WRITE);
|
||||
return false;
|
||||
}
|
||||
if (!_verify) {
|
||||
_md5.add(_buffer, _bufferLen);
|
||||
}
|
||||
_currentAddress += _bufferLen;
|
||||
_bufferLen = 0;
|
||||
return true;
|
||||
@ -426,8 +500,9 @@ void UpdaterClass::printError(Print &out){
|
||||
} else if(_error == UPDATE_ERROR_STREAM){
|
||||
out.println(F("Stream Read Timeout"));
|
||||
} else if(_error == UPDATE_ERROR_MD5){
|
||||
//out.println(F("MD5 Check Failed"));
|
||||
out.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str());
|
||||
out.printf_P(PSTR("MD5 Failed: expected:%s, calculated:%s\n"), _target_md5.c_str(), _md5.toString().c_str());
|
||||
} else if(_error == UPDATE_ERROR_SIGN){
|
||||
out.println(F("Signature verification failed"));
|
||||
} else if(_error == UPDATE_ERROR_FLASH_CONFIG){
|
||||
out.printf_P(PSTR("Flash config wrong real: %d IDE: %d\n"), ESP.getFlashChipRealSize(), ESP.getFlashChipSize());
|
||||
} else if(_error == UPDATE_ERROR_NEW_FLASH_CONFIG){
|
||||
|
@ -17,6 +17,7 @@
|
||||
#define UPDATE_ERROR_NEW_FLASH_CONFIG (9)
|
||||
#define UPDATE_ERROR_MAGIC_BYTE (10)
|
||||
#define UPDATE_ERROR_BOOTSTRAP (11)
|
||||
#define UPDATE_ERROR_SIGN (12)
|
||||
|
||||
#define U_FLASH 0
|
||||
#define U_SPIFFS 100
|
||||
@ -28,9 +29,30 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Abstract class to implement whatever signing hash desired
|
||||
class UpdaterHashClass {
|
||||
public:
|
||||
virtual void begin() = 0;
|
||||
virtual void add(const void *data, uint32_t len) = 0;
|
||||
virtual void end() = 0;
|
||||
virtual int len() = 0;
|
||||
virtual const void *hash() = 0;
|
||||
};
|
||||
|
||||
// Abstract class to implement a signature verifier
|
||||
class UpdaterVerifyClass {
|
||||
public:
|
||||
virtual uint32_t length() = 0; // How many bytes of signature are expected
|
||||
virtual bool verify(UpdaterHashClass *hash, const void *signature, uint32_t signatureLen) = 0; // Verify, return "true" on success
|
||||
};
|
||||
|
||||
class UpdaterClass {
|
||||
public:
|
||||
UpdaterClass();
|
||||
|
||||
/* Optionally add a cryptographic signature verification hash and method */
|
||||
void installSignature(UpdaterHashClass *hash, UpdaterVerifyClass *verify) { _hash = hash; _verify = verify; }
|
||||
|
||||
/*
|
||||
Call this to check the space needed for the update
|
||||
Will return false if there is not enough space
|
||||
@ -165,6 +187,10 @@ class UpdaterClass {
|
||||
|
||||
int _ledPin;
|
||||
uint8_t _ledOn;
|
||||
|
||||
// Optional signed binary verification
|
||||
UpdaterHashClass *_hash;
|
||||
UpdaterVerifyClass *_verify;
|
||||
};
|
||||
|
||||
extern UpdaterClass Update;
|
||||
|
3
cores/esp8266/Updater_Signing.h
Normal file
3
cores/esp8266/Updater_Signing.h
Normal file
@ -0,0 +1,3 @@
|
||||
// This file will be overridden when automatic signing is used.
|
||||
// By default, no signing.
|
||||
#define ARDUINO_SIGNING 0
|
@ -17,12 +17,17 @@ Arduino IDE option is intended primarily for software development phase. The two
|
||||
|
||||
In any case, the first firmware upload has to be done over a serial port. If the OTA routines are correctly implemented in a sketch, then all subsequent uploads may be done over the air.
|
||||
|
||||
There is no imposed security on OTA process from being hacked. It is up to developer to ensure that updates are allowed only from legitimate / trusted sources. Once the update is complete, the module restarts, and the new code is executed. The developer should ensure that the application running on the module is shut down and restarted in a safe manner. Chapters below provide additional information regarding security and safety of OTA process.
|
||||
By default there is no imposed security on OTA process. It is up to developer to ensure that updates are allowed only from legitimate / trusted sources. Once the update is complete, the module restarts, and the new code is executed. The developer should ensure that the application running on the module is shut down and restarted in a safe manner. Chapters below provide additional information regarding security and safety of OTA process.
|
||||
|
||||
Security
|
||||
~~~~~~~~
|
||||
Security Disclaimer
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Module has to be exposed wirelessly to get it updated with a new sketch. That poses chances of module being violently hacked and loaded with some other code. To reduce likelihood of being hacked consider protecting your uploads with a password, selecting certain OTA port, etc.
|
||||
No guarantees as to the level of security provided for your application by the following methods is implied. Please refer to the GNU LGPL license associated for this project for full disclaimers. If you do find security weaknesses, please don't hesitate to contact the maintainers or supply pull requests with fixes. The MD5 verification and password protection schemes are already known as supplying a very weak level of security.
|
||||
|
||||
Basic Security
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
The module has to be exposed wirelessly to get it updated with a new sketch. That poses chances of module being violently hacked and loaded with some other code. To reduce likelihood of being hacked consider protecting your uploads with a password, selecting certain OTA port, etc.
|
||||
|
||||
Check functionality provided with `ArduinoOTA <https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA>`__ library that may improve security:
|
||||
|
||||
@ -36,6 +41,90 @@ Certain protection functionality is already built in and do not require any addi
|
||||
|
||||
Make your own risk analysis and depending on application decide what library functions to implement. If required, consider implementation of other means of protection from being hacked, e.g. exposing module for uploads only according to specific schedule, trigger OTA only be user pressing dedicated “Update” button wired to ESP, etc.
|
||||
|
||||
Advanced Security - Signed Updates
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
While the above password-based security will dissuade casual hacking attempts, it is not highly secure. For applications where a higher level of security is needed, cryptographically signed OTA updates can be required. It uses SHA256 hashing in place of MD5 (which is known to be cryptographically broken) and RSA-2048 bit level encryption to guarantee only the holder of a cryptographic private key can generate code accepted by the OTA update mechanisms.
|
||||
|
||||
These are updates whose compiled binary are signed with a private key (held by the developer) and verified with a public key (stored in the application and available for all to see). The signing process computes a hash of the binary code, encrypts the hash with the developer's private key, and appends this encrypted hash to the binary that is uploaded (via OTA, web, or HTTP server). If the code is modified or replaced in any way by anyone by the developer with the key, the hash will not match and the ESP8266 will reject the upload and not accept it.
|
||||
|
||||
Cryptographic signing only protects against tampering of binaries delivered OTA. If someone has physical access they will always be able to flash the device over the serial port. Signing also does not encrypt anything but the hash (so that it can't be modified), so this does not provide protection for code inside the device. Again, if a user has physical access they can read out your program.
|
||||
|
||||
**Securing your private key is paramount. The same private/public keypair needs to be used to sign binaries as the original upload. Loss of the private key associated with a binary means that you will not be able to OTA to update any of your devices in the field. Alternatively, if the private key is copied, then the copy can be used to sign binaries which will be accepted.**
|
||||
|
||||
Signed Binary Format
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The format of a signed binary is compatible with the standard binary format, and can be uploaded to a non-signed ESP8266 via serial or OTA without any conditions. Note, however, that once an unsigned OTA app is overwritten by this signed version, further updates will require signing.
|
||||
|
||||
As shown below, the signed hash is appended to the unsigned binary followed by the total length of the signed hash (i.e. if the signed hash was 64 bytes, then this uint32 will contain 64). This format allows for extensibility (such as adding in a CA-based validation scheme allowing multiple signing keys all based off of a trust anchor), and pull requests are always welcome.
|
||||
|
||||
.. code::
|
||||
|
||||
NORMAL-BINARY <SIGNED HASH> <uint32 LENGTH-OF-SIGNING-DATA-INCLUDING-THIS-32-BITS>
|
||||
|
||||
Signed Binary Prequisites
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
OpenSSL is required to run the standard signing steps, and should be available on any UNIX-like or Windows system. As usual, the latest stable version of OpenSSL is recommended.
|
||||
|
||||
Signing requires the generation of an RSA-2048 key (other bit lengths are supported as well, but 2048 is a good selection today) using any appropriate tool. The following lines will generate a new public/private keypair. Run them in the sketch directory:
|
||||
|
||||
.. code:: bash
|
||||
|
||||
openssl genrsa -out private.key 2048
|
||||
openssl rsa -in private.key -outform PEM -pubout -out public.key
|
||||
|
||||
Automatic Signing -- Only available on Linux and Mac
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The simplest way of implementing signing is to use the automatic mode, which is only possible on Linux and Mac presently due to missing tools under Windows. This mode uses the IDE to configure the source code to enable sigining verification with a given public key, and signs binaries as part of the standard build process using a given public key.
|
||||
|
||||
To enable this mode, just include `private.key` and `public.key` in the sketch `.ino` directory. The IDE will call a helper script (`tools/signing.py`) before the build begins to create a header to enable key validation using the given public key, and after the build process to actually do the signing, generating a `sketch.bin.signed` file. When OTA is enabled (ArduinoOTA, Web, or HTTP) the binary will only accept signed updates automatically.
|
||||
|
||||
When the signing process starts, the message:
|
||||
|
||||
.. code::
|
||||
|
||||
Enabling binary signing
|
||||
|
||||
Will appear in the IDE window before a compile is launched, and at the completion of the build the signed binary file well be displayed in the IDE build window as:
|
||||
|
||||
.. code::
|
||||
|
||||
Signed binary: /full/path/to/sketch.bin.signed
|
||||
|
||||
If you receive either of the following messages in the IDE window, the signing was not completed and you will need to verify the `public.key` and `private.key`:
|
||||
|
||||
.. code::
|
||||
|
||||
Not enabling binary signing
|
||||
... or ...
|
||||
Not signing the generated binary
|
||||
|
||||
Manual Signing Binaries
|
||||
^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Users may also manually sign executables and require the OTA process to verify their signature. In the main code, before enabling any update methods, add the call:
|
||||
|
||||
.. code:: cpp
|
||||
|
||||
<in globals>
|
||||
BearSSL::PublicKey signPubKey( ... key contents ... );
|
||||
BearSSL::HashSHA256 hash;
|
||||
BearSSL::SigningVerifier sign( &signPubKey );
|
||||
...
|
||||
<in setup()>
|
||||
Update.installSignature( &hash, &sign );
|
||||
|
||||
The above snipped creates a BearSSL public key, a SHA256 hash verifier, and tells the Update object to use them to validate any updates it receives from any method.
|
||||
|
||||
Compile the sketch normally and, once a `.bin` file is available, sign it using the signer script:
|
||||
|
||||
.. code:: bash
|
||||
|
||||
<ESP8266ArduioPath>/tools/signing.py --mode sign --privatekey <path-to-private.key> --bin <path-to-unsigned-bin> --out <path-to-signed-binary>
|
||||
|
||||
Safety
|
||||
~~~~~~
|
||||
|
||||
@ -52,8 +141,8 @@ The following functions are provided with `ArduinoOTA <https://github.com/esp826
|
||||
void onProgress(OTA_CALLBACK_PROGRESS(fn));
|
||||
void onError(OTA_CALLBACK_ERROR (fn));
|
||||
|
||||
Basic Requirements
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
OTA Basic Requirements
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Flash chip size should be able to hold the old sketch (currently running) and the new sketch (OTA) at the same time.
|
||||
|
||||
|
@ -826,6 +826,62 @@ bool X509List::append(const uint8_t *derCert, size_t derLen) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// SHA256 hash for updater
|
||||
void HashSHA256::begin() {
|
||||
br_sha256_init( &_cc );
|
||||
memset( _sha256, 0, sizeof(_sha256) );
|
||||
}
|
||||
|
||||
void HashSHA256::add(const void *data, uint32_t len) {
|
||||
br_sha256_update( &_cc, data, len );
|
||||
}
|
||||
|
||||
void HashSHA256::end() {
|
||||
br_sha256_out( &_cc, _sha256 );
|
||||
}
|
||||
|
||||
int HashSHA256::len() {
|
||||
return sizeof(_sha256);
|
||||
}
|
||||
|
||||
const void *HashSHA256::hash() {
|
||||
return (const void*) _sha256;
|
||||
}
|
||||
|
||||
// SHA256 verifier
|
||||
uint32_t SigningVerifier::length()
|
||||
{
|
||||
if (!_pubKey) {
|
||||
return 0;
|
||||
} else if (_pubKey->isRSA()) {
|
||||
return _pubKey->getRSA()->nlen;
|
||||
} else if (_pubKey->isEC()) {
|
||||
return _pubKey->getEC()->qlen;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool SigningVerifier::verify(UpdaterHashClass *hash, const void *signature, uint32_t signatureLen) {
|
||||
if (!_pubKey || !hash || !signature || signatureLen != length()) return false;
|
||||
|
||||
if (_pubKey->isRSA()) {
|
||||
bool ret;
|
||||
unsigned char vrf[hash->len()];
|
||||
br_rsa_pkcs1_vrfy vrfy = br_rsa_pkcs1_vrfy_get_default();
|
||||
ret = vrfy((const unsigned char *)signature, signatureLen, NULL, sizeof(vrf), _pubKey->getRSA(), vrf);
|
||||
if (!ret || memcmp(vrf, hash->hash(), sizeof(vrf)) ) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
br_ecdsa_vrfy vrfy = br_ecdsa_vrfy_raw_get_default();
|
||||
// The EC verifier actually does the compare, unlike the RSA one
|
||||
return vrfy(br_ec_get_default(), hash->hash(), hash->len(), _pubKey->getEC(), (const unsigned char *)signature, signatureLen);
|
||||
}
|
||||
};
|
||||
|
||||
#if !CORE_MOCK
|
||||
|
||||
// Second stack thunked helpers
|
||||
|
@ -24,6 +24,8 @@
|
||||
#define _BEARSSLHELPERS_H
|
||||
|
||||
#include <bearssl/bearssl.h>
|
||||
#include <Updater.h>
|
||||
|
||||
|
||||
// Internal opaque structures, not needed by user applications
|
||||
namespace brssl {
|
||||
@ -136,6 +138,31 @@ class Session {
|
||||
br_ssl_session_parameters _session;
|
||||
};
|
||||
|
||||
// Updater SHA256 hash and signature verification
|
||||
class HashSHA256 : public UpdaterHashClass {
|
||||
public:
|
||||
virtual void begin() override;
|
||||
virtual void add(const void *data, uint32_t len) override;
|
||||
virtual void end() override;
|
||||
virtual int len() override;
|
||||
virtual const void *hash() override;
|
||||
private:
|
||||
br_sha256_context _cc;
|
||||
unsigned char _sha256[32];
|
||||
};
|
||||
|
||||
class SigningVerifier : public UpdaterVerifyClass {
|
||||
public:
|
||||
virtual uint32_t length() override;
|
||||
virtual bool verify(UpdaterHashClass *hash, const void *signature, uint32_t signatureLen) override;
|
||||
|
||||
public:
|
||||
SigningVerifier(PublicKey *pubKey) { _pubKey = pubKey; }
|
||||
|
||||
private:
|
||||
PublicKey *_pubKey;
|
||||
};
|
||||
|
||||
// Stack thunked versions of calls
|
||||
extern "C" {
|
||||
extern unsigned char *thunk_br_ssl_engine_recvapp_buf( const br_ssl_engine_context *cc, size_t *len);
|
||||
|
@ -0,0 +1,112 @@
|
||||
/*
|
||||
httpUpdateSigned.ino - Earle F. Philhower, III
|
||||
Released into the Public Domain
|
||||
|
||||
For use while building under Linux or Mac.
|
||||
|
||||
Automatic code signing is not supported on Windows, so this example
|
||||
DOES NOT WORK UNDER WINDOWS.
|
||||
|
||||
Shows how to use a public key extracted from your private certificate to
|
||||
only allow updates that you have signed to be applied over HTTP. Remote
|
||||
updates will require your private key to sign them, but of course
|
||||
**ANYONE WITH PHYSICAL ACCESS CAN UPDATE THE 8266 VIA THE SERIAL PORT**.
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WiFiMulti.h>
|
||||
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ESP8266httpUpdate.h>
|
||||
|
||||
ESP8266WiFiMulti WiFiMulti;
|
||||
|
||||
#define MANUAL_SIGNING 0
|
||||
|
||||
// This example is now configured to use the automated signing support
|
||||
// present in the Arduino IDE by having a "private.key" and "public.key"
|
||||
// in the sketch folder. You can also programmatically enable signing
|
||||
// using the method shown here.
|
||||
|
||||
// This key is taken from the server public certificate in BearSSL examples
|
||||
// You should make your own private/public key pair and guard the private
|
||||
// key (never upload it to the 8266).
|
||||
const char pubkey[] PROGMEM = R"EOF(
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyW5a4OO7xd6pRDTETO7h
|
||||
vEMBOr/wCqcTi/gi2/99rPnVvT7IH/qGSiYMxpGFKCXVqS4rU5k2XspALEquyGse
|
||||
Uav5hqsgHO6CQFFALqXzUVNCsJA9V6raUFhBaIqqCKmWzmeAkV+avM/zDQR9Wj1Q
|
||||
TCmi997sJJ5ICQc8cGSdvrhisUSbfPpKI9Ql4FApOZRABBBuZKhN9ujIzTv3OIAa
|
||||
rpQVfACKKuv7a2N2qU0uxRDojeO6odT1c6AZv6BlcF76GQGTo+/oBhqPdbAQuaBy
|
||||
cuWNgTnDQd6KUzV0E4it2fNG+cHN4kEvofN6gHx8IbOrXwFttlpAH/o7bcfCnUVh
|
||||
TQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
)EOF";
|
||||
#if MANUAL_SIGNING
|
||||
BearSSL::PublicKey *signPubKey = nullptr;
|
||||
BearSSL::HashSHA256 *hash;
|
||||
BearSSL::SigningVerifier *sign;
|
||||
#endif
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
// Serial.setDebugOutput(true);
|
||||
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
|
||||
for (uint8_t t = 4; t > 0; t--) {
|
||||
Serial.printf("[SETUP] WAIT %d...\n", t);
|
||||
Serial.flush();
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFiMulti.addAP("SSID", "PASS");
|
||||
|
||||
#if MANUAL_SIGNING
|
||||
signPubKey = new BearSSL::PublicKey(pubkey);
|
||||
hash = new BearSSL::HashSHA256();
|
||||
sign = new BearSSL::SigningVerifier(signPubKey);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
// wait for WiFi connection
|
||||
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||
|
||||
WiFiClient client;
|
||||
|
||||
#if MANUAL_SIGNING
|
||||
// Ensure all updates are signed appropriately. W/o this call, all will be accepted.
|
||||
Update.installSignature(hash, sign);
|
||||
#endif
|
||||
// If the key files are present in the build directory, signing will be
|
||||
// enabled using them automatically
|
||||
|
||||
ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);
|
||||
|
||||
t_httpUpdate_return ret = ESPhttpUpdate.update(client, "http://192.168.1.8/esp8266.bin");
|
||||
|
||||
switch (ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
break;
|
||||
}
|
||||
}
|
||||
delay(10000);
|
||||
}
|
||||
|
@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEogIBAAKCAQEAu1Pt7yEk/xI+6cozLj5Bu4xV8gXDXcHS0rSJFfl4wBTk4UXp
|
||||
aJRaLfR1k0juEEa5LBRZaoA0iLj2e6kfCibONx0VVoWmeqN2HBc3zkA1eqCksI0Q
|
||||
Uudzto4KhKHp0odiZ2zo6c/2Tn1zqD/m3OLoSjVTbsJmGuwx8RGMBXozpg/uL0hH
|
||||
flihX+HND4Xfw92QXv7SaPBhgvM9xyRxn0/w3J2nNjtuPuVN5vcQkd8ncMexVfy9
|
||||
AWp+HSA5AT5N8CJ/EeIsdDMY1US28bUePzj1WIo75bZHKZNFw/iXe2xoPpm74qri
|
||||
MNSlW2craFP2K3KYnI28vJeUU6t9I6LS9zt2zQIDAQABAoIBAE5GpuDKb8Qp4qIc
|
||||
fMBxAVSWMn+cSuONj0O+bp4BDaTt1ioP5ZVukDQtt0ehLOEePFgf9LEc+1a6Ozy3
|
||||
EaJTTs4W2Ai8djE+xqa8SPRlPjOMluSzPUP3NRHuTpTXd3YiXksrZjP1U02+/Cos
|
||||
8ZIROtFvcPqSPso3MjMyitjrFFPqEtf1P+UiamjDrMSM72YX4W55kOkiCWCnAOmw
|
||||
mGTlXOIqDSTBb1lloKWJfpB3RdnNo2izkU1HMBn7hVi433NUBA22o+RZhDFSZdD4
|
||||
3kbkUqXd4p+vc/sh6muJtWS/COSIPFkLzdEYpBdt3XQ4FhlsRtILJaPWXa4OPjR6
|
||||
ZoOwMB0CgYEA6OHfIofQiu4+HlTDN5YdyTmtYEYcrtbaQUxuQSEa2mshBphHP8uT
|
||||
mYRVl2BzuprFmXZPz+FcjnPnfxqEehljvA3wMjA/PE+nQo9yyOC0N4ulXpkkqHdR
|
||||
f+4KZVR7D+hesGe+57OQmvTqYZSHEt/ubjC9wZ90UFonLjsa4zibbrsCgYEAzexn
|
||||
XDnThb3ffyBgvprP0IJjgMAEY0pXD++PKPQqPu9JMz68t7roYzkKFCFVOsaWpKxC
|
||||
vX9mvYjTBjLpWh+ltIAN+EFz6seIbeSJ0RNybsAXYwT/mFWGHx2tMtlW6DgBu3UD
|
||||
J2Yf76n0JaddBkfNMQI00Dl41+MU+AwwTB9fTBcCgYB2+f6Pm6d1cyYVROS/X1g0
|
||||
V9011FwPDwFOXwftCka31Ad5YQ71jsIHqk44GjTF3xCYyJMZ917cAGcCzr9jydjk
|
||||
WJKgcXm9DEy9ep//9Jzdy+BepgrObrcajriM8E424FaP9VDY+yojoICl/cXMZM9h
|
||||
SFGJvDcmXgiqW9PuxhrSxQKBgAMN2oqXoPd+1W3BQS4ShbqF9IvYTThbxebKmsj0
|
||||
thuw2NkVuR7Qetnd4rRhui3g/CL9GxBMb22oNdkFsEhR59dBfvOLpPh6dR+MIC8l
|
||||
prDV0IL7c/8CZbbYbdUvPAa9rejl12IiNZ8MWj6kuNB7CCQN8FKWR6CMEaeMJrs6
|
||||
S+OJAoGAbehNOUwEzmUKkfxf+279kBkgabcQ3NTaeSx0QOnI9KWHFGLYLQk9cMSu
|
||||
maQJ1TYpbIoP1njzJ4bI2tynhwEuSMEhh4afP6U5H10NJX4PqSd0Rqc1vSJYcszr
|
||||
5mUWil8FfbCBZ8jod2NQ55KYMVY5CphCqaK/s2bw2pvIR3uqJGg=
|
||||
-----END RSA PRIVATE KEY-----
|
@ -0,0 +1,9 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1Pt7yEk/xI+6cozLj5B
|
||||
u4xV8gXDXcHS0rSJFfl4wBTk4UXpaJRaLfR1k0juEEa5LBRZaoA0iLj2e6kfCibO
|
||||
Nx0VVoWmeqN2HBc3zkA1eqCksI0QUudzto4KhKHp0odiZ2zo6c/2Tn1zqD/m3OLo
|
||||
SjVTbsJmGuwx8RGMBXozpg/uL0hHflihX+HND4Xfw92QXv7SaPBhgvM9xyRxn0/w
|
||||
3J2nNjtuPuVN5vcQkd8ncMexVfy9AWp+HSA5AT5N8CJ/EeIsdDMY1US28bUePzj1
|
||||
WIo75bZHKZNFw/iXe2xoPpm74qriMNSlW2craFP2K3KYnI28vJeUU6t9I6LS9zt2
|
||||
zQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
13
platform.txt
13
platform.txt
@ -10,6 +10,7 @@ version=2.5.0-dev
|
||||
|
||||
runtime.tools.xtensa-lx106-elf-gcc.path={runtime.platform.path}/tools/xtensa-lx106-elf
|
||||
runtime.tools.esptool.path={runtime.platform.path}/tools/esptool
|
||||
runtime.tools.signing={runtime.platform.path}/tools/signing.py
|
||||
|
||||
compiler.warning_flags=-w
|
||||
compiler.warning_flags.none=-w
|
||||
@ -74,9 +75,12 @@ compiler.elf2hex.extra_flags=
|
||||
## needs bash, git, and echo
|
||||
recipe.hooks.core.prebuild.1.pattern=bash -c "mkdir -p {build.path}/core && echo \#define ARDUINO_ESP8266_GIT_VER 0x`git --git-dir {runtime.platform.path}/.git rev-parse --short=8 HEAD 2>/dev/null || echo ffffffff` >{build.path}/core/core_version.h"
|
||||
recipe.hooks.core.prebuild.2.pattern=bash -c "mkdir -p {build.path}/core && echo \#define ARDUINO_ESP8266_GIT_DESC `cd "{runtime.platform.path}"; git describe --tags 2>/dev/null || echo unix-{version}` >>{build.path}/core/core_version.h"
|
||||
recipe.hooks.core.prebuild.3.pattern="{runtime.tools.signing}" --mode header --publickey "{build.source.path}/public.key" --out "{build.path}/core/Updater_Signing.h"
|
||||
|
||||
## windows-compatible version without git
|
||||
recipe.hooks.core.prebuild.1.pattern.windows=cmd.exe /c mkdir {build.path}\core & (echo #define ARDUINO_ESP8266_GIT_VER 0x00000000 & echo #define ARDUINO_ESP8266_GIT_DESC win-{version} ) > {build.path}\core\core_version.h
|
||||
recipe.hooks.core.prebuild.2.pattern.windows=
|
||||
recipe.hooks.core.prebuild.2.pattern.windows=cmd.exe /c if exist {build.source.path}\public.key echo #error Cannot automatically build signed binaries on Windows > {build.path}\core\Updater_Signing.h
|
||||
recipe.hooks.core.prebuild.3.pattern.windows=
|
||||
|
||||
## Build the app.ld linker file
|
||||
recipe.hooks.linking.prelink.1.pattern="{compiler.path}{compiler.c.cmd}" -CC -E -P {build.vtable_flags} "{runtime.platform.path}/tools/sdk/ld/eagle.app.v6.common.ld.h" -o "{build.path}/local.eagle.app.v6.common.ld"
|
||||
@ -102,7 +106,12 @@ recipe.objcopy.eep.pattern=
|
||||
## Create hex
|
||||
#recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex"
|
||||
|
||||
recipe.objcopy.hex.pattern="{runtime.tools.esptool.path}/{compiler.esptool.cmd}" -eo "{runtime.platform.path}/bootloaders/eboot/eboot.elf" -bo "{build.path}/{build.project_name}.bin" -bm {build.flash_mode} -bf {build.flash_freq} -bz {build.flash_size} -bs .text -bp 4096 -ec -eo "{build.path}/{build.project_name}.elf" -bs .irom0.text -bs .text -bs .data -bs .rodata -bc -ec
|
||||
recipe.objcopy.hex.1.pattern="{runtime.tools.esptool.path}/{compiler.esptool.cmd}" -eo "{runtime.platform.path}/bootloaders/eboot/eboot.elf" -bo "{build.path}/{build.project_name}.bin" -bm {build.flash_mode} -bf {build.flash_freq} -bz {build.flash_size} -bs .text -bp 4096 -ec -eo "{build.path}/{build.project_name}.elf" -bs .irom0.text -bs .text -bs .data -bs .rodata -bc -ec
|
||||
recipe.objcopy.hex.2.pattern="{runtime.tools.signing}" --mode sign --privatekey "{build.source.path}/private.key" --bin "{build.path}/{build.project_name}.bin" --out "{build.path}/{build.project_name}.bin.signed"
|
||||
|
||||
# No signing on Windows
|
||||
recipe.objcopy.hex.1.pattern.windows="{runtime.tools.esptool.path}/{compiler.esptool.cmd}" -eo "{runtime.platform.path}/bootloaders/eboot/eboot.elf" -bo "{build.path}/{build.project_name}.bin" -bm {build.flash_mode} -bf {build.flash_freq} -bz {build.flash_size} -bs .text -bp 4096 -ec -eo "{build.path}/{build.project_name}.elf" -bs .irom0.text -bs .text -bs .data -bs .rodata -bc -ec
|
||||
recipe.objcopy.hex.2.pattern.windows=
|
||||
|
||||
## Save hex
|
||||
recipe.output.tmp_file={build.project_name}.bin
|
||||
|
72
tools/signing.py
Executable file
72
tools/signing.py
Executable file
@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description='Binary signing tool')
|
||||
parser.add_argument('-m', '--mode', help='Mode (header, sign)')
|
||||
parser.add_argument('-b', '--bin', help='Unsigned binary')
|
||||
parser.add_argument('-o', '--out', help='Output file');
|
||||
parser.add_argument('-p', '--publickey', help='Public key file');
|
||||
parser.add_argument('-s', '--privatekey', help='Private(secret) key file');
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
if args.mode == "header":
|
||||
val = ""
|
||||
try:
|
||||
with open(args.publickey, "rb") as f:
|
||||
pub = f.read()
|
||||
val += "#include <pgmspace.h>\n"
|
||||
val += "#define ARDUINO_SIGNING 1\n"
|
||||
val += "static const char signing_pubkey[] PROGMEM = {\n"
|
||||
for i in pub:
|
||||
val += "0x%02x, \n" % ord(i)
|
||||
val = val[:-3]
|
||||
val +="\n};\n"
|
||||
sys.stderr.write("Enabling binary signing\n")
|
||||
except:
|
||||
# Silence the default case to avoid people thinking something is wrong.
|
||||
# Only people who care about signing will know what it means, anyway,
|
||||
# and they can check for the positive acknowledgement above.
|
||||
# sys.stderr.write("Not enabling binary signing\n")
|
||||
val += "#define ARDUINO_SIGNING 0\n"
|
||||
with open(args.out, "w") as f:
|
||||
f.write(val)
|
||||
return 0
|
||||
elif args.mode == "sign":
|
||||
val = ""
|
||||
if not os.path.isfile(args.privatekey):
|
||||
return
|
||||
try:
|
||||
with open(args.bin, "rb") as b:
|
||||
bin = b.read()
|
||||
sha256 = hashlib.sha256(bin)
|
||||
signcmd = [ 'openssl', 'rsautl', '-sign', '-inkey', args.privatekey ]
|
||||
proc = subprocess.Popen(signcmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
signout, signerr = proc.communicate(input=sha256.digest())
|
||||
if proc.returncode:
|
||||
sys.stderr.write("OpenSSL returned an error signing the binary: " + str(proc.returncode) + "\nSTDERR: " + str(signerr))
|
||||
else:
|
||||
with open(args.out, "wb") as out:
|
||||
out.write(bin)
|
||||
out.write(signout)
|
||||
out.write(b'\x00\x01\x00\x00')
|
||||
sys.stderr.write("Signed binary: " + args.out + "\n")
|
||||
except Exception as e:
|
||||
sys.stderr.write(str(e))
|
||||
sys.stderr.write("Not signing the generated binary\n")
|
||||
return 0
|
||||
else:
|
||||
sys.stderr.write("ERROR: Mode not specified as header or sign\n")
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
|
Loading…
x
Reference in New Issue
Block a user