1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/cert/x509_certificate.h"
6 
7 #include <stdint.h>
8 
9 #include <memory>
10 
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/hash/sha1.h"
14 #include "base/pickle.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "crypto/rsa_private_key.h"
20 #include "net/base/net_errors.h"
21 #include "net/cert/asn1_util.h"
22 #include "net/cert/pem.h"
23 #include "net/cert/x509_util.h"
24 #include "net/test/cert_test_util.h"
25 #include "net/test/test_certificate_data.h"
26 #include "net/test/test_data_directory.h"
27 #include "testing/gtest/include/gtest/gtest.h"
28 
29 using base::HexEncode;
30 using base::Time;
31 
32 namespace net {
33 
34 // Certificates for test data. They're obtained with:
35 //
36 // $ openssl s_client -connect [host]:443 -showcerts > /tmp/host.pem < /dev/null
37 // $ openssl x509 -inform PEM -outform DER < /tmp/host.pem > /tmp/host.der
38 //
39 // For fingerprint
40 // $ openssl x509 -inform DER -fingerprint -noout < /tmp/host.der
41 
42 // For valid_start, valid_expiry
43 // $ openssl x509 -inform DER -text -noout < /tmp/host.der |
44 //    grep -A 2 Validity
45 // $ date +%s -d '<date str>'
46 
47 // Google's cert.
48 SHA256HashValue google_fingerprint = {
49     {0x21, 0xaf, 0x58, 0x74, 0xea, 0x6b, 0xad, 0xbd, 0xe4, 0xb3, 0xb1,
50      0xaa, 0x53, 0x32, 0x80, 0x8f, 0xbf, 0x8a, 0x24, 0x7d, 0x98, 0xec,
51      0x7f, 0x77, 0x49, 0x38, 0x42, 0x81, 0x26, 0x7f, 0xed, 0x38}};
52 
53 // The fingerprint of the Google certificate used in the parsing tests,
54 // which is newer than the one included in the x509_certificate_data.h
55 SHA256HashValue google_parse_fingerprint = {
56     {0xf6, 0x41, 0xc3, 0x6c, 0xfe, 0xf4, 0x9b, 0xc0, 0x71, 0x35, 0x9e,
57      0xcf, 0x88, 0xee, 0xd9, 0x31, 0x7b, 0x73, 0x8b, 0x59, 0x89, 0x41,
58      0x6a, 0xd4, 0x01, 0x72, 0x0c, 0x0a, 0x4e, 0x2e, 0x63, 0x52}};
59 
60 // The fingerprint for the Thawte SGC certificate
61 SHA256HashValue thawte_parse_fingerprint = {
62     {0x10, 0x85, 0xa6, 0xf4, 0x54, 0xd0, 0xc9, 0x11, 0x98, 0xfd, 0xda,
63      0xb1, 0x1a, 0x31, 0xc7, 0x16, 0xd5, 0xdc, 0xd6, 0x8d, 0xf9, 0x1c,
64      0x03, 0x9c, 0xe1, 0x8d, 0xca, 0x9b, 0xeb, 0x3c, 0xde, 0x3d}};
65 
66 // Dec 18 00:00:00 2009 GMT
67 const double kGoogleParseValidFrom = 1261094400;
68 // Dec 18 23:59:59 2011 GMT
69 const double kGoogleParseValidTo = 1324252799;
70 
CheckGoogleCert(const scoped_refptr<X509Certificate> & google_cert,const SHA256HashValue & expected_fingerprint,double valid_from,double valid_to)71 void CheckGoogleCert(const scoped_refptr<X509Certificate>& google_cert,
72                      const SHA256HashValue& expected_fingerprint,
73                      double valid_from,
74                      double valid_to) {
75   ASSERT_NE(static_cast<X509Certificate*>(nullptr), google_cert.get());
76 
77   const CertPrincipal& subject = google_cert->subject();
78   EXPECT_EQ("www.google.com", subject.common_name);
79   EXPECT_EQ("Mountain View", subject.locality_name);
80   EXPECT_EQ("California", subject.state_or_province_name);
81   EXPECT_EQ("US", subject.country_name);
82   EXPECT_EQ(0U, subject.street_addresses.size());
83   ASSERT_EQ(1U, subject.organization_names.size());
84   EXPECT_EQ("Google Inc", subject.organization_names[0]);
85   EXPECT_EQ(0U, subject.organization_unit_names.size());
86   EXPECT_EQ(0U, subject.domain_components.size());
87 
88   const CertPrincipal& issuer = google_cert->issuer();
89   EXPECT_EQ("Thawte SGC CA", issuer.common_name);
90   EXPECT_EQ("", issuer.locality_name);
91   EXPECT_EQ("", issuer.state_or_province_name);
92   EXPECT_EQ("ZA", issuer.country_name);
93   EXPECT_EQ(0U, issuer.street_addresses.size());
94   ASSERT_EQ(1U, issuer.organization_names.size());
95   EXPECT_EQ("Thawte Consulting (Pty) Ltd.", issuer.organization_names[0]);
96   EXPECT_EQ(0U, issuer.organization_unit_names.size());
97   EXPECT_EQ(0U, issuer.domain_components.size());
98 
99   // Use DoubleT because its epoch is the same on all platforms
100   const Time& valid_start = google_cert->valid_start();
101   EXPECT_EQ(valid_from, valid_start.ToDoubleT());
102 
103   const Time& valid_expiry = google_cert->valid_expiry();
104   EXPECT_EQ(valid_to, valid_expiry.ToDoubleT());
105 
106   EXPECT_EQ(expected_fingerprint, X509Certificate::CalculateFingerprint256(
107                                       google_cert->cert_buffer()));
108 
109 }
110 
TEST(X509CertificateTest,GoogleCertParsing)111 TEST(X509CertificateTest, GoogleCertParsing) {
112   scoped_refptr<X509Certificate> google_cert(
113       X509Certificate::CreateFromBytes(
114           reinterpret_cast<const char*>(google_der), sizeof(google_der)));
115 
116   CheckGoogleCert(google_cert, google_fingerprint,
117                   1238192407,   // Mar 27 22:20:07 2009 GMT
118                   1269728407);  // Mar 27 22:20:07 2010 GMT
119 }
120 
TEST(X509CertificateTest,WebkitCertParsing)121 TEST(X509CertificateTest, WebkitCertParsing) {
122   scoped_refptr<X509Certificate> webkit_cert(X509Certificate::CreateFromBytes(
123       reinterpret_cast<const char*>(webkit_der), sizeof(webkit_der)));
124 
125   ASSERT_NE(static_cast<X509Certificate*>(nullptr), webkit_cert.get());
126 
127   const CertPrincipal& subject = webkit_cert->subject();
128   EXPECT_EQ("Cupertino", subject.locality_name);
129   EXPECT_EQ("California", subject.state_or_province_name);
130   EXPECT_EQ("US", subject.country_name);
131   EXPECT_EQ(0U, subject.street_addresses.size());
132   ASSERT_EQ(1U, subject.organization_names.size());
133   EXPECT_EQ("Apple Inc.", subject.organization_names[0]);
134   ASSERT_EQ(1U, subject.organization_unit_names.size());
135   EXPECT_EQ("Mac OS Forge", subject.organization_unit_names[0]);
136   EXPECT_EQ(0U, subject.domain_components.size());
137 
138   const CertPrincipal& issuer = webkit_cert->issuer();
139   EXPECT_EQ("Go Daddy Secure Certification Authority", issuer.common_name);
140   EXPECT_EQ("Scottsdale", issuer.locality_name);
141   EXPECT_EQ("Arizona", issuer.state_or_province_name);
142   EXPECT_EQ("US", issuer.country_name);
143   EXPECT_EQ(0U, issuer.street_addresses.size());
144   ASSERT_EQ(1U, issuer.organization_names.size());
145   EXPECT_EQ("GoDaddy.com, Inc.", issuer.organization_names[0]);
146   ASSERT_EQ(1U, issuer.organization_unit_names.size());
147   EXPECT_EQ("http://certificates.godaddy.com/repository",
148       issuer.organization_unit_names[0]);
149   EXPECT_EQ(0U, issuer.domain_components.size());
150 
151   // Use DoubleT because its epoch is the same on all platforms
152   const Time& valid_start = webkit_cert->valid_start();
153   EXPECT_EQ(1205883319, valid_start.ToDoubleT());  // Mar 18 23:35:19 2008 GMT
154 
155   const Time& valid_expiry = webkit_cert->valid_expiry();
156   EXPECT_EQ(1300491319, valid_expiry.ToDoubleT());  // Mar 18 23:35:19 2011 GMT
157 
158   std::vector<std::string> dns_names;
159   EXPECT_TRUE(webkit_cert->GetSubjectAltName(&dns_names, nullptr));
160   ASSERT_EQ(2U, dns_names.size());
161   EXPECT_EQ("*.webkit.org", dns_names[0]);
162   EXPECT_EQ("webkit.org", dns_names[1]);
163 
164   // Test that the wildcard cert matches properly.
165   EXPECT_TRUE(webkit_cert->VerifyNameMatch("www.webkit.org"));
166   EXPECT_TRUE(webkit_cert->VerifyNameMatch("foo.webkit.org"));
167   EXPECT_TRUE(webkit_cert->VerifyNameMatch("webkit.org"));
168   EXPECT_FALSE(webkit_cert->VerifyNameMatch("www.webkit.com"));
169   EXPECT_FALSE(webkit_cert->VerifyNameMatch("www.foo.webkit.com"));
170 }
171 
TEST(X509CertificateTest,ThawteCertParsing)172 TEST(X509CertificateTest, ThawteCertParsing) {
173   scoped_refptr<X509Certificate> thawte_cert(X509Certificate::CreateFromBytes(
174       reinterpret_cast<const char*>(thawte_der), sizeof(thawte_der)));
175 
176   ASSERT_NE(static_cast<X509Certificate*>(nullptr), thawte_cert.get());
177 
178   const CertPrincipal& subject = thawte_cert->subject();
179   EXPECT_EQ("www.thawte.com", subject.common_name);
180   EXPECT_EQ("Mountain View", subject.locality_name);
181   EXPECT_EQ("California", subject.state_or_province_name);
182   EXPECT_EQ("US", subject.country_name);
183   EXPECT_EQ(0U, subject.street_addresses.size());
184   ASSERT_EQ(1U, subject.organization_names.size());
185   EXPECT_EQ("Thawte Inc", subject.organization_names[0]);
186   EXPECT_EQ(0U, subject.organization_unit_names.size());
187   EXPECT_EQ(0U, subject.domain_components.size());
188 
189   const CertPrincipal& issuer = thawte_cert->issuer();
190   EXPECT_EQ("thawte Extended Validation SSL CA", issuer.common_name);
191   EXPECT_EQ("", issuer.locality_name);
192   EXPECT_EQ("", issuer.state_or_province_name);
193   EXPECT_EQ("US", issuer.country_name);
194   EXPECT_EQ(0U, issuer.street_addresses.size());
195   ASSERT_EQ(1U, issuer.organization_names.size());
196   EXPECT_EQ("thawte, Inc.", issuer.organization_names[0]);
197   ASSERT_EQ(1U, issuer.organization_unit_names.size());
198   EXPECT_EQ("Terms of use at https://www.thawte.com/cps (c)06",
199             issuer.organization_unit_names[0]);
200   EXPECT_EQ(0U, issuer.domain_components.size());
201 
202   // Use DoubleT because its epoch is the same on all platforms
203   const Time& valid_start = thawte_cert->valid_start();
204   EXPECT_EQ(1227052800, valid_start.ToDoubleT());  // Nov 19 00:00:00 2008 GMT
205 
206   const Time& valid_expiry = thawte_cert->valid_expiry();
207   EXPECT_EQ(1263772799, valid_expiry.ToDoubleT());  // Jan 17 23:59:59 2010 GMT
208 }
209 
210 // Test that all desired AttributeAndValue pairs can be extracted when only
211 // a single RelativeDistinguishedName is present. "Normally" there is only
212 // one AVA per RDN, but some CAs place all AVAs within a single RDN.
213 // This is a regression test for http://crbug.com/101009
TEST(X509CertificateTest,MultivalueRDN)214 TEST(X509CertificateTest, MultivalueRDN) {
215   base::FilePath certs_dir = GetTestCertsDirectory();
216 
217   scoped_refptr<X509Certificate> multivalue_rdn_cert =
218       ImportCertFromFile(certs_dir, "multivalue_rdn.pem");
219   ASSERT_NE(static_cast<X509Certificate*>(nullptr), multivalue_rdn_cert.get());
220 
221   const CertPrincipal& subject = multivalue_rdn_cert->subject();
222   EXPECT_EQ("Multivalue RDN Test", subject.common_name);
223   EXPECT_EQ("", subject.locality_name);
224   EXPECT_EQ("", subject.state_or_province_name);
225   EXPECT_EQ("US", subject.country_name);
226   EXPECT_EQ(0U, subject.street_addresses.size());
227   ASSERT_EQ(1U, subject.organization_names.size());
228   EXPECT_EQ("Chromium", subject.organization_names[0]);
229   ASSERT_EQ(1U, subject.organization_unit_names.size());
230   EXPECT_EQ("Chromium net_unittests", subject.organization_unit_names[0]);
231   ASSERT_EQ(1U, subject.domain_components.size());
232   EXPECT_EQ("Chromium", subject.domain_components[0]);
233 }
234 
235 // Test that characters which would normally be escaped in the string form,
236 // such as '=' or '"', are not escaped when parsed as individual components.
237 // This is a regression test for http://crbug.com/102839
TEST(X509CertificateTest,UnescapedSpecialCharacters)238 TEST(X509CertificateTest, UnescapedSpecialCharacters) {
239   base::FilePath certs_dir = GetTestCertsDirectory();
240 
241   scoped_refptr<X509Certificate> unescaped_cert =
242       ImportCertFromFile(certs_dir, "unescaped.pem");
243   ASSERT_NE(static_cast<X509Certificate*>(nullptr), unescaped_cert.get());
244 
245   const CertPrincipal& subject = unescaped_cert->subject();
246   EXPECT_EQ("127.0.0.1", subject.common_name);
247   EXPECT_EQ("Mountain View", subject.locality_name);
248   EXPECT_EQ("California", subject.state_or_province_name);
249   EXPECT_EQ("US", subject.country_name);
250   ASSERT_EQ(1U, subject.street_addresses.size());
251   EXPECT_EQ("1600 Amphitheatre Parkway", subject.street_addresses[0]);
252   ASSERT_EQ(1U, subject.organization_names.size());
253   EXPECT_EQ("Chromium = \"net_unittests\"", subject.organization_names[0]);
254   ASSERT_EQ(2U, subject.organization_unit_names.size());
255   EXPECT_EQ("net_unittests", subject.organization_unit_names[0]);
256   EXPECT_EQ("Chromium", subject.organization_unit_names[1]);
257   EXPECT_EQ(0U, subject.domain_components.size());
258 }
259 
TEST(X509CertificateTest,InvalidPrintableStringIsUtf8)260 TEST(X509CertificateTest, InvalidPrintableStringIsUtf8) {
261   base::FilePath certs_dir =
262       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
263 
264   std::string file_data;
265   ASSERT_TRUE(base::ReadFileToString(
266       certs_dir.AppendASCII(
267           "subject_printable_string_containing_utf8_client_cert.pem"),
268       &file_data));
269 
270   net::PEMTokenizer pem_tokenizer(file_data, {"CERTIFICATE"});
271   ASSERT_TRUE(pem_tokenizer.GetNext());
272   std::string cert_der(pem_tokenizer.data());
273   ASSERT_FALSE(pem_tokenizer.GetNext());
274 
275   bssl::UniquePtr<CRYPTO_BUFFER> cert_handle =
276       x509_util::CreateCryptoBuffer(cert_der);
277   ASSERT_TRUE(cert_handle);
278 
279   EXPECT_FALSE(
280       X509Certificate::CreateFromBuffer(bssl::UpRef(cert_handle.get()), {}));
281 
282   X509Certificate::UnsafeCreateOptions options;
283   options.printable_string_is_utf8 = true;
284   scoped_refptr<X509Certificate> cert =
285       X509Certificate::CreateFromBufferUnsafeOptions(
286           bssl::UpRef(cert_handle.get()), {}, options);
287 
288   const CertPrincipal& subject = cert->subject();
289   EXPECT_EQ("Foo@#_ Clïênt Cërt", subject.common_name);
290 }
291 
TEST(X509CertificateTest,TeletexStringIsLatin1)292 TEST(X509CertificateTest, TeletexStringIsLatin1) {
293   base::FilePath certs_dir =
294       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
295 
296   scoped_refptr<X509Certificate> cert =
297       ImportCertFromFile(certs_dir, "subject_t61string.pem");
298   ASSERT_TRUE(cert);
299 
300   const CertPrincipal& subject = cert->subject();
301   EXPECT_EQ(
302       " !\"#$%&'()*+,-./"
303       "0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
304       "abcdefghijklmnopqrstuvwxyz{|}~"
305       " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæç"
306       "èéêëìíîïðñòóôõö÷øùúûüýþÿ",
307       subject.organization_names[0]);
308 }
309 
TEST(X509CertificateTest,TeletexStringControlChars)310 TEST(X509CertificateTest, TeletexStringControlChars) {
311   base::FilePath certs_dir =
312       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
313 
314   scoped_refptr<X509Certificate> cert =
315       ImportCertFromFile(certs_dir, "subject_t61string_1-32.pem");
316   ASSERT_TRUE(cert);
317 
318   const CertPrincipal& subject = cert->subject();
319   EXPECT_EQ(
320       "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12"
321       "\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20",
322       subject.organization_names[0]);
323 }
324 
TEST(X509CertificateTest,TeletexStringIsLatin1NotCp1252)325 TEST(X509CertificateTest, TeletexStringIsLatin1NotCp1252) {
326   base::FilePath certs_dir =
327       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
328 
329   scoped_refptr<X509Certificate> cert =
330       ImportCertFromFile(certs_dir, "subject_t61string_126-160.pem");
331   ASSERT_TRUE(cert);
332 
333   const CertPrincipal& subject = cert->subject();
334   // TeletexString is decoded as latin1, so 127-160 get decoded to equivalent
335   // unicode control chars.
336   EXPECT_EQ(
337       "~\x7F\xC2\x80\xC2\x81\xC2\x82\xC2\x83\xC2\x84\xC2\x85\xC2\x86\xC2\x87"
338       "\xC2\x88\xC2\x89\xC2\x8A\xC2\x8B\xC2\x8C\xC2\x8D\xC2\x8E\xC2\x8F\xC2\x90"
339       "\xC2\x91\xC2\x92\xC2\x93\xC2\x94\xC2\x95\xC2\x96\xC2\x97\xC2\x98\xC2\x99"
340       "\xC2\x9A\xC2\x9B\xC2\x9C\xC2\x9D\xC2\x9E\xC2\x9F\xC2\xA0",
341       subject.organization_names[0]);
342 }
343 
TEST(X509CertificateTest,TeletexStringIsNotARealT61String)344 TEST(X509CertificateTest, TeletexStringIsNotARealT61String) {
345   base::FilePath certs_dir =
346       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
347 
348   scoped_refptr<X509Certificate> cert =
349       ImportCertFromFile(certs_dir, "subject_t61string_actual.pem");
350   ASSERT_TRUE(cert);
351 
352   const CertPrincipal& subject = cert->subject();
353   // If TeletexStrings were actually parsed according to T.61, this would be
354   // "あ". (Probably. Not verified against a real implementation.)
355   EXPECT_EQ("\x1B$@$\"", subject.organization_names[0]);
356 }
357 
TEST(X509CertificateTest,SerialNumbers)358 TEST(X509CertificateTest, SerialNumbers) {
359   scoped_refptr<X509Certificate> google_cert(
360       X509Certificate::CreateFromBytes(
361           reinterpret_cast<const char*>(google_der), sizeof(google_der)));
362   ASSERT_TRUE(google_cert);
363 
364   static const uint8_t google_serial[16] = {
365     0x01,0x2a,0x39,0x76,0x0d,0x3f,0x4f,0xc9,
366     0x0b,0xe7,0xbd,0x2b,0xcf,0x95,0x2e,0x7a,
367   };
368 
369   ASSERT_EQ(sizeof(google_serial), google_cert->serial_number().size());
370   EXPECT_TRUE(memcmp(google_cert->serial_number().data(), google_serial,
371                      sizeof(google_serial)) == 0);
372 }
373 
TEST(X509CertificateTest,SerialNumberZeroPadded)374 TEST(X509CertificateTest, SerialNumberZeroPadded) {
375   base::FilePath certs_dir =
376       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
377   scoped_refptr<X509Certificate> cert =
378       ImportCertFromFile(certs_dir, "serial_zero_padded.pem");
379   ASSERT_TRUE(cert);
380 
381   // Check a serial number where the first byte is >= 0x80, the DER returned by
382   // serial() should contain the leading 0 padding byte.
383   static const uint8_t expected_serial[3] = {0x00, 0x80, 0x01};
384   ASSERT_EQ(sizeof(expected_serial), cert->serial_number().size());
385   EXPECT_TRUE(memcmp(cert->serial_number().data(), expected_serial,
386                      sizeof(expected_serial)) == 0);
387 }
388 
TEST(X509CertificateTest,SerialNumberZeroPadded21BytesLong)389 TEST(X509CertificateTest, SerialNumberZeroPadded21BytesLong) {
390   base::FilePath certs_dir =
391       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
392   scoped_refptr<X509Certificate> cert =
393       ImportCertFromFile(certs_dir, "serial_zero_padded_21_bytes.pem");
394   ASSERT_TRUE(cert);
395 
396   // Check a serial number where the first byte is >= 0x80, causing the encoded
397   // length to be 21 bytes long. This should be an error, but serial number
398   // parsing is currently permissive.
399   static const uint8_t expected_serial[21] = {
400       0x00, 0x80, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
401       0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13};
402   ASSERT_EQ(sizeof(expected_serial), cert->serial_number().size());
403   EXPECT_TRUE(memcmp(cert->serial_number().data(), expected_serial,
404                      sizeof(expected_serial)) == 0);
405 }
406 
TEST(X509CertificateTest,SerialNumberNegative)407 TEST(X509CertificateTest, SerialNumberNegative) {
408   base::FilePath certs_dir =
409       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
410   scoped_refptr<X509Certificate> cert =
411       ImportCertFromFile(certs_dir, "serial_negative.pem");
412   ASSERT_TRUE(cert);
413 
414   // RFC 5280 does not allow serial numbers to be negative, but serial number
415   // parsing is currently permissive, so this does not cause an error.
416   static const uint8_t expected_serial[2] = {0x80, 0x01};
417   ASSERT_EQ(sizeof(expected_serial), cert->serial_number().size());
418   EXPECT_TRUE(memcmp(cert->serial_number().data(), expected_serial,
419                      sizeof(expected_serial)) == 0);
420 }
421 
TEST(X509CertificateTest,SerialNumber37BytesLong)422 TEST(X509CertificateTest, SerialNumber37BytesLong) {
423   base::FilePath certs_dir =
424       GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
425   scoped_refptr<X509Certificate> cert =
426       ImportCertFromFile(certs_dir, "serial_37_bytes.pem");
427   ASSERT_TRUE(cert);
428 
429   // Check a serial number which is very long. This should be an error, but
430   // serial number parsing is currently permissive.
431   static const uint8_t expected_serial[37] = {
432       0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
433       0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
434       0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e,
435       0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25};
436   ASSERT_EQ(sizeof(expected_serial), cert->serial_number().size());
437   EXPECT_TRUE(memcmp(cert->serial_number().data(), expected_serial,
438                      sizeof(expected_serial)) == 0);
439 }
440 
TEST(X509CertificateTest,SHA256FingerprintsCorrectly)441 TEST(X509CertificateTest, SHA256FingerprintsCorrectly) {
442   scoped_refptr<X509Certificate> google_cert(X509Certificate::CreateFromBytes(
443       reinterpret_cast<const char*>(google_der), sizeof(google_der)));
444   ASSERT_TRUE(google_cert);
445 
446   const SHA256HashValue google_sha256_fingerprint = {
447       {0x21, 0xaf, 0x58, 0x74, 0xea, 0x6b, 0xad, 0xbd, 0xe4, 0xb3, 0xb1,
448        0xaa, 0x53, 0x32, 0x80, 0x8f, 0xbf, 0x8a, 0x24, 0x7d, 0x98, 0xec,
449        0x7f, 0x77, 0x49, 0x38, 0x42, 0x81, 0x26, 0x7f, 0xed, 0x38}};
450 
451   EXPECT_EQ(google_sha256_fingerprint, X509Certificate::CalculateFingerprint256(
452                                            google_cert->cert_buffer()));
453 }
454 
TEST(X509CertificateTest,CAFingerprints)455 TEST(X509CertificateTest, CAFingerprints) {
456   base::FilePath certs_dir = GetTestCertsDirectory();
457 
458   scoped_refptr<X509Certificate> server_cert =
459       ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
460   ASSERT_NE(static_cast<X509Certificate*>(nullptr), server_cert.get());
461 
462   scoped_refptr<X509Certificate> intermediate_cert1 =
463       ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
464   ASSERT_NE(static_cast<X509Certificate*>(nullptr), intermediate_cert1.get());
465 
466   scoped_refptr<X509Certificate> intermediate_cert2 =
467       ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
468   ASSERT_NE(static_cast<X509Certificate*>(nullptr), intermediate_cert2.get());
469 
470   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
471   intermediates.push_back(bssl::UpRef(intermediate_cert1->cert_buffer()));
472   scoped_refptr<X509Certificate> cert_chain1 =
473       X509Certificate::CreateFromBuffer(bssl::UpRef(server_cert->cert_buffer()),
474                                         std::move(intermediates));
475   ASSERT_TRUE(cert_chain1);
476 
477   intermediates.clear();
478   intermediates.push_back(bssl::UpRef(intermediate_cert2->cert_buffer()));
479   scoped_refptr<X509Certificate> cert_chain2 =
480       X509Certificate::CreateFromBuffer(bssl::UpRef(server_cert->cert_buffer()),
481                                         std::move(intermediates));
482   ASSERT_TRUE(cert_chain2);
483 
484   // No intermediate CA certicates.
485   intermediates.clear();
486   scoped_refptr<X509Certificate> cert_chain3 =
487       X509Certificate::CreateFromBuffer(bssl::UpRef(server_cert->cert_buffer()),
488                                         std::move(intermediates));
489   ASSERT_TRUE(cert_chain3);
490 
491   SHA256HashValue cert_chain1_chain_fingerprint_256 = {
492       {0xac, 0xff, 0xcc, 0x63, 0x0d, 0xd0, 0xa7, 0x19, 0x78, 0xb5, 0x8a,
493        0x47, 0x8b, 0x67, 0x97, 0xcb, 0x8d, 0xe1, 0x6a, 0x8a, 0x57, 0x70,
494        0xda, 0x9a, 0x53, 0x72, 0xe2, 0xa0, 0x08, 0xab, 0xcc, 0x8f}};
495   SHA256HashValue cert_chain2_chain_fingerprint_256 = {
496       {0x67, 0x3a, 0x11, 0x20, 0xd6, 0x94, 0x14, 0xe4, 0x16, 0x9f, 0x58,
497        0xe2, 0x8b, 0xf7, 0x27, 0xed, 0xbb, 0xe8, 0xa7, 0xff, 0x1c, 0x8c,
498        0x0f, 0x21, 0x38, 0x16, 0x7c, 0xad, 0x1f, 0x22, 0x6f, 0x9b}};
499   SHA256HashValue cert_chain3_chain_fingerprint_256 = {
500       {0x16, 0x7a, 0xbd, 0xb4, 0x57, 0x04, 0x65, 0x3c, 0x3b, 0xef, 0x6e,
501        0x6a, 0xa6, 0x02, 0x73, 0x30, 0x3e, 0x34, 0x1b, 0x43, 0xc2, 0x7c,
502        0x98, 0x52, 0x9f, 0x34, 0x7f, 0x55, 0x97, 0xe9, 0x1a, 0x10}};
503   EXPECT_EQ(cert_chain1_chain_fingerprint_256,
504             cert_chain1->CalculateChainFingerprint256());
505   EXPECT_EQ(cert_chain2_chain_fingerprint_256,
506             cert_chain2->CalculateChainFingerprint256());
507   EXPECT_EQ(cert_chain3_chain_fingerprint_256,
508             cert_chain3->CalculateChainFingerprint256());
509 }
510 
TEST(X509CertificateTest,ParseSubjectAltNames)511 TEST(X509CertificateTest, ParseSubjectAltNames) {
512   base::FilePath certs_dir = GetTestCertsDirectory();
513 
514   scoped_refptr<X509Certificate> san_cert =
515       ImportCertFromFile(certs_dir, "subjectAltName_sanity_check.pem");
516   ASSERT_NE(static_cast<X509Certificate*>(nullptr), san_cert.get());
517 
518   // Ensure that testing for SAN without using it is accepted.
519   EXPECT_TRUE(san_cert->GetSubjectAltName(nullptr, nullptr));
520 
521   // Ensure that it's possible to get just dNSNames.
522   std::vector<std::string> dns_names;
523   EXPECT_TRUE(san_cert->GetSubjectAltName(&dns_names, nullptr));
524 
525   // Ensure that it's possible to get just iPAddresses.
526   std::vector<std::string> ip_addresses;
527   EXPECT_TRUE(san_cert->GetSubjectAltName(nullptr, &ip_addresses));
528 
529   // Ensure that DNS names are correctly parsed.
530   ASSERT_EQ(1U, dns_names.size());
531   EXPECT_EQ("test.example", dns_names[0]);
532 
533   // Ensure that both IPv4 and IPv6 addresses are correctly parsed.
534   ASSERT_EQ(2U, ip_addresses.size());
535 
536   static const uint8_t kIPv4Address[] = {
537       0x7F, 0x00, 0x00, 0x02
538   };
539   ASSERT_EQ(base::size(kIPv4Address), ip_addresses[0].size());
540   EXPECT_EQ(0, memcmp(ip_addresses[0].data(), kIPv4Address,
541                       base::size(kIPv4Address)));
542 
543   static const uint8_t kIPv6Address[] = {
544       0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
545       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
546   };
547   ASSERT_EQ(base::size(kIPv6Address), ip_addresses[1].size());
548   EXPECT_EQ(0, memcmp(ip_addresses[1].data(), kIPv6Address,
549                       base::size(kIPv6Address)));
550 
551   // Ensure the subjectAltName dirName has not influenced the handling of
552   // the subject commonName.
553   EXPECT_EQ("127.0.0.1", san_cert->subject().common_name);
554 
555   scoped_refptr<X509Certificate> no_san_cert =
556       ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
557   ASSERT_NE(static_cast<X509Certificate*>(nullptr), no_san_cert.get());
558 
559   EXPECT_NE(0u, dns_names.size());
560   EXPECT_NE(0u, ip_addresses.size());
561   EXPECT_FALSE(no_san_cert->GetSubjectAltName(&dns_names, &ip_addresses));
562   EXPECT_EQ(0u, dns_names.size());
563   EXPECT_EQ(0u, ip_addresses.size());
564 }
565 
TEST(X509CertificateTest,ExtractSPKIFromDERCert)566 TEST(X509CertificateTest, ExtractSPKIFromDERCert) {
567   base::FilePath certs_dir = GetTestCertsDirectory();
568   scoped_refptr<X509Certificate> cert =
569       ImportCertFromFile(certs_dir, "nist.der");
570   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
571 
572   base::StringPiece spkiBytes;
573   EXPECT_TRUE(asn1::ExtractSPKIFromDERCert(
574       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()), &spkiBytes));
575 
576   uint8_t hash[base::kSHA1Length];
577   base::SHA1HashBytes(reinterpret_cast<const uint8_t*>(spkiBytes.data()),
578                       spkiBytes.size(), hash);
579 
580   EXPECT_EQ(0, memcmp(hash, kNistSPKIHash, sizeof(hash)));
581 }
582 
TEST(X509CertificateTest,HasTLSFeatureExtension)583 TEST(X509CertificateTest, HasTLSFeatureExtension) {
584   base::FilePath certs_dir = GetTestCertsDirectory();
585   scoped_refptr<X509Certificate> cert =
586       ImportCertFromFile(certs_dir, "tls_feature_extension.pem");
587   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
588 
589   EXPECT_TRUE(asn1::HasTLSFeatureExtension(
590       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer())));
591 }
592 
TEST(X509CertificateTest,DoesNotHaveTLSFeatureExtension)593 TEST(X509CertificateTest, DoesNotHaveTLSFeatureExtension) {
594   base::FilePath certs_dir = GetTestCertsDirectory();
595   scoped_refptr<X509Certificate> cert =
596       ImportCertFromFile(certs_dir, "ok_cert.pem");
597   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
598 
599   EXPECT_FALSE(asn1::HasTLSFeatureExtension(
600       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer())));
601 }
602 
TEST(X509CertificateTest,HasCanSignHttpExchangesDraftExtension)603 TEST(X509CertificateTest, HasCanSignHttpExchangesDraftExtension) {
604   base::FilePath certs_dir = GetTestCertsDirectory();
605   scoped_refptr<X509Certificate> cert = ImportCertFromFile(
606       certs_dir, "can_sign_http_exchanges_draft_extension.pem");
607   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
608 
609   EXPECT_TRUE(asn1::HasCanSignHttpExchangesDraftExtension(
610       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer())));
611 }
612 
TEST(X509CertificateTest,HasCanSignHttpExchangesDraftExtensionInvalid)613 TEST(X509CertificateTest, HasCanSignHttpExchangesDraftExtensionInvalid) {
614   base::FilePath certs_dir = GetTestCertsDirectory();
615   scoped_refptr<X509Certificate> cert = ImportCertFromFile(
616       certs_dir, "can_sign_http_exchanges_draft_extension_invalid.pem");
617   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
618 
619   EXPECT_FALSE(asn1::HasCanSignHttpExchangesDraftExtension(
620       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer())));
621 }
622 
TEST(X509CertificateTest,DoesNotHaveCanSignHttpExchangesDraftExtension)623 TEST(X509CertificateTest, DoesNotHaveCanSignHttpExchangesDraftExtension) {
624   base::FilePath certs_dir = GetTestCertsDirectory();
625   scoped_refptr<X509Certificate> cert =
626       ImportCertFromFile(certs_dir, "ok_cert.pem");
627   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
628 
629   EXPECT_FALSE(asn1::HasCanSignHttpExchangesDraftExtension(
630       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer())));
631 }
632 
TEST(X509CertificateTest,ExtractExtension)633 TEST(X509CertificateTest, ExtractExtension) {
634   base::FilePath certs_dir = GetTestCertsDirectory();
635   scoped_refptr<X509Certificate> cert =
636       ImportCertFromFile(certs_dir, "ok_cert.pem");
637   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
638 
639   static constexpr uint8_t kBasicConstraintsOID[] = {0x55, 0x1d, 0x13};
640   bool present, critical;
641   base::StringPiece contents;
642   ASSERT_TRUE(asn1::ExtractExtensionFromDERCert(
643       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()),
644       base::StringPiece(reinterpret_cast<const char*>(kBasicConstraintsOID),
645                         sizeof(kBasicConstraintsOID)),
646       &present, &critical, &contents));
647   EXPECT_TRUE(present);
648   EXPECT_TRUE(critical);
649   ASSERT_EQ(base::StringPiece("\x30\x00", 2), contents);
650 
651   static constexpr uint8_t kNonsenseOID[] = {0x56, 0x1d, 0x13};
652   ASSERT_TRUE(asn1::ExtractExtensionFromDERCert(
653       x509_util::CryptoBufferAsStringPiece(cert->cert_buffer()),
654       base::StringPiece(reinterpret_cast<const char*>(kNonsenseOID),
655                         sizeof(kNonsenseOID)),
656       &present, &critical, &contents));
657   ASSERT_FALSE(present);
658 }
659 
660 // Tests CRYPTO_BUFFER deduping via X509Certificate::CreateFromBuffer.  We
661 // call X509Certificate::CreateFromBuffer several times and observe whether
662 // it returns a cached or new CRYPTO_BUFFER.
TEST(X509CertificateTest,Cache)663 TEST(X509CertificateTest, Cache) {
664   bssl::UniquePtr<CRYPTO_BUFFER> google_cert_handle;
665   bssl::UniquePtr<CRYPTO_BUFFER> thawte_cert_handle;
666 
667   // Add a single certificate to the certificate cache.
668   google_cert_handle = X509Certificate::CreateCertBufferFromBytes(
669       reinterpret_cast<const char*>(google_der), sizeof(google_der));
670   ASSERT_TRUE(google_cert_handle);
671   scoped_refptr<X509Certificate> cert1(
672       X509Certificate::CreateFromBuffer(std::move(google_cert_handle), {}));
673   ASSERT_TRUE(cert1);
674 
675   // Add the same certificate, but as a new handle.
676   google_cert_handle = X509Certificate::CreateCertBufferFromBytes(
677       reinterpret_cast<const char*>(google_der), sizeof(google_der));
678   ASSERT_TRUE(google_cert_handle);
679   scoped_refptr<X509Certificate> cert2(
680       X509Certificate::CreateFromBuffer(std::move(google_cert_handle), {}));
681   ASSERT_TRUE(cert2);
682 
683   // A new X509Certificate should be returned.
684   EXPECT_NE(cert1.get(), cert2.get());
685   // But both instances should share the underlying OS certificate handle.
686   EXPECT_EQ(cert1->cert_buffer(), cert2->cert_buffer());
687   EXPECT_EQ(0u, cert1->intermediate_buffers().size());
688   EXPECT_EQ(0u, cert2->intermediate_buffers().size());
689 
690   // Add the same certificate, but this time with an intermediate. This
691   // should result in the intermediate being cached. Note that this is not
692   // a legitimate chain, but is suitable for testing.
693   google_cert_handle = X509Certificate::CreateCertBufferFromBytes(
694       reinterpret_cast<const char*>(google_der), sizeof(google_der));
695   thawte_cert_handle = X509Certificate::CreateCertBufferFromBytes(
696       reinterpret_cast<const char*>(thawte_der), sizeof(thawte_der));
697   ASSERT_TRUE(google_cert_handle);
698   ASSERT_TRUE(thawte_cert_handle);
699   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
700   intermediates.push_back(std::move(thawte_cert_handle));
701   scoped_refptr<X509Certificate> cert3(X509Certificate::CreateFromBuffer(
702       std::move(google_cert_handle), std::move(intermediates)));
703   ASSERT_TRUE(cert3);
704 
705   // Test that the new certificate, even with intermediates, results in the
706   // same underlying handle being used.
707   EXPECT_EQ(cert1->cert_buffer(), cert3->cert_buffer());
708   // Though they use the same OS handle, the intermediates should be different.
709   EXPECT_NE(cert1->intermediate_buffers().size(),
710             cert3->intermediate_buffers().size());
711 }
712 
TEST(X509CertificateTest,Pickle)713 TEST(X509CertificateTest, Pickle) {
714   bssl::UniquePtr<CRYPTO_BUFFER> google_cert_handle =
715       X509Certificate::CreateCertBufferFromBytes(
716           reinterpret_cast<const char*>(google_der), sizeof(google_der));
717   ASSERT_TRUE(google_cert_handle);
718   bssl::UniquePtr<CRYPTO_BUFFER> thawte_cert_handle =
719       X509Certificate::CreateCertBufferFromBytes(
720           reinterpret_cast<const char*>(thawte_der), sizeof(thawte_der));
721   ASSERT_TRUE(thawte_cert_handle);
722 
723   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
724   intermediates.push_back(std::move(thawte_cert_handle));
725   scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBuffer(
726       std::move(google_cert_handle), std::move(intermediates));
727   ASSERT_TRUE(cert);
728 
729   base::Pickle pickle;
730   cert->Persist(&pickle);
731 
732   base::PickleIterator iter(pickle);
733   scoped_refptr<X509Certificate> cert_from_pickle =
734       X509Certificate::CreateFromPickle(&iter);
735   ASSERT_TRUE(cert_from_pickle);
736   EXPECT_TRUE(x509_util::CryptoBufferEqual(cert->cert_buffer(),
737                                            cert_from_pickle->cert_buffer()));
738   const auto& cert_intermediates = cert->intermediate_buffers();
739   const auto& pickle_intermediates = cert_from_pickle->intermediate_buffers();
740   ASSERT_EQ(cert_intermediates.size(), pickle_intermediates.size());
741   for (size_t i = 0; i < cert_intermediates.size(); ++i) {
742     EXPECT_TRUE(x509_util::CryptoBufferEqual(cert_intermediates[i].get(),
743                                              pickle_intermediates[i].get()));
744   }
745 }
746 
TEST(X509CertificateTest,IntermediateCertificates)747 TEST(X509CertificateTest, IntermediateCertificates) {
748   scoped_refptr<X509Certificate> webkit_cert(
749       X509Certificate::CreateFromBytes(
750           reinterpret_cast<const char*>(webkit_der), sizeof(webkit_der)));
751   ASSERT_TRUE(webkit_cert);
752 
753   scoped_refptr<X509Certificate> thawte_cert(
754       X509Certificate::CreateFromBytes(
755           reinterpret_cast<const char*>(thawte_der), sizeof(thawte_der)));
756   ASSERT_TRUE(thawte_cert);
757 
758   bssl::UniquePtr<CRYPTO_BUFFER> google_handle;
759   // Create object with no intermediates:
760   google_handle = X509Certificate::CreateCertBufferFromBytes(
761       reinterpret_cast<const char*>(google_der), sizeof(google_der));
762   scoped_refptr<X509Certificate> cert1;
763   cert1 =
764       X509Certificate::CreateFromBuffer(bssl::UpRef(google_handle.get()), {});
765   ASSERT_TRUE(cert1);
766   EXPECT_EQ(0u, cert1->intermediate_buffers().size());
767 
768   // Create object with 2 intermediates:
769   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates2;
770   intermediates2.push_back(bssl::UpRef(webkit_cert->cert_buffer()));
771   intermediates2.push_back(bssl::UpRef(thawte_cert->cert_buffer()));
772   scoped_refptr<X509Certificate> cert2;
773   cert2 = X509Certificate::CreateFromBuffer(std::move(google_handle),
774                                             std::move(intermediates2));
775   ASSERT_TRUE(cert2);
776 
777   // Verify it has all the intermediates:
778   const auto& cert2_intermediates = cert2->intermediate_buffers();
779   ASSERT_EQ(2u, cert2_intermediates.size());
780   EXPECT_TRUE(x509_util::CryptoBufferEqual(cert2_intermediates[0].get(),
781                                            webkit_cert->cert_buffer()));
782   EXPECT_TRUE(x509_util::CryptoBufferEqual(cert2_intermediates[1].get(),
783                                            thawte_cert->cert_buffer()));
784 }
785 
TEST(X509CertificateTest,Equals)786 TEST(X509CertificateTest, Equals) {
787   CertificateList certs = CreateCertificateListFromFile(
788       GetTestCertsDirectory(), "multi-root-chain1.pem",
789       X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
790   ASSERT_EQ(4u, certs.size());
791 
792   // Comparing X509Certificates with no intermediates.
793   EXPECT_TRUE(certs[0]->EqualsExcludingChain(certs[0].get()));
794   EXPECT_FALSE(certs[1]->EqualsExcludingChain(certs[0].get()));
795   EXPECT_FALSE(certs[0]->EqualsExcludingChain(certs[1].get()));
796   EXPECT_TRUE(certs[0]->EqualsIncludingChain(certs[0].get()));
797   EXPECT_FALSE(certs[1]->EqualsIncludingChain(certs[0].get()));
798   EXPECT_FALSE(certs[0]->EqualsIncludingChain(certs[1].get()));
799 
800   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates1;
801   intermediates1.push_back(bssl::UpRef(certs[1]->cert_buffer()));
802   scoped_refptr<X509Certificate> cert0_with_intermediate =
803       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
804                                         std::move(intermediates1));
805   ASSERT_TRUE(cert0_with_intermediate);
806 
807   // Comparing X509Certificate with one intermediate to X509Certificate with no
808   // intermediates.
809   EXPECT_TRUE(certs[0]->EqualsExcludingChain(cert0_with_intermediate.get()));
810   EXPECT_TRUE(cert0_with_intermediate->EqualsExcludingChain(certs[0].get()));
811   EXPECT_FALSE(certs[0]->EqualsIncludingChain(cert0_with_intermediate.get()));
812   EXPECT_FALSE(cert0_with_intermediate->EqualsIncludingChain(certs[0].get()));
813 
814   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates2;
815   intermediates2.push_back(bssl::UpRef(certs[2]->cert_buffer()));
816   scoped_refptr<X509Certificate> cert0_with_intermediate2 =
817       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
818                                         std::move(intermediates1));
819   ASSERT_TRUE(cert0_with_intermediate2);
820 
821   // Comparing X509Certificate with one intermediate to X509Certificate with
822   // one different intermediate.
823   EXPECT_TRUE(cert0_with_intermediate2->EqualsExcludingChain(
824       cert0_with_intermediate.get()));
825   EXPECT_TRUE(cert0_with_intermediate->EqualsExcludingChain(
826       cert0_with_intermediate2.get()));
827   EXPECT_FALSE(cert0_with_intermediate2->EqualsIncludingChain(
828       cert0_with_intermediate.get()));
829   EXPECT_FALSE(cert0_with_intermediate->EqualsIncludingChain(
830       cert0_with_intermediate2.get()));
831 
832   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates12;
833   intermediates12.push_back(bssl::UpRef(certs[1]->cert_buffer()));
834   intermediates12.push_back(bssl::UpRef(certs[2]->cert_buffer()));
835   scoped_refptr<X509Certificate> cert0_with_intermediates12 =
836       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
837                                         std::move(intermediates12));
838   ASSERT_TRUE(cert0_with_intermediates12);
839 
840   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates21;
841   intermediates21.push_back(bssl::UpRef(certs[2]->cert_buffer()));
842   intermediates21.push_back(bssl::UpRef(certs[1]->cert_buffer()));
843   scoped_refptr<X509Certificate> cert0_with_intermediates21 =
844       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
845                                         std::move(intermediates21));
846   ASSERT_TRUE(cert0_with_intermediates21);
847 
848   // Comparing X509Certificate with two intermediates to X509Certificate with
849   // same two intermediates but in reverse order
850   EXPECT_TRUE(cert0_with_intermediates21->EqualsExcludingChain(
851       cert0_with_intermediates12.get()));
852   EXPECT_TRUE(cert0_with_intermediates12->EqualsExcludingChain(
853       cert0_with_intermediates21.get()));
854   EXPECT_FALSE(cert0_with_intermediates21->EqualsIncludingChain(
855       cert0_with_intermediates12.get()));
856   EXPECT_FALSE(cert0_with_intermediates12->EqualsIncludingChain(
857       cert0_with_intermediates21.get()));
858 
859   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates12b;
860   intermediates12b.push_back(bssl::UpRef(certs[1]->cert_buffer()));
861   intermediates12b.push_back(bssl::UpRef(certs[2]->cert_buffer()));
862   scoped_refptr<X509Certificate> cert0_with_intermediates12b =
863       X509Certificate::CreateFromBuffer(bssl::UpRef(certs[0]->cert_buffer()),
864                                         std::move(intermediates12b));
865   ASSERT_TRUE(cert0_with_intermediates12b);
866 
867   // Comparing X509Certificate with two intermediates to X509Certificate with
868   // same two intermediates in same order.
869   EXPECT_TRUE(cert0_with_intermediates12->EqualsExcludingChain(
870       cert0_with_intermediates12b.get()));
871   EXPECT_TRUE(cert0_with_intermediates12b->EqualsExcludingChain(
872       cert0_with_intermediates12.get()));
873   EXPECT_TRUE(cert0_with_intermediates12->EqualsIncludingChain(
874       cert0_with_intermediates12b.get()));
875   EXPECT_TRUE(cert0_with_intermediates12b->EqualsIncludingChain(
876       cert0_with_intermediates12.get()));
877 }
878 
TEST(X509CertificateTest,IsIssuedByEncoded)879 TEST(X509CertificateTest, IsIssuedByEncoded) {
880   base::FilePath certs_dir = GetTestCertsDirectory();
881 
882   // Test a client certificate from MIT.
883   scoped_refptr<X509Certificate> mit_davidben_cert(
884       ImportCertFromFile(certs_dir, "mit.davidben.der"));
885   ASSERT_NE(static_cast<X509Certificate*>(nullptr), mit_davidben_cert.get());
886 
887   std::string mit_issuer(reinterpret_cast<const char*>(MITDN),
888                          sizeof(MITDN));
889 
890   // Test a certificate from Google, issued by Thawte
891   scoped_refptr<X509Certificate> google_cert(
892       ImportCertFromFile(certs_dir, "google.single.der"));
893   ASSERT_NE(static_cast<X509Certificate*>(nullptr), google_cert.get());
894 
895   std::string thawte_issuer(reinterpret_cast<const char*>(ThawteDN),
896                             sizeof(ThawteDN));
897 
898   // Check that the David Ben certificate is issued by MIT, but not
899   // by Thawte.
900   std::vector<std::string> issuers;
901   issuers.clear();
902   issuers.push_back(mit_issuer);
903   EXPECT_TRUE(mit_davidben_cert->IsIssuedByEncoded(issuers));
904   EXPECT_FALSE(google_cert->IsIssuedByEncoded(issuers));
905 
906   // Check that the Google certificate is issued by Thawte and not
907   // by MIT.
908   issuers.clear();
909   issuers.push_back(thawte_issuer);
910   EXPECT_FALSE(mit_davidben_cert->IsIssuedByEncoded(issuers));
911   EXPECT_TRUE(google_cert->IsIssuedByEncoded(issuers));
912 
913   // Check that they both pass when given a list of the two issuers.
914   issuers.clear();
915   issuers.push_back(mit_issuer);
916   issuers.push_back(thawte_issuer);
917   EXPECT_TRUE(mit_davidben_cert->IsIssuedByEncoded(issuers));
918   EXPECT_TRUE(google_cert->IsIssuedByEncoded(issuers));
919 }
920 
TEST(X509CertificateTest,IsSelfSigned)921 TEST(X509CertificateTest, IsSelfSigned) {
922   base::FilePath certs_dir = GetTestCertsDirectory();
923 
924   scoped_refptr<X509Certificate> cert(
925       ImportCertFromFile(certs_dir, "mit.davidben.der"));
926   ASSERT_NE(static_cast<X509Certificate*>(nullptr), cert.get());
927   EXPECT_FALSE(X509Certificate::IsSelfSigned(cert->cert_buffer()));
928 
929   scoped_refptr<X509Certificate> self_signed(
930       ImportCertFromFile(certs_dir, "aia-root.pem"));
931   ASSERT_NE(static_cast<X509Certificate*>(nullptr), self_signed.get());
932   EXPECT_TRUE(X509Certificate::IsSelfSigned(self_signed->cert_buffer()));
933 
934   scoped_refptr<X509Certificate> bad_name(
935       ImportCertFromFile(certs_dir, "self-signed-invalid-name.pem"));
936   ASSERT_NE(static_cast<X509Certificate*>(nullptr), bad_name.get());
937   EXPECT_FALSE(X509Certificate::IsSelfSigned(bad_name->cert_buffer()));
938 
939   scoped_refptr<X509Certificate> bad_sig(
940       ImportCertFromFile(certs_dir, "self-signed-invalid-sig.pem"));
941   ASSERT_NE(static_cast<X509Certificate*>(nullptr), bad_sig.get());
942   EXPECT_FALSE(X509Certificate::IsSelfSigned(bad_sig->cert_buffer()));
943 }
944 
TEST(X509CertificateTest,IsIssuedByEncodedWithIntermediates)945 TEST(X509CertificateTest, IsIssuedByEncodedWithIntermediates) {
946   static const unsigned char kPolicyRootDN[] = {
947     0x30, 0x1e, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c,
948     0x13, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x20, 0x54, 0x65, 0x73, 0x74,
949     0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41
950   };
951   static const unsigned char kPolicyIntermediateDN[] = {
952     0x30, 0x26, 0x31, 0x24, 0x30, 0x22, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c,
953     0x1b, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x20, 0x54, 0x65, 0x73, 0x74,
954     0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x74,
955     0x65, 0x20, 0x43, 0x41
956   };
957 
958   base::FilePath certs_dir = GetTestCertsDirectory();
959 
960   CertificateList policy_chain = CreateCertificateListFromFile(
961       certs_dir, "explicit-policy-chain.pem", X509Certificate::FORMAT_AUTO);
962   ASSERT_EQ(3u, policy_chain.size());
963 
964   // The intermediate CA certificate's policyConstraints extension has a
965   // requireExplicitPolicy field with SkipCerts=0.
966   std::string policy_intermediate_dn(
967       reinterpret_cast<const char*>(kPolicyIntermediateDN),
968       sizeof(kPolicyIntermediateDN));
969   std::string policy_root_dn(reinterpret_cast<const char*>(kPolicyRootDN),
970                              sizeof(kPolicyRootDN));
971 
972   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
973   intermediates.push_back(bssl::UpRef(policy_chain[1]->cert_buffer()));
974   scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromBuffer(
975       bssl::UpRef(policy_chain[0]->cert_buffer()), std::move(intermediates));
976   ASSERT_TRUE(cert_chain);
977 
978   std::vector<std::string> issuers;
979 
980   // Check that the chain is issued by the intermediate.
981   issuers.clear();
982   issuers.push_back(policy_intermediate_dn);
983   EXPECT_TRUE(cert_chain->IsIssuedByEncoded(issuers));
984 
985   // Check that the chain is also issued by the root.
986   issuers.clear();
987   issuers.push_back(policy_root_dn);
988   EXPECT_TRUE(cert_chain->IsIssuedByEncoded(issuers));
989 
990   // Check that the chain is issued by either the intermediate or the root.
991   issuers.clear();
992   issuers.push_back(policy_intermediate_dn);
993   issuers.push_back(policy_root_dn);
994   EXPECT_TRUE(cert_chain->IsIssuedByEncoded(issuers));
995 
996   // Check that an empty issuers list returns false.
997   issuers.clear();
998   EXPECT_FALSE(cert_chain->IsIssuedByEncoded(issuers));
999 
1000   // Check that the chain is not issued by Verisign
1001   std::string mit_issuer(reinterpret_cast<const char*>(VerisignDN),
1002                          sizeof(VerisignDN));
1003   issuers.clear();
1004   issuers.push_back(mit_issuer);
1005   EXPECT_FALSE(cert_chain->IsIssuedByEncoded(issuers));
1006 }
1007 
1008 const struct CertificateFormatTestData {
1009   const char* file_name;
1010   X509Certificate::Format format;
1011   SHA256HashValue* chain_fingerprints[3];
1012 } kFormatTestData[] = {
1013     // DER Parsing - single certificate, DER encoded
1014     {"google.single.der",
1015      X509Certificate::FORMAT_SINGLE_CERTIFICATE,
1016      {
1017          &google_parse_fingerprint,
1018          nullptr,
1019      }},
1020     // DER parsing - single certificate, PEM encoded
1021     {"google.single.pem",
1022      X509Certificate::FORMAT_SINGLE_CERTIFICATE,
1023      {
1024          &google_parse_fingerprint,
1025          nullptr,
1026      }},
1027     // PEM parsing - single certificate, PEM encoded with a PEB of
1028     // "CERTIFICATE"
1029     {"google.single.pem",
1030      X509Certificate::FORMAT_PEM_CERT_SEQUENCE,
1031      {
1032          &google_parse_fingerprint,
1033          nullptr,
1034      }},
1035     // PEM parsing - sequence of certificates, PEM encoded with a PEB of
1036     // "CERTIFICATE"
1037     {"google.chain.pem",
1038      X509Certificate::FORMAT_PEM_CERT_SEQUENCE,
1039      {
1040          &google_parse_fingerprint,
1041          &thawte_parse_fingerprint,
1042          nullptr,
1043      }},
1044     // PKCS#7 parsing - "degenerate" SignedData collection of certificates, DER
1045     // encoding
1046     {"google.binary.p7b",
1047      X509Certificate::FORMAT_PKCS7,
1048      {
1049          &google_parse_fingerprint,
1050          &thawte_parse_fingerprint,
1051          nullptr,
1052      }},
1053     // PKCS#7 parsing - "degenerate" SignedData collection of certificates, PEM
1054     // encoded with a PEM PEB of "CERTIFICATE"
1055     {"google.pem_cert.p7b",
1056      X509Certificate::FORMAT_PKCS7,
1057      {
1058          &google_parse_fingerprint,
1059          &thawte_parse_fingerprint,
1060          nullptr,
1061      }},
1062     // PKCS#7 parsing - "degenerate" SignedData collection of certificates, PEM
1063     // encoded with a PEM PEB of "PKCS7"
1064     {"google.pem_pkcs7.p7b",
1065      X509Certificate::FORMAT_PKCS7,
1066      {
1067          &google_parse_fingerprint,
1068          &thawte_parse_fingerprint,
1069          nullptr,
1070      }},
1071     // All of the above, this time using auto-detection
1072     {"google.single.der",
1073      X509Certificate::FORMAT_AUTO,
1074      {
1075          &google_parse_fingerprint,
1076          nullptr,
1077      }},
1078     {"google.single.pem",
1079      X509Certificate::FORMAT_AUTO,
1080      {
1081          &google_parse_fingerprint,
1082          nullptr,
1083      }},
1084     {"google.chain.pem",
1085      X509Certificate::FORMAT_AUTO,
1086      {
1087          &google_parse_fingerprint,
1088          &thawte_parse_fingerprint,
1089          nullptr,
1090      }},
1091     {"google.binary.p7b",
1092      X509Certificate::FORMAT_AUTO,
1093      {
1094          &google_parse_fingerprint,
1095          &thawte_parse_fingerprint,
1096          nullptr,
1097      }},
1098     {"google.pem_cert.p7b",
1099      X509Certificate::FORMAT_AUTO,
1100      {
1101          &google_parse_fingerprint,
1102          &thawte_parse_fingerprint,
1103          nullptr,
1104      }},
1105     {"google.pem_pkcs7.p7b",
1106      X509Certificate::FORMAT_AUTO,
1107      {
1108          &google_parse_fingerprint,
1109          &thawte_parse_fingerprint,
1110          nullptr,
1111      }},
1112 };
1113 
1114 class X509CertificateParseTest
1115     : public testing::TestWithParam<CertificateFormatTestData> {
1116  public:
1117   virtual ~X509CertificateParseTest() = default;
SetUp()1118   void SetUp() override { test_data_ = GetParam(); }
TearDown()1119   void TearDown() override {}
1120 
1121  protected:
1122   CertificateFormatTestData test_data_;
1123 };
1124 
TEST_P(X509CertificateParseTest,CanParseFormat)1125 TEST_P(X509CertificateParseTest, CanParseFormat) {
1126   base::FilePath certs_dir = GetTestCertsDirectory();
1127   CertificateList certs = CreateCertificateListFromFile(
1128       certs_dir, test_data_.file_name, test_data_.format);
1129   ASSERT_FALSE(certs.empty());
1130   ASSERT_LE(certs.size(), base::size(test_data_.chain_fingerprints));
1131   CheckGoogleCert(certs.front(), google_parse_fingerprint,
1132                   kGoogleParseValidFrom, kGoogleParseValidTo);
1133 
1134   for (size_t i = 0; i < base::size(test_data_.chain_fingerprints); ++i) {
1135     if (!test_data_.chain_fingerprints[i]) {
1136       // No more test certificates expected - make sure no more were
1137       // returned before marking this test a success.
1138       EXPECT_EQ(i, certs.size());
1139       break;
1140     }
1141 
1142     // A cert is expected - make sure that one was parsed.
1143     ASSERT_LT(i, certs.size());
1144     ASSERT_TRUE(certs[i]);
1145 
1146     // Compare the parsed certificate with the expected certificate, by
1147     // comparing fingerprints.
1148     EXPECT_EQ(
1149         *test_data_.chain_fingerprints[i],
1150         X509Certificate::CalculateFingerprint256(certs[i]->cert_buffer()));
1151   }
1152 }
1153 
1154 INSTANTIATE_TEST_SUITE_P(All,
1155                          X509CertificateParseTest,
1156                          testing::ValuesIn(kFormatTestData));
1157 
1158 struct CertificateNameVerifyTestData {
1159   // true iff we expect hostname to match an entry in cert_names.
1160   bool expected;
1161   // The hostname to match.
1162   const char* hostname;
1163   // Comma separated list of certificate names to match against. Any occurrence
1164   // of '#' will be replaced with a null character before processing.
1165   const char* dns_names;
1166   // Comma separated list of certificate IP Addresses to match against. Each
1167   // address is x prefixed 16 byte hex code for v6 or dotted-decimals for v4.
1168   const char* ip_addrs;
1169 };
1170 
1171 // GTest 'magic' pretty-printer, so that if/when a test fails, it knows how
1172 // to output the parameter that was passed. Without this, it will simply
1173 // attempt to print out the first twenty bytes of the object, which depending
1174 // on platform and alignment, may result in an invalid read.
PrintTo(const CertificateNameVerifyTestData & data,std::ostream * os)1175 void PrintTo(const CertificateNameVerifyTestData& data, std::ostream* os) {
1176   ASSERT_TRUE(data.hostname);
1177   ASSERT_TRUE(data.dns_names || data.ip_addrs);
1178   // Using StringPiece to allow for optional fields being NULL.
1179   *os << " expected: " << data.expected << "; hostname: " << data.hostname
1180       << "; dns_names: " << base::StringPiece(data.dns_names)
1181       << "; ip_addrs: " << base::StringPiece(data.ip_addrs);
1182 }
1183 
1184 const CertificateNameVerifyTestData kNameVerifyTestData[] = {
1185     {true, "foo.com", "foo.com"},
1186     {true, "f", "f"},
1187     {false, "h", "i"},
1188     {true, "bar.foo.com", "*.foo.com"},
1189     {true, "www.test.fr", "*.test.com,*.test.co.uk,*.test.de,*.test.fr"},
1190     {true, "wwW.tESt.fr", ",*.*,*.test.de,*.test.FR,www"},
1191     {false, "f.uk", ".uk"},
1192     {false, "w.bar.foo.com", "?.bar.foo.com"},
1193     {false, "www.foo.com", "(www|ftp).foo.com"},
1194     {false, "www.foo.com", "www.foo.com#"},  // # = null char.
1195     {false, "www.foo.com", "www.foo.com#*.foo.com,#,#"},
1196     {false, "www.house.example", "ww.house.example"},
1197     {false, "test.org", "www.test.org,*.test.org,*.org"},
1198     {false, "w.bar.foo.com", "w*.bar.foo.com"},
1199     {false, "www.bar.foo.com", "ww*ww.bar.foo.com"},
1200     {false, "wwww.bar.foo.com", "ww*ww.bar.foo.com"},
1201     {false, "wwww.bar.foo.com", "w*w.bar.foo.com"},
1202     {false, "wwww.bar.foo.com", "w*w.bar.foo.c0m"},
1203     {false, "WALLY.bar.foo.com", "wa*.bar.foo.com"},
1204     {false, "wally.bar.foo.com", "*Ly.bar.foo.com"},
1205     // Hostname escaping tests
1206     {true, "ww%57.foo.com", "www.foo.com"},
1207     {true, "www%2Efoo.com", "www.foo.com"},
1208     {false, "www%00.foo.com", "www,foo.com,www.foo.com"},
1209     {false, "www%0D.foo.com", "www.foo.com,www\r.foo.com"},
1210     {false, "www%40foo.com", "www@foo.com"},
1211     {false, "www%2E%2Efoo.com", "www.foo.com,www..foo.com"},
1212     {false, "www%252Efoo.com", "www.foo.com"},
1213     // IDN tests
1214     {true, "xn--poema-9qae5a.com.br", "xn--poema-9qae5a.com.br"},
1215     {true, "www.xn--poema-9qae5a.com.br", "*.xn--poema-9qae5a.com.br"},
1216     {false, "xn--poema-9qae5a.com.br",
1217      "*.xn--poema-9qae5a.com.br,"
1218      "xn--poema-*.com.br,"
1219      "xn--*-9qae5a.com.br,"
1220      "*--poema-9qae5a.com.br"},
1221     // The following are adapted from the  examples quoted from
1222     // http://tools.ietf.org/html/rfc6125#section-6.4.3
1223     //  (e.g., *.example.com would match foo.example.com but
1224     //   not bar.foo.example.com or example.com).
1225     {true, "foo.example.com", "*.example.com"},
1226     {false, "bar.foo.example.com", "*.example.com"},
1227     {false, "example.com", "*.example.com"},
1228     //   Partial wildcards are disallowed, though RFC 2818 rules allow them.
1229     //   That is, forms such as baz*.example.net, *baz.example.net, and
1230     //   b*z.example.net should NOT match domains. Instead, the wildcard must
1231     //   always be the left-most label, and only a single label.
1232     {false, "baz1.example.net", "baz*.example.net"},
1233     {false, "foobaz.example.net", "*baz.example.net"},
1234     {false, "buzz.example.net", "b*z.example.net"},
1235     {false, "www.test.example.net", "www.*.example.net"},
1236     // Wildcards should not be valid for public registry controlled domains,
1237     // and unknown/unrecognized domains, at least three domain components must
1238     // be present.
1239     {true, "www.test.example", "*.test.example"},
1240     {true, "test.example.co.uk", "*.example.co.uk"},
1241     {false, "test.example", "*.example"},
1242     {false, "example.co.uk", "*.co.uk"},
1243     {false, "foo.com", "*.com"},
1244     {false, "foo.us", "*.us"},
1245     {false, "foo", "*"},
1246     // IDN variants of wildcards and registry controlled domains.
1247     {true, "www.xn--poema-9qae5a.com.br", "*.xn--poema-9qae5a.com.br"},
1248     {true, "test.example.xn--mgbaam7a8h", "*.example.xn--mgbaam7a8h"},
1249     {false, "xn--poema-9qae5a.com.br", "*.com.br"},
1250     {false, "example.xn--mgbaam7a8h", "*.xn--mgbaam7a8h"},
1251     // Wildcards should be permissible for 'private' registry controlled
1252     // domains.
1253     {true, "www.appspot.com", "*.appspot.com"},
1254     {true, "foo.s3.amazonaws.com", "*.s3.amazonaws.com"},
1255     // Multiple wildcards are not valid.
1256     {false, "foo.example.com", "*.*.com"},
1257     {false, "foo.bar.example.com", "*.bar.*.com"},
1258     // Absolute vs relative DNS name tests. Although not explicitly specified
1259     // in RFC 6125, absolute reference names (those ending in a .) should
1260     // match either absolute or relative presented names.
1261     {true, "foo.com", "foo.com."},
1262     {true, "foo.com.", "foo.com"},
1263     {true, "foo.com.", "foo.com."},
1264     {true, "f", "f."},
1265     {true, "f.", "f"},
1266     {true, "f.", "f."},
1267     {true, "www-3.bar.foo.com", "*.bar.foo.com."},
1268     {true, "www-3.bar.foo.com.", "*.bar.foo.com"},
1269     {true, "www-3.bar.foo.com.", "*.bar.foo.com."},
1270     {false, ".", "."},
1271     {false, "example.com", "*.com."},
1272     {false, "example.com.", "*.com"},
1273     {false, "example.com.", "*.com."},
1274     {false, "foo.", "*."},
1275     {false, "foo", "*."},
1276     {false, "foo.co.uk", "*.co.uk."},
1277     {false, "foo.co.uk.", "*.co.uk."},
1278     // IP addresses in subject alternative name
1279     {true, "10.1.2.3", "", "10.1.2.3"},
1280     {true, "14.15", "", "14.0.0.15"},
1281     {false, "10.1.2.7", "", "10.1.2.6,10.1.2.8"},
1282     {false, "10.1.2.8", "foo"},
1283     {true, "::4.5.6.7", "", "x00000000000000000000000004050607"},
1284     {false, "::6.7.8.9", "::6.7.8.9",
1285      "x00000000000000000000000006070808,x0000000000000000000000000607080a,"
1286      "xff000000000000000000000006070809,6.7.8.9"},
1287     {true, "FE80::200:f8ff:fe21:67cf", "",
1288      "x00000000000000000000000006070808,xfe800000000000000200f8fffe2167cf,"
1289      "xff0000000000000000000000060708ff,10.0.0.1"},
1290     // Numeric only hostnames (none of these are considered valid IP addresses).
1291     {false, "121.2.3.512", "1*1.2.3.512,*1.2.3.512,1*.2.3.512,*.2.3.512",
1292      "121.2.3.0"},
1293     {false, "1.2.3.4.5.6", "*.2.3.4.5.6"},
1294     {true, "1.2.3.4.5", "1.2.3.4.5"},
1295     // Invalid host names.
1296     {false, ".", ""},
1297     {false, ".", "."},
1298     {false, "1.2.3.4..", "", "1.2.3.4"},
1299     {false, "www..domain.example", "www.domain.example"},
1300     {false, "www^domain.example", "www^domain.example"},
1301     {false, "www%20.domain.example", "www .domain.example"},
1302     {false, "www%2520.domain.example", "www .domain.example"},
1303     {false, "www%5E.domain.example", "www^domain.example"},
1304     {false, "www,domain.example", "www,domain.example"},
1305     {false, "0x000000002200037955161..", "0x000000002200037955161"},
1306     {false, "junk)(£)$*!@~#", "junk)(£)$*!@~#"},
1307     {false, "www.*.com", "www.*.com"},
1308     {false, "w$w.f.com", "w$w.f.com"},
1309     {false, "nocolonallowed:example", "nocolonallowed:example"},
1310     {false, "www-1.[::FFFF:129.144.52.38]", "*.[::FFFF:129.144.52.38]"},
1311     {false, "[::4.5.6.9]", "", "x00000000000000000000000004050609"},
1312 };
1313 
1314 class X509CertificateNameVerifyTest
1315     : public testing::TestWithParam<CertificateNameVerifyTestData> {
1316 };
1317 
TEST_P(X509CertificateNameVerifyTest,VerifyHostname)1318 TEST_P(X509CertificateNameVerifyTest, VerifyHostname) {
1319   CertificateNameVerifyTestData test_data = GetParam();
1320 
1321   std::vector<std::string> dns_names, ip_addressses;
1322   if (test_data.dns_names) {
1323     // Build up the certificate DNS names list.
1324     std::string dns_name_line(test_data.dns_names);
1325     std::replace(dns_name_line.begin(), dns_name_line.end(), '#', '\0');
1326     dns_names = base::SplitString(dns_name_line, ",", base::TRIM_WHITESPACE,
1327                                   base::SPLIT_WANT_ALL);
1328   }
1329 
1330   if (test_data.ip_addrs) {
1331     // Build up the certificate IP address list.
1332     std::string ip_addrs_line(test_data.ip_addrs);
1333     std::vector<std::string> ip_addressses_ascii = base::SplitString(
1334         ip_addrs_line, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1335     for (size_t i = 0; i < ip_addressses_ascii.size(); ++i) {
1336       std::string& addr_ascii = ip_addressses_ascii[i];
1337       ASSERT_NE(0U, addr_ascii.length());
1338       if (addr_ascii[0] == 'x') {  // Hex encoded address
1339         addr_ascii.erase(0, 1);
1340         std::string bytes;
1341         EXPECT_TRUE(base::HexStringToString(addr_ascii, &bytes))
1342             << "Could not parse hex address " << addr_ascii << " i = " << i;
1343         ip_addressses.push_back(std::move(bytes));
1344         ASSERT_EQ(16U, ip_addressses.back().size()) << i;
1345       } else {  // Decimal groups
1346         std::vector<std::string> decimals_ascii = base::SplitString(
1347             addr_ascii, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1348         EXPECT_EQ(4U, decimals_ascii.size()) << i;
1349         std::string addr_bytes;
1350         for (size_t j = 0; j < decimals_ascii.size(); ++j) {
1351           int decimal_value;
1352           EXPECT_TRUE(base::StringToInt(decimals_ascii[j], &decimal_value));
1353           EXPECT_GE(decimal_value, 0);
1354           EXPECT_LE(decimal_value, 255);
1355           addr_bytes.push_back(static_cast<char>(decimal_value));
1356         }
1357         ip_addressses.push_back(addr_bytes);
1358         ASSERT_EQ(4U, ip_addressses.back().size()) << i;
1359       }
1360     }
1361   }
1362 
1363   EXPECT_EQ(test_data.expected,
1364             X509Certificate::VerifyHostname(test_data.hostname, dns_names,
1365                                             ip_addressses));
1366 }
1367 
1368 INSTANTIATE_TEST_SUITE_P(All,
1369                          X509CertificateNameVerifyTest,
1370                          testing::ValuesIn(kNameVerifyTestData));
1371 
1372 const struct PublicKeyInfoTestData {
1373   const char* cert_file;
1374   size_t expected_bits;
1375   X509Certificate::PublicKeyType expected_type;
1376 } kPublicKeyInfoTestData[] = {
1377     {"768-rsa-ee-by-768-rsa-intermediate.pem", 768,
1378      X509Certificate::kPublicKeyTypeRSA},
1379     {"1024-rsa-ee-by-768-rsa-intermediate.pem", 1024,
1380      X509Certificate::kPublicKeyTypeRSA},
1381     {"prime256v1-ecdsa-ee-by-1024-rsa-intermediate.pem", 256,
1382      X509Certificate::kPublicKeyTypeECDSA},
1383     {"large_key.pem", 8200, X509Certificate::kPublicKeyTypeRSA},
1384 };
1385 
1386 class X509CertificatePublicKeyInfoTest
1387     : public testing::TestWithParam<PublicKeyInfoTestData> {
1388 };
1389 
TEST_P(X509CertificatePublicKeyInfoTest,GetPublicKeyInfo)1390 TEST_P(X509CertificatePublicKeyInfoTest, GetPublicKeyInfo) {
1391   PublicKeyInfoTestData data = GetParam();
1392 
1393   scoped_refptr<X509Certificate> cert(
1394       ImportCertFromFile(GetTestCertsDirectory(), data.cert_file));
1395   ASSERT_TRUE(cert.get());
1396 
1397   size_t actual_bits = 0;
1398   X509Certificate::PublicKeyType actual_type =
1399       X509Certificate::kPublicKeyTypeUnknown;
1400 
1401   X509Certificate::GetPublicKeyInfo(cert->cert_buffer(), &actual_bits,
1402                                     &actual_type);
1403 
1404   EXPECT_EQ(data.expected_bits, actual_bits);
1405   EXPECT_EQ(data.expected_type, actual_type);
1406 }
1407 
1408 INSTANTIATE_TEST_SUITE_P(All,
1409                          X509CertificatePublicKeyInfoTest,
1410                          testing::ValuesIn(kPublicKeyInfoTestData));
1411 
1412 }  // namespace net
1413