blob: 1d136d7298fa62fd0acc5a30ea629604639e1308 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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// Handling of certificates and keypairs for SSLStreamAdapter's peer mode.
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020012#include "rtc_base/sslidentity.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Yves Gerey2e00abc2018-10-05 15:39:24 +020014#include <string.h> // for strspn
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +010015#include <ctime>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#include <string>
17
Yves Gerey2e00abc2018-10-05 15:39:24 +020018#include "rtc_base/checks.h" // for FatalLogCall, RTC_DC...
19#include "rtc_base/opensslidentity.h" // for OpenSSLIdentity
20#include "rtc_base/strings/string_builder.h" // for StringBuilder
21#include "rtc_base/third_party/base64/base64.h" // for Base64, Base64::DO_P...
22#include "rtc_base/timeutils.h" // for TmToSeconds
deadbeeff33491e2017-01-20 17:01:45 -080023
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024namespace rtc {
25
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070026//////////////////////////////////////////////////////////////////////
27// KeyParams
28//////////////////////////////////////////////////////////////////////
29
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030const char kPemTypeCertificate[] = "CERTIFICATE";
31const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY";
Torbjorn Granlundb6d4ec42015-08-17 14:08:59 +020032const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033
torbjorng4e572472015-10-08 09:42:49 -070034KeyParams::KeyParams(KeyType key_type) {
35 if (key_type == KT_ECDSA) {
36 type_ = KT_ECDSA;
37 params_.curve = EC_NIST_P256;
38 } else if (key_type == KT_RSA) {
39 type_ = KT_RSA;
40 params_.rsa.mod_size = kRsaDefaultModSize;
41 params_.rsa.pub_exp = kRsaDefaultExponent;
42 } else {
43 RTC_NOTREACHED();
44 }
45}
46
47// static
48KeyParams KeyParams::RSA(int mod_size, int pub_exp) {
49 KeyParams kt(KT_RSA);
50 kt.params_.rsa.mod_size = mod_size;
51 kt.params_.rsa.pub_exp = pub_exp;
52 return kt;
53}
54
55// static
56KeyParams KeyParams::ECDSA(ECCurve curve) {
57 KeyParams kt(KT_ECDSA);
58 kt.params_.curve = curve;
59 return kt;
60}
61
62bool KeyParams::IsValid() const {
63 if (type_ == KT_RSA) {
64 return (params_.rsa.mod_size >= kRsaMinModSize &&
65 params_.rsa.mod_size <= kRsaMaxModSize &&
66 params_.rsa.pub_exp > params_.rsa.mod_size);
67 } else if (type_ == KT_ECDSA) {
68 return (params_.curve == EC_NIST_P256);
69 }
70 return false;
71}
72
73RSAParams KeyParams::rsa_params() const {
74 RTC_DCHECK(type_ == KT_RSA);
75 return params_.rsa;
76}
77
78ECCurve KeyParams::ec_curve() const {
79 RTC_DCHECK(type_ == KT_ECDSA);
80 return params_.curve;
81}
82
Henrik Boström9b5476d2015-09-22 14:12:57 +020083KeyType IntKeyTypeFamilyToKeyType(int key_type_family) {
84 return static_cast<KeyType>(key_type_family);
85}
86
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070087//////////////////////////////////////////////////////////////////////
88// SSLIdentity
89//////////////////////////////////////////////////////////////////////
90
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091bool SSLIdentity::PemToDer(const std::string& pem_type,
92 const std::string& pem_string,
93 std::string* der) {
94 // Find the inner body. We need this to fulfill the contract of
95 // returning pem_length.
96 size_t header = pem_string.find("-----BEGIN " + pem_type + "-----");
97 if (header == std::string::npos)
98 return false;
99
100 size_t body = pem_string.find("\n", header);
101 if (body == std::string::npos)
102 return false;
103
104 size_t trailer = pem_string.find("-----END " + pem_type + "-----");
105 if (trailer == std::string::npos)
106 return false;
107
108 std::string inner = pem_string.substr(body + 1, trailer - (body + 1));
109
Yves Gerey665174f2018-06-19 15:03:05 +0200110 *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE | Base64::DO_PAD_ANY |
111 Base64::DO_TERM_BUFFER);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112 return true;
113}
114
115std::string SSLIdentity::DerToPem(const std::string& pem_type,
116 const unsigned char* data,
117 size_t length) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200118 rtc::StringBuilder result;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119
120 result << "-----BEGIN " << pem_type << "-----\n";
121
122 std::string b64_encoded;
123 Base64::EncodeFromArray(data, length, &b64_encoded);
124
125 // Divide the Base-64 encoded data into 64-character chunks, as per
126 // 4.3.2.4 of RFC 1421.
127 static const size_t kChunkSize = 64;
128 size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
129 for (size_t i = 0, chunk_offset = 0; i < chunks;
130 ++i, chunk_offset += kChunkSize) {
131 result << b64_encoded.substr(chunk_offset, kChunkSize);
132 result << "\n";
133 }
134
135 result << "-----END " << pem_type << "-----\n";
136
Jonas Olsson84df1c72018-09-14 16:59:32 +0200137 return result.Release();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138}
139
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100140// static
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200141SSLIdentity* SSLIdentity::GenerateWithExpiration(const std::string& common_name,
142 const KeyParams& key_params,
143 time_t certificate_lifetime) {
144 return OpenSSLIdentity::GenerateWithExpiration(common_name, key_params,
145 certificate_lifetime);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146}
147
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100148// static
149SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
150 const KeyParams& key_params) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200151 return OpenSSLIdentity::GenerateWithExpiration(
152 common_name, key_params, kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100153}
154
155// static
156SSLIdentity* SSLIdentity::Generate(const std::string& common_name,
157 KeyType key_type) {
Torbjorn Granlund1d846b22016-03-31 16:21:04 +0200158 return OpenSSLIdentity::GenerateWithExpiration(
159 common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds);
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100160}
161
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) {
163 return OpenSSLIdentity::GenerateForTest(params);
164}
165
Torbjorn Granlunda3dc79e2016-02-16 13:33:53 +0100166// static
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
168 const std::string& certificate) {
169 return OpenSSLIdentity::FromPEMStrings(private_key, certificate);
170}
171
Jian Cui0a8798b2017-11-16 16:58:02 -0800172// static
173SSLIdentity* SSLIdentity::FromPEMChainStrings(
174 const std::string& private_key,
175 const std::string& certificate_chain) {
176 return OpenSSLIdentity::FromPEMChainStrings(private_key, certificate_chain);
177}
178
hbos6b470a92016-04-28 05:14:21 -0700179bool operator==(const SSLIdentity& a, const SSLIdentity& b) {
180 return static_cast<const OpenSSLIdentity&>(a) ==
181 static_cast<const OpenSSLIdentity&>(b);
182}
183bool operator!=(const SSLIdentity& a, const SSLIdentity& b) {
184 return !(a == b);
185}
186
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700187//////////////////////////////////////////////////////////////////////
188// Helper Functions
189//////////////////////////////////////////////////////////////////////
190
Torbjorn Granlund46c9cc02015-12-01 13:06:34 +0100191// Read |n| bytes from ASN1 number string at *|pp| and return the numeric value.
192// Update *|pp| and *|np| to reflect number of read bytes.
193static inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) {
194 const unsigned char* p = *pp;
195 int x = 0;
196 for (size_t i = 0; i < n; i++)
197 x = 10 * x + p[i] - '0';
198 *pp = p + n;
199 *np = *np - n;
200 return x;
201}
202
203int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) {
204 size_t bytes_left = length;
205
206 // Make sure the string ends with Z. Doing it here protects the strspn call
207 // from running off the end of the string in Z's absense.
208 if (length == 0 || s[length - 1] != 'Z')
209 return -1;
210
211 // Make sure we only have ASCII digits so that we don't need to clutter the
212 // code below and ASN1ReadInt with error checking.
213 size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789");
214 if (n + 1 != length)
215 return -1;
216
217 int year;
218
219 // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME"
220 // format. Both format use UTC in this context.
221 if (long_format) {
222 // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but
223 // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ.
224
225 if (bytes_left < 11)
226 return -1;
227
228 year = ASN1ReadInt(&s, &bytes_left, 4);
229 year -= 1900;
230 } else {
231 // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280
232 // requires us to only support exactly yymmddhhmmssZ.
233
234 if (bytes_left < 9)
235 return -1;
236
237 year = ASN1ReadInt(&s, &bytes_left, 2);
238 if (year < 50) // Per RFC 5280 4.1.2.5.1
239 year += 100;
240 }
241
242 std::tm tm;
243 tm.tm_year = year;
244
245 // Read out remaining ASN1 time data and store it in |tm| in documented
246 // std::tm format.
247 tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1;
248 tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2);
249 tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2);
250 tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2);
251 tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2);
252
253 if (bytes_left != 1) {
254 // Now just Z should remain. Its existence was asserted above.
255 return -1;
256 }
257
258 return TmToSeconds(tm);
259}
260
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261} // namespace rtc