mirror of
https://github.com/savoirfairelinux/opendht.git
synced 2026-11-08 12:28:42 +00:00
Compare commits
3
Commits
message_split
...
ocsp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9cc010e0f0 | ||
|
|
42a789b479 | ||
|
|
37c732b715 |
No files matched your search
+12
-14
@@ -36,9 +36,6 @@ option (OPENDHT_C "Build C bindings" OFF)
|
||||
find_package(Doxygen)
|
||||
option (OPENDHT_DOCUMENTATION "Create and install the HTML based API documentation (requires Doxygen)" ${DOXYGEN_FOUND})
|
||||
|
||||
# native windows build
|
||||
set (MSVC (CMAKE_CXX_COMPILER_ID MATCHES "MSVC"))
|
||||
|
||||
# Dependencies
|
||||
list (APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
|
||||
if (NOT MSVC)
|
||||
@@ -98,10 +95,6 @@ if (NOT MSVC)
|
||||
set(OPENDHT_PROXY_OPENSSL OFF)
|
||||
endif ()
|
||||
else ()
|
||||
add_definitions(-D_WINSOCK_DEPRECATED_NO_WARNINGS
|
||||
-D_CRT_SECURE_NO_WARNINGS
|
||||
-DWIN32_LEAN_AND_MEAN)
|
||||
|
||||
set (WIN32_DEP_DIR ${PROJECT_SOURCE_DIR}/../)
|
||||
include_directories(${WIN32_DEP_DIR}/../msvc/include) # SMP gnutls
|
||||
include_directories(${WIN32_DEP_DIR}/argon2/include)
|
||||
@@ -141,7 +134,12 @@ if (NOT MSVC)
|
||||
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fstack-protector-strong")
|
||||
endif ()
|
||||
else ()
|
||||
set(DISABLE_MSC_WARNINGS "/wd4101 /wd4244 /wd4267 /wd4273 /wd4804 /wd4834")
|
||||
add_definitions(-D_WINSOCK_DEPRECATED_NO_WARNINGS
|
||||
-D_CRT_SECURE_NO_WARNINGS
|
||||
-DWIN32_LEAN_AND_MEAN
|
||||
-DSTATIC_GETOPT
|
||||
-DGNUTLS_INTERNAL_BUILD)
|
||||
set(DISABLE_MSC_WARNINGS "/wd4101 /wd4244 /wd4267 /wd4273 /wd4804 /wd4834 /wd4996")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${DISABLE_MSC_WARNINGS}")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
|
||||
endif ()
|
||||
@@ -328,10 +326,13 @@ if(OPENDHT_ARGON2)
|
||||
include_directories(argon2/include/)
|
||||
endif()
|
||||
|
||||
# cross-platform compatibility sources
|
||||
set (COMPAT_DIR ${PROJECT_SOURCE_DIR}/src/compat/)
|
||||
list (APPEND opendht_SOURCES ${COMPAT_DIR}/os_cert.cpp)
|
||||
|
||||
if (MSVC)
|
||||
set (MSC_COMPAT_DIR ${PROJECT_SOURCE_DIR}/compat/msvc/)
|
||||
list (APPEND opendht_HEADERS ${MSC_COMPAT_DIR}/unistd.h)
|
||||
#include_directories(${PROJECT_SOURCE_DIR}/compat/msvc/)
|
||||
set (MSC_COMPAT_DIR ${COMPAT_DIR}/msvc/)
|
||||
list (APPEND opendht_SOURCES ${MSC_COMPAT_DIR}/unistd.h)
|
||||
endif ()
|
||||
|
||||
# Targets
|
||||
@@ -368,13 +369,11 @@ if (OPENDHT_STATIC)
|
||||
)
|
||||
if (OPENDHT_HTTP)
|
||||
add_obj_lib (win32_fmt ${WIN32_DEP_DIR}/fmt/msvc/Release/fmt.lib)
|
||||
#add_obj_lib (win32_asio ${WIN32_DEP_DIR}/asio/asio/msvc/x64/Release/asio.lib)
|
||||
add_obj_lib (win32_http_parser ${WIN32_DEP_DIR}/http_parser/x64/Release/http-parser.lib)
|
||||
add_obj_lib (win32_ssl ${WIN32_DEP_DIR}/openssl/libssl_static.lib)
|
||||
add_obj_lib (win32_crypto ${WIN32_DEP_DIR}/openssl/libcrypto_static.lib)
|
||||
list (APPEND obj_libs
|
||||
$<TARGET_OBJECTS:win32_fmt>
|
||||
#$<TARGET_OBJECTS:win32_asio>
|
||||
$<TARGET_OBJECTS:win32_http_parser>
|
||||
$<TARGET_OBJECTS:win32_ssl>
|
||||
$<TARGET_OBJECTS:win32_crypto>
|
||||
@@ -389,7 +388,6 @@ if (OPENDHT_STATIC)
|
||||
list (APPEND win32_Libs
|
||||
${PROJECT_SOURCE_DIR}/../fmt/msvc/Release/fmt.lib
|
||||
${PROJECT_SOURCE_DIR}/../http_parser/x64/Release/http-parser.lib
|
||||
${PROJECT_SOURCE_DIR}/../asio/asio/msvc/x64/Release/asio.lib
|
||||
${PROJECT_SOURCE_DIR}/../openssl/libssl.lib
|
||||
${PROJECT_SOURCE_DIR}/../openssl/libcrypto.lib
|
||||
)
|
||||
|
||||
@@ -290,6 +290,9 @@ public:
|
||||
|
||||
void send();
|
||||
|
||||
/** Send and block for response */
|
||||
const Response& await();
|
||||
|
||||
/**
|
||||
* User action to cancel the Request and call the completion callbacks.
|
||||
*/
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Savoir-faire Linux Inc.
|
||||
* Author: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program 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 General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "os_cert.h"
|
||||
|
||||
#include "log_enable.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#include <wincrypt.h>
|
||||
#pragma comment(lib, "crypt32.lib")
|
||||
#include <openssl/ssl.h>
|
||||
#undef X509_NAME
|
||||
#undef OCSP_REQUEST
|
||||
#undef OCSP_RESPONSE
|
||||
#endif /*WIN32*/
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <Security/Security.h>
|
||||
#endif /*__APPLE__*/
|
||||
|
||||
#ifdef _WIN32
|
||||
#define GENTIME_LENGTH 15
|
||||
#define UTCTIME_LENGTH 13
|
||||
#define ATOI2(ar) ((ar) += 2, ((ar)[-2] - '0') * 10 + ((ar)[-1] - '0'))
|
||||
// Taken from libressl/src/crypto/asn1/a_time_tm.c
|
||||
/*
|
||||
* Parse an RFC 5280 format ASN.1 time string.
|
||||
*
|
||||
* mode must be:
|
||||
* 0 if we expect to parse a time as specified in RFC 5280 for an X509 object.
|
||||
* V_ASN1_UTCTIME if we wish to parse an RFC5280 format UTC time.
|
||||
* V_ASN1_GENERALIZEDTIME if we wish to parse an RFC5280 format Generalized time.
|
||||
*
|
||||
* Returns:
|
||||
* -1 if the string was invalid.
|
||||
* V_ASN1_UTCTIME if the string validated as a UTC time string.
|
||||
* V_ASN1_GENERALIZEDTIME if the string validated as a Generalized time string.
|
||||
*
|
||||
* Fills in *tm with the corresponding time if tm is non NULL.
|
||||
*/
|
||||
int
|
||||
ASN1_time_parse(const char* bytes, size_t len, struct tm* tm, int mode)
|
||||
{
|
||||
size_t i;
|
||||
int type = 0;
|
||||
struct tm ltm;
|
||||
struct tm* lt;
|
||||
const char* p;
|
||||
|
||||
if (bytes == NULL)
|
||||
return (-1);
|
||||
|
||||
/* Constrain to valid lengths. */
|
||||
if (len != UTCTIME_LENGTH && len != GENTIME_LENGTH)
|
||||
return (-1);
|
||||
|
||||
lt = tm;
|
||||
if (lt == NULL) {
|
||||
memset(<m, 0, sizeof(ltm));
|
||||
lt = <m;
|
||||
}
|
||||
|
||||
/* Timezone is required and must be GMT (Zulu). */
|
||||
if (bytes[len - 1] != 'Z')
|
||||
return (-1);
|
||||
|
||||
/* Make sure everything else is digits. */
|
||||
for (i = 0; i < len - 1; i++) {
|
||||
if (isdigit((unsigned char) bytes[i]))
|
||||
continue;
|
||||
return (-1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Validate and convert the time
|
||||
*/
|
||||
p = bytes;
|
||||
switch (len) {
|
||||
case GENTIME_LENGTH:
|
||||
if (mode == V_ASN1_UTCTIME)
|
||||
return (-1);
|
||||
lt->tm_year = (ATOI2(p) * 100) - 1900; /* cc */
|
||||
type = V_ASN1_GENERALIZEDTIME;
|
||||
/* FALLTHROUGH */
|
||||
case UTCTIME_LENGTH:
|
||||
if (type == 0) {
|
||||
if (mode == V_ASN1_GENERALIZEDTIME)
|
||||
return (-1);
|
||||
type = V_ASN1_UTCTIME;
|
||||
}
|
||||
lt->tm_year += ATOI2(p); /* yy */
|
||||
if (type == V_ASN1_UTCTIME) {
|
||||
if (lt->tm_year < 50)
|
||||
lt->tm_year += 100;
|
||||
}
|
||||
lt->tm_mon = ATOI2(p) - 1; /* mm */
|
||||
if (lt->tm_mon < 0 || lt->tm_mon > 11)
|
||||
return (-1);
|
||||
lt->tm_mday = ATOI2(p); /* dd */
|
||||
if (lt->tm_mday < 1 || lt->tm_mday > 31)
|
||||
return (-1);
|
||||
lt->tm_hour = ATOI2(p); /* HH */
|
||||
if (lt->tm_hour < 0 || lt->tm_hour > 23)
|
||||
return (-1);
|
||||
lt->tm_min = ATOI2(p); /* MM */
|
||||
if (lt->tm_min < 0 || lt->tm_min > 59)
|
||||
return (-1);
|
||||
lt->tm_sec = ATOI2(p); /* SS */
|
||||
/* Leap second 60 is not accepted. Reconsider later? */
|
||||
if (lt->tm_sec < 0 || lt->tm_sec > 59)
|
||||
return (-1);
|
||||
break;
|
||||
default:
|
||||
return (-1);
|
||||
}
|
||||
|
||||
return (type);
|
||||
}
|
||||
#endif /*_WIN32*/
|
||||
|
||||
namespace dht {
|
||||
namespace http {
|
||||
|
||||
void
|
||||
addSystemCaCertificates(SSL_CTX* ctx, const std::shared_ptr<Logger>& logger)
|
||||
{
|
||||
X509_STORE* store = SSL_CTX_get_cert_store(ctx);
|
||||
if (store == nullptr) {
|
||||
if (logger)
|
||||
logger->e("couldn't get the context cert store");
|
||||
return;
|
||||
}
|
||||
|
||||
X509* x509cert;
|
||||
#ifdef _WIN32
|
||||
PCCERT_CONTEXT pContext = NULL;
|
||||
HCERTSTORE hSystemStore;
|
||||
hSystemStore = CertOpenSystemStore(NULL, "ROOT");
|
||||
if (!hSystemStore) {
|
||||
if (logger)
|
||||
logger->e("couldn't open the system cert store");
|
||||
return;
|
||||
}
|
||||
while (pContext = CertEnumCertificatesInStore(hSystemStore, pContext)) {
|
||||
x509cert = nullptr;
|
||||
const uint8_t* encoded_cert = pContext->pbCertEncoded;
|
||||
x509cert = d2i_X509(nullptr, &encoded_cert, pContext->cbCertEncoded);
|
||||
if (x509cert) {
|
||||
if (X509_STORE_add_cert(store, x509cert) == 1) {
|
||||
if (logger)
|
||||
logger->d("local certificate added");
|
||||
}
|
||||
X509_free(x509cert);
|
||||
}
|
||||
}
|
||||
CertCloseStore(hSystemStore, 0);
|
||||
#elif __APPLE__
|
||||
CFArrayRef result = NULL;
|
||||
OSStatus osStatus;
|
||||
|
||||
if ((osStatus = SecTrustCopyAnchorCertificates(&result)) != 0) {
|
||||
if (logger) {
|
||||
CFStringRef statusString = SecCopyErrorMessageString(osStatus, NULL);
|
||||
logger->d("Error enumerating certificates: %s",
|
||||
CFStringGetCStringPtr(statusString, kCFStringEncodingASCII));
|
||||
CFRelease(statusString);
|
||||
}
|
||||
if (result != NULL) {
|
||||
CFRelease(result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
CFDataRef rawData = NULL;
|
||||
for (CFIndex i = 0; i < CFArrayGetCount(result); i++) {
|
||||
x509cert = nullptr;
|
||||
SecCertificateRef cert = (SecCertificateRef) CFArrayGetValueAtIndex(result, i);
|
||||
rawData = SecCertificateCopyData(cert);
|
||||
if (!rawData) {
|
||||
if (logger)
|
||||
logger->e("couldn't copy raw certificate data");
|
||||
break;
|
||||
}
|
||||
const uint8_t* rawDataPtr = CFDataGetBytePtr(rawData);
|
||||
x509cert = d2i_X509(nullptr, &rawDataPtr, CFDataGetLength(rawData));
|
||||
if (x509cert) {
|
||||
if (X509_STORE_add_cert(store, x509cert) == 1) {
|
||||
if (logger)
|
||||
logger->d("local certificate added");
|
||||
}
|
||||
X509_free(x509cert);
|
||||
}
|
||||
CFRelease(rawData);
|
||||
rawData = NULL;
|
||||
}
|
||||
if (result != NULL) {
|
||||
CFRelease(result);
|
||||
}
|
||||
if (rawData != NULL) {
|
||||
CFRelease(rawData);
|
||||
}
|
||||
#endif /*__APPLE__, _WIN32*/
|
||||
}
|
||||
|
||||
} /*namespace http*/
|
||||
} /*namespace dht*/
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Savoir-faire Linux Inc.
|
||||
* Author: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program 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 General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "log_enable.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include <openssl/x509.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define V_ASN1_UTCTIME 23
|
||||
#define V_ASN1_GENERALIZEDTIME 24
|
||||
#define timegm _mkgmtime
|
||||
int ASN1_time_parse(const char* bytes, size_t len, struct tm* tm, int mode);
|
||||
#endif /*_WIN32*/
|
||||
|
||||
namespace dht {
|
||||
namespace http {
|
||||
void addSystemCaCertificates(SSL_CTX* ctx, const std::shared_ptr<Logger>& logger);
|
||||
}
|
||||
} // namespace dht
|
||||
+308
-9
@@ -20,12 +20,23 @@
|
||||
#include "log_enable.h"
|
||||
#include "crypto.h"
|
||||
#include "base64.h"
|
||||
#include "compat/os_cert.h"
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <restinio/impl/tls_socket.hpp>
|
||||
#include <http_parser.h>
|
||||
#include <json/json.h>
|
||||
|
||||
#include <openssl/ocsp.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/asn1.h>
|
||||
|
||||
#include <crypto/x509.h>
|
||||
|
||||
#define MAXAGE_SEC (14*24*60*60)
|
||||
#define JITTER_SEC (60)
|
||||
#define OCSP_MAX_RESPONSE_SIZE (20480)
|
||||
|
||||
namespace dht {
|
||||
namespace http {
|
||||
|
||||
@@ -97,6 +108,8 @@ Connection::Connection(asio::io_context& ctx, const bool ssl, std::shared_ptr<dh
|
||||
ssl_ctx_->set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
|
||||
#ifdef __ANDROID__
|
||||
ssl_ctx_->add_verify_path("/system/etc/security/cacerts");
|
||||
#elif defined(WIN32) || defined(__APPLE__)
|
||||
addSystemCaCertificates(ssl_ctx_->native_handle(), l);
|
||||
#else
|
||||
ssl_ctx_->set_default_verify_paths();
|
||||
#endif
|
||||
@@ -118,9 +131,11 @@ Connection::Connection(asio::io_context& ctx, std::shared_ptr<dht::crypto::Certi
|
||||
ssl_ctx_ = std::make_shared<asio::ssl::context>(asio::ssl::context::tls_client);
|
||||
ssl_ctx_->set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
|
||||
#ifdef __ANDROID__
|
||||
ssl_ctx_->add_verify_path("/system/etc/security/cacerts");
|
||||
ssl_ctx_->add_verify_path("/system/etc/security/cacerts");
|
||||
#elif WIN32
|
||||
addSystemCaCertificates(ssl_ctx_->native_handle(), l);
|
||||
#else
|
||||
ssl_ctx_->set_default_verify_paths();
|
||||
ssl_ctx_->set_default_verify_paths();
|
||||
#endif
|
||||
asio::error_code ec;
|
||||
if (server_ca){
|
||||
@@ -184,6 +199,253 @@ Connection::is_ssl() const
|
||||
return ssl_ctx_ ? true : false;
|
||||
}
|
||||
|
||||
static time_t
|
||||
parse_ocsp_time(ASN1_GENERALIZEDTIME* gt)
|
||||
{
|
||||
struct tm tm;
|
||||
time_t rv = -1;
|
||||
|
||||
if (gt == nullptr)
|
||||
return -1;
|
||||
// RFC 6960 specifies that all times in OCSP must be GENERALIZEDTIME
|
||||
if (ASN1_time_parse((const char*)gt->data, gt->length, &tm, V_ASN1_GENERALIZEDTIME) == -1)
|
||||
return -1;
|
||||
if ((rv = timegm(&tm)) == -1)
|
||||
return -1;
|
||||
return rv;
|
||||
}
|
||||
|
||||
static inline X509*
|
||||
cert_from_chain(STACK_OF(X509)* fullchain)
|
||||
{
|
||||
return sk_X509_value(fullchain, 0);
|
||||
}
|
||||
|
||||
static X509*
|
||||
issuer_from_chain(STACK_OF(X509)* fullchain)
|
||||
{
|
||||
X509 *cert, *issuer;
|
||||
X509_NAME *issuer_name;
|
||||
|
||||
cert = cert_from_chain(fullchain);
|
||||
if ((issuer_name = X509_get_issuer_name(cert)) == nullptr)
|
||||
return nullptr;
|
||||
|
||||
issuer = X509_find_by_subject(fullchain, issuer_name);
|
||||
return issuer;
|
||||
}
|
||||
|
||||
using OscpRequestPtr = std::unique_ptr<OCSP_REQUEST, decltype(&OCSP_REQUEST_free)>;
|
||||
struct OscpRequestInfo {
|
||||
OscpRequestPtr req {nullptr, &OCSP_REQUEST_free};
|
||||
std::vector<uint8_t> data;
|
||||
std::string url;
|
||||
};
|
||||
|
||||
static std::unique_ptr<OscpRequestInfo>
|
||||
ocspRequestFromCert(STACK_OF(X509)* fullchain, const std::shared_ptr<Logger>& logger, bool nonce = false)
|
||||
{
|
||||
if (fullchain == nullptr)
|
||||
return {};
|
||||
|
||||
if (sk_X509_num(fullchain) <= 1) {
|
||||
if (logger)
|
||||
logger->e("Cert does not contain a cert chain");
|
||||
return {};
|
||||
}
|
||||
X509* cert = cert_from_chain(fullchain);
|
||||
if (cert == nullptr) {
|
||||
if (logger)
|
||||
logger->e("No certificate found");
|
||||
return {};
|
||||
}
|
||||
X509* issuer = issuer_from_chain(fullchain);
|
||||
if (issuer == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to find issuer for cert");
|
||||
return {};
|
||||
}
|
||||
|
||||
auto urls = X509_get1_ocsp(cert);
|
||||
if (urls == nullptr || sk_OPENSSL_STRING_num(urls) <= 0) {
|
||||
if (logger)
|
||||
logger->e("Certificate contains no OCSP url");
|
||||
return {};
|
||||
}
|
||||
auto url = sk_OPENSSL_STRING_value(urls, 0);
|
||||
if (url == nullptr)
|
||||
return {};
|
||||
|
||||
auto request = std::make_unique<OscpRequestInfo>();
|
||||
request->req = OscpRequestPtr(OCSP_REQUEST_new(), &OCSP_REQUEST_free);
|
||||
request->url = strdup(url);
|
||||
X509_email_free(urls);
|
||||
|
||||
OCSP_CERTID* id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
|
||||
if (id == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to get certificate id from cert");
|
||||
return {};
|
||||
}
|
||||
if (OCSP_request_add0_id(request->req.get(), id) == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to add certificate id to request");
|
||||
return {};
|
||||
}
|
||||
|
||||
if (nonce)
|
||||
OCSP_request_add1_nonce(request->req.get(), nullptr, -1);
|
||||
|
||||
int size;
|
||||
uint8_t* data {nullptr};
|
||||
if ((size = i2d_OCSP_REQUEST(request->req.get(), &data)) <= 0) {
|
||||
if (logger)
|
||||
logger->e("Unable to encode ocsp request");
|
||||
return {};
|
||||
}
|
||||
if (data == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to allocte memory");
|
||||
return {};
|
||||
}
|
||||
request->data = std::vector<uint8_t>(data, data+size);
|
||||
free(data);
|
||||
return request;
|
||||
}
|
||||
|
||||
bool
|
||||
ocspValidateResponse(const OscpRequestInfo& info, STACK_OF(X509)* fullchain, const std::string& response, X509_STORE *store, const std::shared_ptr<Logger>& logger)
|
||||
{
|
||||
ASN1_GENERALIZEDTIME *revtime = nullptr, *thisupd = nullptr, *nextupd = nullptr;
|
||||
const uint8_t* p = (const uint8_t*)response.data();
|
||||
int status, cert_status=0, crl_reason=0;
|
||||
time_t now, rev_t = -1, this_t, next_t;
|
||||
OCSP_RESPONSE *resp;
|
||||
OCSP_BASICRESP *bresp;
|
||||
OCSP_CERTID *cid;
|
||||
|
||||
X509* cert = cert_from_chain(fullchain);
|
||||
if (cert == nullptr) {
|
||||
if (logger)
|
||||
logger->e("No certificate found");
|
||||
return false;
|
||||
}
|
||||
X509* issuer = issuer_from_chain(fullchain);
|
||||
if (issuer == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to find issuer for cert");
|
||||
return false;
|
||||
}
|
||||
if ((cid = OCSP_cert_to_id(nullptr, cert, issuer)) == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Unable to get issuer cert/CID");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((resp = d2i_OCSP_RESPONSE(nullptr, &p, response.size())) == nullptr) {
|
||||
if (logger)
|
||||
logger->e("OCSP response unserializable");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((bresp = OCSP_response_get1_basic(resp)) == nullptr) {
|
||||
if (logger)
|
||||
logger->e("Failed to load OCSP response");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (OCSP_basic_verify(bresp, fullchain, store, OCSP_TRUSTOTHER) != 1) {
|
||||
if (logger)
|
||||
logger->w("OCSP verify failed");
|
||||
return false;
|
||||
}
|
||||
printf("OCSP response signature validated\n");
|
||||
|
||||
status = OCSP_response_status(resp);
|
||||
if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
|
||||
if (logger)
|
||||
logger->w("OCSP Failure: code %d (%s)", status, OCSP_response_status_str(status));
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check the nonce if we sent one
|
||||
if (OCSP_check_nonce(info.req.get(), bresp) <= 0) {
|
||||
if (logger)
|
||||
logger->w("No OCSP nonce, or mismatch");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (OCSP_resp_find_status(bresp, cid, &cert_status, &crl_reason,
|
||||
&revtime, &thisupd, &nextupd) != 1) {
|
||||
if (logger)
|
||||
logger->w("OCSP verify failed: no result for cert");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (revtime && (rev_t = parse_ocsp_time(revtime)) == -1) {
|
||||
if (logger)
|
||||
logger->w("Unable to parse revocation time in OCSP reply");
|
||||
return false;
|
||||
}
|
||||
// Belt and suspenders, Treat it as revoked if there is either
|
||||
// a revocation time, or status revoked.
|
||||
if (rev_t != -1 || cert_status == V_OCSP_CERTSTATUS_REVOKED) {
|
||||
if (logger)
|
||||
logger->w("Invalid OCSP reply: certificate is revoked");
|
||||
if (rev_t != -1) {
|
||||
if (logger)
|
||||
logger->w("Certificate revoked at: %s", ctime(&rev_t));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if ((this_t = parse_ocsp_time(thisupd)) == -1) {
|
||||
if (logger)
|
||||
logger->w("unable to parse this update time in OCSP reply");
|
||||
return false;
|
||||
}
|
||||
if ((next_t = parse_ocsp_time(nextupd)) == -1) {
|
||||
if (logger)
|
||||
logger->w("unable to parse next update time in OCSP reply");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't allow this update to precede next update
|
||||
if (this_t >= next_t) {
|
||||
if (logger)
|
||||
logger->w("Invalid OCSP reply: this update >= next update");
|
||||
return false;
|
||||
}
|
||||
|
||||
now = time(nullptr);
|
||||
// Check that this update is not more than JITTER seconds in the future.
|
||||
if (this_t > now + JITTER_SEC) {
|
||||
if (logger)
|
||||
logger->e("Invalid OCSP reply: this update is in the future (%s)", ctime(&this_t));
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that this update is not more than MAXSEC in the past.
|
||||
if (this_t < now - MAXAGE_SEC) {
|
||||
if (logger)
|
||||
logger->e("Invalid OCSP reply: this update is too old (%s)", ctime(&this_t));
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that next update is still valid
|
||||
if (next_t < now - JITTER_SEC) {
|
||||
if (logger)
|
||||
logger->w("Invalid OCSP reply: reply has expired (%s)", ctime(&next_t));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (logger) {
|
||||
logger->d("OCSP response validated");
|
||||
logger->d(" This Update: %s", ctime(&this_t));
|
||||
logger->d(" Next Update: %s", ctime(&next_t));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
Connection::set_ssl_verification(const std::string& hostname, const asio::ssl::verify_mode verify_mode)
|
||||
{
|
||||
@@ -196,18 +458,42 @@ Connection::set_ssl_verification(const std::string& hostname, const asio::ssl::v
|
||||
ssl_socket_->asio_ssl_stream().set_verify_callback([
|
||||
id = id_, logger = logger_, hostname
|
||||
] (bool preverified, asio::ssl::verify_context& ctx) -> bool {
|
||||
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
|
||||
if (logger) {
|
||||
char subject_name[1024];
|
||||
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
|
||||
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 1024);
|
||||
logger->d("[connection:%i] verify %s compliance to RFC 2818:\n%s", id, hostname.c_str(), subject_name);
|
||||
}
|
||||
|
||||
// starts from CA and goes down the presented chain
|
||||
auto verifier = asio::ssl::rfc2818_verification(hostname);
|
||||
bool verified = verifier(preverified, ctx);
|
||||
auto verify_ec = X509_STORE_CTX_get_error(ctx.native_handle());
|
||||
if (verify_ec != 0 /*X509_V_OK*/ and logger)
|
||||
logger->e("[http::connection:%i] ssl verification error=%i %d", id, verify_ec, verified);
|
||||
if (verified) {
|
||||
auto chain = X509_STORE_CTX_get1_chain(ctx.native_handle());
|
||||
if (auto ocspInfo = ocspRequestFromCert(chain, logger)) {
|
||||
if (logger)
|
||||
logger->w("[http::connection:%i] TLS OCSP server: %s, request size: %zu", id, ocspInfo->url.c_str(), ocspInfo->data.size());
|
||||
bool ocspVerified = false;
|
||||
asio::io_context io_ctx;
|
||||
auto ocspReq = std::make_shared<Request>(io_ctx, ocspInfo->url, [&](const Response& ocspResp){
|
||||
if (ocspResp.status_code == 200) {
|
||||
ocspVerified = ocspValidateResponse(*ocspInfo, chain, ocspResp.body, ctx.native_handle()->ctx, logger);
|
||||
} else {
|
||||
if (logger)
|
||||
logger->w("[http::connection:%i] TLS OCSP check error", id);
|
||||
}
|
||||
}, logger);
|
||||
ocspReq->set_method(restinio::http_method_post());
|
||||
ocspReq->set_body({ocspInfo->data.begin(), ocspInfo->data.end()});
|
||||
ocspReq->send();
|
||||
io_ctx.run();
|
||||
if (not ocspVerified)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return verified;
|
||||
}
|
||||
);
|
||||
@@ -274,6 +560,8 @@ Connection::async_handshake(HandlerCb cb)
|
||||
this_.logger_->d("[connection:%i] self-signed certificate in handshake: %i", this_.id_, verify_ec);
|
||||
else if (verify_ec != X509_V_OK)
|
||||
this_.logger_->e("[connection:%i] verify handshake error: %i", this_.id_, verify_ec);
|
||||
else
|
||||
this_.logger_->w("[connection:%i] verify handshake success", this_.id_);
|
||||
}
|
||||
}
|
||||
if (cb)
|
||||
@@ -818,12 +1106,7 @@ Request::connect(std::vector<asio::ip::tcp::endpoint>&& endpoints, HandlerCb cb)
|
||||
conn_ = std::make_shared<Connection>(ctx_, server_ca_, client_identity_, logger_);
|
||||
else
|
||||
conn_ = std::make_shared<Connection>(ctx_, true/*ssl*/, logger_);
|
||||
#if !defined(LINUX) || defined(__ANDROID__)
|
||||
conn_->set_ssl_verification(get_url().host, asio::ssl::verify_none);
|
||||
#else
|
||||
conn_->set_ssl_verification(get_url().host, asio::ssl::verify_peer
|
||||
| asio::ssl::verify_fail_if_no_peer_cert);
|
||||
#endif
|
||||
conn_->set_ssl_verification(get_url().host, asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert);
|
||||
}
|
||||
else
|
||||
conn_ = std::make_shared<Connection>(ctx_, false/*ssl*/, logger_);
|
||||
@@ -1096,5 +1379,21 @@ Request::getRelativePath(const Url& origin, const std::string& path)
|
||||
return newPath.toString();
|
||||
}
|
||||
|
||||
const Response&
|
||||
Request::await()
|
||||
{
|
||||
std::mutex mtx;
|
||||
std::unique_lock<std::mutex> lock(mtx);
|
||||
std::condition_variable cv;
|
||||
bool ok {false};
|
||||
add_on_done_callback([&](const Response& resp){
|
||||
std::lock_guard<std::mutex> lk(mtx);
|
||||
ok = true;
|
||||
cv.notify_all();
|
||||
});
|
||||
cv.wait(lock, [&]{ return ok; });
|
||||
return response_;
|
||||
}
|
||||
|
||||
} // namespace http
|
||||
} // namespace dht
|
||||
+3
-3
@@ -54,7 +54,7 @@ main(int argc, char **argv)
|
||||
print_usage();
|
||||
return 0;
|
||||
}
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_init();
|
||||
#endif
|
||||
|
||||
@@ -76,7 +76,7 @@ main(int argc, char **argv)
|
||||
|
||||
const InfoHash myid = dht.getId();
|
||||
|
||||
#ifndef WIN32_NATIVE
|
||||
#ifndef _MSC_VER
|
||||
// using the GNU History API
|
||||
using_history();
|
||||
#endif
|
||||
@@ -144,7 +144,7 @@ main(int argc, char **argv)
|
||||
|
||||
std::cout << std::endl << "Stopping node..." << std::endl;
|
||||
dht.join();
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_deinit();
|
||||
#endif
|
||||
return 0;
|
||||
|
||||
@@ -77,7 +77,7 @@ step(DhtRunner& dht, std::atomic_uint& done, std::shared_ptr<NodeSet> all_nodes,
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_init();
|
||||
#endif
|
||||
auto params = parseArgs(argc, argv);
|
||||
@@ -123,7 +123,7 @@ main(int argc, char **argv)
|
||||
}
|
||||
|
||||
dht.join();
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_deinit();
|
||||
#endif
|
||||
return 0;
|
||||
|
||||
+2
-2
@@ -132,7 +132,7 @@ benchPingPong(unsigned netSize, unsigned n_parallel) {
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_init();
|
||||
#endif
|
||||
auto params = parseArgs(argc, argv);
|
||||
@@ -173,7 +173,7 @@ main(int argc, char **argv)
|
||||
std::cout << print_duration(totalTime/totalOps) << " per rt, "
|
||||
<< totalOps/std::chrono::duration<double>(totalTime).count() << " ping per s" << std::endl << std::endl;
|
||||
|
||||
#ifdef WIN32_NATIVE
|
||||
#ifdef _MSC_VER
|
||||
gnutls_global_deinit();
|
||||
#endif
|
||||
return 0;
|
||||
|
||||
Reference in new issue
Block a user