1 // Copyright 2017 Google Inc.
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/subtle/aes_gcm_hkdf_stream_segment_encrypter.h"
18
19 #include <cstdint>
20 #include <cstring>
21 #include <limits>
22 #include <memory>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27 #include "absl/algorithm/container.h"
28 #include "absl/base/config.h"
29 #include "absl/memory/memory.h"
30 #include "absl/status/status.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/string_view.h"
33 #include "absl/types/span.h"
34 #include "tink/aead/internal/ssl_aead.h"
35 #include "tink/internal/err_util.h"
36 #include "tink/subtle/random.h"
37 #include "tink/subtle/subtle_util.h"
38 #include "tink/util/status.h"
39 #include "tink/util/statusor.h"
40
41 namespace crypto {
42 namespace tink {
43 namespace subtle {
44
45 namespace {
46
ByteSwap(uint32_t val)47 uint32_t ByteSwap(uint32_t val) {
48 return ((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) |
49 ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24);
50 }
51
BigEndianStore32(uint8_t dst[4],uint32_t val)52 void BigEndianStore32(uint8_t dst[4], uint32_t val) {
53 #if defined(ABSL_IS_LITTLE_ENDIAN)
54 val = ByteSwap(val);
55 #elif !defined(ABSL_IS_BIG_ENDIAN)
56 #error Unknown endianness
57 #endif
58 std::memcpy(dst, &val, sizeof(val));
59 }
60
Validate(const AesGcmHkdfStreamSegmentEncrypter::Params & params)61 util::Status Validate(const AesGcmHkdfStreamSegmentEncrypter::Params& params) {
62 if (params.key.size() != 16 && params.key.size() != 32) {
63 return util::Status(absl::StatusCode::kInvalidArgument,
64 "key must have 16 or 32 bytes");
65 }
66 if (params.key.size() != params.salt.size()) {
67 return util::Status(absl::StatusCode::kInvalidArgument,
68 "salt must have same size as the key");
69 }
70 if (params.ciphertext_offset < 0) {
71 return util::Status(absl::StatusCode::kInvalidArgument,
72 "ciphertext_offset must be non-negative");
73 }
74 int header_size = 1 + params.salt.size() +
75 AesGcmHkdfStreamSegmentEncrypter::kNoncePrefixSizeInBytes;
76 if (params.ciphertext_segment_size <=
77 params.ciphertext_offset + header_size +
78 AesGcmHkdfStreamSegmentEncrypter::kTagSizeInBytes) {
79 return util::Status(absl::StatusCode::kInvalidArgument,
80 "ciphertext_segment_size too small");
81 }
82 return util::OkStatus();
83 }
84
CreateHeader(absl::string_view salt,absl::string_view nonce_prefix)85 std::vector<uint8_t> CreateHeader(absl::string_view salt,
86 absl::string_view nonce_prefix) {
87 uint8_t header_size = static_cast<uint8_t>(
88 1 + salt.size() +
89 AesGcmHkdfStreamSegmentEncrypter::kNoncePrefixSizeInBytes);
90 std::vector<uint8_t> header(header_size);
91 header[0] = header_size;
92 absl::c_copy(salt, header.begin() + 1);
93 absl::c_copy(nonce_prefix, header.begin() + 1 + salt.size());
94 return header;
95 }
96
97 // Constructs the nonce as | `nonce_prefix` | `segment_number` | 0 if
98 // `is_last_segment` or 1 |.
ConstructNonce(absl::string_view nonce_prefix,uint32_t segment_number,bool is_last_segment)99 std::string ConstructNonce(absl::string_view nonce_prefix,
100 uint32_t segment_number, bool is_last_segment) {
101 std::string iv;
102 ResizeStringUninitialized(
103 &iv, AesGcmHkdfStreamSegmentEncrypter::kNonceSizeInBytes);
104 absl::c_copy(nonce_prefix, absl::MakeSpan(iv).begin());
105 BigEndianStore32(
106 reinterpret_cast<uint8_t*>(&iv[0]) +
107 AesGcmHkdfStreamSegmentEncrypter::kNoncePrefixSizeInBytes,
108 segment_number);
109 iv.back() = is_last_segment ? 1 : 0;
110 return iv;
111 }
112
113 } // namespace
114
get_plaintext_segment_size() const115 int AesGcmHkdfStreamSegmentEncrypter::get_plaintext_segment_size() const {
116 return ciphertext_segment_size_ - kTagSizeInBytes;
117 }
118
AesGcmHkdfStreamSegmentEncrypter(std::unique_ptr<internal::SslOneShotAead> aead,const Params & params)119 AesGcmHkdfStreamSegmentEncrypter::AesGcmHkdfStreamSegmentEncrypter(
120 std::unique_ptr<internal::SslOneShotAead> aead, const Params& params)
121 : aead_(std::move(aead)),
122 nonce_prefix_(Random::GetRandomBytes(kNoncePrefixSizeInBytes)),
123 header_(CreateHeader(params.salt, nonce_prefix_)),
124 ciphertext_segment_size_(params.ciphertext_segment_size),
125 ciphertext_offset_(params.ciphertext_offset) {}
126
127 util::StatusOr<std::unique_ptr<StreamSegmentEncrypter>>
New(Params params)128 AesGcmHkdfStreamSegmentEncrypter::New(Params params) {
129 util::Status status = Validate(params);
130 if (!status.ok()) {
131 return status;
132 }
133 util::StatusOr<std::unique_ptr<internal::SslOneShotAead>> aead =
134 internal::CreateAesGcmOneShotCrypter(params.key);
135 if (!aead.ok()) {
136 return aead.status();
137 }
138 return {absl::WrapUnique(
139 new AesGcmHkdfStreamSegmentEncrypter(*std::move(aead), params))};
140 }
141
EncryptSegment(const std::vector<uint8_t> & plaintext,bool is_last_segment,std::vector<uint8_t> * ciphertext_buffer)142 util::Status AesGcmHkdfStreamSegmentEncrypter::EncryptSegment(
143 const std::vector<uint8_t>& plaintext, bool is_last_segment,
144 std::vector<uint8_t>* ciphertext_buffer) {
145 if (plaintext.size() > get_plaintext_segment_size()) {
146 return util::Status(absl::StatusCode::kInvalidArgument,
147 "plaintext too long");
148 }
149 if (ciphertext_buffer == nullptr) {
150 return util::Status(absl::StatusCode::kInvalidArgument,
151 "ciphertext_buffer must be non-null");
152 }
153 if (get_segment_number() > std::numeric_limits<uint32_t>::max() ||
154 (get_segment_number() == std::numeric_limits<uint32_t>::max() &&
155 !is_last_segment)) {
156 return util::Status(absl::StatusCode::kInvalidArgument,
157 "too many segments");
158 }
159
160 const int64_t kCiphertextSize = plaintext.size() + kTagSizeInBytes;
161 ciphertext_buffer->resize(kCiphertextSize);
162
163 // Construct IV.
164 std::string iv =
165 ConstructNonce(nonce_prefix_, static_cast<uint32_t>(get_segment_number()),
166 is_last_segment);
167
168 util::StatusOr<uint64_t> written_bytes = aead_->Encrypt(
169 absl::string_view(reinterpret_cast<const char*>(plaintext.data()),
170 plaintext.size()),
171 /*associated_data=*/absl::string_view(""), iv,
172 absl::MakeSpan(reinterpret_cast<char*>(ciphertext_buffer->data()),
173 ciphertext_buffer->size()));
174
175 if (!written_bytes.ok()) {
176 return written_bytes.status();
177 }
178
179 IncSegmentNumber();
180 return util::OkStatus();
181 }
182
183 } // namespace subtle
184 } // namespace tink
185 } // namespace crypto
186