certificate.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "certificate.hpp"
  19. #include "threadpool.hpp"
  20. #include <cassert>
  21. #include <chrono>
  22. #include <iomanip>
  23. #include <mutex>
  24. #include <sstream>
  25. #include <unordered_map>
  26. namespace rtc::impl {
  27. const string COMMON_NAME = "libdatachannel";
  28. #if USE_GNUTLS
  29. Certificate::Certificate(string crt_pem, string key_pem)
  30. : mCredentials(gnutls::new_credentials(), gnutls::free_credentials) {
  31. gnutls_datum_t crt_datum = gnutls::make_datum(crt_pem.data(), crt_pem.size());
  32. gnutls_datum_t key_datum = gnutls::make_datum(key_pem.data(), key_pem.size());
  33. gnutls::check(gnutls_certificate_set_x509_key_mem(*mCredentials, &crt_datum, &key_datum,
  34. GNUTLS_X509_FMT_PEM),
  35. "Unable to import PEM");
  36. auto new_crt_list = [this]() -> gnutls_x509_crt_t * {
  37. gnutls_x509_crt_t *crt_list = nullptr;
  38. unsigned int crt_list_size = 0;
  39. gnutls::check(gnutls_certificate_get_x509_crt(*mCredentials, 0, &crt_list, &crt_list_size));
  40. assert(crt_list_size == 1);
  41. return crt_list;
  42. };
  43. auto free_crt_list = [](gnutls_x509_crt_t *crt_list) {
  44. gnutls_x509_crt_deinit(crt_list[0]);
  45. gnutls_free(crt_list);
  46. };
  47. unique_ptr<gnutls_x509_crt_t, decltype(free_crt_list)> crt_list(new_crt_list(), free_crt_list);
  48. mFingerprint = make_fingerprint(*crt_list);
  49. }
  50. Certificate::Certificate(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey)
  51. : mCredentials(gnutls::new_credentials(), gnutls::free_credentials),
  52. mFingerprint(make_fingerprint(crt)) {
  53. gnutls::check(gnutls_certificate_set_x509_key(*mCredentials, &crt, 1, privkey),
  54. "Unable to set certificate and key pair in credentials");
  55. }
  56. gnutls_certificate_credentials_t Certificate::credentials() const { return *mCredentials; }
  57. string Certificate::fingerprint() const { return mFingerprint; }
  58. string make_fingerprint(gnutls_x509_crt_t crt) {
  59. const size_t size = 32;
  60. unsigned char buffer[size];
  61. size_t len = size;
  62. gnutls::check(gnutls_x509_crt_get_fingerprint(crt, GNUTLS_DIG_SHA256, buffer, &len),
  63. "X509 fingerprint error");
  64. std::ostringstream oss;
  65. oss << std::hex << std::uppercase << std::setfill('0');
  66. for (size_t i = 0; i < len; ++i) {
  67. if (i)
  68. oss << std::setw(1) << ':';
  69. oss << std::setw(2) << unsigned(buffer[i]);
  70. }
  71. return oss.str();
  72. }
  73. namespace {
  74. certificate_ptr make_certificate_impl(CertificateType type) {
  75. PLOG_DEBUG << "Generating certificate (GnuTLS)";
  76. using namespace gnutls;
  77. unique_ptr<gnutls_x509_crt_t, decltype(&free_crt)> crt(new_crt(), free_crt);
  78. unique_ptr<gnutls_x509_privkey_t, decltype(&free_privkey)> privkey(new_privkey(), free_privkey);
  79. switch (type) {
  80. // RFC 8827 WebRTC Security Architecture 6.5. Communications Security
  81. // All implementations MUST support DTLS 1.2 with the TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  82. // cipher suite and the P-256 curve
  83. // See https://tools.ietf.org/html/rfc8827#section-6.5
  84. case CertificateType::Default:
  85. case CertificateType::Ecdsa: {
  86. gnutls::check(gnutls_x509_privkey_generate(*privkey, GNUTLS_PK_ECDSA,
  87. GNUTLS_CURVE_TO_BITS(GNUTLS_ECC_CURVE_SECP256R1),
  88. 0),
  89. "Unable to generate ECDSA P-256 key pair");
  90. break;
  91. }
  92. case CertificateType::Rsa: {
  93. const unsigned int bits = 2048;
  94. gnutls::check(gnutls_x509_privkey_generate(*privkey, GNUTLS_PK_RSA, bits, 0),
  95. "Unable to generate RSA key pair");
  96. break;
  97. }
  98. default:
  99. throw std::invalid_argument("Unknown certificate type");
  100. }
  101. using namespace std::chrono;
  102. auto now = time_point_cast<seconds>(system_clock::now());
  103. gnutls_x509_crt_set_activation_time(*crt, (now - hours(1)).time_since_epoch().count());
  104. gnutls_x509_crt_set_expiration_time(*crt, (now + hours(24 * 365)).time_since_epoch().count());
  105. gnutls_x509_crt_set_version(*crt, 1);
  106. gnutls_x509_crt_set_key(*crt, *privkey);
  107. gnutls_x509_crt_set_dn_by_oid(*crt, GNUTLS_OID_X520_COMMON_NAME, 0, COMMON_NAME.data(),
  108. COMMON_NAME.size());
  109. const size_t serialSize = 16;
  110. char serial[serialSize];
  111. gnutls_rnd(GNUTLS_RND_NONCE, serial, serialSize);
  112. gnutls_x509_crt_set_serial(*crt, serial, serialSize);
  113. gnutls::check(gnutls_x509_crt_sign2(*crt, *crt, *privkey, GNUTLS_DIG_SHA256, 0),
  114. "Unable to auto-sign certificate");
  115. return std::make_shared<Certificate>(*crt, *privkey);
  116. }
  117. } // namespace
  118. #else // USE_GNUTLS==0
  119. Certificate::Certificate(string crt_pem, string key_pem) {
  120. BIO *bio = BIO_new(BIO_s_mem());
  121. BIO_write(bio, crt_pem.data(), int(crt_pem.size()));
  122. mX509 = shared_ptr<X509>(PEM_read_bio_X509(bio, nullptr, 0, 0), X509_free);
  123. BIO_free(bio);
  124. if (!mX509)
  125. throw std::invalid_argument("Unable to import certificate PEM");
  126. bio = BIO_new(BIO_s_mem());
  127. BIO_write(bio, key_pem.data(), int(key_pem.size()));
  128. mPKey = shared_ptr<EVP_PKEY>(PEM_read_bio_PrivateKey(bio, nullptr, 0, 0), EVP_PKEY_free);
  129. BIO_free(bio);
  130. if (!mPKey)
  131. throw std::invalid_argument("Unable to import PEM key PEM");
  132. mFingerprint = make_fingerprint(mX509.get());
  133. }
  134. Certificate::Certificate(shared_ptr<X509> x509, shared_ptr<EVP_PKEY> pkey)
  135. : mX509(std::move(x509)), mPKey(std::move(pkey)) {
  136. mFingerprint = make_fingerprint(mX509.get());
  137. }
  138. string Certificate::fingerprint() const { return mFingerprint; }
  139. std::tuple<X509 *, EVP_PKEY *> Certificate::credentials() const {
  140. return {mX509.get(), mPKey.get()};
  141. }
  142. string make_fingerprint(X509 *x509) {
  143. const size_t size = 32;
  144. unsigned char buffer[size];
  145. unsigned int len = size;
  146. if (!X509_digest(x509, EVP_sha256(), buffer, &len))
  147. throw std::runtime_error("X509 fingerprint error");
  148. std::ostringstream oss;
  149. oss << std::hex << std::uppercase << std::setfill('0');
  150. for (size_t i = 0; i < len; ++i) {
  151. if (i)
  152. oss << std::setw(1) << ':';
  153. oss << std::setw(2) << unsigned(buffer[i]);
  154. }
  155. return oss.str();
  156. }
  157. namespace {
  158. certificate_ptr make_certificate_impl(CertificateType type) {
  159. PLOG_DEBUG << "Generating certificate (OpenSSL)";
  160. shared_ptr<X509> x509(X509_new(), X509_free);
  161. shared_ptr<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free);
  162. unique_ptr<BIGNUM, decltype(&BN_free)> serial_number(BN_new(), BN_free);
  163. unique_ptr<X509_NAME, decltype(&X509_NAME_free)> name(X509_NAME_new(), X509_NAME_free);
  164. if (!x509 || !pkey || !serial_number || !name)
  165. throw std::runtime_error("Unable to allocate structures for certificate generation");
  166. switch (type) {
  167. // RFC 8827 WebRTC Security Architecture 6.5. Communications Security
  168. // All implementations MUST support DTLS 1.2 with the TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  169. // cipher suite and the P-256 curve
  170. // See https://tools.ietf.org/html/rfc8827#section-6.5
  171. case CertificateType::Default:
  172. case CertificateType::Ecdsa: {
  173. PLOG_VERBOSE << "Generating ECDSA P-256 key pair";
  174. unique_ptr<EC_KEY, decltype(&EC_KEY_free)> ecc(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1),
  175. EC_KEY_free);
  176. if (!ecc)
  177. throw std::runtime_error("Unable to allocate structure for ECDSA P-256 key pair");
  178. EC_KEY_set_asn1_flag(ecc.get(), OPENSSL_EC_NAMED_CURVE); // Set ASN1 OID
  179. if (!EC_KEY_generate_key(ecc.get()) ||
  180. !EVP_PKEY_assign_EC_KEY(pkey.get(),
  181. ecc.release())) // the key will be freed when pkey is freed
  182. throw std::runtime_error("Unable to generate ECDSA P-256 key pair");
  183. break;
  184. }
  185. case CertificateType::Rsa: {
  186. PLOG_VERBOSE << "Generating RSA key pair";
  187. const int bits = 2048;
  188. const unsigned int e = 65537; // 2^16 + 1
  189. unique_ptr<RSA, decltype(&RSA_free)> rsa(RSA_new(), RSA_free);
  190. unique_ptr<BIGNUM, decltype(&BN_free)> exponent(BN_new(), BN_free);
  191. if (!rsa || !exponent)
  192. throw std::runtime_error("Unable to allocate structures for RSA key pair");
  193. if (!BN_set_word(exponent.get(), e) ||
  194. !RSA_generate_key_ex(rsa.get(), bits, exponent.get(), NULL) ||
  195. !EVP_PKEY_assign_RSA(pkey.get(),
  196. rsa.release())) // the key will be freed when pkey is freed
  197. throw std::runtime_error("Unable to generate RSA key pair");
  198. break;
  199. }
  200. default:
  201. throw std::invalid_argument("Unknown certificate type");
  202. }
  203. const size_t serialSize = 16;
  204. auto *commonNameBytes =
  205. reinterpret_cast<unsigned char *>(const_cast<char *>(COMMON_NAME.c_str()));
  206. if (!X509_set_pubkey(x509.get(), pkey.get()))
  207. throw std::runtime_error("Unable to set certificate public key");
  208. if (!X509_gmtime_adj(X509_getm_notBefore(x509.get()), 3600 * -1) ||
  209. !X509_gmtime_adj(X509_getm_notAfter(x509.get()), 3600 * 24 * 365) ||
  210. !X509_set_version(x509.get(), 1) ||
  211. !BN_pseudo_rand(serial_number.get(), serialSize, 0, 0) ||
  212. !BN_to_ASN1_INTEGER(serial_number.get(), X509_get_serialNumber(x509.get())) ||
  213. !X509_NAME_add_entry_by_NID(name.get(), NID_commonName, MBSTRING_UTF8, commonNameBytes, -1,
  214. -1, 0) ||
  215. !X509_set_subject_name(x509.get(), name.get()) ||
  216. !X509_set_issuer_name(x509.get(), name.get()))
  217. throw std::runtime_error("Unable to set certificate properties");
  218. if (!X509_sign(x509.get(), pkey.get(), EVP_sha256()))
  219. throw std::runtime_error("Unable to auto-sign certificate");
  220. return std::make_shared<Certificate>(x509, pkey);
  221. }
  222. } // namespace
  223. #endif
  224. // Common for GnuTLS and OpenSSL
  225. future_certificate_ptr make_certificate(CertificateType type) {
  226. return ThreadPool::Instance().enqueue(make_certificate_impl, type);
  227. }
  228. } // namespace rtc::impl