de4f40fdf23a5914920c25e14e6ab9ccb4df060f
[folly.git] / folly / ssl / test / OpenSSLCertUtilsTest.cpp
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/ssl/OpenSSLCertUtils.h>
17
18 #include <folly/Format.h>
19 #include <folly/Range.h>
20 #include <folly/String.h>
21 #include <folly/container/Enumerate.h>
22 #include <folly/portability/GTest.h>
23 #include <folly/portability/OpenSSL.h>
24 #include <folly/ssl/Init.h>
25 #include <folly/ssl/OpenSSLPtrTypes.h>
26
27 using namespace testing;
28 using namespace folly;
29
30 const char* kTestCertWithoutSan = "folly/io/async/test/certs/tests-cert.pem";
31 const char* kTestCa = "folly/io/async/test/certs/ca-cert.pem";
32
33 // Test key
34 // -----BEGIN EC PRIVATE KEY-----
35 // MHcCAQEEIBskFwVZ9miFN+SKCFZPe9WEuFGmP+fsecLUnsTN6bOcoAoGCCqGSM49
36 // AwEHoUQDQgAE7/f4YYOYunAM/VkmjDYDg3AWUgyyTIraWmmQZsnu0bYNV/lLLfNz
37 // CtHggxGSwEtEe40nNb9C8wQmHUvb7VBBlw==
38 // -----END EC PRIVATE KEY-----
39 const std::string kTestCertWithSan = folly::stripLeftMargin(R"(
40   -----BEGIN CERTIFICATE-----
41   MIIDXDCCAkSgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBQMQswCQYDVQQGEwJVUzEL
42   MAkGA1UECAwCQ0ExDTALBgNVBAoMBEFzb3gxJTAjBgNVBAMMHEFzb3ggQ2VydGlm
43   aWNhdGlvbiBBdXRob3JpdHkwHhcNMTcwMjEzMjMyMTAzWhcNNDQwNzAxMjMyMTAz
44   WjAwMQswCQYDVQQGEwJVUzENMAsGA1UECgwEQXNveDESMBAGA1UEAwwJMTI3LjAu
45   MC4xMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7/f4YYOYunAM/VkmjDYDg3AW
46   UgyyTIraWmmQZsnu0bYNV/lLLfNzCtHggxGSwEtEe40nNb9C8wQmHUvb7VBBl6OC
47   ASowggEmMAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJh
48   dGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRx1kmdZEfXHmWLHpSDI0Lh8hmfwzAf
49   BgNVHSMEGDAWgBQX3ykJKb97nxp/6UZJyDvts7noezAxBgNVHREEKjAoghJhbm90
50   aGVyZXhhbXBsZS5jb22CEioudGhpcmRleGFtcGxlLmNvbTB4BggrBgEFBQcBAQRs
51   MGowaAYIKwYBBQUHMAKGXGh0dHBzOi8vcGhhYnJpY2F0b3IuZmIuY29tL2RpZmZ1
52   c2lvbi9GQkNPREUvYnJvd3NlL21hc3Rlci90aS90ZXN0X2NlcnRzL2NhX2NlcnQu
53   cGVtP3ZpZXc9cmF3MA0GCSqGSIb3DQEBCwUAA4IBAQCj3FLjLMLudaFDiYo9pAPQ
54   NBYNpG27aajQCvnEsYaMAGnNBxUUhv/E4xpnJEhatiCJWlPgGebdjXkpXYkLxnFj
55   38UmpfZbNcvPPKxXmjIlkpYeFwcHTAUpFmMXVHdr8FjkDSN+qWHLllMFNAAqp0U6
56   4VWjDlq9xCjzNw+8fdcEpwylpPrbNyQHqSO1k+DhM2qPuQfiWPmHe2PbJv8JB3no
57   HWGi9SNe0FjtJM3066L0Gj8g/bFDo/pnyKguQyGkS7PaepK5/u5Y2fMMBO/m4+U0
58   b9Yb0TvatsqL688CoZcSn73A0yAjptwbD/4HmcVlG2j/y8eTVpXisugu6Xz+QQGu
59   -----END CERTIFICATE-----
60 )");
61
62 const std::string kTestCertBundle = folly::stripLeftMargin(R"(
63   -----BEGIN CERTIFICATE-----
64   MIIDgzCCAmugAwIBAgIJAIkcS3PQcCm+MA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNV
65   BAYTAlhYMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0RlZmF1bHQg
66   Q29tcGFueSBMdGQxFDASBgNVBAMMC3Rlc3QgY2VydCAxMB4XDTE3MTAyMzIwNTcw
67   M1oXDTE4MTAyMzIwNTcwM1owWDELMAkGA1UEBhMCWFgxFTATBgNVBAcMDERlZmF1
68   bHQgQ2l0eTEcMBoGA1UECgwTRGVmYXVsdCBDb21wYW55IEx0ZDEUMBIGA1UEAwwL
69   dGVzdCBjZXJ0IDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCplTzR
70   6shdhVNbx5HFViiYDBjRYXCWiUeR0/0+XPkyI+DPIGAQ6Mre8WD03GPebYn7j3Lr
71   JwgV06BJNvVCLDy0SJbf6ToxGfKWSLEWOoip32nIpb9qxURtx44NUvhChP54hhKI
72   zAf8nNlS+qKUYbmixJHeUWO//8wNpsMKDkvtfVUZ6oVV3JPOOihJ+sQ0sIc5x+xk
73   3eWfa0cNoZnxu4plQg2O4RlHOv8ruMW6BttpcqQ8I+Rxq+/YOhNQhX+6GZ1+Rs+f
74   ddWXYNH6tFxsLIEbgCqHhLGw7g+JRms9R+CxLCpjmhYhR2xgl6KQu/Racr2T/17z
75   897VfY7X94PmamidAgMBAAGjUDBOMB0GA1UdDgQWBBRHQvRr2p3/83y1yXiiVnnS
76   zObpzTAfBgNVHSMEGDAWgBRHQvRr2p3/83y1yXiiVnnSzObpzTAMBgNVHRMEBTAD
77   AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAk61K1sjrS7rrLnGND1o1Q6D2ebgb1wcfU
78   WX+ZnhlkUxjSS1nHmaulMftpvzbgrOt7HWZKMXIpetnDSfksrGpw6QJ3VWFIJlH5
79   P4x8//p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BOMB0GA1UdDgQWBBQkmeMfPQaax9wCZL16jSSG
97   XigBWjAfBgNVHSMEGDAWgBQkmeMfPQaax9wCZL16jSSGXigBWjAMBgNVHRMEBTAD
98   AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCXzqxYp1FqMS2M+opCSPezgPDBdE2S9g6d
99   HJHV5CLptGnu1vQIlyCXy/7X9b6Qq8UzuYyFacN/37tbNw6sGyTRfL8sEeFYfFoT
100   GvgSrRqSM47ZBYx5jW/Uslkc5qbq+v4zeGCq5611stQKsJYIudu0+PjJmgtNF6en
101   zTx8B6eS79GRN3/M7/kFLlxeZNCQpmKwvPp8P7JE4ZHUtuzQoKtjdt/etWpS76fV
102   Akx7VhCFg/lw80tmgSclq885hYRYc6DOKfUubWOacKVfmHwL4oDiSffBonI7MoH8
103   SJbzsCBpVd/tkDADZpxBQplGV7AaDBoNS0qvZHfH5x9R9R5lx9M+
104   -----END CERTIFICATE-----
105   -----BEGIN CERTIFICATE-----
106   MIIDgzCCAmugAwIBAgIJAOzqPJDDfSKDMA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNV
107   BAYTAlhYMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0RlZmF1bHQg
108   Q29tcGFueSBMdGQxFDASBgNVBAMMC3Rlc3QgY2VydCAzMB4XDTE3MTAyMzIwNTcy
109   NVoXDTE4MTAyMzIwNTcyNVowWDELMAkGA1UEBhMCWFgxFTATBgNVBAcMDERlZmF1
110   bHQgQ2l0eTEcMBoGA1UECgwTRGVmYXVsdCBDb21wYW55IEx0ZDEUMBIGA1UEAwwL
111   dGVzdCBjZXJ0IDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDWqU2b
112   eBzaOAja6od84hFfgvitOGrCYqLXMUXe0X7AlldzXV4zHaVyTKdEwDwvKDi5p9OF
113   uTxSZkZ0JSPHZeH2/rHXidNMWdtiy5x/5ra1u9ctN7jHeboIxmdpfxoGq7s6cRA5
114   oRh0bCNmw+Y7K+1RITmPloB7155RbrJYZR5MOFIaCnZV3j/icKjASTOg3ivXX4lx
115   BoHGMYF8rl+51FIJsuXvnBgF+GhadMVSWl4Qy6gLliml1MgujlmFg9/1y/xzdWZg
116   yyLI3tvw7fo/NN62u41VQBdCGdpvnVxU4ADu2/T0vhAS+Bh2CMK1OAAw61x1507S
117   f68mab9s8at49qefAgMBAAGjUDBOMB0GA1UdDgQWBBQnn76Swsnld6Q1weLgpo/S
118   tt0KeTAfBgNVHSMEGDAWgBQnn76Swsnld6Q1weLgpo/Stt0KeTAMBgNVHRMEBTAD
119   AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCB0XANIWyP7DYROh6MFQLqeylngd9iUGNe
120   BMT4pWu60p5ZX13kK/gbV/P2cayUkkWEMWpzKcIX70IkaB5y/OxVMXUXo94UupsM
121   b1T736wHA0TLeL7yDj9OnMYj/qa2r8pAyEObI84KoWRGMHH9UPSRbVMVrhg/agBA
122   LA6eZhwiGctkCy09kp+SFbUpv+SMyVp60UrPub6j68Hzd0FioGY01Os7nScuPNo0
123   rl2S+G36bcem8Z5MOkJ0LEFi6ctK9JdLcHkr1SVavo3fsYZaIZraJxFGcYUVyLT+
124   Rw7ydBokxHWsmVJczuRmEovXcTmgIphti234e7usKjw8M5mGwYfa
125   -----END CERTIFICATE-----
126 )");
127
128 class OpenSSLCertUtilsTest : public Test {
129  public:
130   void SetUp() override {
131     folly::ssl::init();
132   }
133 };
134
135 static folly::ssl::X509UniquePtr readCertFromFile(const std::string& filename) {
136   folly::ssl::BioUniquePtr bio(BIO_new(BIO_s_file()));
137   if (!bio) {
138     throw std::runtime_error("Couldn't create BIO");
139   }
140
141   if (BIO_read_filename(bio.get(), filename.c_str()) != 1) {
142     throw std::runtime_error("Couldn't read cert file: " + filename);
143   }
144   return folly::ssl::X509UniquePtr(
145       PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
146 }
147
148 static folly::ssl::X509UniquePtr readCertFromData(
149     const folly::StringPiece data) {
150   folly::ssl::BioUniquePtr bio(BIO_new_mem_buf(data.data(), data.size()));
151   if (!bio) {
152     throw std::runtime_error("Couldn't create BIO");
153   }
154   return folly::ssl::X509UniquePtr(
155       PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
156 }
157
158 TEST_F(OpenSSLCertUtilsTest, TestX509CN) {
159   auto x509 = readCertFromFile(kTestCertWithoutSan);
160   EXPECT_NE(x509, nullptr);
161   auto identity = folly::ssl::OpenSSLCertUtils::getCommonName(*x509);
162   EXPECT_EQ(identity.value(), "Asox Company");
163   auto sans = folly::ssl::OpenSSLCertUtils::getSubjectAltNames(*x509);
164   EXPECT_EQ(sans.size(), 0);
165 }
166
167 TEST_F(OpenSSLCertUtilsTest, TestX509Sans) {
168   auto x509 = readCertFromData(kTestCertWithSan);
169   EXPECT_NE(x509, nullptr);
170   auto identity = folly::ssl::OpenSSLCertUtils::getCommonName(*x509);
171   EXPECT_EQ(identity.value(), "127.0.0.1");
172   auto altNames = folly::ssl::OpenSSLCertUtils::getSubjectAltNames(*x509);
173   EXPECT_EQ(altNames.size(), 2);
174   EXPECT_EQ(altNames[0], "anotherexample.com");
175   EXPECT_EQ(altNames[1], "*.thirdexample.com");
176 }
177
178 TEST_F(OpenSSLCertUtilsTest, TestX509IssuerAndSubject) {
179   auto x509 = readCertFromData(kTestCertWithSan);
180   EXPECT_NE(x509, nullptr);
181   auto issuer = folly::ssl::OpenSSLCertUtils::getIssuer(*x509);
182   EXPECT_EQ(
183       issuer.value(),
184       "C = US, ST = CA, O = Asox, CN = Asox Certification Authority");
185   auto subj = folly::ssl::OpenSSLCertUtils::getSubject(*x509);
186   EXPECT_EQ(subj.value(), "C = US, O = Asox, CN = 127.0.0.1");
187 }
188
189 TEST_F(OpenSSLCertUtilsTest, TestX509Dates) {
190   auto x509 = readCertFromData(kTestCertWithSan);
191   EXPECT_NE(x509, nullptr);
192   auto notBefore = folly::ssl::OpenSSLCertUtils::getNotBeforeTime(*x509);
193   EXPECT_EQ(notBefore, "Feb 13 23:21:03 2017 GMT");
194   auto notAfter = folly::ssl::OpenSSLCertUtils::getNotAfterTime(*x509);
195   EXPECT_EQ(notAfter, "Jul  1 23:21:03 2044 GMT");
196 }
197
198 TEST_F(OpenSSLCertUtilsTest, TestX509Summary) {
199   auto x509 = readCertFromData(kTestCertWithSan);
200   EXPECT_NE(x509, nullptr);
201   auto summary = folly::ssl::OpenSSLCertUtils::toString(*x509);
202   EXPECT_EQ(
203       summary.value(),
204       "        Version: 3 (0x2)\n        Serial Number: 2 (0x2)\n"
205       "        Issuer: C = US, ST = CA, O = Asox, CN = Asox Certification Authority\n"
206       "        Validity\n            Not Before: Feb 13 23:21:03 2017 GMT\n"
207       "            Not After : Jul  1 23:21:03 2044 GMT\n"
208       "        Subject: C = US, O = Asox, CN = 127.0.0.1\n"
209       "        X509v3 extensions:\n"
210       "            X509v3 Basic Constraints: \n"
211       "                CA:FALSE\n"
212       "            Netscape Comment: \n"
213       "                OpenSSL Generated Certificate\n"
214       "            X509v3 Subject Key Identifier: \n"
215       "                71:D6:49:9D:64:47:D7:1E:65:8B:1E:94:83:23:42:E1:F2:19:9F:C3\n"
216       "            X509v3 Authority Key Identifier: \n"
217       "                keyid:17:DF:29:09:29:BF:7B:9F:1A:7F:E9:46:49:C8:3B:ED:B3:B9:E8:7B\n\n"
218       "            X509v3 Subject Alternative Name: \n"
219       "                DNS:anotherexample.com, DNS:*.thirdexample.com\n"
220       "            Authority Information Access: \n"
221       "                CA Issuers - URI:https://phabricator.fb.com/diffusion/FBCODE/browse/master/ti/test_certs/ca_cert.pem?view=raw\n\n");
222 }
223
224 TEST_F(OpenSSLCertUtilsTest, TestDerEncodeDecode) {
225   auto x509 = readCertFromData(kTestCertWithSan);
226
227   auto der = folly::ssl::OpenSSLCertUtils::derEncode(*x509);
228   auto decoded = folly::ssl::OpenSSLCertUtils::derDecode(der->coalesce());
229
230   EXPECT_EQ(
231       folly::ssl::OpenSSLCertUtils::toString(*x509),
232       folly::ssl::OpenSSLCertUtils::toString(*decoded));
233 }
234
235 TEST_F(OpenSSLCertUtilsTest, TestDerDecodeJunkData) {
236   StringPiece junk{"MyFakeCertificate"};
237   EXPECT_THROW(
238       folly::ssl::OpenSSLCertUtils::derDecode(junk), std::runtime_error);
239 }
240
241 TEST_F(OpenSSLCertUtilsTest, TestDerDecodeTooShort) {
242   auto x509 = readCertFromData(kTestCertWithSan);
243
244   auto der = folly::ssl::OpenSSLCertUtils::derEncode(*x509);
245   der->trimEnd(1);
246   EXPECT_THROW(
247       folly::ssl::OpenSSLCertUtils::derDecode(der->coalesce()),
248       std::runtime_error);
249 }
250
251 TEST_F(OpenSSLCertUtilsTest, TestReadCertsFromBuffer) {
252   auto certs = folly::ssl::OpenSSLCertUtils::readCertsFromBuffer(
253       StringPiece(kTestCertBundle));
254   EXPECT_EQ(certs.size(), 3);
255   for (auto i : folly::enumerate(certs)) {
256     auto identity = folly::ssl::OpenSSLCertUtils::getCommonName(**i);
257     EXPECT_TRUE(identity);
258     EXPECT_EQ(*identity, folly::sformat("test cert {}", i.index + 1));
259   }
260 }
261
262 TEST_F(OpenSSLCertUtilsTest, TestX509Digest) {
263   auto x509 = readCertFromFile(kTestCertWithoutSan);
264   EXPECT_NE(x509, nullptr);
265
266   auto sha1Digest = folly::ssl::OpenSSLCertUtils::getDigestSha1(*x509);
267   EXPECT_EQ(
268       folly::hexlify(folly::range(sha1Digest)),
269       "b84e951d6c4e6cc70346357fab43d7ed73a07b0f");
270
271   auto sha2Digest = folly::ssl::OpenSSLCertUtils::getDigestSha256(*x509);
272   EXPECT_EQ(
273       folly::hexlify(folly::range(sha2Digest)),
274       "364d3a6a0b10d0635ce59b40c0b7f505ab2cd9fd0a06661cdc61d9cb8c9c9821");
275 }
276
277 TEST_F(OpenSSLCertUtilsTest, TestX509Store) {
278   auto store = folly::ssl::OpenSSLCertUtils::readStoreFromFile(kTestCa);
279   EXPECT_NE(store, nullptr);
280
281   auto x509 = readCertFromFile(kTestCertWithoutSan);
282   folly::ssl::X509StoreCtxUniquePtr ctx(X509_STORE_CTX_new());
283   auto rc = X509_STORE_CTX_init(ctx.get(), store.get(), x509.get(), nullptr);
284   EXPECT_EQ(rc, 1);
285   rc = X509_verify_cert(ctx.get());
286   EXPECT_EQ(rc, 1);
287 }