1 // Copyright 2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ////////////////////////////////////////////////////////////////////////////////
16
17 #include "tink/aead/internal/cord_aes_gcm_boringssl.h"
18
19 #include <memory>
20 #include <string>
21 #include <utility>
22 #include <vector>
23
24 #include "gmock/gmock.h"
25 #include "gtest/gtest.h"
26 #include "absl/strings/cord.h"
27 #include "absl/strings/cord_test_helpers.h"
28 #include "absl/strings/escaping.h"
29 #include "absl/strings/str_cat.h"
30 #include "absl/strings/str_split.h"
31 #include "openssl/err.h"
32 #include "include/rapidjson/document.h"
33 #include "tink/subtle/aes_gcm_boringssl.h"
34 #include "tink/subtle/wycheproof_util.h"
35 #include "tink/util/secret_data.h"
36 #include "tink/util/statusor.h"
37 #include "tink/util/test_matchers.h"
38
39 namespace crypto {
40 namespace tink {
41 namespace internal {
42 namespace {
43
44 constexpr absl::string_view key_128 = "000102030405060708090a0b0c0d0e0f";
45 constexpr absl::string_view kMessage = "Some data to encrypt.";
46 constexpr absl::string_view kLongMessage =
47 "This is some long message which will be fragmented.";
48 constexpr absl::string_view kAssociatedData = "Some associated data.";
49
50 using ::crypto::tink::test::IsOk;
51 using ::testing::Eq;
52 using ::testing::Not;
53 using ::testing::SizeIs;
54 using ::testing::Test;
55
56 class CordAesGcmBoringSslTest : public Test {
57 protected:
SetUp()58 void SetUp() override {
59 key_ = util::SecretDataFromStringView(absl::HexStringToBytes(key_128));
60 util::StatusOr<std::unique_ptr<CordAead>> res =
61 CordAesGcmBoringSsl::New(key_);
62 ASSERT_THAT(res, IsOk());
63 cipher_ = std::move(*res);
64 }
65
66 util::SecretData key_;
67 std::unique_ptr<CordAead> cipher_;
68 };
69
TEST_F(CordAesGcmBoringSslTest,EncryptDecryptCord)70 TEST_F(CordAesGcmBoringSslTest, EncryptDecryptCord) {
71 absl::Cord message_cord = absl::Cord(kMessage);
72 absl::Cord associated_data_cord = absl::Cord(kAssociatedData);
73 util::StatusOr<absl::Cord> ct =
74 cipher_->Encrypt(message_cord, associated_data_cord);
75 ASSERT_THAT(ct, IsOk());
76 EXPECT_THAT(*ct, SizeIs(message_cord.size() + 12 + 16));
77 util::StatusOr<absl::Cord> pt = cipher_->Decrypt(*ct, associated_data_cord);
78 ASSERT_THAT(pt, IsOk());
79 EXPECT_EQ(*pt, message_cord.Flatten());
80 }
81
TEST_F(CordAesGcmBoringSslTest,ChunkyCordEncrypt)82 TEST_F(CordAesGcmBoringSslTest, ChunkyCordEncrypt) {
83 absl::Cord message_cord =
84 absl::MakeFragmentedCord(absl::StrSplit(kLongMessage, absl::ByLength(3)));
85 absl::Cord associated_data_cord = absl::Cord(kAssociatedData);
86 util::StatusOr<absl::Cord> ct =
87 cipher_->Encrypt(message_cord, associated_data_cord);
88 ASSERT_THAT(ct, IsOk());
89 EXPECT_THAT(*ct, SizeIs(message_cord.size() + 12 + 16));
90 util::StatusOr<absl::Cord> pt = cipher_->Decrypt(*ct, associated_data_cord);
91 ASSERT_THAT(pt, IsOk());
92 EXPECT_THAT(*pt, Eq(kLongMessage));
93 }
94
TEST_F(CordAesGcmBoringSslTest,ChunkyCordDecrypt)95 TEST_F(CordAesGcmBoringSslTest, ChunkyCordDecrypt) {
96 absl::Cord message_cord = absl::Cord(kLongMessage);
97 absl::Cord associated_data_cord = absl::Cord(kAssociatedData);
98 util::StatusOr<absl::Cord> ct =
99 cipher_->Encrypt(message_cord, associated_data_cord);
100 ASSERT_THAT(ct, IsOk());
101 absl::Cord fragmented_ct = absl::MakeFragmentedCord(
102 absl::StrSplit(ct->Flatten(), absl::ByLength(3)));
103 util::StatusOr<absl::Cord> pt =
104 cipher_->Decrypt(fragmented_ct, associated_data_cord);
105 ASSERT_THAT(pt, IsOk());
106 EXPECT_THAT(*pt, Eq(kLongMessage));
107 }
108
TEST_F(CordAesGcmBoringSslTest,CanDecryptWithStringAead)109 TEST_F(CordAesGcmBoringSslTest, CanDecryptWithStringAead) {
110 absl::Cord message_cord = absl::Cord(kMessage);
111 absl::Cord associated_data_cord = absl::Cord(kAssociatedData);
112 util::StatusOr<absl::Cord> ct =
113 cipher_->Encrypt(message_cord, associated_data_cord);
114 ASSERT_THAT(ct, IsOk());
115 EXPECT_EQ(ct->size(), message_cord.size() + 12 + 16);
116 util::StatusOr<absl::Cord> pt = cipher_->Decrypt(*ct, associated_data_cord);
117 ASSERT_THAT(pt, IsOk());
118 EXPECT_EQ(*pt, message_cord.Flatten());
119
120 // Decrypt as string and check if it gives same result.
121 util::StatusOr<std::unique_ptr<Aead>> string_aead =
122 subtle::AesGcmBoringSsl::New(key_);
123 ASSERT_THAT(string_aead, IsOk());
124 util::StatusOr<std::string> plaintext =
125 (*string_aead)
126 ->Decrypt(ct.value().Flatten(), associated_data_cord.Flatten());
127 ASSERT_THAT(plaintext, IsOk());
128 EXPECT_EQ(*plaintext, kMessage);
129 }
130
TEST_F(CordAesGcmBoringSslTest,ModifiedCord)131 TEST_F(CordAesGcmBoringSslTest, ModifiedCord) {
132 absl::Cord message = absl::Cord(kMessage);
133 absl::Cord ad = absl::Cord(kAssociatedData);
134 util::StatusOr<absl::Cord> ct = cipher_->Encrypt(message, ad);
135 ASSERT_THAT(ct, IsOk());
136 util::StatusOr<absl::Cord> plaintext = cipher_->Decrypt(*ct, ad);
137 ASSERT_THAT(plaintext, IsOk());
138 EXPECT_EQ(*plaintext, message);
139
140 // Modify the ciphertext.
141 for (size_t i = 0; i < ct->size() * 8; i++) {
142 std::string modified_ct = std::string(ct->Flatten());
143 modified_ct[i / 8] ^= 1 << (i % 8);
144 absl::Cord modified_ct_cord;
145 modified_ct_cord = absl::Cord(modified_ct);
146 EXPECT_THAT(cipher_->Decrypt(modified_ct_cord, ad), Not(IsOk()))
147 << i;
148 }
149 // Modify the associated data.
150 for (size_t i = 0; i < ad.size() * 8; i++) {
151 std::string modified_ad = std::string(ad.Flatten());
152 modified_ad[i / 8] ^= 1 << (i % 8);
153 absl::Cord modified_associated_data_cord;
154 modified_associated_data_cord = absl::Cord(modified_ad);
155 util::StatusOr<absl::Cord> decrypted =
156 cipher_->Decrypt(*ct, modified_associated_data_cord);
157 EXPECT_THAT(decrypted, Not(IsOk())) << i << " pt: " << *decrypted;
158 }
159 // Truncate the ciphertext.
160 for (size_t i = 0; i < ct->size(); i++) {
161 std::string truncated_ct(std::string(ct->Flatten()), 0, i);
162 absl::Cord truncated_ct_cord;
163 truncated_ct_cord = absl::Cord(truncated_ct);
164 EXPECT_THAT(cipher_->Decrypt(truncated_ct_cord, ad), Not(IsOk()))
165 << i;
166 }
167 }
168
GetError()169 static std::string GetError() {
170 auto err = ERR_peek_last_error();
171 // Sometimes there is no error message on the stack.
172 if (err == 0) {
173 return "";
174 }
175 std::string lib(ERR_lib_error_string(err));
176 std::string func(ERR_func_error_string(err));
177 std::string reason(ERR_reason_error_string(err));
178 return lib + ":" + func + ":" + reason;
179 }
180
181 // Test with test vectors from Wycheproof project.
WycheproofTest(const rapidjson::Document & root)182 bool WycheproofTest(const rapidjson::Document& root) {
183 int errors = 0;
184 for (const rapidjson::Value& test_group : root["testGroups"].GetArray()) {
185 const size_t iv_size = test_group["ivSize"].GetInt();
186 const size_t key_size = test_group["keySize"].GetInt();
187 const size_t tag_size = test_group["tagSize"].GetInt();
188 // CordAesGcmBoringSsl only supports 12-byte IVs and 16-byte
189 // authentication tag. Also 24-byte keys are not supported.
190 if (iv_size != 96 || tag_size != 128 || key_size == 192) {
191 // Not supported
192 continue;
193 }
194 for (const rapidjson::Value& test : test_group["tests"].GetArray()) {
195 std::string comment = test["comment"].GetString();
196 std::string key = subtle::WycheproofUtil::GetBytes(test["key"]);
197 std::string iv = subtle::WycheproofUtil::GetBytes(test["iv"]);
198 std::string msg = subtle::WycheproofUtil::GetBytes(test["msg"]);
199 std::string ct = subtle::WycheproofUtil::GetBytes(test["ct"]);
200 std::string ad = subtle::WycheproofUtil::GetBytes(test["aad"]);
201 std::string tag = subtle::WycheproofUtil::GetBytes(test["tag"]);
202 std::string id = absl::StrCat(test["tcId"].GetInt());
203 std::string expected = test["result"].GetString();
204
205 std::unique_ptr<CordAead> cipher = std::move(
206 *CordAesGcmBoringSsl::New(util::SecretDataFromStringView(key)));
207 // Convert the ciphertext to cord.
208 absl::Cord ct_cord = absl::Cord(iv + ct + tag);
209 absl::Cord associated_data_cord = absl::Cord(ad);
210 util::StatusOr<absl::Cord> result =
211 cipher->Decrypt(ct_cord, associated_data_cord);
212 if (result.ok()) {
213 std::string decrypted = std::string(result->Flatten());
214 if (expected == "invalid") {
215 ADD_FAILURE() << "Decrypted invalid ciphertext:" << id;
216 errors++;
217 } else if (msg != decrypted) {
218 ADD_FAILURE() << "Incorrect decryption:" << id;
219 errors++;
220 }
221 } else {
222 if (expected == "valid" || expected == "acceptable") {
223 ADD_FAILURE() << "Could not decrypt test with tcId:" << id
224 << " iv_size:" << iv_size << " tag_size:" << tag_size
225 << " key_size:" << key_size << " error:" << GetError();
226 errors++;
227 }
228 }
229 }
230 }
231 return errors == 0;
232 }
233
TEST(CordAesGcmBoringSslWycheproofTest,TestVectors)234 TEST(CordAesGcmBoringSslWycheproofTest, TestVectors) {
235 std::unique_ptr<rapidjson::Document> root =
236 subtle::WycheproofUtil::ReadTestVectors("aes_gcm_test.json");
237 ASSERT_TRUE(WycheproofTest(*root));
238 }
239
240 } // namespace
241 } // namespace internal
242 } // namespace tink
243 } // namespace crypto
244