1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-06-29 16:03:14 +03:00

Remove axTLS from code and documentation (#7437)

This commit is contained in:
Earle F. Philhower, III
2020-07-09 09:21:38 -07:00
committed by GitHub
parent 1ead157558
commit 70e4457041
29 changed files with 10 additions and 3533 deletions

View File

@ -20,27 +20,6 @@
*/
//#include "WiFiClientSecureAxTLS.h"
//using namespace axTLS;
/**********************************
* !! Now BearSSL is the default !!
*
* While not advised,
* Use legacy API without updating with:
*
#define USING_AXTLS
#include <ESP8266WiFi.h>
//#include <WiFiClientSecure.h>
#include "WiFiClientSecureAxTLS.h"
using namespace axTLS;
*
*
**********************************/
#include "WiFiClientSecureBearSSL.h"
#ifndef USING_AXTLS
// do not default to BearSSL API ("using" has no "unusing" counterpart)
using namespace BearSSL;
#endif

View File

@ -1,512 +0,0 @@
/*
WiFiClientSecure.cpp - 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
*/
#define LWIP_INTERNAL
#include "debug.h"
#include "ESP8266WiFi.h"
#include "WiFiClientSecure.h"
#include "WiFiClient.h"
#ifdef DEBUG_ESP_SSL
#define DEBUG_SSL
#endif
#ifdef DEBUG_SSL
#define SSL_DEBUG_OPTS (SSL_DISPLAY_STATES | SSL_DISPLAY_CERTS)
#else
#define SSL_DEBUG_OPTS 0
#endif
// Pull in required classes
#include "include/SSLContext.h"
#include "include/ClientContext.h"
namespace axTLS {
SSL_CTX* SSLContext::_ssl_client_ctx = nullptr;
int SSLContext::_ssl_client_ctx_refcnt = 0;
SSL_CTX* SSLContext::_ssl_svr_ctx = nullptr;
int SSLContext::_ssl_svr_ctx_refcnt = 0;
WiFiClientSecure::WiFiClientSecure()
{
// TLS handshake may take more than the 5 second default timeout
_timeout = 15000;
}
WiFiClientSecure::~WiFiClientSecure()
{
_ssl = nullptr;
}
// Only called by the WifiServerSecure, need to get the keys/certs loaded before beginning
WiFiClientSecure::WiFiClientSecure(ClientContext* client, bool usePMEM,
const uint8_t *rsakey, int rsakeyLen,
const uint8_t *cert, int certLen)
{
// TLS handshake may take more than the 5 second default timeout
_timeout = 15000;
// We've been given the client context from the available() call
_client = client;
_client->ref();
// Make the "_ssl" SSLContext, in the constructor there should be none yet
SSLContext *_new_ssl = new SSLContext(true);
std::shared_ptr<SSLContext> _new_ssl_shared(_new_ssl);
_ssl = _new_ssl_shared;
if (usePMEM) {
if (rsakey && rsakeyLen) {
_ssl->loadObject_P(SSL_OBJ_RSA_KEY, rsakey, rsakeyLen);
}
if (cert && certLen) {
_ssl->loadObject_P(SSL_OBJ_X509_CERT, cert, certLen);
}
} else {
if (rsakey && rsakeyLen) {
_ssl->loadObject(SSL_OBJ_RSA_KEY, rsakey, rsakeyLen);
}
if (cert && certLen) {
_ssl->loadObject(SSL_OBJ_X509_CERT, cert, certLen);
}
}
_ssl->connectServer(client, _timeout);
}
int WiFiClientSecure::connect(IPAddress ip, uint16_t port)
{
if (!WiFiClient::connect(ip, port)) {
return 0;
}
return _connectSSL(nullptr);
}
int WiFiClientSecure::connect(const char* name, uint16_t port)
{
IPAddress remote_addr;
if (!WiFi.hostByName(name, remote_addr)) {
return 0;
}
if (!WiFiClient::connect(remote_addr, port)) {
return 0;
}
return _connectSSL(name);
}
int WiFiClientSecure::connect(const String& host, uint16_t port)
{
return connect(host.c_str(), port);
}
int WiFiClientSecure::_connectSSL(const char* hostName)
{
if (!_ssl) {
_ssl = std::make_shared<SSLContext>();
if (!_ssl) {
return 0;
}
}
_ssl->connect(_client, hostName, _timeout);
auto status = ssl_handshake_status(*_ssl);
if (status != SSL_OK) {
_ssl = nullptr;
return 0;
}
return 1;
}
size_t WiFiClientSecure::write(const uint8_t *buf, size_t size)
{
if (!_ssl) {
return 0;
}
int rc = _ssl->write(buf, size);
if (rc >= 0) {
return rc;
}
if (rc != SSL_CLOSE_NOTIFY) {
_ssl = nullptr;
}
return 0;
}
size_t WiFiClientSecure::write_P(PGM_P buf, size_t size)
{
// Copy to RAM and call normal send. alloca() auto-frees on return
uint8_t *copy = (uint8_t*)alloca(size);
memcpy_P(copy, buf, size);
return write(copy, size);
}
// The axTLS bare libs don't understand anything about Arduino Streams,
// so we have to manually read and send individual chunks.
size_t WiFiClientSecure::write(Stream& stream)
{
size_t totalSent = 0;
size_t countRead;
size_t countSent;
if (!_ssl) {
return 0;
}
do {
uint8_t temp[256]; // Temporary chunk size same as ClientContext
countSent = 0;
countRead = stream.readBytes(temp, sizeof(temp));
if (countRead) {
countSent = write(temp, countRead);
totalSent += countSent;
}
yield(); // Feed the WDT
} while ( (countSent == countRead) && (countSent > 0) );
return totalSent;
}
int WiFiClientSecure::read(uint8_t *buf, size_t size)
{
if (!_ssl) {
return 0;
}
return _ssl->read(buf, size);
}
int WiFiClientSecure::read()
{
if (!_ssl) {
return -1;
}
return _ssl->read();
}
int WiFiClientSecure::peek()
{
if (!_ssl) {
return -1;
}
return _ssl->peek();
}
size_t WiFiClientSecure::peekBytes(uint8_t *buffer, size_t length)
{
size_t count = 0;
if (!_ssl) {
return 0;
}
_startMillis = millis();
while ((available() < (int) length) && ((millis() - _startMillis) < _timeout)) {
yield();
}
if (!_ssl) {
return 0;
}
if (available() < (int) length) {
count = available();
} else {
count = length;
}
return _ssl->peekBytes((char *)buffer, count);
}
int WiFiClientSecure::available()
{
if (!_ssl) {
return 0;
}
return _ssl->available();
}
/*
SSL TCP RX data connected
null x x N
!null x Y Y
Y Y x Y
x N N N
err x N N
*/
uint8_t WiFiClientSecure::connected()
{
if (_ssl) {
if (_ssl->hasData()) {
return true;
}
if (_client && _client->state() == ESTABLISHED && _ssl->connected()) {
return true;
}
}
return false;
}
bool WiFiClientSecure::stop(unsigned int maxWaitMs)
{
if (_ssl) {
_ssl->stop();
}
return WiFiClient::stop(maxWaitMs);
}
static bool parseHexNibble(char pb, uint8_t* res)
{
if (pb >= '0' && pb <= '9') {
*res = (uint8_t) (pb - '0'); return true;
} else if (pb >= 'a' && pb <= 'f') {
*res = (uint8_t) (pb - 'a' + 10); return true;
} else if (pb >= 'A' && pb <= 'F') {
*res = (uint8_t) (pb - 'A' + 10); return true;
}
return false;
}
// Compare a name from certificate and domain name, return true if they match
static bool matchName(const String& name, const String& domainName)
{
int wildcardPos = name.indexOf('*');
if (wildcardPos == -1) {
// Not a wildcard, expect an exact match
return name == domainName;
}
int firstDotPos = name.indexOf('.');
if (wildcardPos > firstDotPos) {
// Wildcard is not part of leftmost component of domain name
// Do not attempt to match (rfc6125 6.4.3.1)
return false;
}
if (wildcardPos != 0 || firstDotPos != 1) {
// Matching of wildcards such as baz*.example.com and b*z.example.com
// is optional. Maybe implement this in the future?
return false;
}
int domainNameFirstDotPos = domainName.indexOf('.');
if (domainNameFirstDotPos < 0) {
return false;
}
return domainName.substring(domainNameFirstDotPos) == name.substring(firstDotPos);
}
bool WiFiClientSecure::verify(const char* fp, const char* domain_name)
{
if (!_ssl) {
return false;
}
uint8_t sha1[20];
int len = strlen(fp);
int pos = 0;
for (size_t i = 0; i < sizeof(sha1); ++i) {
while (pos < len && ((fp[pos] == ' ') || (fp[pos] == ':'))) {
++pos;
}
if (pos > len - 2) {
DEBUGV("pos:%d len:%d fingerprint too short\r\n", pos, len);
return false;
}
uint8_t high, low;
if (!parseHexNibble(fp[pos], &high) || !parseHexNibble(fp[pos+1], &low)) {
DEBUGV("pos:%d len:%d invalid hex sequence: %c%c\r\n", pos, len, fp[pos], fp[pos+1]);
return false;
}
pos += 2;
sha1[i] = low | (high << 4);
}
if (ssl_match_fingerprint(*_ssl, sha1) != 0) {
DEBUGV("fingerprint doesn't match\r\n");
return false;
}
return _verifyDN(domain_name);
}
bool WiFiClientSecure::_verifyDN(const char* domain_name)
{
DEBUGV("domain name: '%s'\r\n", (domain_name)?domain_name:"(null)");
String domain_name_str(domain_name);
domain_name_str.toLowerCase();
const char* san = nullptr;
int i = 0;
while ((san = ssl_get_cert_subject_alt_dnsname(*_ssl, i)) != nullptr) {
String san_str(san);
san_str.toLowerCase();
if (matchName(san_str, domain_name_str)) {
return true;
}
DEBUGV("SAN %d: '%s', no match\r\n", i, san);
++i;
}
const char* common_name = ssl_get_cert_dn(*_ssl, SSL_X509_CERT_COMMON_NAME);
String common_name_str(common_name);
common_name_str.toLowerCase();
if (common_name && matchName(common_name_str, domain_name_str)) {
return true;
}
DEBUGV("CN: '%s', no match\r\n", (common_name)?common_name:"(null)");
return false;
}
bool WiFiClientSecure::verifyCertChain(const char* domain_name)
{
if (!_ssl) {
return false;
}
if (!_ssl->verifyCert()) {
return false;
}
return _verifyDN(domain_name);
}
void WiFiClientSecure::_initSSLContext()
{
if (!_ssl) {
_ssl = std::make_shared<SSLContext>();
}
}
bool WiFiClientSecure::setCACert(const uint8_t* pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_X509_CACERT, pk, size) : false;
}
bool WiFiClientSecure::setCertificate(const uint8_t* pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_X509_CERT, pk, size) : false;
}
bool WiFiClientSecure::setPrivateKey(const uint8_t* pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_RSA_KEY, pk, size) : false;
}
bool WiFiClientSecure::setCACert_P(PGM_VOID_P pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject_P(SSL_OBJ_X509_CACERT, pk, size) : false;
}
bool WiFiClientSecure::setCertificate_P(PGM_VOID_P pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject_P(SSL_OBJ_X509_CERT, pk, size) : false;
}
bool WiFiClientSecure::setPrivateKey_P(PGM_VOID_P pk, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject_P(SSL_OBJ_RSA_KEY, pk, size) : false;
}
bool WiFiClientSecure::loadCACert(Stream& stream, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_X509_CACERT, stream, size) : false;
}
bool WiFiClientSecure::loadCertificate(Stream& stream, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_X509_CERT, stream, size) : false;
}
bool WiFiClientSecure::loadPrivateKey(Stream& stream, size_t size)
{
_initSSLContext();
return _ssl ? _ssl->loadObject(SSL_OBJ_RSA_KEY, stream, size) : false;
}
void WiFiClientSecure::allowSelfSignedCerts()
{
_initSSLContext();
if (_ssl) {
_ssl->allowSelfSignedCerts();
}
}
extern "C" int __ax_port_read(int fd, uint8_t* buffer, size_t count)
{
ClientContext* _client = SSLContext::getIOContext(fd);
if (!_client || (_client->state() != ESTABLISHED && !_client->getSize())) {
errno = EIO;
return -1;
}
size_t cb = _client->read((char*) buffer, count);
if (cb != count) {
errno = EAGAIN;
}
if (cb == 0) {
optimistic_yield(100);
return -1;
}
return cb;
}
extern "C" int ax_port_read(int fd, uint8_t* buffer, size_t count) __attribute__ ((weak, alias("__ax_port_read")));
extern "C" int __ax_port_write(int fd, uint8_t* buffer, size_t count)
{
ClientContext* _client = SSLContext::getIOContext(fd);
if (!_client || _client->state() != ESTABLISHED) {
errno = EIO;
return -1;
}
size_t cb = _client->write(buffer, count);
if (cb != count) {
errno = EAGAIN;
}
return cb;
}
extern "C" int ax_port_write(int fd, uint8_t* buffer, size_t count) __attribute__ ((weak, alias("__ax_port_write")));
extern "C" int __ax_get_file(const char *filename, uint8_t **buf)
{
(void) filename;
*buf = 0;
return 0;
}
extern "C" int ax_get_file(const char *filename, uint8_t **buf) __attribute__ ((weak, alias("__ax_get_file")));
extern "C" void __ax_wdt_feed()
{
optimistic_yield(10000);
}
extern "C" void ax_wdt_feed() __attribute__ ((weak, alias("__ax_wdt_feed")));
};

