blob: 92443a4458541841844529ac552d9809eb3107a0 [file] [log] [blame]
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "rtc_base/opensslcertificate.h"
12
13#include <memory>
14#include <utility>
15#include <vector>
16
17#if defined(WEBRTC_WIN)
18// Must be included first before openssl headers.
19#include "rtc_base/win32.h" // NOLINT
20#endif // WEBRTC_WIN
21
22#include <openssl/bio.h>
23#include <openssl/bn.h>
24#include <openssl/crypto.h>
25#include <openssl/err.h>
26#include <openssl/pem.h>
27#include <openssl/rsa.h>
28
Karl Wiberg918f50c2018-07-05 11:40:33 +020029#include "absl/memory/memory.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070030#include "rtc_base/arraysize.h"
31#include "rtc_base/checks.h"
32#include "rtc_base/helpers.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/numerics/safe_conversions.h"
35#include "rtc_base/openssl.h"
36#include "rtc_base/openssldigest.h"
37#include "rtc_base/opensslidentity.h"
38#include "rtc_base/opensslutility.h"
Mirko Bonadeib889a202018-08-15 11:41:27 +020039#ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070040#include "rtc_base/sslroots.h"
Mirko Bonadeib889a202018-08-15 11:41:27 +020041#endif // WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070042
43namespace rtc {
44
45//////////////////////////////////////////////////////////////////////
46// OpenSSLCertificate
47//////////////////////////////////////////////////////////////////////
48
49// We could have exposed a myriad of parameters for the crypto stuff,
50// but keeping it simple seems best.
51
52// Random bits for certificate serial number
53static const int SERIAL_RAND_BITS = 64;
54
55// Generate a self-signed certificate, with the public key from the
56// given key pair. Caller is responsible for freeing the returned object.
57static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
58 RTC_LOG(LS_INFO) << "Making certificate for " << params.common_name;
59 X509* x509 = nullptr;
60 BIGNUM* serial_number = nullptr;
61 X509_NAME* name = nullptr;
62 time_t epoch_off = 0; // Time offset since epoch.
63
64 if ((x509 = X509_new()) == nullptr)
65 goto error;
66
67 if (!X509_set_pubkey(x509, pkey))
68 goto error;
69
70 // serial number
71 // temporary reference to serial number inside x509 struct
72 ASN1_INTEGER* asn1_serial_number;
73 if ((serial_number = BN_new()) == nullptr ||
74 !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
75 (asn1_serial_number = X509_get_serialNumber(x509)) == nullptr ||
76 !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
77 goto error;
78
79 if (!X509_set_version(x509, 2L)) // version 3
80 goto error;
81
82 // There are a lot of possible components for the name entries. In
83 // our P2P SSL mode however, the certificates are pre-exchanged
84 // (through the secure XMPP channel), and so the certificate
85 // identification is arbitrary. It can't be empty, so we set some
86 // arbitrary common_name. Note that this certificate goes out in
87 // clear during SSL negotiation, so there may be a privacy issue in
88 // putting anything recognizable here.
89 if ((name = X509_NAME_new()) == nullptr ||
90 !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_UTF8,
91 (unsigned char*)params.common_name.c_str(),
92 -1, -1, 0) ||
93 !X509_set_subject_name(x509, name) || !X509_set_issuer_name(x509, name))
94 goto error;
95
96 if (!X509_time_adj(X509_get_notBefore(x509), params.not_before, &epoch_off) ||
97 !X509_time_adj(X509_get_notAfter(x509), params.not_after, &epoch_off))
98 goto error;
99
100 if (!X509_sign(x509, pkey, EVP_sha256()))
101 goto error;
102
103 BN_free(serial_number);
104 X509_NAME_free(name);
105 RTC_LOG(LS_INFO) << "Returning certificate";
106 return x509;
107
108error:
109 BN_free(serial_number);
110 X509_NAME_free(name);
111 X509_free(x509);
112 return nullptr;
113}
114
115#if !defined(NDEBUG)
116// Print a certificate to the log, for debugging.
117static void PrintCert(X509* x509) {
118 BIO* temp_memory_bio = BIO_new(BIO_s_mem());
119 if (!temp_memory_bio) {
120 RTC_DLOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
121 return;
122 }
123 X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
124 BIO_write(temp_memory_bio, "\0", 1);
125 char* buffer;
126 BIO_get_mem_data(temp_memory_bio, &buffer);
127 RTC_DLOG(LS_VERBOSE) << buffer;
128 BIO_free(temp_memory_bio);
129}
130#endif
131
132OpenSSLCertificate::OpenSSLCertificate(X509* x509) : x509_(x509) {
Steve Antonf25303e2018-10-16 15:23:31 -0700133 RTC_DCHECK(x509_ != nullptr);
134 X509_up_ref(x509_);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700135}
136
Steve Antonf25303e2018-10-16 15:23:31 -0700137std::unique_ptr<OpenSSLCertificate> OpenSSLCertificate::Generate(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700138 OpenSSLKeyPair* key_pair,
139 const SSLIdentityParams& params) {
140 SSLIdentityParams actual_params(params);
141 if (actual_params.common_name.empty()) {
142 // Use a random string, arbitrarily 8chars long.
143 actual_params.common_name = CreateRandomString(8);
144 }
145 X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
146 if (!x509) {
147 openssl::LogSSLErrors("Generating certificate");
148 return nullptr;
149 }
150#if !defined(NDEBUG)
151 PrintCert(x509);
152#endif
Steve Antonf25303e2018-10-16 15:23:31 -0700153 auto ret = absl::make_unique<OpenSSLCertificate>(x509);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700154 X509_free(x509);
155 return ret;
156}
157
Steve Antonf25303e2018-10-16 15:23:31 -0700158std::unique_ptr<OpenSSLCertificate> OpenSSLCertificate::FromPEMString(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700159 const std::string& pem_string) {
160 BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
161 if (!bio)
162 return nullptr;
163 BIO_set_mem_eof_return(bio, 0);
164 X509* x509 =
165 PEM_read_bio_X509(bio, nullptr, nullptr, const_cast<char*>("\0"));
166 BIO_free(bio); // Frees the BIO, but not the pointed-to string.
167
168 if (!x509)
169 return nullptr;
170
Steve Antonf25303e2018-10-16 15:23:31 -0700171 auto ret = absl::make_unique<OpenSSLCertificate>(x509);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700172 X509_free(x509);
173 return ret;
174}
175
176// NOTE: This implementation only functions correctly after InitializeSSL
177// and before CleanupSSL.
178bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
179 std::string* algorithm) const {
180 int nid = X509_get_signature_nid(x509_);
181 switch (nid) {
182 case NID_md5WithRSA:
183 case NID_md5WithRSAEncryption:
184 *algorithm = DIGEST_MD5;
185 break;
186 case NID_ecdsa_with_SHA1:
187 case NID_dsaWithSHA1:
188 case NID_dsaWithSHA1_2:
189 case NID_sha1WithRSA:
190 case NID_sha1WithRSAEncryption:
191 *algorithm = DIGEST_SHA_1;
192 break;
193 case NID_ecdsa_with_SHA224:
194 case NID_sha224WithRSAEncryption:
195 case NID_dsa_with_SHA224:
196 *algorithm = DIGEST_SHA_224;
197 break;
198 case NID_ecdsa_with_SHA256:
199 case NID_sha256WithRSAEncryption:
200 case NID_dsa_with_SHA256:
201 *algorithm = DIGEST_SHA_256;
202 break;
203 case NID_ecdsa_with_SHA384:
204 case NID_sha384WithRSAEncryption:
205 *algorithm = DIGEST_SHA_384;
206 break;
207 case NID_ecdsa_with_SHA512:
208 case NID_sha512WithRSAEncryption:
209 *algorithm = DIGEST_SHA_512;
210 break;
211 default:
212 // Unknown algorithm. There are several unhandled options that are less
213 // common and more complex.
214 RTC_LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
215 algorithm->clear();
216 return false;
217 }
218 return true;
219}
220
221bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
222 unsigned char* digest,
223 size_t size,
224 size_t* length) const {
225 return ComputeDigest(x509_, algorithm, digest, size, length);
226}
227
228bool OpenSSLCertificate::ComputeDigest(const X509* x509,
229 const std::string& algorithm,
230 unsigned char* digest,
231 size_t size,
232 size_t* length) {
233 const EVP_MD* md;
234 unsigned int n;
235
236 if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
237 return false;
238
239 if (size < static_cast<size_t>(EVP_MD_size(md)))
240 return false;
241
242 X509_digest(x509, md, digest, &n);
243
244 *length = n;
245
246 return true;
247}
248
249OpenSSLCertificate::~OpenSSLCertificate() {
250 X509_free(x509_);
251}
252
Steve Antonf25303e2018-10-16 15:23:31 -0700253std::unique_ptr<SSLCertificate> OpenSSLCertificate::Clone() const {
254 return absl::make_unique<OpenSSLCertificate>(x509_);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700255}
256
257std::string OpenSSLCertificate::ToPEMString() const {
258 BIO* bio = BIO_new(BIO_s_mem());
259 if (!bio) {
260 FATAL() << "unreachable code";
261 }
262 if (!PEM_write_bio_X509(bio, x509_)) {
263 BIO_free(bio);
264 FATAL() << "unreachable code";
265 }
266 BIO_write(bio, "\0", 1);
267 char* buffer;
268 BIO_get_mem_data(bio, &buffer);
269 std::string ret(buffer);
270 BIO_free(bio);
271 return ret;
272}
273
274void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
275 // In case of failure, make sure to leave the buffer empty.
276 der_buffer->SetSize(0);
277
278 // Calculates the DER representation of the certificate, from scratch.
279 BIO* bio = BIO_new(BIO_s_mem());
280 if (!bio) {
281 FATAL() << "unreachable code";
282 }
283 if (!i2d_X509_bio(bio, x509_)) {
284 BIO_free(bio);
285 FATAL() << "unreachable code";
286 }
287 char* data;
288 size_t length = BIO_get_mem_data(bio, &data);
289 der_buffer->SetData(data, length);
290 BIO_free(bio);
291}
292
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700293bool OpenSSLCertificate::operator==(const OpenSSLCertificate& other) const {
294 return X509_cmp(x509_, other.x509_) == 0;
295}
296
297bool OpenSSLCertificate::operator!=(const OpenSSLCertificate& other) const {
298 return !(*this == other);
299}
300
301// Documented in sslidentity.h.
302int64_t OpenSSLCertificate::CertificateExpirationTime() const {
303 ASN1_TIME* expire_time = X509_get_notAfter(x509_);
304 bool long_format;
305
306 if (expire_time->type == V_ASN1_UTCTIME) {
307 long_format = false;
308 } else if (expire_time->type == V_ASN1_GENERALIZEDTIME) {
309 long_format = true;
310 } else {
311 return -1;
312 }
313
314 return ASN1TimeToSec(expire_time->data, expire_time->length, long_format);
315}
316
317} // namespace rtc