• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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.
12 #include "rtc_base/ssl_identity.h"
13 
14 #include <string.h>
15 #include <time.h>
16 #include <string>
17 
18 #include "rtc_base/checks.h"
19 #include "rtc_base/openssl_identity.h"
20 #include "rtc_base/ssl_certificate.h"
21 #include "rtc_base/strings/string_builder.h"
22 #include "rtc_base/third_party/base64/base64.h"
23 #include "rtc_base/time_utils.h"
24 
25 namespace rtc {
26 
27 //////////////////////////////////////////////////////////////////////
28 // Helper Functions
29 //////////////////////////////////////////////////////////////////////
30 
31 namespace {
32 // Read |n| bytes from ASN1 number string at *|pp| and return the numeric value.
33 // Update *|pp| and *|np| to reflect number of read bytes.
34 // TODO(bugs.webrtc.org/9860) - Remove this code.
ASN1ReadInt(const unsigned char ** pp,size_t * np,size_t n)35 inline int ASN1ReadInt(const unsigned char** pp, size_t* np, size_t n) {
36   const unsigned char* p = *pp;
37   int x = 0;
38   for (size_t i = 0; i < n; i++) {
39     x = 10 * x + p[i] - '0';
40   }
41   *pp = p + n;
42   *np = *np - n;
43   return x;
44 }
45 
46 }  // namespace
47 
48 // TODO(bugs.webrtc.org/9860) - Remove this code.
ASN1TimeToSec(const unsigned char * s,size_t length,bool long_format)49 int64_t ASN1TimeToSec(const unsigned char* s, size_t length, bool long_format) {
50   size_t bytes_left = length;
51   // Make sure the string ends with Z.  Doing it here protects the strspn call
52   // from running off the end of the string in Z's absense.
53   if (length == 0 || s[length - 1] != 'Z') {
54     return -1;
55   }
56   // Make sure we only have ASCII digits so that we don't need to clutter the
57   // code below and ASN1ReadInt with error checking.
58   size_t n = strspn(reinterpret_cast<const char*>(s), "0123456789");
59   if (n + 1 != length) {
60     return -1;
61   }
62   // Read out ASN1 year, in either 2-char "UTCTIME" or 4-char "GENERALIZEDTIME"
63   // format.  Both format use UTC in this context.
64   int year = 0;
65   if (long_format) {
66     // ASN1 format: yyyymmddhh[mm[ss[.fff]]]Z where the Z is literal, but
67     // RFC 5280 requires us to only support exactly yyyymmddhhmmssZ.
68     if (bytes_left < 11) {
69       return -1;
70     }
71     year = ASN1ReadInt(&s, &bytes_left, 4);
72     year -= 1900;
73   } else {
74     // ASN1 format: yymmddhhmm[ss]Z where the Z is literal, but RFC 5280
75     // requires us to only support exactly yymmddhhmmssZ.
76     if (bytes_left < 9) {
77       return -1;
78     }
79     year = ASN1ReadInt(&s, &bytes_left, 2);
80     // Per RFC 5280 4.1.2.5.1
81     if (year < 50) {
82       year += 100;
83     }
84   }
85 
86   // Read out remaining ASN1 time data and store it in |tm| in documented
87   // std::tm format.
88   tm tm;
89   tm.tm_year = year;
90   tm.tm_mon = ASN1ReadInt(&s, &bytes_left, 2) - 1;
91   tm.tm_mday = ASN1ReadInt(&s, &bytes_left, 2);
92   tm.tm_hour = ASN1ReadInt(&s, &bytes_left, 2);
93   tm.tm_min = ASN1ReadInt(&s, &bytes_left, 2);
94   tm.tm_sec = ASN1ReadInt(&s, &bytes_left, 2);
95 
96   // Now just Z should remain.  Its existence was asserted above.
97   if (bytes_left != 1) {
98     return -1;
99   }
100   return TmToSeconds(tm);
101 }
102 
103 //////////////////////////////////////////////////////////////////////
104 // KeyParams
105 //////////////////////////////////////////////////////////////////////
106 
107 const char kPemTypeCertificate[] = "CERTIFICATE";
108 const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY";
109 const char kPemTypeEcPrivateKey[] = "EC PRIVATE KEY";
110 
KeyParams(KeyType key_type)111 KeyParams::KeyParams(KeyType key_type) {
112   if (key_type == KT_ECDSA) {
113     type_ = KT_ECDSA;
114     params_.curve = EC_NIST_P256;
115   } else if (key_type == KT_RSA) {
116     type_ = KT_RSA;
117     params_.rsa.mod_size = kRsaDefaultModSize;
118     params_.rsa.pub_exp = kRsaDefaultExponent;
119   } else {
120     RTC_NOTREACHED();
121   }
122 }
123 
124 // static
RSA(int mod_size,int pub_exp)125 KeyParams KeyParams::RSA(int mod_size, int pub_exp) {
126   KeyParams kt(KT_RSA);
127   kt.params_.rsa.mod_size = mod_size;
128   kt.params_.rsa.pub_exp = pub_exp;
129   return kt;
130 }
131 
132 // static
ECDSA(ECCurve curve)133 KeyParams KeyParams::ECDSA(ECCurve curve) {
134   KeyParams kt(KT_ECDSA);
135   kt.params_.curve = curve;
136   return kt;
137 }
138 
IsValid() const139 bool KeyParams::IsValid() const {
140   if (type_ == KT_RSA) {
141     return (params_.rsa.mod_size >= kRsaMinModSize &&
142             params_.rsa.mod_size <= kRsaMaxModSize &&
143             params_.rsa.pub_exp > params_.rsa.mod_size);
144   } else if (type_ == KT_ECDSA) {
145     return (params_.curve == EC_NIST_P256);
146   }
147   return false;
148 }
149 
rsa_params() const150 RSAParams KeyParams::rsa_params() const {
151   RTC_DCHECK(type_ == KT_RSA);
152   return params_.rsa;
153 }
154 
ec_curve() const155 ECCurve KeyParams::ec_curve() const {
156   RTC_DCHECK(type_ == KT_ECDSA);
157   return params_.curve;
158 }
159 
IntKeyTypeFamilyToKeyType(int key_type_family)160 KeyType IntKeyTypeFamilyToKeyType(int key_type_family) {
161   return static_cast<KeyType>(key_type_family);
162 }
163 
164 //////////////////////////////////////////////////////////////////////
165 // SSLIdentity
166 //////////////////////////////////////////////////////////////////////
167 
PemToDer(const std::string & pem_type,const std::string & pem_string,std::string * der)168 bool SSLIdentity::PemToDer(const std::string& pem_type,
169                            const std::string& pem_string,
170                            std::string* der) {
171   // Find the inner body. We need this to fulfill the contract of returning
172   // pem_length.
173   size_t header = pem_string.find("-----BEGIN " + pem_type + "-----");
174   if (header == std::string::npos) {
175     return false;
176   }
177   size_t body = pem_string.find('\n', header);
178   if (body == std::string::npos) {
179     return false;
180   }
181   size_t trailer = pem_string.find("-----END " + pem_type + "-----");
182   if (trailer == std::string::npos) {
183     return false;
184   }
185   std::string inner = pem_string.substr(body + 1, trailer - (body + 1));
186   *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE | Base64::DO_PAD_ANY |
187                                    Base64::DO_TERM_BUFFER);
188   return true;
189 }
190 
DerToPem(const std::string & pem_type,const unsigned char * data,size_t length)191 std::string SSLIdentity::DerToPem(const std::string& pem_type,
192                                   const unsigned char* data,
193                                   size_t length) {
194   rtc::StringBuilder result;
195   result << "-----BEGIN " << pem_type << "-----\n";
196 
197   std::string b64_encoded;
198   Base64::EncodeFromArray(data, length, &b64_encoded);
199   // Divide the Base-64 encoded data into 64-character chunks, as per 4.3.2.4
200   // of RFC 1421.
201   static const size_t kChunkSize = 64;
202   size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
203   for (size_t i = 0, chunk_offset = 0; i < chunks;
204        ++i, chunk_offset += kChunkSize) {
205     result << b64_encoded.substr(chunk_offset, kChunkSize);
206     result << "\n";
207   }
208   result << "-----END " << pem_type << "-----\n";
209   return result.Release();
210 }
211 
212 // static
Create(const std::string & common_name,const KeyParams & key_param,time_t certificate_lifetime)213 std::unique_ptr<SSLIdentity> SSLIdentity::Create(const std::string& common_name,
214                                                  const KeyParams& key_param,
215                                                  time_t certificate_lifetime) {
216   return OpenSSLIdentity::CreateWithExpiration(common_name, key_param,
217                                                certificate_lifetime);
218 }
219 
220 // static
Create(const std::string & common_name,const KeyParams & key_param)221 std::unique_ptr<SSLIdentity> SSLIdentity::Create(const std::string& common_name,
222                                                  const KeyParams& key_param) {
223   return OpenSSLIdentity::CreateWithExpiration(
224       common_name, key_param, kDefaultCertificateLifetimeInSeconds);
225 }
226 
227 // static
Create(const std::string & common_name,KeyType key_type)228 std::unique_ptr<SSLIdentity> SSLIdentity::Create(const std::string& common_name,
229                                                  KeyType key_type) {
230   return OpenSSLIdentity::CreateWithExpiration(
231       common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds);
232 }
233 
234 //  static
CreateForTest(const SSLIdentityParams & params)235 std::unique_ptr<SSLIdentity> SSLIdentity::CreateForTest(
236     const SSLIdentityParams& params) {
237   return OpenSSLIdentity::CreateForTest(params);
238 }
239 
240 // Construct an identity from a private key and a certificate.
241 // static
CreateFromPEMStrings(const std::string & private_key,const std::string & certificate)242 std::unique_ptr<SSLIdentity> SSLIdentity::CreateFromPEMStrings(
243     const std::string& private_key,
244     const std::string& certificate) {
245   return OpenSSLIdentity::CreateFromPEMStrings(private_key, certificate);
246 }
247 
248 // Construct an identity from a private key and a certificate chain.
249 // static
CreateFromPEMChainStrings(const std::string & private_key,const std::string & certificate_chain)250 std::unique_ptr<SSLIdentity> SSLIdentity::CreateFromPEMChainStrings(
251     const std::string& private_key,
252     const std::string& certificate_chain) {
253   return OpenSSLIdentity::CreateFromPEMChainStrings(private_key,
254                                                     certificate_chain);
255 }
256 
operator ==(const SSLIdentity & a,const SSLIdentity & b)257 bool operator==(const SSLIdentity& a, const SSLIdentity& b) {
258   return static_cast<const OpenSSLIdentity&>(a) ==
259          static_cast<const OpenSSLIdentity&>(b);
260 }
operator !=(const SSLIdentity & a,const SSLIdentity & b)261 bool operator!=(const SSLIdentity& a, const SSLIdentity& b) {
262   return !(a == b);
263 }
264 
265 }  // namespace rtc
266