View File

@ -1,101 +0,0 @@
/*
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() __attribute__((deprecated("Upgrade to BearSSL is advised, check https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiClientSecure.h#L25-L99")));
~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 { (void)stop(0); }
bool stop(unsigned int maxWaitMs);
bool setCACert(const uint8_t* pk, size_t size);
bool setCertificate(const uint8_t* pk, size_t size);
bool setPrivateKey(const uint8_t* pk, size_t size);
bool setCACert_P(PGM_VOID_P pk, size_t size);
bool setCertificate_P(PGM_VOID_P pk, size_t size);
bool setPrivateKey_P(PGM_VOID_P pk, size_t size);
bool loadCACert(Stream& stream, size_t size);
bool loadCertificate(Stream& stream, size_t size);
bool loadPrivateKey(Stream& stream, size_t size);
void allowSelfSignedCerts();
template<typename TFile>
bool loadCertificate(TFile& file) {
return loadCertificate(file, file.size());
}
template<typename TFile>
bool loadPrivateKey(TFile& file) {
return loadPrivateKey(file, file.size());
}
template<typename TFile>
bool loadCACert(TFile& file) {
return loadCACert(file, file.size());
}
friend class WiFiServerSecure; // Needs access to custom constructor below
protected:
// Only called by WiFiServerSecure
WiFiClientSecure(ClientContext* client, bool usePMEM, const uint8_t *rsakey, int rsakeyLen, const uint8_t *cert, int certLen);
protected:
void _initSSLContext();
int _connectSSL(const char* hostName);
bool _verifyDN(const char* name);
std::shared_ptr<SSLContext> _ssl = nullptr;
};
};
#endif //wificlientsecure_h

View File

@ -19,5 +19,4 @@
#include <WiFiClientSecure.h>
//#include "WiFiServerSecureAxTLS.h"
#include "WiFiServerSecureBearSSL.h"

View File

@ -1,87 +0,0 @@
/*
WiFiServerSecure.cpp - SSL server for esp8266, mostly compatible
with Arduino WiFi shield library
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
*/
#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 "WiFiClientSecureAxTLS.h"
#include "WiFiServerSecureAxTLS.h"
namespace axTLS {
WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port)
{
}
WiFiServerSecure::WiFiServerSecure(uint16_t port) : WiFiServer(port)
{
}
void WiFiServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen)
{
this->usePMEM = false;
this->rsakey = key;
this->rsakeyLen = keyLen;
this->cert = cert;
this->certLen = certLen;
}
void WiFiServerSecure::setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen)
{
this->usePMEM = true;
this->rsakey = key;
this->rsakeyLen = keyLen;
this->cert = cert;
this->certLen = certLen;
}
WiFiClientSecure WiFiServerSecure::available(uint8_t* status)
{
(void) status; // Unused
if (_unclaimed) {
WiFiClientSecure result(_unclaimed, usePMEM, rsakey, rsakeyLen, cert, certLen);
_unclaimed = _unclaimed->next();
result.setNoDelay(_noDelay);
DEBUGV("WS:av\r\n");
return result;
}
optimistic_yield(1000);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
return WiFiClientSecure();
#pragma GCC diagnostic pop
}
};

