You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

313 lines
9.6 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2008, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #if HAVE_OPENSSL_SSL_H
  28. #include "talk/base/opensslidentity.h"
  29. // Must be included first before openssl headers.
  30. #include "talk/base/win32.h" // NOLINT
  31. #include <openssl/ssl.h>
  32. #include <openssl/bio.h>
  33. #include <openssl/err.h>
  34. #include <openssl/pem.h>
  35. #include <openssl/bn.h>
  36. #include <openssl/rsa.h>
  37. #include <openssl/crypto.h>
  38. #include "talk/base/helpers.h"
  39. #include "talk/base/logging.h"
  40. #include "talk/base/openssldigest.h"
  41. namespace talk_base {
  42. // We could have exposed a myriad of parameters for the crypto stuff,
  43. // but keeping it simple seems best.
  44. // Strength of generated keys. Those are RSA.
  45. static const int KEY_LENGTH = 1024;
  46. // Random bits for certificate serial number
  47. static const int SERIAL_RAND_BITS = 64;
  48. // Certificate validity lifetime
  49. static const int CERTIFICATE_LIFETIME = 60*60*24*365; // one year, arbitrarily
  50. // Generate a key pair. Caller is responsible for freeing the returned object.
  51. static EVP_PKEY* MakeKey() {
  52. LOG(LS_INFO) << "Making key pair";
  53. EVP_PKEY* pkey = EVP_PKEY_new();
  54. #if OPENSSL_VERSION_NUMBER < 0x00908000l
  55. // Only RSA_generate_key is available. Use that.
  56. RSA* rsa = RSA_generate_key(KEY_LENGTH, 0x10001, NULL, NULL);
  57. if (!EVP_PKEY_assign_RSA(pkey, rsa)) {
  58. EVP_PKEY_free(pkey);
  59. RSA_free(rsa);
  60. return NULL;
  61. }
  62. #else
  63. // RSA_generate_key is deprecated. Use _ex version.
  64. BIGNUM* exponent = BN_new();
  65. RSA* rsa = RSA_new();
  66. if (!pkey || !exponent || !rsa ||
  67. !BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
  68. !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
  69. !EVP_PKEY_assign_RSA(pkey, rsa)) {
  70. EVP_PKEY_free(pkey);
  71. BN_free(exponent);
  72. RSA_free(rsa);
  73. return NULL;
  74. }
  75. // ownership of rsa struct was assigned, don't free it.
  76. BN_free(exponent);
  77. #endif
  78. LOG(LS_INFO) << "Returning key pair";
  79. return pkey;
  80. }
  81. // Generate a self-signed certificate, with the public key from the
  82. // given key pair. Caller is responsible for freeing the returned object.
  83. static X509* MakeCertificate(EVP_PKEY* pkey, const char* common_name) {
  84. LOG(LS_INFO) << "Making certificate for " << common_name;
  85. X509* x509 = NULL;
  86. BIGNUM* serial_number = NULL;
  87. X509_NAME* name = NULL;
  88. if ((x509=X509_new()) == NULL)
  89. goto error;
  90. if (!X509_set_pubkey(x509, pkey))
  91. goto error;
  92. // serial number
  93. // temporary reference to serial number inside x509 struct
  94. ASN1_INTEGER* asn1_serial_number;
  95. if ((serial_number = BN_new()) == NULL ||
  96. !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
  97. (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
  98. !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
  99. goto error;
  100. if (!X509_set_version(x509, 0L)) // version 1
  101. goto error;
  102. // There are a lot of possible components for the name entries. In
  103. // our P2P SSL mode however, the certificates are pre-exchanged
  104. // (through the secure XMPP channel), and so the certificate
  105. // identification is arbitrary. It can't be empty, so we set some
  106. // arbitrary common_name. Note that this certificate goes out in
  107. // clear during SSL negotiation, so there may be a privacy issue in
  108. // putting anything recognizable here.
  109. if ((name = X509_NAME_new()) == NULL ||
  110. !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_UTF8,
  111. (unsigned char*)common_name, -1, -1, 0) ||
  112. !X509_set_subject_name(x509, name) ||
  113. !X509_set_issuer_name(x509, name))
  114. goto error;
  115. if (!X509_gmtime_adj(X509_get_notBefore(x509), 0) ||
  116. !X509_gmtime_adj(X509_get_notAfter(x509), CERTIFICATE_LIFETIME))
  117. goto error;
  118. if (!X509_sign(x509, pkey, EVP_sha1()))
  119. goto error;
  120. BN_free(serial_number);
  121. X509_NAME_free(name);
  122. LOG(LS_INFO) << "Returning certificate";
  123. return x509;
  124. error:
  125. BN_free(serial_number);
  126. X509_NAME_free(name);
  127. X509_free(x509);
  128. return NULL;
  129. }
  130. // This dumps the SSL error stack to the log.
  131. static void LogSSLErrors(const std::string& prefix) {
  132. char error_buf[200];
  133. unsigned long err;
  134. while ((err = ERR_get_error()) != 0) {
  135. ERR_error_string_n(err, error_buf, sizeof(error_buf));
  136. LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
  137. }
  138. }
  139. OpenSSLKeyPair* OpenSSLKeyPair::Generate() {
  140. EVP_PKEY* pkey = MakeKey();
  141. if (!pkey) {
  142. LogSSLErrors("Generating key pair");
  143. return NULL;
  144. }
  145. return new OpenSSLKeyPair(pkey);
  146. }
  147. OpenSSLKeyPair::~OpenSSLKeyPair() {
  148. EVP_PKEY_free(pkey_);
  149. }
  150. void OpenSSLKeyPair::AddReference() {
  151. CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
  152. }
  153. #ifdef _DEBUG
  154. // Print a certificate to the log, for debugging.
  155. static void PrintCert(X509* x509) {
  156. BIO* temp_memory_bio = BIO_new(BIO_s_mem());
  157. if (!temp_memory_bio) {
  158. LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
  159. return;
  160. }
  161. X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
  162. BIO_write(temp_memory_bio, "\0", 1);
  163. char* buffer;
  164. BIO_get_mem_data(temp_memory_bio, &buffer);
  165. LOG(LS_VERBOSE) << buffer;
  166. BIO_free(temp_memory_bio);
  167. }
  168. #endif
  169. OpenSSLCertificate* OpenSSLCertificate::Generate(
  170. OpenSSLKeyPair* key_pair, const std::string& common_name) {
  171. std::string actual_common_name = common_name;
  172. if (actual_common_name.empty())
  173. // Use a random string, arbitrarily 8chars long.
  174. actual_common_name = CreateRandomString(8);
  175. X509* x509 = MakeCertificate(key_pair->pkey(), actual_common_name.c_str());
  176. if (!x509) {
  177. LogSSLErrors("Generating certificate");
  178. return NULL;
  179. }
  180. #ifdef _DEBUG
  181. PrintCert(x509);
  182. #endif
  183. return new OpenSSLCertificate(x509);
  184. }
  185. OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
  186. const std::string& pem_string, int* pem_length) {
  187. BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
  188. if (!bio)
  189. return NULL;
  190. (void)BIO_set_close(bio, BIO_NOCLOSE);
  191. BIO_set_mem_eof_return(bio, 0);
  192. X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
  193. const_cast<char*>("\0"));
  194. char *ptr;
  195. int remaining_length = BIO_get_mem_data(bio, &ptr);
  196. BIO_free(bio);
  197. if (pem_length)
  198. *pem_length = pem_string.length() - remaining_length;
  199. if (x509)
  200. return new OpenSSLCertificate(x509);
  201. else
  202. return NULL;
  203. }
  204. bool OpenSSLCertificate::ComputeDigest(const std::string &algorithm,
  205. unsigned char *digest,
  206. std::size_t size,
  207. std::size_t *length) const {
  208. return ComputeDigest(x509_, algorithm, digest, size, length);
  209. }
  210. bool OpenSSLCertificate::ComputeDigest(const X509 *x509,
  211. const std::string &algorithm,
  212. unsigned char *digest,
  213. std::size_t size,
  214. std::size_t *length) {
  215. const EVP_MD *md;
  216. unsigned int n;
  217. if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
  218. return false;
  219. if (size < static_cast<size_t>(EVP_MD_size(md)))
  220. return false;
  221. X509_digest(x509, md, digest, &n);
  222. *length = n;
  223. return true;
  224. }
  225. OpenSSLCertificate::~OpenSSLCertificate() {
  226. X509_free(x509_);
  227. }
  228. std::string OpenSSLCertificate::ToPEMString() const {
  229. BIO* bio = BIO_new(BIO_s_mem());
  230. if (!bio)
  231. return NULL;
  232. if (!PEM_write_bio_X509(bio, x509_)) {
  233. BIO_free(bio);
  234. return NULL;
  235. }
  236. BIO_write(bio, "\0", 1);
  237. char* buffer;
  238. BIO_get_mem_data(bio, &buffer);
  239. std::string ret(buffer);
  240. BIO_free(bio);
  241. return ret;
  242. }
  243. void OpenSSLCertificate::AddReference() const {
  244. CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
  245. }
  246. OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
  247. OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
  248. if (key_pair) {
  249. OpenSSLCertificate *certificate =
  250. OpenSSLCertificate::Generate(key_pair, common_name);
  251. if (certificate)
  252. return new OpenSSLIdentity(key_pair, certificate);
  253. delete key_pair;
  254. }
  255. LOG(LS_INFO) << "Identity generation failed";
  256. return NULL;
  257. }
  258. bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
  259. // 1 is the documented success return code.
  260. if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
  261. SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
  262. LogSSLErrors("Configuring key and certificate");
  263. return false;
  264. }
  265. return true;
  266. }
  267. } // namespace talk_base
  268. #endif // HAVE_OPENSSL_SSL_H