1 //
2 // Copyright 2022 gRPC authors.
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
17 #include "src/core/tsi/ssl_transport_security_utils.h"
18
19 #include <array>
20 #include <string>
21 #include <vector>
22
23 #include <gmock/gmock.h>
24 #include <gtest/gtest.h>
25 #include <openssl/bio.h>
26 #include <openssl/crypto.h>
27 #include <openssl/ssl.h>
28 #include <openssl/x509.h>
29
30 #include "absl/status/status.h"
31 #include "absl/status/statusor.h"
32 #include "absl/strings/match.h"
33 #include "absl/strings/str_cat.h"
34 #include "absl/strings/string_view.h"
35
36 #include "src/core/lib/gprpp/load_file.h"
37 #include "src/core/lib/slice/slice.h"
38 #include "src/core/tsi/transport_security.h"
39 #include "src/core/tsi/transport_security_interface.h"
40 #include "test/core/tsi/transport_security_test_lib.h"
41 #include "test/core/util/test_config.h"
42
43 namespace grpc_core {
44 namespace testing {
45
46 const char* kValidCrl = "test/core/tsi/test_creds/crl_data/crls/current.crl";
47 const char* kCrlIssuer = "test/core/tsi/test_creds/crl_data/ca.pem";
48 const char* kModifiedSignature =
49 "test/core/tsi/test_creds/crl_data/bad_crls/invalid_signature.crl";
50 const char* kModifiedContent =
51 "test/core/tsi/test_creds/crl_data/bad_crls/invalid_content.crl";
52 const char* kIntermediateCrl =
53 "test/core/tsi/test_creds/crl_data/crls/intermediate.crl";
54 const char* kIntermediateCrlIssuer =
55 "test/core/tsi/test_creds/crl_data/intermediate_ca.pem";
56 const char* kLeafCert =
57 "test/core/tsi/test_creds/crl_data/leaf_signed_by_intermediate.pem";
58 const char* kEvilCa = "test/core/tsi/test_creds/crl_data/evil_ca.pem";
59 const char* kCaWithAkid = "test/core/tsi/test_creds/crl_data/ca_with_akid.pem";
60 const char* kCrlWithAkid =
61 "test/core/tsi/test_creds/crl_data/crl_with_akid.crl";
62
63 using ::testing::ContainerEq;
64 using ::testing::NotNull;
65 using ::testing::TestWithParam;
66 using ::testing::ValuesIn;
67
68 constexpr std::size_t kMaxPlaintextBytesPerTlsRecord = 16384;
69 constexpr std::size_t kTlsRecordOverhead = 100;
70 constexpr std::array<std::size_t, 4> kTestPlainTextSizeArray = {
71 1, 1000, kMaxPlaintextBytesPerTlsRecord,
72 kMaxPlaintextBytesPerTlsRecord + 1000};
73
74 struct FrameProtectorUtilTestData {
75 std::size_t plaintext_size;
76 std::size_t expected_encrypted_bytes_size;
77 };
78
79 // Generates the testing data |FrameProtectorUtilTestData|.
GenerateTestData()80 std::vector<FrameProtectorUtilTestData> GenerateTestData() {
81 std::vector<FrameProtectorUtilTestData> data;
82 for (std::size_t plaintext_size : kTestPlainTextSizeArray) {
83 std::size_t expected_size = plaintext_size + kTlsRecordOverhead;
84 if (plaintext_size > kMaxPlaintextBytesPerTlsRecord) {
85 expected_size = kMaxPlaintextBytesPerTlsRecord + kTlsRecordOverhead;
86 }
87 data.push_back({plaintext_size, expected_size});
88 }
89 return data;
90 }
91
92 // TODO(gtcooke94) - Tests current failing with OpenSSL 1.1.1 and 3.0. Fix and
93 // re-enable.
94 #ifdef OPENSSL_IS_BORINGSSL
95 class FlowTest : public TestWithParam<FrameProtectorUtilTestData> {
96 protected:
SetUpTestSuite()97 static void SetUpTestSuite() {
98 #if OPENSSL_VERSION_NUMBER >= 0x10100000
99 OPENSSL_init_ssl(/*opts=*/0, /*settings=*/nullptr);
100 #else
101 SSL_library_init();
102 SSL_load_error_strings();
103 OpenSSL_add_all_algorithms();
104 #endif
105 }
106
107 // Used for debugging.
VerifySucceed(X509_STORE_CTX *,void *)108 static int VerifySucceed(X509_STORE_CTX* /*store_ctx*/, void* /*arg*/) {
109 return 1;
110 }
111
112 // Drives two SSL objects to finish a complete handshake with the hard-coded
113 // credentials and outputs those two SSL objects to `out_client` and
114 // `out_server` respectively.
DoHandshake(SSL ** out_client,SSL ** out_server)115 static absl::Status DoHandshake(SSL** out_client, SSL** out_server) {
116 if (out_client == nullptr || out_server == nullptr) {
117 return absl::InvalidArgumentError(
118 "Client and server SSL object must not be null.");
119 }
120 std::string cert_pem =
121 "-----BEGIN CERTIFICATE-----\n"
122 "MIICZzCCAdCgAwIBAgIIN18/ctj3wpAwDQYJKoZIhvcNAQELBQAwKjEXMBUGA1UE\n"
123 "ChMOR29vZ2xlIFRFU1RJTkcxDzANBgNVBAMTBnRlc3RDQTAeFw0xNTAxMDEwMDAw\n"
124 "MDBaFw0yNTAxMDEwMDAwMDBaMC8xFzAVBgNVBAoTDkdvb2dsZSBURVNUSU5HMRQw\n"
125 "EgYDVQQDDAt0ZXN0X2NlcnRfMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\n"
126 "20oOyI+fNCCeHJ3DNjGooPPP43Q6emhVvuWD8ppta582Rgxq/4j1bl9cPHdoCdyy\n"
127 "HsWFVUZzscj2qhClmlBAMEA595OU2NX2d81nSih5dwZWLMRQkEIzyxUR7Vee3eyo\n"
128 "nQD4HSamaevMSv79WTUBCozEGITqWnjYA152KUbA/IsCAwEAAaOBkDCBjTAOBgNV\n"
129 "HQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1Ud\n"
130 "EwEB/wQCMAAwGQYDVR0OBBIEECnFWP/UkDrV+SoXra58k64wGwYDVR0jBBQwEoAQ\n"
131 "p7JSbajiTZaIRUDSV1C81jAWBgNVHREEDzANggt0ZXN0X2NlcnRfMTANBgkqhkiG\n"
132 "9w0BAQsFAAOBgQCpJJssfN62T3G5z+5SBB+9KCzXnGxcTHtaTJkb04KLe+19EwhV\n"
133 "yRY4lZadKHjcNS6GCBogd069wNFUVYOU9VI7uUiEPdcTO+VRV5MYW0wjSi1zlkBZ\n"
134 "e8OAfYVeGUMfvThFpJ41f8vZ6GHgg95Lwv+Zh89SL8g1J3RWll9YVG8HWw==\n"
135 "-----END CERTIFICATE-----\n";
136 std::string key_pem =
137 "-----BEGIN RSA PRIVATE KEY-----\n"
138 "MIICXQIBAAKBgQDbSg7Ij580IJ4cncM2Maig88/jdDp6aFW+5YPymm1rnzZGDGr/\n"
139 "iPVuX1w8d2gJ3LIexYVVRnOxyPaqEKWaUEAwQDn3k5TY1fZ3zWdKKHl3BlYsxFCQ\n"
140 "QjPLFRHtV57d7KidAPgdJqZp68xK/v1ZNQEKjMQYhOpaeNgDXnYpRsD8iwIDAQAB\n"
141 "AoGAbq4kZApJeo/z/dGK0/GggQxOIylo0puSm7VQMcTL8YP8asKdxrgj2D99WG+U\n"
142 "LVYc+PcM4wuaHWOnTBL24roaitCNhrpIsJfWDkexzHXMj622SYlUcCuwsfjYOEyw\n"
143 "ntoNAnh0o4S+beYAfzT5VHCh4is9G9u+mwKYiGpJXROrYUECQQD4eq4nuGq3mfYJ\n"
144 "B0+md30paDVVCyBsuZTAtnu3MbRjMXy5LLE+vhno5nocvVSTOv3QC7Wk6yAa8/bG\n"
145 "iPT/MWixAkEA4e0zqPGo8tSimVv/1ei8Chyb+YqdSx+Oj5eZpa6X/KB/C1uS1tm6\n"
146 "DTgHW2GUhV4ypqdGH+t8quprJUtFuzqH+wJBAMRiicSg789eouMt4RjrdYPFdela\n"
147 "Gu1zm4rYb10xrqV7Vl0wYoH5U5cMmdSfGvomdLX6mzzWDJDg4ti1JBWRonECQQCD\n"
148 "Umtq0j1QGQUCe5Vz8zoJ7qNDI61WU1t8X7Rxt9CkiW4PXgU2WYxpzp2IImpAM4bh\n"
149 "k+2Q9EKc3nG1VdGMiPMtAkARkQF+pL8SBrUoh8G8glCam0brh3tW/cdW8L4UGTNF\n"
150 "2ZKC/LFH6DQBjYs3UXjvMGJxz4k9LysyY6o2Nf1JG6/L\n"
151 "-----END RSA PRIVATE KEY-----\n";
152
153 // Create the context objects.
154 SSL_CTX* client_ctx = nullptr;
155 SSL_CTX* server_ctx = nullptr;
156 #if OPENSSL_VERSION_NUMBER >= 0x10100000
157 client_ctx = SSL_CTX_new(TLS_method());
158 server_ctx = SSL_CTX_new(TLS_method());
159 #else
160 client_ctx = SSL_CTX_new(TLSv1_2_method());
161 server_ctx = SSL_CTX_new(TLSv1_2_method());
162 #endif
163
164 BIO* client_cert_bio(BIO_new_mem_buf(cert_pem.c_str(), cert_pem.size()));
165 X509* client_cert = PEM_read_bio_X509(client_cert_bio, /*x=*/nullptr,
166 /*cb=*/nullptr, /*u=*/nullptr);
167 BIO* client_key_bio(BIO_new_mem_buf(key_pem.c_str(), key_pem.size()));
168 EVP_PKEY* client_key =
169 PEM_read_bio_PrivateKey(client_key_bio, /*x=*/nullptr,
170 /*cb=*/nullptr, /*u=*/nullptr);
171
172 BIO* server_cert_bio(BIO_new_mem_buf(cert_pem.c_str(), cert_pem.size()));
173 X509* server_cert = PEM_read_bio_X509(server_cert_bio, /*x=*/nullptr,
174 /*cb=*/nullptr, /*u=*/nullptr);
175 BIO* server_key_bio(BIO_new_mem_buf(key_pem.c_str(), key_pem.size()));
176 EVP_PKEY* server_key =
177 PEM_read_bio_PrivateKey(server_key_bio, /*x=*/nullptr,
178 /*cb=*/nullptr, /*u=*/nullptr);
179
180 // Set both client and server certificate and private key.
181 SSL_CTX_use_certificate(client_ctx, client_cert);
182 SSL_CTX_use_PrivateKey(client_ctx, client_key);
183 SSL_CTX_use_certificate(server_ctx, server_cert);
184 SSL_CTX_use_PrivateKey(server_ctx, server_key);
185
186 EVP_PKEY_free(client_key);
187 BIO_free(client_key_bio);
188 X509_free(client_cert);
189 BIO_free(client_cert_bio);
190
191 EVP_PKEY_free(server_key);
192 BIO_free(server_key_bio);
193 X509_free(server_cert);
194 BIO_free(server_cert_bio);
195
196 // Configure both client and server to request (and accept any)
197 // certificate but fail if none is sent.
198 SSL_CTX_set_verify(client_ctx,
199 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
200 /*callback=*/nullptr);
201 SSL_CTX_set_cert_verify_callback(client_ctx, VerifySucceed,
202 /*arg=*/nullptr);
203 SSL_CTX_set_verify(server_ctx,
204 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
205 /*callback=*/nullptr);
206 SSL_CTX_set_cert_verify_callback(server_ctx, VerifySucceed,
207 /*arg=*/nullptr);
208
209 // Turns off the session caching.
210 SSL_CTX_set_session_cache_mode(client_ctx, SSL_SESS_CACHE_OFF);
211 SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
212
213 #if OPENSSL_VERSION_NUMBER >= 0x10100000
214 #if defined(TLS1_3_VERSION)
215 // Set both the min and max TLS version to 1.3
216 SSL_CTX_set_min_proto_version(client_ctx, TLS1_3_VERSION);
217 SSL_CTX_set_min_proto_version(server_ctx, TLS1_3_VERSION);
218 SSL_CTX_set_max_proto_version(client_ctx, TLS1_3_VERSION);
219 SSL_CTX_set_max_proto_version(server_ctx, TLS1_3_VERSION);
220 #else
221 SSL_CTX_set_min_proto_version(client_ctx, TLS1_2_VERSION);
222 SSL_CTX_set_min_proto_version(server_ctx, TLS1_2_VERSION);
223 SSL_CTX_set_max_proto_version(client_ctx, TLS1_2_VERSION);
224 SSL_CTX_set_max_proto_version(server_ctx, TLS1_2_VERSION);
225 #endif
226 #endif
227
228 // Create client and server connection objects and configure their BIOs.
229 SSL* client(SSL_new(client_ctx));
230 SSL* server(SSL_new(server_ctx));
231
232 SSL_CTX_free(client_ctx);
233 SSL_CTX_free(server_ctx);
234
235 // Turns off issuance of session tickets by servers.
236 SSL_set_options(client, SSL_OP_NO_TICKET);
237 SSL_set_options(server, SSL_OP_NO_TICKET);
238
239 SSL_set_connect_state(client);
240 SSL_set_accept_state(server);
241 BIO* bio1;
242 BIO* bio2;
243 BIO_new_bio_pair(&bio1, /*writebuf1=*/0, &bio2, /*writebuf2=*/0);
244 SSL_set_bio(client, bio1, bio1);
245 SSL_set_bio(server, bio2, bio2);
246
247 // Drive both the client and server handshake operations to completion.
248 while (true) {
249 int client_ret = SSL_do_handshake(client);
250 int client_err = SSL_get_error(client, client_ret);
251 if (client_err != SSL_ERROR_NONE && client_err != SSL_ERROR_WANT_READ &&
252 client_err != SSL_ERROR_WANT_WRITE) {
253 return absl::InternalError(absl::StrCat("Client error:", client_err));
254 }
255
256 int server_ret = SSL_do_handshake(server);
257 int server_err = SSL_get_error(server, server_ret);
258 if (server_err != SSL_ERROR_NONE && server_err != SSL_ERROR_WANT_READ &&
259 server_err != SSL_ERROR_WANT_WRITE) {
260 return absl::InternalError(absl::StrCat("Server error:", server_err));
261 }
262 if (client_ret == 1 && server_ret == 1) {
263 break;
264 }
265 }
266
267 *out_client = client;
268 *out_server = server;
269
270 return absl::OkStatus();
271 }
272
CalculateRecordSizeFromHeader(uint8_t fourth_header_byte,uint8_t fifth_header_byte)273 static std::size_t CalculateRecordSizeFromHeader(uint8_t fourth_header_byte,
274 uint8_t fifth_header_byte) {
275 return (static_cast<int>(fourth_header_byte & 0xff) << 8) +
276 static_cast<int>(fifth_header_byte & 0xff);
277 }
278
SetUp()279 void SetUp() override {
280 ASSERT_EQ(DoHandshake(&client_ssl, &server_ssl), absl::OkStatus());
281
282 ASSERT_THAT(client_ssl, NotNull());
283 ASSERT_THAT(server_ssl, NotNull());
284
285 BIO* client_ssl_bio = nullptr;
286 ASSERT_EQ(BIO_new_bio_pair(&client_bio, /*writebuf1=*/0, &client_ssl_bio,
287 /*writebuf2=*/0),
288 1);
289 SSL_set_bio(client_ssl, client_ssl_bio, client_ssl_bio);
290
291 BIO* server_ssl_bio = nullptr;
292 ASSERT_EQ(BIO_new_bio_pair(&server_bio, /*writebuf1=*/0, &server_ssl_bio,
293 /*writebuf2=*/0),
294 1);
295 SSL_set_bio(server_ssl, server_ssl_bio, server_ssl_bio);
296
297 client_buffer_offset = 0;
298 client_buffer.resize(kMaxPlaintextBytesPerTlsRecord);
299 server_buffer_offset = 0;
300 server_buffer.resize(kMaxPlaintextBytesPerTlsRecord);
301 }
302
TearDown()303 void TearDown() override {
304 BIO_free(client_bio);
305 SSL_free(client_ssl);
306 BIO_free(server_bio);
307 SSL_free(server_ssl);
308 }
309
310 SSL* client_ssl;
311 BIO* client_bio;
312 std::vector<uint8_t> client_buffer;
313 std::size_t client_buffer_offset;
314
315 SSL* server_ssl;
316 BIO* server_bio;
317 std::vector<uint8_t> server_buffer;
318 std::size_t server_buffer_offset;
319 };
320
321 // This test consists of two tests, namely for each combination of parameters,
322 // we create a message on one side, protect it (encrypt it), and send it to
323 // the other side for unprotecting (decrypting).
TEST_P(FlowTest,ClientMessageToServerCanBeProtectedAndUnprotectedSuccessfully)324 TEST_P(FlowTest,
325 ClientMessageToServerCanBeProtectedAndUnprotectedSuccessfully) {
326 std::vector<uint8_t> unprotected_bytes(GetParam().plaintext_size, 'a');
327 std::size_t unprotected_bytes_size = unprotected_bytes.size();
328
329 std::vector<uint8_t> protected_output_frames(
330 GetParam().expected_encrypted_bytes_size);
331 std::size_t protected_output_frames_size = protected_output_frames.size();
332
333 EXPECT_EQ(SslProtectorProtect(unprotected_bytes.data(), client_buffer.size(),
334 client_buffer_offset, client_buffer.data(),
335 client_ssl, client_bio, &unprotected_bytes_size,
336 protected_output_frames.data(),
337 &protected_output_frames_size),
338 tsi_result::TSI_OK);
339
340 // If |GetParam().plaintext_size| is larger than the inner client_buffer
341 // size (kMaxPlaintextBytesPerTlsRecord), then |Protect| will copy up to
342 // |kMaxPlaintextBytesPerTlsRecord| bytes and output the protected
343 // frame. Otherwise we need to manually flush the copied data in order
344 // to get the protected frame.
345 if (GetParam().plaintext_size >= kMaxPlaintextBytesPerTlsRecord) {
346 EXPECT_EQ(unprotected_bytes_size, kMaxPlaintextBytesPerTlsRecord);
347 } else {
348 EXPECT_EQ(unprotected_bytes_size, GetParam().plaintext_size);
349 EXPECT_EQ(protected_output_frames_size, 0);
350 protected_output_frames_size = protected_output_frames.size();
351
352 std::size_t still_pending_size = 0;
353 EXPECT_EQ(SslProtectorProtectFlush(
354 client_buffer_offset, client_buffer.data(), client_ssl,
355 client_bio, protected_output_frames.data(),
356 &protected_output_frames_size, &still_pending_size),
357 tsi_result::TSI_OK);
358 EXPECT_EQ(still_pending_size, 0);
359 }
360
361 // The first three bytes are always 0x17, 0x03, 0x03.
362 EXPECT_EQ(protected_output_frames[0], '\x17');
363 EXPECT_EQ(protected_output_frames[1], '\x03');
364 EXPECT_EQ(protected_output_frames[2], '\x03');
365 // The next two bytes are the size of the record, which is 5 bytes less
366 // than the size of the whole frame.
367 EXPECT_EQ(CalculateRecordSizeFromHeader(protected_output_frames[3],
368 protected_output_frames[4]),
369 protected_output_frames_size - 5);
370
371 std::vector<uint8_t> unprotected_output_bytes(GetParam().plaintext_size);
372 std::size_t unprotected_output_bytes_size = unprotected_output_bytes.size();
373
374 // This frame should be decrypted by peer correctly.
375 EXPECT_EQ(SslProtectorUnprotect(protected_output_frames.data(), server_ssl,
376 server_bio, &protected_output_frames_size,
377 unprotected_output_bytes.data(),
378 &unprotected_output_bytes_size),
379 tsi_result::TSI_OK);
380 EXPECT_EQ(unprotected_output_bytes_size, unprotected_bytes_size);
381 unprotected_output_bytes.resize(unprotected_output_bytes_size);
382 unprotected_bytes.resize(unprotected_bytes_size);
383 EXPECT_THAT(unprotected_output_bytes, ContainerEq(unprotected_bytes));
384 }
385
TEST_P(FlowTest,ServerMessageToClientCanBeProtectedAndUnprotectedSuccessfully)386 TEST_P(FlowTest,
387 ServerMessageToClientCanBeProtectedAndUnprotectedSuccessfully) {
388 std::vector<uint8_t> unprotected_bytes(GetParam().plaintext_size, 'a');
389 std::size_t unprotected_bytes_size = unprotected_bytes.size();
390
391 std::vector<uint8_t> protected_output_frames(
392 GetParam().expected_encrypted_bytes_size);
393 std::size_t protected_output_frames_size = protected_output_frames.size();
394
395 EXPECT_EQ(SslProtectorProtect(unprotected_bytes.data(), server_buffer.size(),
396 server_buffer_offset, server_buffer.data(),
397 server_ssl, server_bio, &unprotected_bytes_size,
398 protected_output_frames.data(),
399 &protected_output_frames_size),
400 tsi_result::TSI_OK);
401
402 // If |GetParam().plaintext_size| is larger than the inner server_buffer
403 // size (kMaxPlaintextBytesPerTlsRecord), then |Protect| will copy up to
404 // |kMaxPlaintextBytesPerTlsRecord| bytes and output the protected
405 // frame. Otherwise we need to manually flush the copied data in order
406 // to get the protected frame.
407 if (GetParam().plaintext_size >= kMaxPlaintextBytesPerTlsRecord) {
408 EXPECT_EQ(unprotected_bytes_size, kMaxPlaintextBytesPerTlsRecord);
409 } else {
410 EXPECT_EQ(unprotected_bytes_size, GetParam().plaintext_size);
411 EXPECT_EQ(protected_output_frames_size, 0);
412 protected_output_frames_size = protected_output_frames.size();
413
414 std::size_t still_pending_size = 0;
415 EXPECT_EQ(SslProtectorProtectFlush(
416 server_buffer_offset, server_buffer.data(), server_ssl,
417 server_bio, protected_output_frames.data(),
418 &protected_output_frames_size, &still_pending_size),
419 tsi_result::TSI_OK);
420 EXPECT_EQ(still_pending_size, 0);
421 }
422
423 // The first three bytes are always 0x17, 0x03, 0x03.
424 EXPECT_EQ(protected_output_frames[0], '\x17');
425 EXPECT_EQ(protected_output_frames[1], '\x03');
426 EXPECT_EQ(protected_output_frames[2], '\x03');
427 // The next two bytes are the size of the record, which is 5 bytes less
428 // than the size of the whole frame.
429 EXPECT_EQ(CalculateRecordSizeFromHeader(protected_output_frames[3],
430 protected_output_frames[4]),
431 protected_output_frames_size - 5);
432
433 std::vector<uint8_t> unprotected_output_bytes(GetParam().plaintext_size);
434 std::size_t unprotected_output_bytes_size = unprotected_output_bytes.size();
435
436 // This frame should be decrypted by peer correctly.
437 EXPECT_EQ(SslProtectorUnprotect(protected_output_frames.data(), client_ssl,
438 client_bio, &protected_output_frames_size,
439 unprotected_output_bytes.data(),
440 &unprotected_output_bytes_size),
441 tsi_result::TSI_OK);
442 EXPECT_EQ(unprotected_output_bytes_size, unprotected_bytes_size);
443 unprotected_output_bytes.resize(unprotected_output_bytes_size);
444 unprotected_bytes.resize(unprotected_bytes_size);
445 EXPECT_THAT(unprotected_output_bytes, ContainerEq(unprotected_bytes));
446 }
447
448 INSTANTIATE_TEST_SUITE_P(FrameProtectorUtil, FlowTest,
449 ValuesIn(GenerateTestData()));
450
451 #endif // OPENSSL_IS_BORINGSSL
452
453 class CrlUtils : public ::testing::Test {
454 public:
SetUpTestSuite()455 static void SetUpTestSuite() {
456 #if OPENSSL_VERSION_NUMBER >= 0x10100000
457 OPENSSL_init_ssl(/*opts=*/0, /*settings=*/nullptr);
458 #else
459 SSL_library_init();
460 SSL_load_error_strings();
461 OpenSSL_add_all_algorithms();
462 #endif
463 }
464
SetUp()465 void SetUp() override {
466 absl::StatusOr<Slice> root_crl = LoadFile(kValidCrl, false);
467 ASSERT_EQ(root_crl.status(), absl::OkStatus()) << root_crl.status();
468 root_crl_ = ReadCrl(root_crl->as_string_view());
469 absl::StatusOr<Slice> intermediate_crl = LoadFile(kIntermediateCrl, false);
470 ASSERT_EQ(intermediate_crl.status(), absl::OkStatus())
471 << intermediate_crl.status();
472 intermediate_crl_ = ReadCrl(intermediate_crl->as_string_view());
473 absl::StatusOr<Slice> invalid_signature_crl =
474 LoadFile(kModifiedSignature, false);
475 ASSERT_EQ(invalid_signature_crl.status(), absl::OkStatus())
476 << invalid_signature_crl.status();
477 invalid_signature_crl_ = ReadCrl(invalid_signature_crl->as_string_view());
478 absl::StatusOr<Slice> akid_crl = LoadFile(kCrlWithAkid, false);
479 ASSERT_EQ(akid_crl.status(), absl::OkStatus()) << akid_crl.status();
480 akid_crl_ = ReadCrl(akid_crl->as_string_view());
481
482 absl::StatusOr<Slice> root_ca = LoadFile(kCrlIssuer, false);
483 ASSERT_EQ(root_ca.status(), absl::OkStatus());
484 root_ca_ = ReadPemCert(root_ca->as_string_view());
485 absl::StatusOr<Slice> intermediate_ca =
486 LoadFile(kIntermediateCrlIssuer, false);
487 ASSERT_EQ(intermediate_ca.status(), absl::OkStatus());
488 intermediate_ca_ = ReadPemCert(intermediate_ca->as_string_view());
489 absl::StatusOr<Slice> leaf_cert = LoadFile(kLeafCert, false);
490 ASSERT_EQ(leaf_cert.status(), absl::OkStatus());
491 leaf_cert_ = ReadPemCert(leaf_cert->as_string_view());
492 absl::StatusOr<Slice> evil_ca = LoadFile(kEvilCa, false);
493 ASSERT_EQ(evil_ca.status(), absl::OkStatus());
494 evil_ca_ = ReadPemCert(evil_ca->as_string_view());
495 absl::StatusOr<Slice> ca_with_akid = LoadFile(kCaWithAkid, false);
496 ASSERT_EQ(ca_with_akid.status(), absl::OkStatus());
497 ca_with_akid_ = ReadPemCert(ca_with_akid->as_string_view());
498 }
499
TearDown()500 void TearDown() override {
501 X509_CRL_free(root_crl_);
502 X509_CRL_free(intermediate_crl_);
503 X509_CRL_free(invalid_signature_crl_);
504 X509_CRL_free(akid_crl_);
505 X509_free(root_ca_);
506 X509_free(intermediate_ca_);
507 X509_free(leaf_cert_);
508 X509_free(evil_ca_);
509 X509_free(ca_with_akid_);
510 }
511
512 protected:
513 X509_CRL* root_crl_;
514 X509_CRL* intermediate_crl_;
515 X509_CRL* invalid_signature_crl_;
516 X509_CRL* akid_crl_;
517 X509* root_ca_;
518 X509* intermediate_ca_;
519 X509* leaf_cert_;
520 X509* evil_ca_;
521 X509* ca_with_akid_;
522 };
523
TEST_F(CrlUtils,VerifySignatureValid)524 TEST_F(CrlUtils, VerifySignatureValid) {
525 EXPECT_TRUE(VerifyCrlSignature(root_crl_, root_ca_));
526 }
527
TEST_F(CrlUtils,VerifySignatureIntermediateValid)528 TEST_F(CrlUtils, VerifySignatureIntermediateValid) {
529 EXPECT_TRUE(VerifyCrlSignature(intermediate_crl_, intermediate_ca_));
530 }
531
TEST_F(CrlUtils,VerifySignatureModifiedSignature)532 TEST_F(CrlUtils, VerifySignatureModifiedSignature) {
533 EXPECT_FALSE(VerifyCrlSignature(invalid_signature_crl_, root_ca_));
534 }
535
TEST_F(CrlUtils,VerifySignatureModifiedContent)536 TEST_F(CrlUtils, VerifySignatureModifiedContent) {
537 absl::StatusOr<Slice> crl_slice = LoadFile(kModifiedContent, false);
538 ASSERT_EQ(crl_slice.status(), absl::OkStatus()) << crl_slice.status();
539 X509_CRL* crl = ReadCrl(crl_slice->as_string_view());
540 EXPECT_EQ(crl, nullptr);
541 }
542
TEST_F(CrlUtils,VerifySignatureWrongIssuer)543 TEST_F(CrlUtils, VerifySignatureWrongIssuer) {
544 EXPECT_FALSE(VerifyCrlSignature(root_crl_, intermediate_ca_));
545 }
546
TEST_F(CrlUtils,VerifySignatureWrongIssuer2)547 TEST_F(CrlUtils, VerifySignatureWrongIssuer2) {
548 EXPECT_FALSE(VerifyCrlSignature(intermediate_crl_, root_ca_));
549 }
550
TEST_F(CrlUtils,VerifySignatureNullCrl)551 TEST_F(CrlUtils, VerifySignatureNullCrl) {
552 EXPECT_FALSE(VerifyCrlSignature(nullptr, root_ca_));
553 }
554
TEST_F(CrlUtils,VerifySignatureNullCert)555 TEST_F(CrlUtils, VerifySignatureNullCert) {
556 EXPECT_FALSE(VerifyCrlSignature(intermediate_crl_, nullptr));
557 }
558
TEST_F(CrlUtils,VerifySignatureNullCrlAndCert)559 TEST_F(CrlUtils, VerifySignatureNullCrlAndCert) {
560 EXPECT_FALSE(VerifyCrlSignature(nullptr, nullptr));
561 }
562
TEST_F(CrlUtils,VerifyIssuerNamesMatch)563 TEST_F(CrlUtils, VerifyIssuerNamesMatch) {
564 EXPECT_TRUE(VerifyCrlCertIssuerNamesMatch(root_crl_, root_ca_));
565 }
566
TEST_F(CrlUtils,VerifyIssuerNamesDontMatch)567 TEST_F(CrlUtils, VerifyIssuerNamesDontMatch) {
568 EXPECT_FALSE(VerifyCrlCertIssuerNamesMatch(root_crl_, leaf_cert_));
569 }
570
TEST_F(CrlUtils,DuplicatedIssuerNamePassesButSignatureCheckFails)571 TEST_F(CrlUtils, DuplicatedIssuerNamePassesButSignatureCheckFails) {
572 // The issuer names will match, but it should fail a signature check
573 EXPECT_TRUE(VerifyCrlCertIssuerNamesMatch(root_crl_, evil_ca_));
574 EXPECT_FALSE(VerifyCrlSignature(root_crl_, evil_ca_));
575 }
576
TEST_F(CrlUtils,VerifyIssuerNameNullCrl)577 TEST_F(CrlUtils, VerifyIssuerNameNullCrl) {
578 EXPECT_FALSE(VerifyCrlCertIssuerNamesMatch(nullptr, root_ca_));
579 }
580
TEST_F(CrlUtils,VerifyIssuerNameNullCert)581 TEST_F(CrlUtils, VerifyIssuerNameNullCert) {
582 EXPECT_FALSE(VerifyCrlCertIssuerNamesMatch(intermediate_crl_, nullptr));
583 }
584
TEST_F(CrlUtils,VerifyIssuerNameNullCrlAndCert)585 TEST_F(CrlUtils, VerifyIssuerNameNullCrlAndCert) {
586 EXPECT_FALSE(VerifyCrlCertIssuerNamesMatch(nullptr, nullptr));
587 }
588
TEST_F(CrlUtils,HasCrlSignBitExists)589 TEST_F(CrlUtils, HasCrlSignBitExists) { EXPECT_TRUE(HasCrlSignBit(root_ca_)); }
590
TEST_F(CrlUtils,HasCrlSignBitMissing)591 TEST_F(CrlUtils, HasCrlSignBitMissing) {
592 EXPECT_FALSE(HasCrlSignBit(leaf_cert_));
593 }
594
TEST_F(CrlUtils,HasCrlSignBitNullCert)595 TEST_F(CrlUtils, HasCrlSignBitNullCert) {
596 EXPECT_FALSE(HasCrlSignBit(nullptr));
597 }
598
TEST_F(CrlUtils,IssuerFromIntermediateCert)599 TEST_F(CrlUtils, IssuerFromIntermediateCert) {
600 auto issuer = IssuerFromCert(intermediate_ca_);
601 // Build the known name for comparison
602 unsigned char* buf = nullptr;
603 X509_NAME* expected_issuer_name = X509_NAME_new();
604 ASSERT_TRUE(
605 X509_NAME_add_entry_by_txt(expected_issuer_name, "C", MBSTRING_ASC,
606 (const unsigned char*)"AU", -1, -1, 0));
607 ASSERT_TRUE(X509_NAME_add_entry_by_txt(
608 expected_issuer_name, "ST", MBSTRING_ASC,
609 (const unsigned char*)"Some-State", -1, -1, 0));
610 ASSERT_TRUE(X509_NAME_add_entry_by_txt(
611 expected_issuer_name, "O", MBSTRING_ASC,
612 (const unsigned char*)"Internet Widgits Pty Ltd", -1, -1, 0));
613 ASSERT_TRUE(
614 X509_NAME_add_entry_by_txt(expected_issuer_name, "CN", MBSTRING_ASC,
615 (const unsigned char*)"testca", -1, -1, 0));
616 int len = i2d_X509_NAME(expected_issuer_name, &buf);
617 std::string expected_issuer_name_der(reinterpret_cast<char const*>(buf), len);
618 OPENSSL_free(buf);
619 X509_NAME_free(expected_issuer_name);
620 ASSERT_EQ(issuer.status(), absl::OkStatus());
621 EXPECT_EQ(*issuer, expected_issuer_name_der);
622 }
623
TEST_F(CrlUtils,IssuerFromLeaf)624 TEST_F(CrlUtils, IssuerFromLeaf) {
625 auto issuer = IssuerFromCert(leaf_cert_);
626 // Build the known name for comparison
627 unsigned char* buf = nullptr;
628 X509_NAME* expected_issuer_name = X509_NAME_new();
629 ASSERT_TRUE(X509_NAME_add_entry_by_txt(
630 expected_issuer_name, "CN", MBSTRING_ASC,
631 (const unsigned char*)"intermediatecert.example.com", -1, -1, 0));
632 int len = i2d_X509_NAME(expected_issuer_name, &buf);
633 std::string expected_issuer_name_der(reinterpret_cast<char const*>(buf), len);
634 OPENSSL_free(buf);
635 X509_NAME_free(expected_issuer_name);
636 ASSERT_EQ(issuer.status(), absl::OkStatus());
637 EXPECT_EQ(*issuer, expected_issuer_name_der);
638 }
639
TEST_F(CrlUtils,IssuerFromCertNull)640 TEST_F(CrlUtils, IssuerFromCertNull) {
641 auto issuer = IssuerFromCert(nullptr);
642 EXPECT_EQ(issuer.status().code(), absl::StatusCode::kInvalidArgument);
643 }
644
TEST_F(CrlUtils,CertCrlAkidValid)645 TEST_F(CrlUtils, CertCrlAkidValid) {
646 auto akid = AkidFromCertificate(ca_with_akid_);
647 EXPECT_EQ(akid.status(), absl::OkStatus());
648 auto crl_akid = AkidFromCrl(akid_crl_);
649 EXPECT_EQ(crl_akid.status(), absl::OkStatus());
650 EXPECT_NE(*akid, "");
651 // It's easiest to compare that these two pull the same value, it's very
652 // difficult to create the known AKID value as a test constant, so we just
653 // check that they are not empty and that they are the same.
654 EXPECT_EQ(*akid, *crl_akid);
655 }
656
TEST_F(CrlUtils,CertNoAkid)657 TEST_F(CrlUtils, CertNoAkid) {
658 auto akid = AkidFromCertificate(root_ca_);
659 EXPECT_EQ(akid.status().code(), absl::StatusCode::kInvalidArgument);
660 }
661
TEST_F(CrlUtils,CrlNoAkid)662 TEST_F(CrlUtils, CrlNoAkid) {
663 auto akid = AkidFromCrl(root_crl_);
664 EXPECT_EQ(akid.status().code(), absl::StatusCode::kInvalidArgument);
665 }
666
TEST_F(CrlUtils,CertAkidNullptr)667 TEST_F(CrlUtils, CertAkidNullptr) {
668 auto akid = AkidFromCertificate(nullptr);
669 EXPECT_EQ(akid.status().code(), absl::StatusCode::kInvalidArgument);
670 }
671
TEST_F(CrlUtils,CrlAkidNullptr)672 TEST_F(CrlUtils, CrlAkidNullptr) {
673 auto akid = AkidFromCrl(nullptr);
674 EXPECT_EQ(akid.status().code(), absl::StatusCode::kInvalidArgument);
675 }
676 } // namespace testing
677 } // namespace grpc_core
678
main(int argc,char ** argv)679 int main(int argc, char** argv) {
680 grpc::testing::TestEnvironment env(&argc, argv);
681 ::testing::InitGoogleTest(&argc, argv);
682 grpc_init();
683 int ret = RUN_ALL_TESTS();
684 grpc_shutdown();
685 return ret;
686 }
687