View File

@ -1,50 +0,0 @@
/*
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);
using ClientType = WiFiClientSecure;
private:
bool usePMEM = false;
const uint8_t *rsakey = nullptr;
int rsakeyLen = 0;
const uint8_t *cert = nullptr;
int certLen = 0;
};
};
#endif

View File

@ -1,441 +0,0 @@
/*
SSLContext.h - Used by WiFiClientAxTLS
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 SSLCONTEXT_H
#define SSLCONTEXT_H
#define LWIP_INTERNAL
extern "C"
{
#include "osapi.h"
#include "ets_sys.h"
}
#include <list>
#include <errno.h>
#include "lwip/opt.h"
#include "lwip/ip.h"
#include "lwip/tcp.h"
#include "lwip/inet.h"
#include "lwip/netif.h"
#include <include/ClientContext.h>
#include <WiFiClientSecureAxTLS.h>
#include "c_types.h"
namespace axTLS {
typedef struct BufferItem
{
BufferItem(const uint8_t* data_, size_t size_)
: size(size_), data(new uint8_t[size])
{
if (data.get() != nullptr) {
memcpy(data.get(), data_, size);
} else {
DEBUGV(":wcs alloc %d failed\r\n", size_);
size = 0;
}
}
size_t size;
std::unique_ptr<uint8_t[]> data;
} BufferItem;
typedef std::list<BufferItem> BufferList;
class SSLContext
{
public:
SSLContext(bool isServer = false)
{
_isServer = isServer;
if (!_isServer) {
if (_ssl_client_ctx_refcnt == 0) {
_ssl_client_ctx = ssl_ctx_new(SSL_SERVER_VERIFY_LATER | SSL_DEBUG_OPTS | SSL_CONNECT_IN_PARTS | SSL_READ_BLOCKING | SSL_NO_DEFAULT_KEY, 0);
}
++_ssl_client_ctx_refcnt;
} else {
if (_ssl_svr_ctx_refcnt == 0) {
_ssl_svr_ctx = ssl_ctx_new(SSL_SERVER_VERIFY_LATER | SSL_DEBUG_OPTS | SSL_CONNECT_IN_PARTS | SSL_READ_BLOCKING | SSL_NO_DEFAULT_KEY, 0);
}
++_ssl_svr_ctx_refcnt;
}
}
~SSLContext()
{
if (io_ctx) {
io_ctx->unref();
io_ctx = nullptr;
}
_ssl = nullptr;
if (!_isServer) {
--_ssl_client_ctx_refcnt;
if (_ssl_client_ctx_refcnt == 0) {
ssl_ctx_free(_ssl_client_ctx);
_ssl_client_ctx = nullptr;
}
} else {
--_ssl_svr_ctx_refcnt;
if (_ssl_svr_ctx_refcnt == 0) {
ssl_ctx_free(_ssl_svr_ctx);
_ssl_svr_ctx = nullptr;
}
}
}
static void _delete_shared_SSL(SSL *_to_del)
{
ssl_free(_to_del);
}
void connect(ClientContext* ctx, const char* hostName, uint32_t timeout_ms)
{
SSL_EXTENSIONS* ext = ssl_ext_new();
ssl_ext_set_host_name(ext, hostName);
if (_ssl) {
/* Creating a new TLS session on top of a new TCP connection.
ssl_free will want to send a close notify alert, but the old TCP connection
is already gone at this point, so reset io_ctx. */
io_ctx = nullptr;
_ssl = nullptr;
_available = 0;
_read_ptr = nullptr;
}
io_ctx = ctx;
ctx->ref();
// Wrap the new SSL with a smart pointer, custom deleter to call ssl_free
SSL *_new_ssl = ssl_client_new(_ssl_client_ctx, reinterpret_cast<int>(this), nullptr, 0, ext);
std::shared_ptr<SSL> _new_ssl_shared(_new_ssl, _delete_shared_SSL);
_ssl = _new_ssl_shared;
uint32_t t = millis();
while (millis() - t < timeout_ms && ssl_handshake_status(_ssl.get()) != SSL_OK) {
uint8_t* data;
int rc = ssl_read(_ssl.get(), &data);
if (rc < SSL_OK) {
ssl_display_error(rc);
break;
}
}
}
void connectServer(ClientContext *ctx, uint32_t timeout_ms)
{
io_ctx = ctx;
ctx->ref();
// Wrap the new SSL with a smart pointer, custom deleter to call ssl_free
SSL *_new_ssl = ssl_server_new(_ssl_svr_ctx, reinterpret_cast<int>(this));
std::shared_ptr<SSL> _new_ssl_shared(_new_ssl, _delete_shared_SSL);
_ssl = _new_ssl_shared;
uint32_t t = millis();
while (millis() - t < timeout_ms && ssl_handshake_status(_ssl.get()) != SSL_OK) {
uint8_t* data;
int rc = ssl_read(_ssl.get(), &data);
if (rc < SSL_OK) {
ssl_display_error(rc);
break;
}
}
}
void stop()
{
if (io_ctx) {
io_ctx->unref();
}
io_ctx = nullptr;
}
bool connected()
{
if (_isServer) {
return _ssl != nullptr;
} else {
return _ssl != nullptr && ssl_handshake_status(_ssl.get()) == SSL_OK;
}
}
int read(uint8_t* dst, size_t size)
{
if (!_available) {
if (!_readAll()) {
return 0;
}
}
size_t will_copy = (_available < size) ? _available : size;
memcpy(dst, _read_ptr, will_copy);
_read_ptr += will_copy;
_available -= will_copy;
if (_available == 0) {
_read_ptr = nullptr;
/* Send pending outgoing data, if any */
if (_hasWriteBuffers()) {
_writeBuffersSend();
}
}
return will_copy;
}
int read()
{
if (!_available) {
if (!_readAll()) {
return -1;
}
}
int result = _read_ptr[0];
++_read_ptr;
--_available;
if (_available == 0) {
_read_ptr = nullptr;
/* Send pending outgoing data, if any */
if (_hasWriteBuffers()) {
_writeBuffersSend();
}
}
return result;
}
int write(const uint8_t* src, size_t size)
{
if (_isServer) {
return _write(src, size);
} else if (!_available) {
if (_hasWriteBuffers()) {
int rc = _writeBuffersSend();
if (rc < 0) {
return rc;
}
}
return _write(src, size);
}
/* Some received data is still present in the axtls fragment buffer.
We can't call ssl_write now, as that will overwrite the contents of
the fragment buffer, corrupting the received data.
Save a copy of the outgoing data, and call ssl_write when all
recevied data has been consumed by the application.
*/
return _writeBufferAdd(src, size);
}
int peek()
{
if (!_available) {
if (!_readAll()) {
return -1;
}
}
return _read_ptr[0];
}
size_t peekBytes(char *dst, size_t size)
{
if (!_available) {
if (!_readAll()) {
return -1;
}
}
size_t will_copy = (_available < size) ? _available : size;
memcpy(dst, _read_ptr, will_copy);
return will_copy;
}
int available()
{
auto cb = _available;
if (cb == 0) {
cb = _readAll();
} else {
optimistic_yield(100);
}
return cb;
}
// similar to available, but doesn't return exact size
bool hasData()
{
return _available > 0 || (io_ctx && io_ctx->getSize() > 0);
}
bool loadObject(int type, Stream& stream, size_t size)
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[size]);
if (!buf.get()) {
DEBUGV("loadObject: failed to allocate memory\n");
return false;
}
size_t cb = stream.readBytes(buf.get(), size);
if (cb != size) {
DEBUGV("loadObject: reading %u bytes, got %u\n", size, cb);
return false;
}
return loadObject(type, buf.get(), size);
}
bool loadObject_P(int type, PGM_VOID_P data, size_t size)
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[size]);
memcpy_P(buf.get(),data, size);
return loadObject(type, buf.get(), size);
}
bool loadObject(int type, const uint8_t* data, size_t size)
{
int rc = ssl_obj_memory_load(_isServer?_ssl_svr_ctx:_ssl_client_ctx, type, data, static_cast<int>(size), nullptr);
if (rc != SSL_OK) {
DEBUGV("loadObject: ssl_obj_memory_load returned %d\n", rc);
return false;
}
return true;
}
bool verifyCert()
{
int rc = ssl_verify_cert(_ssl.get());
if (_allowSelfSignedCerts && rc == SSL_X509_ERROR(X509_VFY_ERROR_SELF_SIGNED)) {
DEBUGV("Allowing self-signed certificate\n");
return true;
} else if (rc != SSL_OK) {
DEBUGV("ssl_verify_cert returned %d\n", rc);
ssl_display_error(rc);
return false;
}
return true;
}
void allowSelfSignedCerts()
{
_allowSelfSignedCerts = true;
}
operator SSL*()
{
return _ssl.get();
}
static ClientContext* getIOContext(int fd)
{
if (fd) {
SSLContext *thisSSL = reinterpret_cast<SSLContext*>(fd);
return thisSSL->io_ctx;
}
return nullptr;
}
protected:
int _readAll()
{
if (!_ssl) {
return 0;
}
optimistic_yield(100);
uint8_t* data;
int rc = ssl_read(_ssl.get(), &data);
if (rc <= 0) {
if (rc < SSL_OK && rc != SSL_CLOSE_NOTIFY && rc != SSL_ERROR_CONN_LOST) {
_ssl = nullptr;
}
return 0;
}
DEBUGV(":wcs ra %d\r\n", rc);
_read_ptr = data;
_available = rc;
return _available;
}
int _write(const uint8_t* src, size_t size)
{
if (!_ssl) {
return 0;
}
int rc = ssl_write(_ssl.get(), src, size);
if (rc >= 0) {
return rc;
}
DEBUGV(":wcs write rc=%d\r\n", rc);
return rc;
}
int _writeBufferAdd(const uint8_t* data, size_t size)
{
if (!_ssl) {
return 0;
}
_writeBuffers.emplace_back(data, size);
if (_writeBuffers.back().data.get() == nullptr) {
_writeBuffers.pop_back();
return 0;
}
return size;
}
int _writeBuffersSend()
{
while (!_writeBuffers.empty()) {
auto& first = _writeBuffers.front();
int rc = _write(first.data.get(), first.size);
_writeBuffers.pop_front();
if (rc < 0) {
if (_hasWriteBuffers()) {
DEBUGV(":wcs _writeBuffersSend dropping unsent data\r\n");
_writeBuffers.clear();
}
return rc;
}
}
return 0;
}
bool _hasWriteBuffers()
{
return !_writeBuffers.empty();
}
bool _isServer = false;
static SSL_CTX* _ssl_client_ctx;
static int _ssl_client_ctx_refcnt;
static SSL_CTX* _ssl_svr_ctx;
static int _ssl_svr_ctx_refcnt;
std::shared_ptr<SSL> _ssl = nullptr;
const uint8_t* _read_ptr = nullptr;
size_t _available = 0;
BufferList _writeBuffers;
bool _allowSelfSignedCerts = false;
ClientContext* io_ctx = nullptr;
};
}; // End namespace axTLS
#endif

