blob: b37900e38a61a30271721fa9886153dfb4d0e14b [file] [log] [blame]
Max Bires57c187a2021-03-03 16:30:16 -08001/*
2 * Copyright (C) 2020 The Android Open Source Project
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 <keymaster/cppcose/cppcose.h>
18
19#include <iostream>
20#include <stdio.h>
21
22#include <cppbor.h>
23#include <cppbor_parse.h>
24
25#include <openssl/err.h>
26
27namespace cppcose {
28
29namespace {
30
31ErrMsgOr<bssl::UniquePtr<EVP_CIPHER_CTX>> aesGcmInitAndProcessAad(const bytevec& key,
32 const bytevec& nonce,
33 const bytevec& aad,
34 bool encrypt) {
35 if (key.size() != kAesGcmKeySize) return "Invalid key size";
36
37 bssl::UniquePtr<EVP_CIPHER_CTX> ctx(EVP_CIPHER_CTX_new());
38 if (!ctx) return "Failed to allocate cipher context";
39
40 if (!EVP_CipherInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr /* engine */, key.data(),
41 nonce.data(), encrypt ? 1 : 0)) {
42 return "Failed to initialize cipher";
43 }
44
45 int outlen;
46 if (!aad.empty() && !EVP_CipherUpdate(ctx.get(), nullptr /* out; null means AAD */, &outlen,
47 aad.data(), aad.size())) {
48 return "Failed to process AAD";
49 }
50
51 return std::move(ctx);
52}
53
54} // namespace
55
Seth Moored24ea202021-04-30 11:42:31 -070056ErrMsgOr<HmacSha256> generateHmacSha256(const bytevec& key, const bytevec& data) {
57 HmacSha256 digest;
58 unsigned int outLen;
59 uint8_t* out = HMAC(EVP_sha256(), //
60 key.data(), key.size(), //
61 data.data(), data.size(), //
62 digest.data(), &outLen);
Seth Moore448141b2021-04-22 20:34:03 +000063
Seth Moored24ea202021-04-30 11:42:31 -070064 if (out == nullptr || outLen != digest.size()) {
65 return "Error generating HMAC";
66 }
67 return digest;
68}
69
70ErrMsgOr<HmacSha256> generateCoseMac0Mac(HmacSha256Function macFunction, const bytevec& externalAad,
71 const bytevec& payload) {
Max Bires57c187a2021-03-03 16:30:16 -080072 auto macStructure = cppbor::Array()
73 .add("MAC0")
74 .add(cppbor::Map().add(ALGORITHM, HMAC_256).canonicalize().encode())
75 .add(externalAad)
76 .add(payload)
77 .encode();
78
Seth Moored24ea202021-04-30 11:42:31 -070079 auto macTag = macFunction(macStructure);
80 if (!macTag) {
Max Bires57c187a2021-03-03 16:30:16 -080081 return "Error computing public key MAC";
82 }
83
Seth Moored24ea202021-04-30 11:42:31 -070084 return *macTag;
Max Bires57c187a2021-03-03 16:30:16 -080085}
86
Seth Moored24ea202021-04-30 11:42:31 -070087ErrMsgOr<cppbor::Array> constructCoseMac0(HmacSha256Function macFunction,
88 const bytevec& externalAad, const bytevec& payload) {
89 auto tag = generateCoseMac0Mac(macFunction, externalAad, payload);
Max Bires57c187a2021-03-03 16:30:16 -080090 if (!tag) return tag.moveMessage();
91
92 return cppbor::Array()
93 .add(cppbor::Map().add(ALGORITHM, HMAC_256).canonicalize().encode())
94 .add(cppbor::Map() /* unprotected */)
95 .add(payload)
Seth Moored24ea202021-04-30 11:42:31 -070096 .add(std::pair(tag->begin(), tag->end()));
Max Bires57c187a2021-03-03 16:30:16 -080097}
98
99ErrMsgOr<bytevec /* payload */> verifyAndParseCoseMac0(const cppbor::Item* macItem,
100 const bytevec& macKey) {
101 auto mac = macItem ? macItem->asArray() : nullptr;
102 if (!mac || mac->size() != kCoseMac0EntryCount) {
103 return "Invalid COSE_Mac0";
104 }
105
106 auto protectedParms = mac->get(kCoseMac0ProtectedParams)->asBstr();
107 auto unprotectedParms = mac->get(kCoseMac0UnprotectedParams)->asMap();
108 auto payload = mac->get(kCoseMac0Payload)->asBstr();
109 auto tag = mac->get(kCoseMac0Tag)->asBstr();
110 if (!protectedParms || !unprotectedParms || !payload || !tag) {
111 return "Invalid COSE_Mac0 contents";
112 }
113
114 auto [protectedMap, _, errMsg] = cppbor::parse(protectedParms);
115 if (!protectedMap || !protectedMap->asMap()) {
116 return "Invalid Mac0 protected: " + errMsg;
117 }
118 auto& algo = protectedMap->asMap()->get(ALGORITHM);
119 if (!algo || !algo->asInt() || algo->asInt()->value() != HMAC_256) {
120 return "Unsupported Mac0 algorithm";
121 }
122
Seth Moored24ea202021-04-30 11:42:31 -0700123 auto macFunction = [&macKey](const bytevec& input) {
124 return generateHmacSha256(macKey, input);
125 };
126 auto macTag = generateCoseMac0Mac(macFunction, {} /* external_aad */, payload->value());
Max Bires57c187a2021-03-03 16:30:16 -0800127 if (!macTag) return macTag.moveMessage();
128
129 if (macTag->size() != tag->value().size() ||
130 CRYPTO_memcmp(macTag->data(), tag->value().data(), macTag->size()) != 0) {
131 return "MAC tag mismatch";
132 }
133
134 return payload->value();
135}
136
137ErrMsgOr<bytevec> createCoseSign1Signature(const bytevec& key, const bytevec& protectedParams,
138 const bytevec& payload, const bytevec& aad) {
139 bytevec signatureInput = cppbor::Array()
140 .add("Signature1") //
141 .add(protectedParams)
142 .add(aad)
143 .add(payload)
144 .encode();
145
146 if (key.size() != ED25519_PRIVATE_KEY_LEN) return "Invalid signing key";
147 bytevec signature(ED25519_SIGNATURE_LEN);
148 if (!ED25519_sign(signature.data(), signatureInput.data(), signatureInput.size(), key.data())) {
149 return "Signing failed";
150 }
151
152 return signature;
153}
154
155ErrMsgOr<cppbor::Array> constructCoseSign1(const bytevec& key, cppbor::Map protectedParams,
156 const bytevec& payload, const bytevec& aad) {
157 bytevec protParms = protectedParams.add(ALGORITHM, EDDSA).canonicalize().encode();
158 auto signature = createCoseSign1Signature(key, protParms, payload, aad);
159 if (!signature) return signature.moveMessage();
160
161 return cppbor::Array()
162 .add(std::move(protParms))
163 .add(cppbor::Map() /* unprotected parameters */)
164 .add(std::move(payload))
165 .add(std::move(*signature));
166}
167
168ErrMsgOr<cppbor::Array> constructCoseSign1(const bytevec& key, const bytevec& payload,
169 const bytevec& aad) {
170 return constructCoseSign1(key, {} /* protectedParams */, payload, aad);
171}
172
173ErrMsgOr<bytevec> verifyAndParseCoseSign1(bool ignoreSignature, const cppbor::Array* coseSign1,
174 const bytevec& signingCoseKey, const bytevec& aad) {
175 if (!coseSign1 || coseSign1->size() != kCoseSign1EntryCount) {
176 return "Invalid COSE_Sign1";
177 }
178
179 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
180 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
181 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
Max Bires57c187a2021-03-03 16:30:16 -0800182
Seth Moore448141b2021-04-22 20:34:03 +0000183 if (!protectedParams || !unprotectedParams || !payload) {
184 return "Missing input parameters";
Max Bires57c187a2021-03-03 16:30:16 -0800185 }
186
187 auto [parsedProtParams, _, errMsg] = cppbor::parse(protectedParams);
188 if (!parsedProtParams) {
189 return errMsg + " when parsing protected params.";
190 }
191 if (!parsedProtParams->asMap()) {
192 return "Protected params must be a map";
193 }
194
195 auto& algorithm = parsedProtParams->asMap()->get(ALGORITHM);
196 if (!algorithm || !algorithm->asInt() || algorithm->asInt()->value() != EDDSA) {
197 return "Unsupported signature algorithm";
198 }
199
200 if (!ignoreSignature) {
Seth Moore448141b2021-04-22 20:34:03 +0000201 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
202 if (!signature || signature->value().empty()) {
203 return "Missing signature input";
204 }
205
Max Bires57c187a2021-03-03 16:30:16 -0800206 bool selfSigned = signingCoseKey.empty();
207 auto key = CoseKey::parseEd25519(selfSigned ? payload->value() : signingCoseKey);
Seth Moore448141b2021-04-22 20:34:03 +0000208 if (!key || key->getBstrValue(CoseKey::PUBKEY_X)->empty()) {
209 return "Bad signing key: " + key.moveMessage();
210 }
Max Bires57c187a2021-03-03 16:30:16 -0800211
212 bytevec signatureInput =
213 cppbor::Array().add("Signature1").add(*protectedParams).add(aad).add(*payload).encode();
214
215 if (!ED25519_verify(signatureInput.data(), signatureInput.size(), signature->value().data(),
216 key->getBstrValue(CoseKey::PUBKEY_X)->data())) {
217 return "Signature verification failed";
218 }
219 }
220
221 return payload->value();
222}
223
224ErrMsgOr<bytevec> createCoseEncryptCiphertext(const bytevec& key, const bytevec& nonce,
225 const bytevec& protectedParams,
226 const bytevec& plaintextPayload, const bytevec& aad) {
227 auto ciphertext = aesGcmEncrypt(key, nonce,
228 cppbor::Array() // Enc strucure as AAD
229 .add("Encrypt") // Context
230 .add(protectedParams) // Protected
231 .add(aad) // External AAD
232 .encode(),
233 plaintextPayload);
234
235 if (!ciphertext) return ciphertext.moveMessage();
236 return ciphertext.moveValue();
237}
238
239ErrMsgOr<cppbor::Array> constructCoseEncrypt(const bytevec& key, const bytevec& nonce,
240 const bytevec& plaintextPayload, const bytevec& aad,
241 cppbor::Array recipients) {
242 auto encryptProtectedHeader = cppbor::Map() //
243 .add(ALGORITHM, AES_GCM_256)
244 .canonicalize()
245 .encode();
246
247 auto ciphertext =
248 createCoseEncryptCiphertext(key, nonce, encryptProtectedHeader, plaintextPayload, aad);
249 if (!ciphertext) return ciphertext.moveMessage();
250
251 return cppbor::Array()
252 .add(encryptProtectedHeader) // Protected
253 .add(cppbor::Map().add(IV, nonce).canonicalize()) // Unprotected
254 .add(*ciphertext) // Payload
255 .add(std::move(recipients));
256}
257
258ErrMsgOr<std::pair<bytevec /* pubkey */, bytevec /* key ID */>>
259getSenderPubKeyFromCoseEncrypt(const cppbor::Item* coseEncrypt) {
260 if (!coseEncrypt || !coseEncrypt->asArray() ||
261 coseEncrypt->asArray()->size() != kCoseEncryptEntryCount) {
262 return "Invalid COSE_Encrypt";
263 }
264
265 auto& recipients = coseEncrypt->asArray()->get(kCoseEncryptRecipients);
266 if (!recipients || !recipients->asArray() || recipients->asArray()->size() != 1) {
267 return "Invalid recipients list";
268 }
269
270 auto& recipient = recipients->asArray()->get(0);
271 if (!recipient || !recipient->asArray() || recipient->asArray()->size() != 3) {
272 return "Invalid COSE_recipient";
273 }
274
275 auto& ciphertext = recipient->asArray()->get(2);
276 if (!ciphertext->asSimple() || !ciphertext->asSimple()->asNull()) {
277 return "Unexpected value in recipients ciphertext field " +
278 cppbor::prettyPrint(ciphertext.get());
279 }
280
281 auto& protParms = recipient->asArray()->get(0);
282 if (!protParms || !protParms->asBstr()) return "Invalid protected params";
283 auto [parsedProtParms, _, errMsg] = cppbor::parse(protParms->asBstr());
284 if (!parsedProtParms) return "Failed to parse protected params: " + errMsg;
285 if (!parsedProtParms->asMap()) return "Invalid protected params";
286
287 auto& algorithm = parsedProtParms->asMap()->get(ALGORITHM);
288 if (!algorithm || !algorithm->asInt() || algorithm->asInt()->value() != ECDH_ES_HKDF_256) {
289 return "Invalid algorithm";
290 }
291
292 auto& unprotParms = recipient->asArray()->get(1);
293 if (!unprotParms || !unprotParms->asMap()) return "Invalid unprotected params";
294
295 auto& senderCoseKey = unprotParms->asMap()->get(COSE_KEY);
296 if (!senderCoseKey || !senderCoseKey->asMap()) return "Invalid sender COSE_Key";
297
298 auto& keyType = senderCoseKey->asMap()->get(CoseKey::KEY_TYPE);
299 if (!keyType || !keyType->asInt() || keyType->asInt()->value() != OCTET_KEY_PAIR) {
300 return "Invalid key type";
301 }
302
303 auto& curve = senderCoseKey->asMap()->get(CoseKey::CURVE);
304 if (!curve || !curve->asInt() || curve->asInt()->value() != X25519) {
305 return "Unsupported curve";
306 }
307
308 auto& pubkey = senderCoseKey->asMap()->get(CoseKey::PUBKEY_X);
309 if (!pubkey || !pubkey->asBstr() ||
310 pubkey->asBstr()->value().size() != X25519_PUBLIC_VALUE_LEN) {
311 return "Invalid X25519 public key";
312 }
313
314 auto& key_id = unprotParms->asMap()->get(KEY_ID);
315 if (key_id && key_id->asBstr()) {
316 return std::make_pair(pubkey->asBstr()->value(), key_id->asBstr()->value());
317 }
318
319 // If no key ID, just return an empty vector.
320 return std::make_pair(pubkey->asBstr()->value(), bytevec{});
321}
322
323ErrMsgOr<bytevec> decryptCoseEncrypt(const bytevec& key, const cppbor::Item* coseEncrypt,
324 const bytevec& external_aad) {
325 if (!coseEncrypt || !coseEncrypt->asArray() ||
326 coseEncrypt->asArray()->size() != kCoseEncryptEntryCount) {
327 return "Invalid COSE_Encrypt";
328 }
329
330 auto& protParms = coseEncrypt->asArray()->get(kCoseEncryptProtectedParams);
331 auto& unprotParms = coseEncrypt->asArray()->get(kCoseEncryptUnprotectedParams);
332 auto& ciphertext = coseEncrypt->asArray()->get(kCoseEncryptPayload);
333 auto& recipients = coseEncrypt->asArray()->get(kCoseEncryptRecipients);
334
335 if (!protParms || !protParms->asBstr() || !unprotParms || !ciphertext || !recipients) {
336 return "Invalid COSE_Encrypt";
337 }
338
339 auto [parsedProtParams, _, errMsg] = cppbor::parse(protParms->asBstr()->value());
340 if (!parsedProtParams) {
341 return errMsg + " when parsing protected params.";
342 }
343 if (!parsedProtParams->asMap()) {
344 return "Protected params must be a map";
345 }
346
347 auto& algorithm = parsedProtParams->asMap()->get(ALGORITHM);
348 if (!algorithm || !algorithm->asInt() || algorithm->asInt()->value() != AES_GCM_256) {
349 return "Unsupported encryption algorithm";
350 }
351
352 if (!unprotParms->asMap() || unprotParms->asMap()->size() != 1) {
353 return "Invalid unprotected params";
354 }
355
356 auto& nonce = unprotParms->asMap()->get(IV);
357 if (!nonce || !nonce->asBstr() || nonce->asBstr()->value().size() != kAesGcmNonceLength) {
358 return "Invalid nonce";
359 }
360
361 if (!ciphertext->asBstr()) return "Invalid ciphertext";
362
363 auto aad = cppbor::Array() // Enc strucure as AAD
364 .add("Encrypt") // Context
365 .add(protParms->asBstr()->value()) // Protected
366 .add(external_aad) // External AAD
367 .encode();
368
369 return aesGcmDecrypt(key, nonce->asBstr()->value(), aad, ciphertext->asBstr()->value());
370}
371
372ErrMsgOr<bytevec> x25519_HKDF_DeriveKey(const bytevec& pubKeyA, const bytevec& privKeyA,
373 const bytevec& pubKeyB, bool senderIsA) {
Seth Moore448141b2021-04-22 20:34:03 +0000374 if (privKeyA.empty() || pubKeyA.empty() || pubKeyB.empty()) {
375 return "Missing input key parameters";
376 }
377
Max Bires57c187a2021-03-03 16:30:16 -0800378 bytevec rawSharedKey(X25519_SHARED_KEY_LEN);
379 if (!::X25519(rawSharedKey.data(), privKeyA.data(), pubKeyB.data())) {
380 return "ECDH operation failed";
381 }
382
383 bytevec kdfContext = cppbor::Array()
384 .add(AES_GCM_256)
385 .add(cppbor::Array() // Sender Info
386 .add(cppbor::Bstr("client"))
387 .add(bytevec{} /* nonce */)
388 .add(senderIsA ? pubKeyA : pubKeyB))
389 .add(cppbor::Array() // Recipient Info
390 .add(cppbor::Bstr("server"))
391 .add(bytevec{} /* nonce */)
392 .add(senderIsA ? pubKeyB : pubKeyA))
393 .add(cppbor::Array() // SuppPubInfo
394 .add(kAesGcmKeySizeBits) // output key length
395 .add(bytevec{})) // protected
396 .encode();
397
398 bytevec retval(SHA256_DIGEST_LENGTH);
399 bytevec salt{};
400 if (!HKDF(retval.data(), retval.size(), //
401 EVP_sha256(), //
402 rawSharedKey.data(), rawSharedKey.size(), //
403 salt.data(), salt.size(), //
404 kdfContext.data(), kdfContext.size())) {
405 return "ECDH HKDF failed";
406 }
407
408 return retval;
409}
410
411ErrMsgOr<bytevec> aesGcmEncrypt(const bytevec& key, const bytevec& nonce, const bytevec& aad,
412 const bytevec& plaintext) {
413 auto ctx = aesGcmInitAndProcessAad(key, nonce, aad, true /* encrypt */);
414 if (!ctx) return ctx.moveMessage();
415
416 bytevec ciphertext(plaintext.size() + kAesGcmTagSize);
417 int outlen;
418 if (!EVP_CipherUpdate(ctx->get(), ciphertext.data(), &outlen, plaintext.data(),
419 plaintext.size())) {
420 return "Failed to encrypt plaintext";
421 }
Max Bires7cccfb42021-06-09 18:15:37 -0700422 assert(plaintext.size() == static_cast<uint64_t>(outlen));
Max Bires57c187a2021-03-03 16:30:16 -0800423
424 if (!EVP_CipherFinal_ex(ctx->get(), ciphertext.data() + outlen, &outlen)) {
425 return "Failed to finalize encryption";
426 }
427 assert(outlen == 0);
428
429 if (!EVP_CIPHER_CTX_ctrl(ctx->get(), EVP_CTRL_GCM_GET_TAG, kAesGcmTagSize,
430 ciphertext.data() + plaintext.size())) {
431 return "Failed to retrieve tag";
432 }
433
434 return ciphertext;
435}
436
437ErrMsgOr<bytevec> aesGcmDecrypt(const bytevec& key, const bytevec& nonce, const bytevec& aad,
438 const bytevec& ciphertextWithTag) {
439 auto ctx = aesGcmInitAndProcessAad(key, nonce, aad, false /* encrypt */);
440 if (!ctx) return ctx.moveMessage();
441
442 if (ciphertextWithTag.size() < kAesGcmTagSize) return "Missing tag";
443
444 bytevec plaintext(ciphertextWithTag.size() - kAesGcmTagSize);
445 int outlen;
446 if (!EVP_CipherUpdate(ctx->get(), plaintext.data(), &outlen, ciphertextWithTag.data(),
447 ciphertextWithTag.size() - kAesGcmTagSize)) {
448 return "Failed to decrypt plaintext";
449 }
Max Bires7cccfb42021-06-09 18:15:37 -0700450 assert(plaintext.size() == static_cast<uint64_t>(outlen));
Max Bires57c187a2021-03-03 16:30:16 -0800451
452 bytevec tag(ciphertextWithTag.end() - kAesGcmTagSize, ciphertextWithTag.end());
453 if (!EVP_CIPHER_CTX_ctrl(ctx->get(), EVP_CTRL_GCM_SET_TAG, kAesGcmTagSize, tag.data())) {
454 return "Failed to set tag: " + std::to_string(ERR_peek_last_error());
455 }
456
457 if (!EVP_CipherFinal_ex(ctx->get(), nullptr, &outlen)) {
458 return "Failed to finalize encryption";
459 }
460 assert(outlen == 0);
461
462 return plaintext;
463}
464
465} // namespace cppcose