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