View File

@ -1,583 +0,0 @@
/*
* Copyright (c) 2007-2016, Cameron Rich
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the axTLS project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @mainpage axTLS API
*
* @image html axolotl.jpg
*
* The axTLS library has features such as:
* - The TLSv1 SSL client/server protocol
* - No requirement to use any openssl libraries.
* - A choice between AES block (128/256 bit) and RC4 (128 bit) stream ciphers.
* - RSA encryption/decryption with variable sized keys (up to 4096 bits).
* - Certificate chaining and peer authentication.
* - Session resumption, session renegotiation.
* - ASN.1, X.509, PKCS#8, PKCS#12 keys/certificates with DER/PEM encoding.
* - Highly configurable compile time options.
* - Portable across many platforms (written in ANSI C), and has language
* bindings in C, C#, VB.NET, Java, Perl and Lua.
* - Partial openssl API compatibility (via a wrapper).
* - A very small footprint (around 50-60kB for the library in 'server-only'
* mode).
* - No dependencies on sockets - can use serial connections for example.
* - A very simple API - ~ 20 functions/methods.
*
* A list of these functions/methods are described below.
*
* @ref c_api
*
* @ref bigint_api
*
* @ref csharp_api
*
* @ref java_api
*/
#ifndef HEADER_SSL_H
#define HEADER_SSL_H
#ifdef __cplusplus
extern "C" {
#endif
/* need to predefine before ssl_lib.h gets to it */
#define SSL_SESSION_ID_SIZE 32
#define EXP_FUNC
#define STDCALL
// struct SSL_CTX_;
typedef struct SSL_CTX_ SSL_CTX;
typedef struct SSL_ SSL;
typedef struct SSL_EXTENSIONS_ SSL_EXTENSIONS;
/* The optional parameters that can be given to the client/server SSL engine */
#define SSL_CLIENT_AUTHENTICATION 0x00010000
#define SSL_SERVER_VERIFY_LATER 0x00020000
#define SSL_NO_DEFAULT_KEY 0x00040000
#define SSL_DISPLAY_STATES 0x00080000
#define SSL_DISPLAY_BYTES 0x00100000
#define SSL_DISPLAY_CERTS 0x00200000
#define SSL_DISPLAY_RSA 0x00400000
#define SSL_CONNECT_IN_PARTS 0x00800000
#define SSL_READ_BLOCKING 0x01000000
/* errors that can be generated */
#define SSL_OK 0
#define SSL_NOT_OK -1
#define SSL_ERROR_DEAD -2
#define SSL_CLOSE_NOTIFY -3
#define SSL_ERROR_CONN_LOST -256
#define SSL_ERROR_RECORD_OVERFLOW -257
#define SSL_ERROR_SOCK_SETUP_FAILURE -258
#define SSL_ERROR_INVALID_HANDSHAKE -260
#define SSL_ERROR_INVALID_PROT_MSG -261
#define SSL_ERROR_INVALID_HMAC -262
#define SSL_ERROR_INVALID_VERSION -263
#define SSL_ERROR_UNSUPPORTED_EXTENSION -264
#define SSL_ERROR_INVALID_SESSION -265
#define SSL_ERROR_NO_CIPHER -266
#define SSL_ERROR_INVALID_CERT_HASH_ALG -267
#define SSL_ERROR_BAD_CERTIFICATE -268
#define SSL_ERROR_INVALID_KEY -269
#define SSL_ERROR_FINISHED_INVALID -271
#define SSL_ERROR_NO_CERT_DEFINED -272
#define SSL_ERROR_NO_CLIENT_RENOG -273
#define SSL_ERROR_NOT_SUPPORTED -274
#define SSL_X509_OFFSET -512
#define SSL_X509_ERROR(A) (SSL_X509_OFFSET+A)
#define X509_OK 0
#define X509_NOT_OK -1
#define X509_VFY_ERROR_NO_TRUSTED_CERT -2
#define X509_VFY_ERROR_BAD_SIGNATURE -3
#define X509_VFY_ERROR_NOT_YET_VALID -4
#define X509_VFY_ERROR_EXPIRED -5
#define X509_VFY_ERROR_SELF_SIGNED -6
#define X509_VFY_ERROR_INVALID_CHAIN -7
#define X509_VFY_ERROR_UNSUPPORTED_DIGEST -8
#define X509_INVALID_PRIV_KEY -9
#define X509_MAX_CERTS -10
#define X509_VFY_ERROR_BASIC_CONSTRAINT -11
/* alert types that are recognized */
#define SSL_ALERT_TYPE_WARNING 1
#define SLL_ALERT_TYPE_FATAL 2
/* these are all the alerts that are recognized */
#define SSL_ALERT_CLOSE_NOTIFY 0
#define SSL_ALERT_UNEXPECTED_MESSAGE 10
#define SSL_ALERT_BAD_RECORD_MAC 20
#define SSL_ALERT_RECORD_OVERFLOW 22
#define SSL_ALERT_HANDSHAKE_FAILURE 40
#define SSL_ALERT_BAD_CERTIFICATE 42
#define SSL_ALERT_UNSUPPORTED_CERTIFICATE 43
#define SSL_ALERT_CERTIFICATE_EXPIRED 45
#define SSL_ALERT_CERTIFICATE_UNKNOWN 46
#define SSL_ALERT_ILLEGAL_PARAMETER 47
#define SSL_ALERT_UNKNOWN_CA 48
#define SSL_ALERT_DECODE_ERROR 50
#define SSL_ALERT_DECRYPT_ERROR 51
#define SSL_ALERT_INVALID_VERSION 70
#define SSL_ALERT_NO_RENEGOTIATION 100
#define SSL_ALERT_UNSUPPORTED_EXTENSION 110
/* The ciphers that are supported */
#define SSL_AES128_SHA 0x2f
#define SSL_AES256_SHA 0x35
#define SSL_AES128_SHA256 0x3c
#define SSL_AES256_SHA256 0x3d
/* build mode ids' */
#define SSL_BUILD_SKELETON_MODE 0x01
#define SSL_BUILD_SERVER_ONLY 0x02
#define SSL_BUILD_ENABLE_VERIFICATION 0x03
#define SSL_BUILD_ENABLE_CLIENT 0x04
#define SSL_BUILD_FULL_MODE 0x05
/* offsets to retrieve configuration information */
#define SSL_BUILD_MODE 0
#define SSL_MAX_CERT_CFG_OFFSET 1
#define SSL_MAX_CA_CERT_CFG_OFFSET 2
#define SSL_HAS_PEM 3
/* default session sizes */
#define SSL_DEFAULT_SVR_SESS 5
#define SSL_DEFAULT_CLNT_SESS 1
/* X.509/X.520 distinguished name types */
#define SSL_X509_CERT_COMMON_NAME 0
#define SSL_X509_CERT_ORGANIZATION 1
#define SSL_X509_CERT_ORGANIZATIONAL_NAME 2
#define SSL_X509_CA_CERT_COMMON_NAME 3
#define SSL_X509_CA_CERT_ORGANIZATION 4
#define SSL_X509_CA_CERT_ORGANIZATIONAL_NAME 5
/* SSL object loader types */
#define SSL_OBJ_X509_CERT 1
#define SSL_OBJ_X509_CACERT 2
#define SSL_OBJ_RSA_KEY 3
#define SSL_OBJ_PKCS8 4
#define SSL_OBJ_PKCS12 5
/**
* @defgroup c_api Standard C API
* @brief The standard interface in C.
* @{
*/
/**
* @brief Establish a new client/server context.
*
* This function is called before any client/server SSL connections are made.
*
* Each new connection will use the this context's private key and
* certificate chain. If a different certificate chain is required, then a
* different context needs to be be used.
*
* There are two threading models supported - a single thread with one
* SSL_CTX can support any number of SSL connections - and multiple threads can
* support one SSL_CTX object each (the default). But if a single SSL_CTX
* object uses many SSL objects in individual threads, then the
* CONFIG_SSL_CTX_MUTEXING option needs to be configured.
*
* @param options [in] Any particular options. At present the options
* supported are:
* - SSL_SERVER_VERIFY_LATER (client only): Don't stop a handshake if the server
* authentication fails. The certificate can be authenticated later with a
* call to ssl_verify_cert().
* - SSL_CLIENT_AUTHENTICATION (server only): Enforce client authentication
* i.e. each handshake will include a "certificate request" message from the
* server. Only available if verification has been enabled.
* - SSL_DISPLAY_BYTES (full mode build only): Display the byte sequences
* during the handshake.
* - SSL_DISPLAY_STATES (full mode build only): Display the state changes
* during the handshake.
* - SSL_DISPLAY_CERTS (full mode build only): Display the certificates that
* are passed during a handshake.
* - SSL_DISPLAY_RSA (full mode build only): Display the RSA key details that
* are passed during a handshake.
* - SSL_CONNECT_IN_PARTS (client only): To use a non-blocking version of
* ssl_client_new().
* @param num_sessions [in] The number of sessions to be used for session
* caching. If this value is 0, then there is no session caching. This option
* is not used in skeleton mode.
* @return A client/server context.
*/
EXP_FUNC SSL_CTX * STDCALL ssl_ctx_new(uint32_t options, int num_sessions);
/**
* @brief Remove a client/server context.
*
* Frees any used resources used by this context. Each connection will be
* sent a "Close Notify" alert (if possible).
* @param ssl_ctx [in] The client/server context.
*/
EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx);
/**
* @brief Allocates new SSL extensions structure and returns pointer to it
*
* @return ssl_ext Pointer to SSL_EXTENSIONS structure
*
*/
EXP_FUNC SSL_EXTENSIONS * STDCALL ssl_ext_new();
/**
* @brief Set the host name for SNI extension
* @param ssl_ext pointer returned by ssl_ext_new
* @param host_name pointer to a zero-terminated string containing host name
*/
EXP_FUNC void STDCALL ssl_ext_set_host_name(SSL_EXTENSIONS * ext, const char* host_name);
/**
* @brief Set the maximum fragment size for the fragment size negotiation extension
* @param ssl_ext pointer returned by ssl_ext_new
* @param fragment_size fragment size, allowed values: 2^9, 2^10 ... 2^14
*/
EXP_FUNC void STDCALL ssl_ext_set_max_fragment_size(SSL_EXTENSIONS * ext, unsigned fragment_size);
/**
* @brief Frees SSL extensions structure
*
* @param ssl_ext [in] Pointer to SSL_EXTENSION structure
*
*/
EXP_FUNC void STDCALL ssl_ext_free(SSL_EXTENSIONS *ssl_ext);
/**
* @brief (server only) Establish a new SSL connection to an SSL client.
*
* It is up to the application to establish the logical connection (whether it
* is a socket, serial connection etc).
* @param ssl_ctx [in] The server context.
* @param client_fd [in] The client's file descriptor.
* @return An SSL object reference.
*/
EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd);
/**
* @brief (client only) Establish a new SSL connection to an SSL server.
*
* It is up to the application to establish the initial logical connection
* (whether it is a socket, serial connection etc).
*
* This is a normally a blocking call - it will finish when the handshake is
* complete (or has failed). To use in non-blocking mode, set
* SSL_CONNECT_IN_PARTS in ssl_ctx_new().
* @param ssl_ctx [in] The client context.
* @param client_fd [in] The client's file descriptor.
* @param session_id [in] A 32 byte session id for session resumption. This
* can be null if no session resumption is being used or required. This option
* is not used in skeleton mode.
* @param sess_id_size The size of the session id (max 32)
* @param ssl_ext pointer to a structure with the activated SSL extensions and their values
* @return An SSL object reference. Use ssl_handshake_status() to check
* if a handshake succeeded.
*/
EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const uint8_t *session_id, uint8_t sess_id_size, SSL_EXTENSIONS* ssl_ext);
/**
* @brief Free any used resources on this connection.
* A "Close Notify" message is sent on this connection (if possible). It is up
* to the application to close the socket or file descriptor.
* @param ssl [in] The ssl object reference.
*/
EXP_FUNC void STDCALL ssl_free(SSL *ssl);
/**
* @brief Read the SSL data stream.
* If the socket is non-blocking and data is blocked then SSO_OK will be
* returned.
* @param ssl [in] An SSL object reference.
* @param in_data [out] If the read was successful, a pointer to the read
* buffer will be here. Do NOT ever free this memory as this buffer is used in
* sucessive calls. If the call was unsuccessful, this value will be null.
* @return The number of decrypted bytes:
* - if > 0, then the handshaking is complete and we are returning the number
* of decrypted bytes.
* - SSL_OK if the handshaking stage is successful (but not yet complete).
* - < 0 if an error.
* @see ssl.h for the error code list.
* @note Use in_data before doing any successive ssl calls.
*/
EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data);
/**
* @brief Write to the SSL data stream.
* if the socket is non-blocking and data is blocked then a check is made
* to ensure that all data is sent (i.e. blocked mode is forced).
* @param ssl [in] An SSL obect reference.
* @param out_data [in] The data to be written
* @param out_len [in] The number of bytes to be written.
* @return The number of bytes sent, or if < 0 if an error.
* @see ssl.h for the error code list.
*/
EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len);
/**
* @brief Calculate the size of the encrypted data from what you are about to send
* @param ssl [in] An SSL obect reference.
* @param out_len [in] The number of bytes to be written.
* @return The number of bytes that will be sent, or if < 0 if an error.
* @see ssl.h for the error code list.
*/
EXP_FUNC int STDCALL ssl_calculate_write_length(SSL *ssl, int out_len);
/**
* @brief Find an ssl object based on a file descriptor.
*
* Goes through the list of SSL objects maintained in a client/server context
* to look for a file descriptor match.
* @param ssl_ctx [in] The client/server context.
* @param client_fd [in] The file descriptor.
* @return A reference to the SSL object. Returns null if the object could not
* be found.
*/
EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd);
/**
* @brief Get the session id for a handshake.
*
* This will be a 32 byte sequence and is available after the first
* handshaking messages are sent.
* @param ssl [in] An SSL object reference.
* @return The session id as a 32 byte sequence.
* @note A SSLv23 handshake may have only 16 valid bytes.
*/
EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl);
/**
* @brief Get the session id size for a handshake.
*
* This will normally be 32 but could be 0 (no session id) or something else.
* @param ssl [in] An SSL object reference.
* @return The size of the session id.
*/
EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl);
/**
* @brief Return the cipher id (in the SSL form).
* @param ssl [in] An SSL object reference.
* @return The cipher id. This will be one of the following:
* - SSL_AES128_SHA (0x2f)
* - SSL_AES256_SHA (0x35)
* - SSL_RC4_128_SHA (0x05)
* - SSL_RC4_128_MD5 (0x04)
*/
EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl);
/**
* @brief Return the status of the handshake.
* @param ssl [in] An SSL object reference.
* @return SSL_OK if the handshake is complete and ok.
* @see ssl.h for the error code list.
*/
EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl);
/**
* @brief Retrieve various parameters about the axTLS engine.
* @param offset [in] The configuration offset. It will be one of the following:
* - SSL_BUILD_MODE The build mode. This will be one of the following:
* - SSL_BUILD_SERVER_ONLY (basic server mode)
* - SSL_BUILD_ENABLE_VERIFICATION (server can do client authentication)
* - SSL_BUILD_ENABLE_CLIENT (client/server capabilties)
* - SSL_BUILD_FULL_MODE (client/server with diagnostics)
* - SSL_BUILD_SKELETON_MODE (skeleton mode)
* - SSL_MAX_CERT_CFG_OFFSET The maximum number of certificates allowed.
* - SSL_MAX_CA_CERT_CFG_OFFSET The maximum number of CA certificates allowed.
* - SSL_HAS_PEM 1 if supported
* @return The value of the requested parameter.
*/
EXP_FUNC int STDCALL ssl_get_config(int offset);
/**
* @brief Display why the handshake failed.
*
* This call is only useful in a 'full mode' build. The output is to stdout.
* @param error_code [in] An error code.
* @see ssl.h for the error code list.
*/
EXP_FUNC void STDCALL ssl_display_error(int error_code);
/**
* @brief Authenticate a received certificate.
*
* This call is usually made by a client after a handshake is complete and the
* context is in SSL_SERVER_VERIFY_LATER mode.
* @param ssl [in] An SSL object reference.
* @return SSL_OK if the certificate is verified.
*/
EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl);
/**
* @brief Check if certificate fingerprint (SHA1) matches the one given.
*
* @param ssl [in] An SSL object reference.
* @param fp [in] SHA1 fingerprint to match against
* @return SSL_OK if the certificate is verified.
*/
EXP_FUNC int STDCALL ssl_match_fingerprint(const SSL *ssl, const uint8_t* fp);
/**
* @brief Check if SHA256 hash of Subject Public Key Info matches the one given.
*
* @param ssl [in] An SSL object reference.
* @param fp [in] SHA256 hash to match against
* @return SSL_OK if the certificate is verified.
*/
EXP_FUNC int STDCALL ssl_match_spki_sha256(const SSL *ssl, const uint8_t* hash);
/**
* @brief Retrieve an X.509 distinguished name component.
*
* When a handshake is complete and a certificate has been exchanged, then the
* details of the remote certificate can be retrieved.
*
* This will usually be used by a client to check that the server's common
* name matches the URL.
*
* @param ssl [in] An SSL object reference.
* @param component [in] one of:
* - SSL_X509_CERT_COMMON_NAME
* - SSL_X509_CERT_ORGANIZATION
* - SSL_X509_CERT_ORGANIZATIONAL_NAME
* - SSL_X509_CA_CERT_COMMON_NAME
* - SSL_X509_CA_CERT_ORGANIZATION
* - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME
* @return The appropriate string (or null if not defined)
* @note Verification build mode must be enabled.
*/
EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component);
/**
* @brief Retrieve a Subject Alternative DNSName
*
* When a handshake is complete and a certificate has been exchanged, then the
* details of the remote certificate can be retrieved.
*
* This will usually be used by a client to check that the server's DNS
* name matches the URL.
*
* @param ssl [in] An SSL object reference.
* @param dnsindex [in] The index of the DNS name to retrieve.
* @return The appropriate string (or null if not defined)
* @note Verification build mode must be enabled.
*/
EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int dnsindex);
/**
* @brief Force the client to perform its handshake again.
*
* For a client this involves sending another "client hello" message.
* For the server is means sending a "hello request" message.
*
* This is a blocking call on the client (until the handshake completes).
*
* @param ssl [in] An SSL object reference.
* @return SSL_OK if renegotiation instantiation was ok
*/
EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl);
/**
* @brief Process a file that is in binary DER or ASCII PEM format.
*
* These are temporary objects that are used to load private keys,
* certificates etc into memory.
* @param ssl_ctx [in] The client/server context.
* @param obj_type [in] The format of the file. Can be one of:
* - SSL_OBJ_X509_CERT (no password required)
* - SSL_OBJ_X509_CACERT (no password required)
* - SSL_OBJ_RSA_KEY (AES128/AES256 PEM encryption supported)
* - SSL_OBJ_PKCS8 (RC4-128 encrypted data supported)
* - SSL_OBJ_PKCS12 (RC4-128 encrypted data supported)
*
* PEM files are automatically detected (if supported). The object type is
* also detected, and so is not relevant for these types of files.
* @param filename [in] The location of a file in DER/PEM format.
* @param password [in] The password used. Can be null if not required.
* @return SSL_OK if all ok
* @note Not available in skeleton build mode.
*/
EXP_FUNC int STDCALL ssl_obj_load(SSL_CTX *ssl_ctx, int obj_type, const char *filename, const char *password);
/**
* @brief Process binary data.
*
* These are temporary objects that are used to load private keys,
* certificates etc into memory.
* @param ssl_ctx [in] The client/server context.
* @param obj_type [in] The format of the memory data.
* @param data [in] The binary data to be loaded.
* @param len [in] The amount of data to be loaded.
* @param password [in] The password used. Can be null if not required.
* @return SSL_OK if all ok
* @see ssl_obj_load for more details on obj_type.
*/
EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int obj_type, const uint8_t *data, int len, const char *password);
#ifdef CONFIG_SSL_GENERATE_X509_CERT
/**
* @brief Create an X.509 certificate.
*
* This certificate is a self-signed v1 cert with a fixed start/stop validity
* times. It is signed with an internal private key in ssl_ctx.
*
* @param ssl_ctx [in] The client/server context.
* @param options [in] Not used yet.
* @param dn [in] An array of distinguished name strings. The array is defined
* by:
* - SSL_X509_CERT_COMMON_NAME (0)
* - If SSL_X509_CERT_COMMON_NAME is empty or not defined, then the
* hostname will be used.
* - SSL_X509_CERT_ORGANIZATION (1)
* - If SSL_X509_CERT_ORGANIZATION is empty or not defined, then $USERNAME
* will be used.
* - SSL_X509_CERT_ORGANIZATIONAL_NAME (2)
* - SSL_X509_CERT_ORGANIZATIONAL_NAME is optional.
* @param cert_data [out] The certificate as a sequence of bytes.
* @return < 0 if an error, or the size of the certificate in bytes.
* @note cert_data must be freed when there is no more need for it.
*/
EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data);
#endif
/**
* @brief Return the axTLS library version as a string.
*/
EXP_FUNC const char * STDCALL ssl_version(void);
/** @} */
#ifdef __cplusplus
}
#endif
#endif