ZLMediaKit/webrtc/DtlsTransport.cpp

1466 lines
35 KiB
C++
Raw Normal View History

2021-04-06 17:23:13 +08:00
#define MS_CLASS "RTC::DtlsTransport"
2021-03-24 16:52:41 +08:00
// #define MS_LOG_DEV_LEVEL 3
2021-03-27 09:13:10 +08:00
#include "DtlsTransport.hpp"
2021-03-26 11:07:03 +08:00
#include "logger.h"
2021-03-24 16:52:41 +08:00
#include <openssl/asn1.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
2021-03-26 11:07:03 +08:00
#include <cstdio> // std::sprintf(), std::fopen()
#include <cstring> // std::memcpy(), std::strcmp()
#include "Util/util.h"
2021-03-26 11:07:03 +08:00
#define LOG_OPENSSL_ERROR(desc) \
do \
{ \
if (ERR_peek_error() == 0) \
MS_ERROR("OpenSSL error [desc:'%s']", desc); \
else \
{ \
int64_t err; \
while ((err = ERR_get_error()) != 0) \
{ \
MS_ERROR("OpenSSL error [desc:'%s', error:'%s']", desc, ERR_error_string(err, nullptr)); \
} \
ERR_clear_error(); \
} \
} while (false)
2021-03-24 16:52:41 +08:00
/* Static methods for OpenSSL callbacks. */
2021-03-26 11:07:03 +08:00
inline static int onSslCertificateVerify(int /*preverifyOk*/, X509_STORE_CTX* /*ctx*/)
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Always valid since DTLS certificates are self-signed.
return 1;
2021-03-24 16:52:41 +08:00
}
2021-03-26 11:07:03 +08:00
inline static unsigned int onSslDtlsTimer(SSL* /*ssl*/, unsigned int timerUs)
{
if (timerUs == 0)
return 100000;
else if (timerUs >= 4000000)
return 4000000;
else
return 2 * timerUs;
2021-03-24 16:52:41 +08:00
}
2021-03-26 11:07:03 +08:00
namespace RTC
{
/* Static. */
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// clang-format off
2021-03-24 16:52:41 +08:00
static constexpr int DtlsMtu{ 1350 };
// AES-HMAC: http://tools.ietf.org/html/rfc3711
static constexpr size_t SrtpMasterKeyLength{ 16 };
static constexpr size_t SrtpMasterSaltLength{ 14 };
static constexpr size_t SrtpMasterLength{ SrtpMasterKeyLength + SrtpMasterSaltLength };
// AES-GCM: http://tools.ietf.org/html/rfc7714
static constexpr size_t SrtpAesGcm256MasterKeyLength{ 32 };
static constexpr size_t SrtpAesGcm256MasterSaltLength{ 12 };
static constexpr size_t SrtpAesGcm256MasterLength{ SrtpAesGcm256MasterKeyLength + SrtpAesGcm256MasterSaltLength };
static constexpr size_t SrtpAesGcm128MasterKeyLength{ 16 };
static constexpr size_t SrtpAesGcm128MasterSaltLength{ 12 };
static constexpr size_t SrtpAesGcm128MasterLength{ SrtpAesGcm128MasterKeyLength + SrtpAesGcm128MasterSaltLength };
2021-03-26 11:07:03 +08:00
// clang-format on
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
/* Class variables. */
// clang-format off
2021-03-24 16:52:41 +08:00
std::map<std::string, DtlsTransport::FingerprintAlgorithm> DtlsTransport::string2FingerprintAlgorithm =
{
{ "sha-1", DtlsTransport::FingerprintAlgorithm::SHA1 },
{ "sha-224", DtlsTransport::FingerprintAlgorithm::SHA224 },
{ "sha-256", DtlsTransport::FingerprintAlgorithm::SHA256 },
{ "sha-384", DtlsTransport::FingerprintAlgorithm::SHA384 },
{ "sha-512", DtlsTransport::FingerprintAlgorithm::SHA512 }
};
std::map<DtlsTransport::FingerprintAlgorithm, std::string> DtlsTransport::fingerprintAlgorithm2String =
{
{ DtlsTransport::FingerprintAlgorithm::SHA1, "sha-1" },
{ DtlsTransport::FingerprintAlgorithm::SHA224, "sha-224" },
{ DtlsTransport::FingerprintAlgorithm::SHA256, "sha-256" },
{ DtlsTransport::FingerprintAlgorithm::SHA384, "sha-384" },
{ DtlsTransport::FingerprintAlgorithm::SHA512, "sha-512" }
};
std::map<std::string, DtlsTransport::Role> DtlsTransport::string2Role =
{
{ "auto", DtlsTransport::Role::AUTO },
{ "client", DtlsTransport::Role::CLIENT },
{ "server", DtlsTransport::Role::SERVER }
};
std::vector<DtlsTransport::SrtpCryptoSuiteMapEntry> DtlsTransport::srtpCryptoSuites =
{
2021-03-26 11:07:03 +08:00
{ RTC::SrtpSession::CryptoSuite::AEAD_AES_256_GCM, "SRTP_AEAD_AES_256_GCM" },
{ RTC::SrtpSession::CryptoSuite::AEAD_AES_128_GCM, "SRTP_AEAD_AES_128_GCM" },
{ RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" },
{ RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" }
2021-03-24 16:52:41 +08:00
};
2021-03-26 11:07:03 +08:00
// clang-format on
2021-03-24 16:52:41 +08:00
INSTANCE_IMP(DtlsTransport::DtlsEnvironment);
2021-03-26 11:07:03 +08:00
/* Class methods. */
2021-03-24 16:52:41 +08:00
DtlsTransport::DtlsEnvironment::DtlsEnvironment()
2021-03-26 11:07:03 +08:00
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Generate a X509 certificate and private key (unless PEM files are provided).
if (true /*
Settings::configuration.dtlsCertificateFile.empty() ||
Settings::configuration.dtlsPrivateKeyFile.empty()*/)
{
GenerateCertificateAndPrivateKey();
}
else
{
ReadCertificateAndPrivateKeyFromFiles();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Create a global SSL_CTX.
CreateSslCtx();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Generate certificate fingerprints.
GenerateFingerprints();
}
2021-03-24 16:52:41 +08:00
DtlsTransport::DtlsEnvironment::~DtlsEnvironment()
2021-03-26 11:07:03 +08:00
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
if (privateKey)
EVP_PKEY_free(privateKey);
if (certificate)
X509_free(certificate);
if (sslCtx)
SSL_CTX_free(sslCtx);
2021-03-26 11:07:03 +08:00
}
2021-03-24 16:52:41 +08:00
void DtlsTransport::DtlsEnvironment::GenerateCertificateAndPrivateKey()
2021-03-26 11:07:03 +08:00
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
int ret{ 0 };
EC_KEY* ecKey{ nullptr };
X509_NAME* certName{ nullptr };
std::string subject =
std::string("mediasoup") + std::to_string(rand() % 999999 + 100000);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Create key with curve.
ecKey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!ecKey)
{
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
EC_KEY_set_asn1_flag(ecKey, OPENSSL_EC_NAMED_CURVE);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOTE: This can take some time.
ret = EC_KEY_generate_key(ecKey);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("EC_KEY_generate_key() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Create a private key object.
privateKey = EVP_PKEY_new();
2021-03-24 16:52:41 +08:00
if (!privateKey)
2021-03-26 11:07:03 +08:00
{
LOG_OPENSSL_ERROR("EVP_PKEY_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
ret = EVP_PKEY_assign_EC_KEY(privateKey, ecKey);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("EVP_PKEY_assign_EC_KEY() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// The EC key now belongs to the private key, so don't clean it up separately.
ecKey = nullptr;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Create the X509 certificate.
certificate = X509_new();
2021-03-24 16:52:41 +08:00
if (!certificate)
2021-03-26 11:07:03 +08:00
{
LOG_OPENSSL_ERROR("X509_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set version 3 (note that 0 means version 1).
X509_set_version(certificate, 2);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set serial number (avoid default 0).
ASN1_INTEGER_set(
X509_get_serialNumber(certificate),
2021-03-26 11:07:03 +08:00
static_cast<uint64_t>(rand() % 999999 + 100000));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set valid period.
X509_gmtime_adj(X509_get_notBefore(certificate), -315360000); // -10 years.
X509_gmtime_adj(X509_get_notAfter(certificate), 315360000); // 10 years.
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set the public key for the certificate using the key.
ret = X509_set_pubkey(certificate, privateKey);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_pubkey() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set certificate fields.
certName = X509_get_subject_name(certificate);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!certName)
{
LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509_NAME_add_entry_by_txt(
certName, "O", MBSTRING_ASC, reinterpret_cast<const uint8_t*>(subject.c_str()), -1, -1, 0);
X509_NAME_add_entry_by_txt(
certName, "CN", MBSTRING_ASC, reinterpret_cast<const uint8_t*>(subject.c_str()), -1, -1, 0);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// It is self-signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(certificate, certName);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Sign the certificate with its own private key.
ret = X509_sign(certificate, privateKey, EVP_sha1());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_sign() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
error:
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ecKey)
EC_KEY_free(ecKey);
2021-03-24 16:52:41 +08:00
if (privateKey)
EVP_PKEY_free(privateKey); // NOTE: This also frees the EC key.
2021-03-24 16:52:41 +08:00
if (certificate)
X509_free(certificate);
2021-03-26 11:07:03 +08:00
MS_THROW_ERROR("DTLS certificate and private key generation failed");
}
2021-03-24 16:52:41 +08:00
void DtlsTransport::DtlsEnvironment::ReadCertificateAndPrivateKeyFromFiles()
2021-03-26 11:07:03 +08:00
{
2021-03-24 16:52:41 +08:00
#if 0
2021-03-26 11:07:03 +08:00
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
FILE* file{ nullptr };
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
file = fopen(Settings::configuration.dtlsCertificateFile.c_str(), "r");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!file)
{
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
2021-03-24 16:52:41 +08:00
if (!certificate)
2021-03-26 11:07:03 +08:00
{
LOG_OPENSSL_ERROR("PEM_read_X509() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
fclose(file);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
file = fopen(Settings::configuration.dtlsPrivateKeyFile.c_str(), "r");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!file)
{
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
2021-03-24 16:52:41 +08:00
if (!privateKey)
2021-03-26 11:07:03 +08:00
{
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
fclose(file);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
error:
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
2021-03-24 16:52:41 +08:00
#endif
2021-03-26 11:07:03 +08:00
}
2021-03-24 16:52:41 +08:00
void DtlsTransport::DtlsEnvironment::CreateSslCtx()
2021-03-26 11:07:03 +08:00
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
std::string dtlsSrtpCryptoSuites;
int ret;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
/* Set the global DTLS context. */
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
sslCtx = SSL_CTX_new(DTLS_method());
2021-03-24 16:52:41 +08:00
if (!sslCtx)
2021-03-26 11:07:03 +08:00
{
LOG_OPENSSL_ERROR("SSL_CTX_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
ret = SSL_CTX_use_certificate(sslCtx, certificate);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
ret = SSL_CTX_use_PrivateKey(sslCtx, privateKey);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
ret = SSL_CTX_check_private_key(sslCtx);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set options.
SSL_CTX_set_options(
sslCtx,
2021-03-26 11:07:03 +08:00
SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE |
SSL_OP_NO_QUERY_MTU);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Don't use sessions cache.
SSL_CTX_set_session_cache_mode(sslCtx, SSL_SESS_CACHE_OFF);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Read always as much into the buffer as possible.
// NOTE: This is the default for DTLS, but a bug in non latest OpenSSL
// versions makes this call required.
SSL_CTX_set_read_ahead(sslCtx, 1);
2021-03-24 16:52:41 +08:00
SSL_CTX_set_verify_depth(sslCtx, 4);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Require certificate from peer.
SSL_CTX_set_verify(
sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, onSslCertificateVerify);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set SSL info callback.
SSL_CTX_set_info_callback(sslCtx, [](const SSL* ssl, int where, int ret){
2021-03-26 11:07:03 +08:00
static_cast<RTC::DtlsTransport*>(SSL_get_ex_data(ssl, 0))->OnSslInfo(where, ret);
});
// Set ciphers.
ret = SSL_CTX_set_cipher_list(
sslCtx, "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Enable ECDH ciphers.
// DOC: http://en.wikibooks.org/wiki/OpenSSL/Diffie-Hellman_parameters
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// NOTE: https://bugs.ruby-lang.org/issues/12324
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// For OpenSSL >= 1.0.2.
SSL_CTX_set_ecdh_auto(sslCtx, 1);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set the "use_srtp" DTLS extension.
for (auto it = DtlsTransport::srtpCryptoSuites.begin();
it != DtlsTransport::srtpCryptoSuites.end();
++it)
{
if (it != DtlsTransport::srtpCryptoSuites.begin())
dtlsSrtpCryptoSuites += ":";
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
SrtpCryptoSuiteMapEntry* cryptoSuiteEntry = std::addressof(*it);
dtlsSrtpCryptoSuites += cryptoSuiteEntry->name;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_DEBUG_2TAGS(dtls, srtp, "setting SRTP cryptoSuites for DTLS: %s", dtlsSrtpCryptoSuites.c_str());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(sslCtx, dtlsSrtpCryptoSuites.c_str());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret != 0)
{
MS_ERROR(
"SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", dtlsSrtpCryptoSuites.c_str());
LOG_OPENSSL_ERROR("SSL_CTX_set_tlsext_use_srtp() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
error:
2021-03-24 16:52:41 +08:00
if (sslCtx)
2021-03-26 11:07:03 +08:00
{
SSL_CTX_free(sslCtx);
sslCtx = nullptr;
2021-03-26 11:07:03 +08:00
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_THROW_ERROR("SSL context creation failed");
}
2021-03-24 16:52:41 +08:00
void DtlsTransport::DtlsEnvironment::GenerateFingerprints()
2021-03-26 11:07:03 +08:00
{
MS_TRACE();
for (auto& kv : DtlsTransport::string2FingerprintAlgorithm)
{
const std::string& algorithmString = kv.first;
FingerprintAlgorithm algorithm = kv.second;
uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size{ 0 };
char hexFingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hashFunction;
int ret;
switch (algorithm)
{
case FingerprintAlgorithm::SHA1:
hashFunction = EVP_sha1();
break;
case FingerprintAlgorithm::SHA224:
hashFunction = EVP_sha224();
break;
case FingerprintAlgorithm::SHA256:
hashFunction = EVP_sha256();
break;
case FingerprintAlgorithm::SHA384:
hashFunction = EVP_sha384();
break;
case FingerprintAlgorithm::SHA512:
hashFunction = EVP_sha512();
break;
default:
MS_THROW_ERROR("unknown algorithm");
}
ret = X509_digest(certificate, hashFunction, binaryFingerprint, &size);
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
MS_ERROR("X509_digest() failed");
MS_THROW_ERROR("Fingerprints generation failed");
}
// Convert to hexadecimal format in uppercase with colons.
for (unsigned int i{ 0 }; i < size; ++i)
{
std::sprintf(hexFingerprint + (i * 3), "%.2X:", binaryFingerprint[i]);
}
hexFingerprint[(size * 3) - 1] = '\0';
MS_DEBUG_TAG(dtls, "%-7s fingerprint: %s", algorithmString.c_str(), hexFingerprint);
// Store it in the vector.
DtlsTransport::Fingerprint fingerprint;
fingerprint.algorithm = DtlsTransport::GetFingerprintAlgorithm(algorithmString);
fingerprint.value = hexFingerprint;
localFingerprints.push_back(fingerprint);
2021-03-26 11:07:03 +08:00
}
}
/* Instance methods. */
DtlsTransport::DtlsTransport(EventPoller::Ptr poller,Listener* listener) : poller(std::move(poller)), listener(listener)
{
MS_TRACE();
env = DtlsEnvironment::Instance().shared_from_this();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
/* Set SSL. */
2021-03-24 16:52:41 +08:00
this->ssl = SSL_new(env->sslCtx);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!this->ssl)
{
LOG_OPENSSL_ERROR("SSL_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set this as custom data.
SSL_set_ex_data(this->ssl, 0, static_cast<void*>(this));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->sslBioFromNetwork = BIO_new(BIO_s_mem());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!this->sslBioFromNetwork)
{
LOG_OPENSSL_ERROR("BIO_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
SSL_free(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->sslBioToNetwork = BIO_new(BIO_s_mem());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!this->sslBioToNetwork)
{
LOG_OPENSSL_ERROR("BIO_new() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
BIO_free(this->sslBioFromNetwork);
SSL_free(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
goto error;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
SSL_set_bio(this->ssl, this->sslBioFromNetwork, this->sslBioToNetwork);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set the MTU so that we don't send packets that are too large with no fragmentation.
SSL_set_mtu(this->ssl, DtlsMtu);
DTLS_set_link_mtu(this->ssl, DtlsMtu);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set callback handler for setting DTLS timer interval.
DTLS_set_timer_cb(this->ssl, onSslDtlsTimer);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
error:
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOTE: At this point SSL_set_bio() was not called so we must free BIOs as
// well.
if (this->sslBioFromNetwork)
BIO_free(this->sslBioFromNetwork);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (this->sslBioToNetwork)
BIO_free(this->sslBioToNetwork);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (this->ssl)
SSL_free(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOTE: If this is not catched by the caller the program will abort, but
// this should never happen.
MS_THROW_ERROR("DtlsTransport instance creation failed");
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
DtlsTransport::~DtlsTransport()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (IsRunning())
{
// Send close alert to the peer.
SSL_shutdown(this->ssl);
SendPendingOutgoingDtlsData();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (this->ssl)
{
SSL_free(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->ssl = nullptr;
this->sslBioFromNetwork = nullptr;
this->sslBioToNetwork = nullptr;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Close the DTLS timer.
this->timer = nullptr;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
void DtlsTransport::Dump() const
{
MS_TRACE();
std::string state{ "new" };
std::string role{ "none " };
switch (this->state)
{
case DtlsState::CONNECTING:
state = "connecting";
break;
case DtlsState::CONNECTED:
state = "connected";
break;
case DtlsState::FAILED:
state = "failed";
break;
case DtlsState::CLOSED:
state = "closed";
break;
default:;
}
switch (this->localRole)
{
case Role::AUTO:
role = "auto";
break;
case Role::SERVER:
role = "server";
break;
case Role::CLIENT:
role = "client";
break;
default:;
}
MS_DUMP("<DtlsTransport>");
MS_DUMP(" state : %s", state.c_str());
MS_DUMP(" role : %s", role.c_str());
MS_DUMP(" handshake done: : %s", this->handshakeDone ? "yes" : "no");
MS_DUMP("</DtlsTransport>");
}
void DtlsTransport::Run(Role localRole)
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_ASSERT(
localRole == Role::CLIENT || localRole == Role::SERVER,
"local DTLS role must be 'client' or 'server'");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
Role previousLocalRole = this->localRole;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (localRole == previousLocalRole)
{
MS_ERROR("same local DTLS role provided, doing nothing");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// If the previous local DTLS role was 'client' or 'server' do reset.
if (previousLocalRole == Role::CLIENT || previousLocalRole == Role::SERVER)
{
MS_DEBUG_TAG(dtls, "resetting DTLS due to local role change");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
Reset();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Update local role.
this->localRole = localRole;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set state and notify the listener.
this->state = DtlsState::CONNECTING;
this->listener->OnDtlsTransportConnecting(this);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
switch (this->localRole)
{
case Role::CLIENT:
{
MS_DEBUG_TAG(dtls, "running [role:client]");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
SSL_set_connect_state(this->ssl);
SSL_do_handshake(this->ssl);
SendPendingOutgoingDtlsData();
SetTimeout();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
break;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
case Role::SERVER:
{
MS_DEBUG_TAG(dtls, "running [role:server]");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
SSL_set_accept_state(this->ssl);
SSL_do_handshake(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
break;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
default:
{
MS_ABORT("invalid local DTLS role");
}
}
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
bool DtlsTransport::SetRemoteFingerprint(Fingerprint fingerprint)
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_ASSERT(
fingerprint.algorithm != FingerprintAlgorithm::NONE, "no fingerprint algorithm provided");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->remoteFingerprint = fingerprint;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// The remote fingerpring may have been set after DTLS handshake was done,
// so we may need to process it now.
if (this->handshakeDone && this->state != DtlsState::CONNECTED)
{
MS_DEBUG_TAG(dtls, "handshake already done, processing it right now");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return ProcessHandshake();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return true;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
void DtlsTransport::ProcessDtlsData(const uint8_t* data, size_t len)
{
MS_TRACE();
int written;
int read;
if (!IsRunning())
{
MS_ERROR("cannot process data while not running");
return;
}
// Write the received DTLS data into the sslBioFromNetwork.
written =
BIO_write(this->sslBioFromNetwork, static_cast<const void*>(data), static_cast<int>(len));
if (written != static_cast<int>(len))
{
MS_WARN_TAG(
dtls,
"OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)",
static_cast<size_t>(written),
len);
}
// Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, static_cast<void*>(DtlsTransport::sslReadBuffer), SslReadBufferSize);
// Send data if it's ready.
SendPendingOutgoingDtlsData();
// Check SSL status and return if it is bad/closed.
if (!CheckStatus(read))
return;
// Set/update the DTLS timeout.
if (!SetTimeout())
return;
// Application data received. Notify to the listener.
if (read > 0)
{
// It is allowed to receive DTLS data even before validating remote fingerprint.
if (!this->handshakeDone)
{
MS_WARN_TAG(dtls, "ignoring application data received while DTLS handshake not done");
return;
}
// Notify the listener.
this->listener->OnDtlsTransportApplicationDataReceived(
this, (uint8_t*)DtlsTransport::sslReadBuffer, static_cast<size_t>(read));
}
}
void DtlsTransport::SendApplicationData(const uint8_t* data, size_t len)
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// We cannot send data to the peer if its remote fingerprint is not validated.
if (this->state != DtlsState::CONNECTED)
{
MS_WARN_TAG(dtls, "cannot send application data while DTLS is not fully connected");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (len == 0)
{
MS_WARN_TAG(dtls, "ignoring 0 length data");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
int written;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
written = SSL_write(this->ssl, static_cast<const void*>(data), static_cast<int>(len));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (written < 0)
{
LOG_OPENSSL_ERROR("SSL_write() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!CheckStatus(written))
return;
}
else if (written != static_cast<int>(len))
{
MS_WARN_TAG(
dtls, "OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len);
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Send data.
SendPendingOutgoingDtlsData();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
void DtlsTransport::Reset()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
int ret;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!IsRunning())
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_WARN_TAG(dtls, "resetting DTLS transport");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Stop the DTLS timer.
this->timer = nullptr;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// We need to reset the SSL instance so we need to "shutdown" it, but we
// don't want to send a Close Alert to the peer, so just don't call
// SendPendingOutgoingDTLSData().
SSL_shutdown(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->localRole = Role::NONE;
this->state = DtlsState::NEW;
this->handshakeDone = false;
this->handshakeDoneNow = false;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Reset SSL status.
// NOTE: For this to properly work, SSL_shutdown() must be called before.
// NOTE: This may fail if not enough DTLS handshake data has been received,
// but we don't care so just clear the error queue.
ret = SSL_clear(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
ERR_clear_error();
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
inline bool DtlsTransport::CheckStatus(int returnCode)
{
MS_TRACE();
int err;
bool wasHandshakeDone = this->handshakeDone;
err = SSL_get_error(this->ssl, returnCode);
switch (err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_SSL:
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SSL");
break;
case SSL_ERROR_WANT_READ:
break;
case SSL_ERROR_WANT_WRITE:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_WRITE");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
MS_DEBUG_TAG(dtls, "SSL status: SSL_ERROR_WANT_X509_LOOKUP");
break;
case SSL_ERROR_SYSCALL:
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SYSCALL");
break;
case SSL_ERROR_ZERO_RETURN:
break;
case SSL_ERROR_WANT_CONNECT:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_CONNECT");
break;
case SSL_ERROR_WANT_ACCEPT:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_ACCEPT");
break;
default:
MS_WARN_TAG(dtls, "SSL status: unknown error");
}
// Check if the handshake (or re-handshake) has been done right now.
if (this->handshakeDoneNow)
{
this->handshakeDoneNow = false;
this->handshakeDone = true;
// Stop the timer.
this->timer = nullptr;
// Process the handshake just once (ignore if DTLS renegotiation).
if (!wasHandshakeDone && this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE)
return ProcessHandshake();
return true;
}
// Check if the peer sent close alert or a fatal error happened.
else if (((SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) != 0) || err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL)
{
if (this->state == DtlsState::CONNECTED)
{
MS_DEBUG_TAG(dtls, "disconnected");
Reset();
// Set state and notify the listener.
this->state = DtlsState::CLOSED;
this->listener->OnDtlsTransportClosed(this);
}
else
{
MS_WARN_TAG(dtls, "connection failed");
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
}
return false;
}
else
{
return true;
}
}
inline void DtlsTransport::SendPendingOutgoingDtlsData()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (BIO_eof(this->sslBioToNetwork))
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
int64_t read;
char* data{ nullptr };
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
read = BIO_get_mem_data(this->sslBioToNetwork, &data); // NOLINT
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (read <= 0)
return;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_DEBUG_DEV("%" PRIu64 " bytes of DTLS data ready to sent to the peer", read);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Notify the listener.
this->listener->OnDtlsTransportSendData(
this, reinterpret_cast<uint8_t*>(data), static_cast<size_t>(read));
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Clear the BIO buffer.
// NOTE: the (void) avoids the -Wunused-value warning.
(void)BIO_reset(this->sslBioToNetwork);
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
inline bool DtlsTransport::SetTimeout()
{
MS_TRACE();
MS_ASSERT(
this->state == DtlsState::CONNECTING || this->state == DtlsState::CONNECTED,
"invalid DTLS state");
int64_t ret;
struct timeval dtlsTimeout{ 0, 0 };
uint64_t timeoutMs;
// NOTE: If ret == 0 then ignore the value in dtlsTimeout.
// NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev.
ret = DTLSv1_get_timeout(this->ssl, static_cast<void*>(&dtlsTimeout)); // NOLINT
if (ret == 0)
return true;
timeoutMs = (dtlsTimeout.tv_sec * static_cast<uint64_t>(1000)) + (dtlsTimeout.tv_usec / 1000);
if (timeoutMs == 0)
{
return true;
}
else if (timeoutMs < 30000)
{
MS_DEBUG_DEV("DTLS timer set in %" PRIu64 "ms", timeoutMs);
weak_ptr<DtlsTransport> weak_self = shared_from_this();
this->timer = std::make_shared<Timer>(timeoutMs / 1000.0f, [weak_self](){
auto strong_self = weak_self.lock();
if(strong_self){
strong_self->OnTimer();
}
return true;
}, this->poller);
return true;
}
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else
{
MS_WARN_TAG(dtls, "DTLS timeout too high (%" PRIu64 "ms), resetting DLTS", timeoutMs);
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
return false;
}
}
inline bool DtlsTransport::ProcessHandshake()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_ASSERT(this->handshakeDone, "handshake not done yet");
MS_ASSERT(
this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Validate the remote fingerprint.
if (!CheckRemoteFingerprint())
{
Reset();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Get the negotiated SRTP crypto suite.
RTC::SrtpSession::CryptoSuite srtpCryptoSuite = GetNegotiatedSrtpCryptoSuite();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (srtpCryptoSuite != RTC::SrtpSession::CryptoSuite::NONE)
{
// Extract the SRTP keys (will notify the listener with them).
ExtractSrtpKeys(srtpCryptoSuite);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return true;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// NOTE: We assume that "use_srtp" DTLS extension is required even if
// there is no audio/video.
MS_WARN_2TAGS(dtls, srtp, "SRTP crypto suite not negotiated");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
Reset();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
inline bool DtlsTransport::CheckRemoteFingerprint()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_ASSERT(
this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509* certificate;
uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size{ 0 };
char hexFingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hashFunction;
int ret;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
certificate = SSL_get_peer_certificate(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!certificate)
{
MS_WARN_TAG(dtls, "no certificate was provided by the peer");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
switch (this->remoteFingerprint.algorithm)
{
case FingerprintAlgorithm::SHA1:
hashFunction = EVP_sha1();
break;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
case FingerprintAlgorithm::SHA224:
hashFunction = EVP_sha224();
break;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
case FingerprintAlgorithm::SHA256:
hashFunction = EVP_sha256();
break;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
case FingerprintAlgorithm::SHA384:
hashFunction = EVP_sha384();
break;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
case FingerprintAlgorithm::SHA512:
hashFunction = EVP_sha512();
break;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
default:
MS_ABORT("unknown algorithm");
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Compare the remote fingerprint with the value given via signaling.
ret = X509_digest(certificate, hashFunction, binaryFingerprint, &size);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret == 0)
{
MS_ERROR("X509_digest() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509_free(certificate);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Convert to hexadecimal format in uppercase with colons.
for (unsigned int i{ 0 }; i < size; ++i)
{
std::sprintf(hexFingerprint + (i * 3), "%.2X:", binaryFingerprint[i]);
}
hexFingerprint[(size * 3) - 1] = '\0';
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (this->remoteFingerprint.value != hexFingerprint)
{
MS_WARN_TAG(
dtls,
"fingerprint in the remote certificate (%s) does not match the announced one (%s)",
hexFingerprint,
this->remoteFingerprint.value.c_str());
X509_free(certificate);
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_DEBUG_TAG(dtls, "valid remote fingerprint");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Get the remote certificate in PEM format.
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
BIO* bio = BIO_new(BIO_s_mem());
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Ensure the underlying BUF_MEM structure is also freed.
// NOTE: Avoid stupid "warning: value computed is not used [-Wunused-value]" since
// BIO_set_close() always returns 1.
(void)BIO_set_close(bio, BIO_CLOSE);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
ret = PEM_write_bio_X509(bio, certificate);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (ret != 1)
{
LOG_OPENSSL_ERROR("PEM_write_bio_X509() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509_free(certificate);
BIO_free(bio);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
BUF_MEM* mem;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
BIO_get_mem_ptr(bio, &mem); // NOLINT[cppcoreguidelines-pro-type-cstyle-cast]
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!mem || !mem->data || mem->length == 0u)
{
LOG_OPENSSL_ERROR("BIO_get_mem_ptr() failed");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509_free(certificate);
BIO_free(bio);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return false;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
this->remoteCert = std::string(mem->data, mem->length);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
X509_free(certificate);
BIO_free(bio);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return true;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
inline void DtlsTransport::ExtractSrtpKeys(RTC::SrtpSession::CryptoSuite srtpCryptoSuite)
{
MS_TRACE();
size_t srtpKeyLength{ 0 };
size_t srtpSaltLength{ 0 };
size_t srtpMasterLength{ 0 };
switch (srtpCryptoSuite)
{
case RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_80:
case RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_32:
{
srtpKeyLength = SrtpMasterKeyLength;
srtpSaltLength = SrtpMasterSaltLength;
srtpMasterLength = SrtpMasterLength;
break;
}
case RTC::SrtpSession::CryptoSuite::AEAD_AES_256_GCM:
{
srtpKeyLength = SrtpAesGcm256MasterKeyLength;
srtpSaltLength = SrtpAesGcm256MasterSaltLength;
srtpMasterLength = SrtpAesGcm256MasterLength;
break;
}
case RTC::SrtpSession::CryptoSuite::AEAD_AES_128_GCM:
{
srtpKeyLength = SrtpAesGcm128MasterKeyLength;
srtpSaltLength = SrtpAesGcm128MasterSaltLength;
srtpMasterLength = SrtpAesGcm128MasterLength;
break;
}
default:
{
MS_ABORT("unknown SRTP crypto suite");
}
}
auto* srtpMaterial = new uint8_t[srtpMasterLength * 2];
uint8_t* srtpLocalKey{ nullptr };
uint8_t* srtpLocalSalt{ nullptr };
uint8_t* srtpRemoteKey{ nullptr };
uint8_t* srtpRemoteSalt{ nullptr };
auto* srtpLocalMasterKey = new uint8_t[srtpMasterLength];
auto* srtpRemoteMasterKey = new uint8_t[srtpMasterLength];
int ret;
ret = SSL_export_keying_material(
this->ssl, srtpMaterial, srtpMasterLength * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0);
MS_ASSERT(ret != 0, "SSL_export_keying_material() failed");
switch (this->localRole)
{
case Role::SERVER:
{
srtpRemoteKey = srtpMaterial;
srtpLocalKey = srtpRemoteKey + srtpKeyLength;
srtpRemoteSalt = srtpLocalKey + srtpKeyLength;
srtpLocalSalt = srtpRemoteSalt + srtpSaltLength;
break;
}
case Role::CLIENT:
{
srtpLocalKey = srtpMaterial;
srtpRemoteKey = srtpLocalKey + srtpKeyLength;
srtpLocalSalt = srtpRemoteKey + srtpKeyLength;
srtpRemoteSalt = srtpLocalSalt + srtpSaltLength;
break;
}
default:
{
MS_ABORT("no DTLS role set");
}
}
// Create the SRTP local master key.
std::memcpy(srtpLocalMasterKey, srtpLocalKey, srtpKeyLength);
std::memcpy(srtpLocalMasterKey + srtpKeyLength, srtpLocalSalt, srtpSaltLength);
// Create the SRTP remote master key.
std::memcpy(srtpRemoteMasterKey, srtpRemoteKey, srtpKeyLength);
std::memcpy(srtpRemoteMasterKey + srtpKeyLength, srtpRemoteSalt, srtpSaltLength);
// Set state and notify the listener.
this->state = DtlsState::CONNECTED;
this->listener->OnDtlsTransportConnected(
this,
srtpCryptoSuite,
srtpLocalMasterKey,
srtpMasterLength,
srtpRemoteMasterKey,
srtpMasterLength,
this->remoteCert);
delete[] srtpMaterial;
delete[] srtpLocalMasterKey;
delete[] srtpRemoteMasterKey;
}
inline RTC::SrtpSession::CryptoSuite DtlsTransport::GetNegotiatedSrtpCryptoSuite()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
RTC::SrtpSession::CryptoSuite negotiatedSrtpCryptoSuite = RTC::SrtpSession::CryptoSuite::NONE;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Ensure that the SRTP crypto suite has been negotiated.
// NOTE: This is a OpenSSL type.
SRTP_PROTECTION_PROFILE* sslSrtpCryptoSuite = SSL_get_selected_srtp_profile(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (!sslSrtpCryptoSuite)
return negotiatedSrtpCryptoSuite;
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Get the negotiated SRTP crypto suite.
for (auto& srtpCryptoSuite : DtlsTransport::srtpCryptoSuites)
{
SrtpCryptoSuiteMapEntry* cryptoSuiteEntry = std::addressof(srtpCryptoSuite);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
if (std::strcmp(sslSrtpCryptoSuite->name, cryptoSuiteEntry->name) == 0)
{
MS_DEBUG_2TAGS(dtls, srtp, "chosen SRTP crypto suite: %s", cryptoSuiteEntry->name);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
negotiatedSrtpCryptoSuite = cryptoSuiteEntry->cryptoSuite;
}
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
MS_ASSERT(
negotiatedSrtpCryptoSuite != RTC::SrtpSession::CryptoSuite::NONE,
"chosen SRTP crypto suite is not an available one");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return negotiatedSrtpCryptoSuite;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
inline void DtlsTransport::OnSslInfo(int where, int ret)
{
MS_TRACE();
int w = where & -SSL_ST_MASK;
const char* role;
if ((w & SSL_ST_CONNECT) != 0)
role = "client";
else if ((w & SSL_ST_ACCEPT) != 0)
role = "server";
else
role = "undefined";
if ((where & SSL_CB_LOOP) != 0)
{
MS_DEBUG_TAG(dtls, "[role:%s, action:'%s']", role, SSL_state_string_long(this->ssl));
}
else if ((where & SSL_CB_ALERT) != 0)
{
const char* alertType;
switch (*SSL_alert_type_string(ret))
{
case 'W':
alertType = "warning";
break;
case 'F':
alertType = "fatal";
break;
default:
alertType = "undefined";
}
if ((where & SSL_CB_READ) != 0)
{
MS_WARN_TAG(dtls, "received DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
else if ((where & SSL_CB_WRITE) != 0)
{
MS_DEBUG_TAG(dtls, "sending DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
else
{
MS_DEBUG_TAG(dtls, "DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
}
else if ((where & SSL_CB_EXIT) != 0)
{
if (ret == 0)
MS_DEBUG_TAG(dtls, "[role:%s, failed:'%s']", role, SSL_state_string_long(this->ssl));
else if (ret < 0)
MS_DEBUG_TAG(dtls, "role: %s, waiting:'%s']", role, SSL_state_string_long(this->ssl));
}
else if ((where & SSL_CB_HANDSHAKE_START) != 0)
{
MS_DEBUG_TAG(dtls, "DTLS handshake start");
}
else if ((where & SSL_CB_HANDSHAKE_DONE) != 0)
{
MS_DEBUG_TAG(dtls, "DTLS handshake done");
this->handshakeDoneNow = true;
}
// NOTE: checking SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN here upon
// receipt of a close alert does not work (the flag is set after this callback).
}
inline void DtlsTransport::OnTimer()
{
MS_TRACE();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Workaround for https://github.com/openssl/openssl/issues/7998.
if (this->handshakeDone)
{
MS_DEBUG_DEV("handshake is done so return");
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
return;
}
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
DTLSv1_handle_timeout(this->ssl);
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// If required, send DTLS data.
SendPendingOutgoingDtlsData();
2021-03-24 16:52:41 +08:00
2021-03-26 11:07:03 +08:00
// Set the DTLS timer again.
SetTimeout();
}
} // namespace RTC