Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2023 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : /**
19 : * @file
20 : * Header that exposes the platform agnostic CHIP crypto primitives
21 : */
22 :
23 : #pragma once
24 :
25 : #if CHIP_HAVE_CONFIG_H
26 : #include <crypto/CryptoBuildConfig.h>
27 : #endif // CHIP_HAVE_CONFIG_H
28 :
29 : #include <system/SystemConfig.h>
30 :
31 : #include <lib/core/CHIPError.h>
32 : #include <lib/core/CHIPVendorIdentifiers.hpp>
33 : #include <lib/core/DataModelTypes.h>
34 : #include <lib/core/Optional.h>
35 : #include <lib/support/BufferReader.h>
36 : #include <lib/support/CodeUtils.h>
37 : #include <lib/support/SafePointerCast.h>
38 : #include <lib/support/Span.h>
39 :
40 : #include <stddef.h>
41 : #include <string.h>
42 :
43 : namespace chip {
44 : namespace Crypto {
45 :
46 : inline constexpr size_t kMax_x509_Certificate_Length = 600;
47 :
48 : inline constexpr size_t kP256_FE_Length = 32;
49 : inline constexpr size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length);
50 : inline constexpr size_t kP256_Point_Length = (2 * kP256_FE_Length + 1);
51 : inline constexpr size_t kSHA256_Hash_Length = 32;
52 : inline constexpr size_t kSHA1_Hash_Length = 20;
53 : inline constexpr size_t kSubjectKeyIdentifierLength = kSHA1_Hash_Length;
54 : inline constexpr size_t kAuthorityKeyIdentifierLength = kSHA1_Hash_Length;
55 : inline constexpr size_t kMaxCertificateSerialNumberLength = 20;
56 : inline constexpr size_t kMaxCertificateDistinguishedNameLength = 200;
57 : inline constexpr size_t kMaxCRLDistributionPointURLLength = 100;
58 :
59 : inline constexpr char kValidCDPURIHttpPrefix[] = "http://";
60 : inline constexpr char kValidCDPURIHttpsPrefix[] = "https://";
61 :
62 : inline constexpr size_t CHIP_CRYPTO_GROUP_SIZE_BYTES = kP256_FE_Length;
63 : inline constexpr size_t CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES = kP256_Point_Length;
64 :
65 : inline constexpr size_t CHIP_CRYPTO_AEAD_MIC_LENGTH_BYTES = 16;
66 : inline constexpr size_t CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES = 16;
67 :
68 : inline constexpr size_t kMax_ECDH_Secret_Length = kP256_FE_Length;
69 : inline constexpr size_t kMax_ECDSA_Signature_Length = kP256_ECDSA_Signature_Length_Raw;
70 : inline constexpr size_t kMAX_FE_Length = kP256_FE_Length;
71 : inline constexpr size_t kMAX_Point_Length = kP256_Point_Length;
72 : inline constexpr size_t kMAX_Hash_Length = kSHA256_Hash_Length;
73 :
74 : // Minimum required CSR length buffer length is relatively small since it's a single
75 : // P256 key and no metadata/extensions are expected to be honored by the CA.
76 : inline constexpr size_t kMIN_CSR_Buffer_Size = 255;
77 :
78 : [[deprecated("This constant is no longer used by common code and should be replaced by kMIN_CSR_Buffer_Size. Checks that a CSR is "
79 : "<= kMAX_CSR_Buffer_size must be updated. This remains to keep valid buffers working from previous public API "
80 : "usage.")]] constexpr size_t kMAX_CSR_Buffer_Size = 255;
81 :
82 : inline constexpr size_t CHIP_CRYPTO_HASH_LEN_BYTES = kSHA256_Hash_Length;
83 :
84 : inline constexpr size_t kSpake2p_Min_PBKDF_Salt_Length = 16;
85 : inline constexpr size_t kSpake2p_Max_PBKDF_Salt_Length = 32;
86 : inline constexpr uint32_t kSpake2p_Min_PBKDF_Iterations = 1000;
87 : inline constexpr uint32_t kSpake2p_Max_PBKDF_Iterations = 100000;
88 :
89 : inline constexpr size_t kP256_PrivateKey_Length = CHIP_CRYPTO_GROUP_SIZE_BYTES;
90 : inline constexpr size_t kP256_PublicKey_Length = CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES;
91 :
92 : inline constexpr size_t kAES_CCM128_Key_Length = 128u / 8u;
93 : inline constexpr size_t kAES_CCM128_Block_Length = kAES_CCM128_Key_Length;
94 : inline constexpr size_t kAES_CCM128_Nonce_Length = 13;
95 : inline constexpr size_t kAES_CCM128_Tag_Length = 16;
96 : inline constexpr size_t kHMAC_CCM128_Key_Length = 128u / 8u;
97 :
98 : inline constexpr size_t CHIP_CRYPTO_AEAD_NONCE_LENGTH_BYTES = kAES_CCM128_Nonce_Length;
99 :
100 : /* These sizes are hardcoded here to remove header dependency on underlying crypto library
101 : * in a public interface file. The validity of these sizes is verified by static_assert in
102 : * the implementation files.
103 : */
104 : inline constexpr size_t kMAX_Spake2p_Context_Size = 1024;
105 : inline constexpr size_t kMAX_P256Keypair_Context_Size = 512;
106 :
107 : inline constexpr size_t kEmitDerIntegerWithoutTagOverhead = 1; // 1 sign stuffer
108 : inline constexpr size_t kEmitDerIntegerOverhead = 3; // Tag + Length byte + 1 sign stuffer
109 :
110 : inline constexpr size_t kMAX_Hash_SHA256_Context_Size = CHIP_CONFIG_SHA256_CONTEXT_SIZE;
111 :
112 : inline constexpr size_t kSpake2p_WS_Length = kP256_FE_Length + 8;
113 : inline constexpr size_t kSpake2p_VerifierSerialized_Length = kP256_FE_Length + kP256_Point_Length;
114 :
115 : inline constexpr char kVIDPrefixForCNEncoding[] = "Mvid:";
116 : inline constexpr char kPIDPrefixForCNEncoding[] = "Mpid:";
117 : inline constexpr size_t kVIDandPIDHexLength = sizeof(uint16_t) * 2;
118 : inline constexpr size_t kMax_CommonNameAttr_Length = 64;
119 :
120 : enum class FabricBindingVersion : uint8_t
121 : {
122 : kVersion1 = 0x01 // Initial version using version 1.0 of the Matter Cryptographic Primitives.
123 : };
124 :
125 : // VidVerificationStatementVersion is on purpose different and non-overlapping with FabricBindingVersion.
126 : enum class VidVerificationStatementVersion : uint8_t
127 : {
128 : kVersion1 = 0x21 // Initial version using version 1.0 of the Matter Cryptographic Primitives.
129 : };
130 :
131 : inline constexpr uint8_t kFabricBindingVersionV1 = 1u;
132 :
133 : inline constexpr size_t kVendorIdVerificationClientChallengeSize = 32u;
134 :
135 : // VIDVerificationStatement := statement_version || vid_verification_signer_skid || vid_verification_statement_signature
136 : inline constexpr size_t kVendorIdVerificationStatementV1Size =
137 : sizeof(uint8_t) + kSubjectKeyIdentifierLength + kP256_ECDSA_Signature_Length_Raw;
138 : static_assert(
139 : kVendorIdVerificationStatementV1Size == 85,
140 : "Expected size of VendorIdVerificationStatement version 1 was computed incorrectly due to changes of fundamental constants");
141 :
142 : // vendor_fabric_binding_message := fabric_binding_version (1 byte) || root_public_key || fabric_id || vendor_id
143 : inline constexpr size_t kVendorFabricBindingMessageV1Size =
144 : sizeof(uint8_t) + CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES + sizeof(uint64_t) + sizeof(uint16_t);
145 : static_assert(
146 : kVendorFabricBindingMessageV1Size == 76,
147 : "Expected size of VendorFabricBindingMessage version 1 was computed incorrectly due to changes of fundamental constants");
148 :
149 : // vendor_id_verification_tbs := fabric_binding_version || client_challenge || attestation_challenge || fabric_index ||
150 : // vendor_fabric_binding_message || <vid_verification_statement>
151 : inline constexpr size_t kVendorIdVerificationTbsV1MaxSize = sizeof(uint8_t) + kVendorIdVerificationClientChallengeSize +
152 : CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES + sizeof(uint8_t) + kVendorFabricBindingMessageV1Size +
153 : kVendorIdVerificationStatementV1Size;
154 :
155 : /*
156 : * Overhead to encode a raw ECDSA signature in X9.62 format in ASN.1 DER
157 : *
158 : * Ecdsa-Sig-Value ::= SEQUENCE {
159 : * r INTEGER,
160 : * s INTEGER
161 : * }
162 : *
163 : * --> SEQUENCE, universal constructed tag (0x30), length over 2 bytes, up to 255 (to support future larger sizes up to 512 bits)
164 : * -> SEQ_OVERHEAD = 3 bytes
165 : * --> INTEGER, universal primitive tag (0x02), length over 1 byte, one extra byte worst case
166 : * over max for 0x00 when MSB is set.
167 : * -> INT_OVERHEAD = 3 bytes
168 : *
169 : * There is 1 sequence of 2 integers. Overhead is SEQ_OVERHEAD + (2 * INT_OVERHEAD) = 3 + (2 * 3) = 9.
170 : */
171 : inline constexpr size_t kMax_ECDSA_X9Dot62_Asn1_Overhead = 9;
172 : inline constexpr size_t kMax_ECDSA_Signature_Length_Der = kMax_ECDSA_Signature_Length + kMax_ECDSA_X9Dot62_Asn1_Overhead;
173 :
174 : static_assert(kMax_ECDH_Secret_Length >= kP256_FE_Length, "ECDH shared secret is too short for crypto suite");
175 : static_assert(kMax_ECDSA_Signature_Length >= kP256_ECDSA_Signature_Length_Raw,
176 : "ECDSA signature buffer length is too short for crypto suite");
177 :
178 : inline constexpr size_t kCompressedFabricIdentifierSize = 8;
179 :
180 : /**
181 : * Spake2+ parameters for P256
182 : * Defined in https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html#name-ciphersuites
183 : */
184 : const uint8_t spake2p_M_p256[] = {
185 : 0x04, 0x88, 0x6e, 0x2f, 0x97, 0xac, 0xe4, 0x6e, 0x55, 0xba, 0x9d, 0xd7, 0x24, 0x25, 0x79, 0xf2, 0x99,
186 : 0x3b, 0x64, 0xe1, 0x6e, 0xf3, 0xdc, 0xab, 0x95, 0xaf, 0xd4, 0x97, 0x33, 0x3d, 0x8f, 0xa1, 0x2f, 0x5f,
187 : 0xf3, 0x55, 0x16, 0x3e, 0x43, 0xce, 0x22, 0x4e, 0x0b, 0x0e, 0x65, 0xff, 0x02, 0xac, 0x8e, 0x5c, 0x7b,
188 : 0xe0, 0x94, 0x19, 0xc7, 0x85, 0xe0, 0xca, 0x54, 0x7d, 0x55, 0xa1, 0x2e, 0x2d, 0x20,
189 : };
190 : const uint8_t spake2p_N_p256[] = {
191 : 0x04, 0xd8, 0xbb, 0xd6, 0xc6, 0x39, 0xc6, 0x29, 0x37, 0xb0, 0x4d, 0x99, 0x7f, 0x38, 0xc3, 0x77, 0x07,
192 : 0x19, 0xc6, 0x29, 0xd7, 0x01, 0x4d, 0x49, 0xa2, 0x4b, 0x4f, 0x98, 0xba, 0xa1, 0x29, 0x2b, 0x49, 0x07,
193 : 0xd6, 0x0a, 0xa6, 0xbf, 0xad, 0xe4, 0x50, 0x08, 0xa6, 0x36, 0x33, 0x7f, 0x51, 0x68, 0xc6, 0x4d, 0x9b,
194 : 0xd3, 0x60, 0x34, 0x80, 0x8c, 0xd5, 0x64, 0x49, 0x0b, 0x1e, 0x65, 0x6e, 0xdb, 0xe7,
195 : };
196 :
197 : /**
198 : * Spake2+ state machine to ensure proper execution of the protocol.
199 : */
200 : enum class CHIP_SPAKE2P_STATE : uint8_t
201 : {
202 : PREINIT = 0, // Before any initialization
203 : INIT, // First initialization
204 : STARTED, // Prover & Verifier starts
205 : R1, // Round one complete
206 : R2, // Round two complete
207 : KC, // Key confirmation complete
208 : };
209 :
210 : /**
211 : * Spake2+ role.
212 : */
213 : enum class CHIP_SPAKE2P_ROLE : uint8_t
214 : {
215 : VERIFIER = 0, // Accessory
216 : PROVER = 1, // Commissioner
217 : };
218 :
219 : enum class SupportedECPKeyTypes : uint8_t
220 : {
221 : ECP256R1 = 0,
222 : };
223 :
224 : enum class ECPKeyTarget : uint8_t
225 : {
226 : ECDH = 0,
227 : ECDSA = 1,
228 : };
229 :
230 : /** @brief Safely clears the first `len` bytes of memory area `buf`.
231 : * @param buf Pointer to a memory buffer holding secret data that must be cleared.
232 : * @param len Specifies secret data size in bytes.
233 : **/
234 : void ClearSecretData(uint8_t * buf, size_t len);
235 :
236 : /**
237 : * Helper for clearing a C array which auto-deduces the size.
238 : */
239 : template <size_t N>
240 413405 : void ClearSecretData(uint8_t (&buf)[N])
241 : {
242 413405 : ClearSecretData(buf, N);
243 413405 : }
244 :
245 : /**
246 : * @brief Constant-time buffer comparison
247 : *
248 : * This function implements constant time memcmp. It's good practice
249 : * to use constant time functions for cryptographic functions.
250 : *
251 : * @param a Pointer to first buffer
252 : * @param b Pointer to Second buffer
253 : * @param n Number of bytes to compare
254 : * @return true if `n` first bytes of both buffers are equal, false otherwise
255 : */
256 : bool IsBufferContentEqualConstantTime(const void * a, const void * b, size_t n);
257 :
258 : template <typename Sig>
259 : class ECPKey
260 : {
261 : protected:
262 : // This base type can't be copied / assigned directly.
263 : // Sub-types should be either uncopyable or final.
264 0 : ECPKey() = default;
265 : ECPKey(const ECPKey &) = default;
266 1596 : ECPKey & operator=(const ECPKey &) = default;
267 :
268 : public:
269 818 : virtual ~ECPKey() = default;
270 :
271 : virtual SupportedECPKeyTypes Type() const = 0;
272 : virtual size_t Length() const = 0;
273 : virtual bool IsUncompressed() const = 0;
274 : virtual operator const uint8_t *() const = 0;
275 : virtual operator uint8_t *() = 0;
276 : virtual const uint8_t * ConstBytes() const = 0;
277 : virtual uint8_t * Bytes() = 0;
278 :
279 0 : virtual bool Matches(const ECPKey<Sig> & other) const
280 : {
281 0 : return (this->Length() == other.Length()) &&
282 0 : IsBufferContentEqualConstantTime(this->ConstBytes(), other.ConstBytes(), this->Length());
283 : }
284 :
285 : virtual CHIP_ERROR ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length, const Sig & signature) const = 0;
286 : virtual CHIP_ERROR ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length,
287 : const Sig & signature) const = 0;
288 : };
289 :
290 : /**
291 : * @brief Helper class for holding sensitive data that should be erased from memory after use.
292 : *
293 : * The sensitive data buffer is a variable-length, fixed-capacity buffer class that securely erases
294 : * the contents of a buffer when the buffer is destroyed.
295 : */
296 : template <size_t kCapacity>
297 : class SensitiveDataBuffer
298 : {
299 : public:
300 3618 : ~SensitiveDataBuffer()
301 : {
302 : // Sanitize after use
303 3618 : ClearSecretData(mBytes);
304 3618 : }
305 3617 : SensitiveDataBuffer() {}
306 1 : SensitiveDataBuffer(const SensitiveDataBuffer & other) { *this = other; }
307 1 : SensitiveDataBuffer & operator=(const SensitiveDataBuffer & other)
308 : {
309 : // Guard self assignment
310 1 : if (this == &other)
311 0 : return *this;
312 :
313 1 : ClearSecretData(mBytes);
314 1 : SetLength(other.Length());
315 1 : ::memcpy(Bytes(), other.ConstBytes(), other.Length());
316 1 : return *this;
317 : }
318 :
319 : /**
320 : * @brief Set current length of the buffer
321 : * @return Error if new length is exceeds capacity of the buffer
322 : */
323 3496 : CHIP_ERROR SetLength(size_t length)
324 : {
325 3496 : VerifyOrReturnError(length <= kCapacity, CHIP_ERROR_INVALID_ARGUMENT);
326 3496 : mLength = length;
327 3496 : return CHIP_NO_ERROR;
328 : }
329 :
330 : /**
331 : * @brief Returns current length of the buffer
332 : */
333 3699 : size_t Length() const { return mLength; }
334 :
335 : /**
336 : * @brief Returns non-const pointer to start of the underlying buffer
337 : */
338 3880 : uint8_t * Bytes() { return &mBytes[0]; }
339 :
340 : /**
341 : * @brief Returns const pointer to start of the underlying buffer
342 : */
343 6165 : const uint8_t * ConstBytes() const { return &mBytes[0]; }
344 :
345 : /**
346 : * @brief Constructs span from the underlying buffer
347 : */
348 21 : ByteSpan Span() const { return ByteSpan(ConstBytes(), Length()); }
349 :
350 : /**
351 : * @brief Returns capacity of the buffer
352 : */
353 1458 : static constexpr size_t Capacity() { return kCapacity; }
354 :
355 : private:
356 : uint8_t mBytes[kCapacity];
357 : size_t mLength = 0;
358 : };
359 :
360 : /**
361 : * @brief Helper class for holding fixed-sized sensitive data that should be erased from memory after use.
362 : *
363 : * The sensitive data buffer is a fixed-length, fixed-capacity buffer class that securely erases
364 : * the contents of a buffer when the buffer is destroyed.
365 : */
366 : template <size_t kCapacity>
367 : class SensitiveDataFixedBuffer
368 : {
369 : public:
370 : SensitiveDataFixedBuffer() = default;
371 :
372 : constexpr explicit SensitiveDataFixedBuffer(const uint8_t (&rawValue)[kCapacity])
373 : {
374 : memcpy(&mBytes[0], &rawValue[0], kCapacity);
375 : }
376 :
377 0 : constexpr explicit SensitiveDataFixedBuffer(const FixedByteSpan<kCapacity> & value)
378 : {
379 0 : memcpy(&mBytes[0], value.data(), kCapacity);
380 0 : }
381 :
382 135323 : ~SensitiveDataFixedBuffer()
383 : {
384 : // Sanitize after use
385 135323 : ClearSecretData(mBytes);
386 135323 : }
387 :
388 : /**
389 : * @brief Returns fixed length of the buffer
390 : */
391 : constexpr size_t Length() const { return kCapacity; }
392 :
393 : /**
394 : * @brief Returns non-const pointer to start of the underlying buffer
395 : */
396 1545 : uint8_t * Bytes() { return &mBytes[0]; }
397 :
398 : /**
399 : * @brief Returns const pointer to start of the underlying buffer
400 : */
401 : const uint8_t * ConstBytes() const { return &mBytes[0]; }
402 :
403 : /**
404 : * @brief Constructs fixed span from the underlying buffer
405 : */
406 0 : FixedByteSpan<kCapacity> Span() const { return FixedByteSpan<kCapacity>(mBytes); }
407 :
408 : /**
409 : * @brief Returns capacity of the buffer
410 : */
411 1530 : static constexpr size_t Capacity() { return kCapacity; }
412 :
413 : private:
414 : uint8_t mBytes[kCapacity];
415 : };
416 :
417 : using P256ECDSASignature = SensitiveDataBuffer<kMax_ECDSA_Signature_Length>;
418 : using P256ECDHDerivedSecret = SensitiveDataBuffer<kMax_ECDH_Secret_Length>;
419 :
420 : using IdentityProtectionKey = SensitiveDataFixedBuffer<CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES>;
421 : using IdentityProtectionKeySpan = FixedByteSpan<Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES>;
422 :
423 : using AttestationChallenge = SensitiveDataFixedBuffer<CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES>;
424 :
425 : class P256PublicKey final // final due to being copyable
426 : : public ECPKey<P256ECDSASignature>
427 : {
428 : public:
429 0 : P256PublicKey() = default;
430 :
431 : template <size_t N>
432 : constexpr P256PublicKey(const uint8_t (&raw_value)[N])
433 : {
434 : static_assert(N == kP256_PublicKey_Length, "Can only array-initialize from proper bounds");
435 : memcpy(&bytes[0], &raw_value[0], N);
436 : }
437 :
438 : template <size_t N>
439 727 : constexpr P256PublicKey(const FixedByteSpan<N> & value)
440 727 : {
441 : static_assert(N == kP256_PublicKey_Length, "Can only initialize from proper sized byte span");
442 727 : memcpy(&bytes[0], value.data(), N);
443 727 : }
444 :
445 : template <size_t N>
446 929 : P256PublicKey & operator=(const FixedByteSpan<N> & value)
447 : {
448 : static_assert(N == kP256_PublicKey_Length, "Can only initialize from proper sized byte span");
449 929 : memcpy(&bytes[0], value.data(), N);
450 929 : return *this;
451 : }
452 :
453 4182 : SupportedECPKeyTypes Type() const override { return SupportedECPKeyTypes::ECP256R1; }
454 14284 : size_t Length() const override { return kP256_PublicKey_Length; }
455 6239 : operator uint8_t *() override { return bytes; }
456 2608 : operator const uint8_t *() const override { return bytes; }
457 3154 : const uint8_t * ConstBytes() const override { return &bytes[0]; }
458 16 : uint8_t * Bytes() override { return &bytes[0]; }
459 797 : bool IsUncompressed() const override
460 : {
461 797 : constexpr uint8_t kUncompressedPointMarker = 0x04;
462 : // SEC1 definition of an uncompressed point is (0x04 || X || Y) where X and Y are
463 : // raw zero-padded big-endian large integers of the group size.
464 797 : return (Length() == ((kP256_FE_Length * 2) + 1)) && (ConstBytes()[0] == kUncompressedPointMarker);
465 : }
466 :
467 : CHIP_ERROR ECDSA_validate_msg_signature(const uint8_t * msg, size_t msg_length,
468 : const P256ECDSASignature & signature) const override;
469 : CHIP_ERROR ECDSA_validate_hash_signature(const uint8_t * hash, size_t hash_length,
470 : const P256ECDSASignature & signature) const override;
471 :
472 : private:
473 : uint8_t bytes[kP256_PublicKey_Length];
474 : };
475 :
476 : template <typename PK, typename Secret, typename Sig>
477 : class ECPKeypair
478 : {
479 : protected:
480 : // This base type can't be copied / assigned directly.
481 : // Sub-types should be either uncopyable or final.
482 1401 : ECPKeypair() = default;
483 : ECPKeypair(const ECPKeypair &) = default;
484 : ECPKeypair & operator=(const ECPKeypair &) = default;
485 :
486 : public:
487 1736 : virtual ~ECPKeypair() = default;
488 :
489 : /** @brief Generate a new Certificate Signing Request (CSR).
490 : * @param csr Newly generated CSR in DER format
491 : * @param csr_length The caller provides the length of input buffer (csr). The function returns the actual length of generated
492 : *CSR.
493 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
494 : **/
495 : virtual CHIP_ERROR NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const = 0;
496 :
497 : /**
498 : * @brief A function to sign a msg using ECDSA
499 : * @param msg Message that needs to be signed
500 : * @param msg_length Length of message
501 : * @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
502 : * in raw <r,s> point form (see SEC1).
503 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
504 : **/
505 : virtual CHIP_ERROR ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, Sig & out_signature) const = 0;
506 :
507 : /** @brief A function to derive a shared secret using ECDH
508 : * @param remote_public_key Public key of remote peer with which we are trying to establish secure channel. remote_public_key is
509 : * ASN.1 DER encoded as padded big-endian field elements as described in SEC 1: Elliptic Curve Cryptography
510 : * [https://www.secg.org/sec1-v2.pdf]
511 : * @param out_secret Buffer to write out secret into. This is a byte array representing the x coordinate of the shared secret.
512 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
513 : **/
514 : virtual CHIP_ERROR ECDH_derive_secret(const PK & remote_public_key, Secret & out_secret) const = 0;
515 :
516 : virtual const PK & Pubkey() const = 0;
517 : };
518 :
519 : struct alignas(size_t) P256KeypairContext
520 : {
521 : uint8_t mBytes[kMAX_P256Keypair_Context_Size];
522 : };
523 :
524 : /**
525 : * A serialized P256 key pair is the concatenation of the public and private keys, in that order.
526 : */
527 : using P256SerializedKeypair = SensitiveDataBuffer<kP256_PublicKey_Length + kP256_PrivateKey_Length>;
528 :
529 : class P256KeypairBase : public ECPKeypair<P256PublicKey, P256ECDHDerivedSecret, P256ECDSASignature>
530 : {
531 : protected:
532 : // This base type can't be copied / assigned directly.
533 : // Sub-types should be either uncopyable or final.
534 1401 : P256KeypairBase() = default;
535 : P256KeypairBase(const P256KeypairBase &) = default;
536 : P256KeypairBase & operator=(const P256KeypairBase &) = default;
537 :
538 : public:
539 : /**
540 : * @brief Initialize the keypair.
541 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
542 : **/
543 : virtual CHIP_ERROR Initialize(ECPKeyTarget key_target) = 0;
544 :
545 : /**
546 : * @brief Serialize the keypair.
547 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
548 : **/
549 : virtual CHIP_ERROR Serialize(P256SerializedKeypair & output) const = 0;
550 :
551 : /**
552 : * @brief Deserialize the keypair.
553 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
554 : **/
555 : virtual CHIP_ERROR Deserialize(P256SerializedKeypair & input) = 0;
556 : };
557 :
558 : class P256Keypair : public P256KeypairBase
559 : {
560 : public:
561 1401 : P256Keypair() = default;
562 : ~P256Keypair() override;
563 :
564 : // P256Keypair can't be copied / assigned.
565 : P256Keypair(const P256Keypair &) = delete;
566 : P256Keypair & operator=(const P256Keypair &) = delete;
567 :
568 : /**
569 : * @brief Initialize the keypair.
570 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
571 : **/
572 : CHIP_ERROR Initialize(ECPKeyTarget key_target) override;
573 :
574 : /**
575 : * @brief Serialize the keypair.
576 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
577 : **/
578 : CHIP_ERROR Serialize(P256SerializedKeypair & output) const override;
579 :
580 : /**
581 : * @brief Deserialize the keypair.
582 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
583 : **/
584 : CHIP_ERROR Deserialize(P256SerializedKeypair & input) override;
585 :
586 : /**
587 : * @brief Generate a new Certificate Signing Request (CSR).
588 : * @param csr Newly generated CSR in DER format
589 : * @param csr_length The caller provides the length of input buffer (csr). The function returns the actual length of generated
590 : *CSR.
591 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
592 : **/
593 : CHIP_ERROR NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const override;
594 :
595 : /**
596 : * @brief A function to sign a msg using ECDSA
597 : * @param msg Message that needs to be signed
598 : * @param msg_length Length of message
599 : * @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
600 : * in raw <r,s> point form (see SEC1).
601 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
602 : **/
603 : CHIP_ERROR ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) const override;
604 :
605 : /**
606 : * @brief A function to derive a shared secret using ECDH
607 : *
608 : * This implements the CHIP_Crypto_ECDH(PrivateKey myPrivateKey, PublicKey theirPublicKey) cryptographic primitive
609 : * from the specification, using this class's private key from `mKeypair` as `myPrivateKey` and the remote
610 : * public key from `remote_public_key` as `theirPublicKey`.
611 : *
612 : * @param remote_public_key Public key of remote peer with which we are trying to establish secure channel. remote_public_key is
613 : * ASN.1 DER encoded as padded big-endian field elements as described in SEC 1: Elliptic Curve Cryptography
614 : * [https://www.secg.org/sec1-v2.pdf]
615 : * @param out_secret Buffer to write out secret into. This is a byte array representing the x coordinate of the shared secret.
616 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
617 : **/
618 : CHIP_ERROR ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const override;
619 :
620 : /** @brief Return public key for the keypair.
621 : **/
622 790 : const P256PublicKey & Pubkey() const override { return mPublicKey; }
623 :
624 : #if CHIP_WITH_NLFAULTINJECTION
625 0 : P256PublicKey & TestOnlyMutablePubkey() { return mPublicKey; }
626 : #endif
627 :
628 : /** Release resources associated with this key pair */
629 : void Clear();
630 :
631 : protected:
632 : #if CHIP_WITH_NLFAULTINJECTION
633 : mutable P256PublicKey mPublicKey;
634 : #else
635 : P256PublicKey mPublicKey;
636 : #endif
637 : // P256PublicKey mPublicKey;
638 : mutable P256KeypairContext mKeypair;
639 : bool mInitialized = false;
640 : };
641 :
642 : /**
643 : * @brief Platform-specific symmetric key handle
644 : *
645 : * The class represents a key used by the Matter stack either in the form of raw key material or key
646 : * reference, depending on the platform. To achieve that, it contains an opaque context that can be
647 : * cast to a concrete representation used by the given platform.
648 : *
649 : * @note SymmetricKeyHandle is an abstract class to force child classes for each key handle type.
650 : * SymmetricKeyHandle class implements all the necessary components for handles.
651 : */
652 : template <size_t ContextSize>
653 : class SymmetricKeyHandle
654 : {
655 : public:
656 : SymmetricKeyHandle(const SymmetricKeyHandle &) = delete;
657 : SymmetricKeyHandle(SymmetricKeyHandle &&) = delete;
658 : void operator=(const SymmetricKeyHandle &) = delete;
659 : void operator=(SymmetricKeyHandle &&) = delete;
660 :
661 : /**
662 : * @brief Get internal context cast to the desired key representation
663 : */
664 : template <class T>
665 30393 : const T & As() const
666 : {
667 30393 : return *SafePointerCast<const T *>(&mContext);
668 : }
669 :
670 : /**
671 : * @brief Get internal context cast to the desired, mutable key representation
672 : */
673 : template <class T>
674 7342 : T & AsMutable()
675 : {
676 7342 : return *SafePointerCast<T *>(&mContext);
677 : }
678 :
679 : protected:
680 271164 : SymmetricKeyHandle() = default;
681 271164 : ~SymmetricKeyHandle() { ClearSecretData(mContext.mOpaque); }
682 :
683 : private:
684 : struct alignas(uintptr_t) OpaqueContext
685 : {
686 : uint8_t mOpaque[ContextSize] = {};
687 : } mContext;
688 : };
689 :
690 : using Symmetric128BitsKeyByteArray = uint8_t[CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES];
691 :
692 : /**
693 : * @brief Platform-specific 128-bit symmetric key handle
694 : */
695 : class Symmetric128BitsKeyHandle : public SymmetricKeyHandle<CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES>
696 : {
697 : };
698 :
699 : /**
700 : * @brief Platform-specific 128-bit AES key handle
701 : */
702 : class Aes128KeyHandle final : public Symmetric128BitsKeyHandle
703 : {
704 : };
705 :
706 : /**
707 : * @brief Platform-specific 128-bit HMAC key handle
708 : */
709 : class Hmac128KeyHandle final : public Symmetric128BitsKeyHandle
710 : {
711 : };
712 :
713 : /**
714 : * @brief Platform-specific HKDF key handle
715 : */
716 : class HkdfKeyHandle final : public SymmetricKeyHandle<CHIP_CONFIG_HKDF_KEY_HANDLE_CONTEXT_SIZE>
717 : {
718 : };
719 :
720 : /**
721 : * @brief Convert a raw ECDSA signature to ASN.1 signature (per X9.62) as used by TLS libraries.
722 : *
723 : * Errors are:
724 : * - CHIP_ERROR_INVALID_ARGUMENT on any argument being invalid (e.g. nullptr), wrong sizes,
725 : * wrong or unsupported format,
726 : * - CHIP_ERROR_BUFFER_TOO_SMALL on running out of space at runtime.
727 : * - CHIP_ERROR_INTERNAL on any unexpected processing error.
728 : *
729 : * @param[in] fe_length_bytes Field Element length in bytes (e.g. 32 for P256 curve)
730 : * @param[in] raw_sig Raw signature of <r,s> concatenated
731 : * @param[out] out_asn1_sig ASN.1 DER signature format output buffer. Size must have space for at least
732 : * kMax_ECDSA_X9Dot62_Asn1_Overhead. On CHIP_NO_ERROR, the out_asn1_sig buffer will be re-assigned
733 : * to have the correct size based on variable-length output.
734 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
735 : */
736 : CHIP_ERROR EcdsaRawSignatureToAsn1(size_t fe_length_bytes, const ByteSpan & raw_sig, MutableByteSpan & out_asn1_sig);
737 :
738 : /**
739 : * @brief Convert an ASN.1 DER signature (per X9.62) as used by TLS libraries to SEC1 raw format
740 : *
741 : * Errors are:
742 : * - CHIP_ERROR_INVALID_ARGUMENT on any argument being invalid (e.g. nullptr), wrong sizes,
743 : * wrong or unsupported format,
744 : * - CHIP_ERROR_BUFFER_TOO_SMALL on running out of space at runtime.
745 : * - CHIP_ERROR_INTERNAL on any unexpected processing error.
746 : *
747 : * @param[in] fe_length_bytes Field Element length in bytes (e.g. 32 for P256 curve)
748 : * @param[in] asn1_sig ASN.1 DER signature input
749 : * @param[out] out_raw_sig Raw signature of <r,s> concatenated format output buffer. Size must be at
750 : * least >= `2 * fe_length_bytes`. On CHIP_NO_ERROR, the out_raw_sig buffer will be re-assigned
751 : * to have the correct size (2 * fe_length_bytes).
752 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
753 : */
754 : CHIP_ERROR EcdsaAsn1SignatureToRaw(size_t fe_length_bytes, const ByteSpan & asn1_sig, MutableByteSpan & out_raw_sig);
755 :
756 : /**
757 : * @brief Utility to read a length field after a tag in a DER-encoded stream.
758 : * @param[in] reader Reader instance from which the input will be read
759 : * @param[out] length Length of the following element read from the stream
760 : * @return CHIP_ERROR_INVALID_ARGUMENT or CHIP_ERROR_BUFFER_TOO_SMALL on error, CHIP_NO_ERROR otherwise
761 : */
762 : CHIP_ERROR ReadDerLength(chip::Encoding::LittleEndian::Reader & reader, size_t & length);
763 :
764 : /**
765 : * @brief Utility to emit a DER-encoded INTEGER given a raw unsigned large integer
766 : * in big-endian order. The `out_der_integer` span is updated to reflect the final
767 : * variable length, including tag and length, and must have at least `kEmitDerIntegerOverhead`
768 : * extra space in addition to the `raw_integer.size()`.
769 : * @param[in] raw_integer Bytes of a large unsigned integer in big-endian, possibly including leading zeroes
770 : * @param[out] out_der_integer Buffer to receive the DER-encoded integer
771 : * @return Returns CHIP_ERROR_INVALID_ARGUMENT or CHIP_ERROR_BUFFER_TOO_SMALL on error, CHIP_NO_ERROR otherwise.
772 : */
773 : CHIP_ERROR ConvertIntegerRawToDer(const ByteSpan & raw_integer, MutableByteSpan & out_der_integer);
774 :
775 : /**
776 : * @brief Utility to emit a DER-encoded INTEGER given a raw unsigned large integer
777 : * in big-endian order. The `out_der_integer` span is updated to reflect the final
778 : * variable length, excluding tag and length, and must have at least `kEmitDerIntegerWithoutTagOverhead`
779 : * extra space in addition to the `raw_integer.size()`.
780 : * @param[in] raw_integer Bytes of a large unsigned integer in big-endian, possibly including leading zeroes
781 : * @param[out] out_der_integer Buffer to receive the DER-encoded integer
782 : * @return Returns CHIP_ERROR_INVALID_ARGUMENT or CHIP_ERROR_BUFFER_TOO_SMALL on error, CHIP_NO_ERROR otherwise.
783 : */
784 : CHIP_ERROR ConvertIntegerRawToDerWithoutTag(const ByteSpan & raw_integer, MutableByteSpan & out_der_integer);
785 :
786 : /**
787 : * @brief A function that implements AES-CCM encryption
788 : *
789 : * This implements the CHIP_Crypto_AEAD_GenerateEncrypt() cryptographic primitive
790 : * from the specification. For an empty plaintext, the user of the API can provide
791 : * an empty string, or a nullptr, and provide plaintext_length as 0. The output buffer,
792 : * ciphertext can also be an empty string, or a nullptr for this case.
793 : *
794 : * @param plaintext Plaintext to encrypt
795 : * @param plaintext_length Length of plain_text
796 : * @param aad Additional authentication data
797 : * @param aad_length Length of additional authentication data
798 : * @param key Encryption key
799 : * @param nonce Encryption nonce
800 : * @param nonce_length Length of encryption nonce
801 : * @param ciphertext Buffer to write ciphertext into. Caller must ensure this is large enough to hold the ciphertext
802 : * @param tag Buffer to write tag into. Caller must ensure this is large enough to hold the tag
803 : * @param tag_length Expected length of tag
804 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
805 : * */
806 : CHIP_ERROR AES_CCM_encrypt(const uint8_t * plaintext, size_t plaintext_length, const uint8_t * aad, size_t aad_length,
807 : const Aes128KeyHandle & key, const uint8_t * nonce, size_t nonce_length, uint8_t * ciphertext,
808 : uint8_t * tag, size_t tag_length);
809 :
810 : /**
811 : * @brief A function that implements AES-CCM decryption
812 : *
813 : * This implements the CHIP_Crypto_AEAD_DecryptVerify() cryptographic primitive
814 : * from the specification. For an empty ciphertext, the user of the API can provide
815 : * an empty string, or a nullptr, and provide ciphertext_length as 0. The output buffer,
816 : * plaintext can also be an empty string, or a nullptr for this case.
817 : *
818 : * @param ciphertext Ciphertext to decrypt
819 : * @param ciphertext_length Length of ciphertext
820 : * @param aad Additional authentical data.
821 : * @param aad_length Length of additional authentication data
822 : * @param tag Tag to use to decrypt
823 : * @param tag_length Length of tag
824 : * @param key Decryption key
825 : * @param nonce Encryption nonce
826 : * @param nonce_length Length of encryption nonce
827 : * @param plaintext Buffer to write plaintext into
828 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
829 : **/
830 : CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_length, const uint8_t * aad, size_t aad_length,
831 : const uint8_t * tag, size_t tag_length, const Aes128KeyHandle & key, const uint8_t * nonce,
832 : size_t nonce_length, uint8_t * plaintext);
833 :
834 : /**
835 : * @brief A function that implements AES-CTR encryption/decryption
836 : *
837 : * This implements the AES-CTR-Encrypt/Decrypt() cryptographic primitives per sections
838 : * 3.7.1 and 3.7.2 of the specification. For an empty input, the user of the API
839 : * can provide an empty string, or a nullptr, and provide input as 0.
840 : * The output buffer can also be an empty string, or a nullptr for this case.
841 : *
842 : * @param input Input text to encrypt/decrypt
843 : * @param input_length Length of ciphertext
844 : * @param key Decryption key
845 : * @param nonce Encryption nonce
846 : * @param nonce_length Length of encryption nonce
847 : * @param output Buffer to write output into
848 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
849 : **/
850 : CHIP_ERROR AES_CTR_crypt(const uint8_t * input, size_t input_length, const Aes128KeyHandle & key, const uint8_t * nonce,
851 : size_t nonce_length, uint8_t * output);
852 :
853 : /**
854 : * @brief Generate a PKCS#10 CSR, usable for Matter, from a P256Keypair.
855 : *
856 : * This uses first principles ASN.1 encoding to avoid relying on the CHIPCryptoPAL backend
857 : * itself, other than to provide an implementation of a P256Keypair * that supports
858 : * at least `::Pubkey()` and `::ECDSA_sign_msg`. This allows using it with
859 : * OS/Platform-bridged private key handling, without requiring a specific
860 : * implementation of other bits like ASN.1.
861 : *
862 : * The CSR will have subject OU set to `CSA`. This is needed since omiting
863 : * subject altogether often trips CSR parsing code. The profile at the CA can
864 : * be configured to ignore CSR requested subject.
865 : *
866 : * @param keypair The key pair for which a CSR should be generated. Must not be null.
867 : * @param csr_span Span to hold the resulting CSR. Must have size at least kMIN_CSR_Buffer_Size.
868 : * Otherwise returns CHIP_ERROR_BUFFER_TOO_SMALL. It will get resized to
869 : * actual size needed on success.
870 :
871 : * @return Returns a CHIP_ERROR from P256Keypair or ASN.1 backend on error, CHIP_NO_ERROR otherwise
872 : **/
873 : CHIP_ERROR GenerateCertificateSigningRequest(const P256Keypair * keypair, MutableByteSpan & csr_span);
874 :
875 : /**
876 : * @brief Common code to validate ASN.1 format/size of a CSR, used by VerifyCertificateSigningRequest.
877 : *
878 : * Ensures it's not obviously malformed and doesn't have trailing garbage.
879 : *
880 : * @param csr CSR in DER format
881 : * @param csr_length The length of the CSR buffer
882 : * @return CHIP_ERROR_UNSUPPORTED_CERT_FORMAT on invalid format, CHIP_NO_ERROR otherwise.
883 : */
884 : CHIP_ERROR VerifyCertificateSigningRequestFormat(const uint8_t * csr, size_t csr_length);
885 :
886 : /**
887 : * @brief Verify the Certificate Signing Request (CSR). If successfully verified, it outputs the public key from the CSR.
888 : *
889 : * The CSR is valid if the format is correct, the signature validates with the embedded public
890 : * key, and there is no trailing garbage data.
891 : *
892 : * @param csr CSR in DER format
893 : * @param csr_length The length of the CSR
894 : * @param pubkey The public key from the verified CSR
895 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
896 : **/
897 : CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr, size_t csr_length, P256PublicKey & pubkey);
898 :
899 : /**
900 : * @brief A function that implements SHA-256 hash
901 : *
902 : * This implements the CHIP_Crypto_Hash() cryptographic primitive
903 : * in the the specification.
904 : *
905 : * @param data The data to hash
906 : * @param data_length Length of the data
907 : * @param out_buffer Pointer to buffer to write output into
908 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
909 : **/
910 :
911 : CHIP_ERROR Hash_SHA256(const uint8_t * data, size_t data_length, uint8_t * out_buffer);
912 :
913 : /**
914 : * @brief A function that implements SHA-1 hash
915 : * @param data The data to hash
916 : * @param data_length Length of the data
917 : * @param out_buffer Pointer to buffer to write output into
918 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
919 : **/
920 :
921 : CHIP_ERROR Hash_SHA1(const uint8_t * data, size_t data_length, uint8_t * out_buffer);
922 :
923 : /**
924 : * @brief A class that defines stream based implementation of SHA-256 hash
925 : * It's expected that the object of this class can be safely copied.
926 : * All implementations must check for std::is_trivially_copyable.
927 : **/
928 :
929 : struct alignas(CHIP_CONFIG_SHA256_CONTEXT_ALIGN) HashSHA256OpaqueContext
930 : {
931 : uint8_t mOpaque[kMAX_Hash_SHA256_Context_Size];
932 : };
933 :
934 : class Hash_SHA256_stream
935 : {
936 : public:
937 : Hash_SHA256_stream();
938 : ~Hash_SHA256_stream();
939 :
940 : /**
941 : * @brief Re-initialize digest computation to an empty context.
942 : *
943 : * @return CHIP_ERROR_INTERNAL on failure to initialize the context,
944 : * CHIP_NO_ERROR otherwise.
945 : */
946 : CHIP_ERROR Begin();
947 :
948 : /**
949 : * @brief Add some data to the digest computation, updating internal state.
950 : *
951 : * @param[in] data The span of bytes to include in the digest update process.
952 : *
953 : * @return CHIP_ERROR_INTERNAL on failure to ingest the data, CHIP_NO_ERROR otherwise.
954 : */
955 : CHIP_ERROR AddData(const ByteSpan data);
956 :
957 : /**
958 : * @brief Get the intermediate padded digest for the current state of the stream.
959 : *
960 : * More data can be added before finish is called.
961 : *
962 : * @param[in,out] out_buffer Output buffer to receive the digest. `out_buffer` must
963 : * be at least `kSHA256_Hash_Length` bytes long. The `out_buffer` size
964 : * will be set to `kSHA256_Hash_Length` on success.
965 : *
966 : * @return CHIP_ERROR_INTERNAL on failure to compute the digest, CHIP_ERROR_BUFFER_TOO_SMALL
967 : * if out_buffer is too small, CHIP_NO_ERROR otherwise.
968 : */
969 : CHIP_ERROR GetDigest(MutableByteSpan & out_buffer);
970 :
971 : /**
972 : * @brief Finalize the stream digest computation, getting the final digest.
973 : *
974 : * @param[in,out] out_buffer Output buffer to receive the digest. `out_buffer` must
975 : * be at least `kSHA256_Hash_Length` bytes long. The `out_buffer` size
976 : * will be set to `kSHA256_Hash_Length` on success.
977 : *
978 : * @return CHIP_ERROR_INTERNAL on failure to compute the digest, CHIP_ERROR_BUFFER_TOO_SMALL
979 : * if out_buffer is too small, CHIP_NO_ERROR otherwise.
980 : */
981 : CHIP_ERROR Finish(MutableByteSpan & out_buffer);
982 :
983 : /**
984 : * @brief Clear-out internal digest data to avoid lingering the state.
985 : */
986 : void Clear();
987 :
988 : private:
989 : // Check if the digest computation has been initialized; implement this if your backend needs it.
990 : bool IsInitialized();
991 :
992 : HashSHA256OpaqueContext mContext;
993 : };
994 :
995 : class HKDF_sha
996 : {
997 : public:
998 : HKDF_sha() = default;
999 3832 : virtual ~HKDF_sha() = default;
1000 :
1001 : /**
1002 : * @brief A function that implements SHA-256 based HKDF
1003 : *
1004 : * This implements the CHIP_Crypto_KDF() cryptographic primitive
1005 : * in the the specification.
1006 : *
1007 : * Error values are:
1008 : * - CHIP_ERROR_INVALID_ARGUMENT: for any bad arguments or nullptr input on
1009 : * any pointer.
1010 : * - CHIP_ERROR_INTERNAL: for any unexpected error arising in the underlying
1011 : * cryptographic layers.
1012 : *
1013 : * @param secret The secret to use as the key to the HKDF
1014 : * @param secret_length Length of the secret
1015 : * @param salt Optional salt to use as input to the HKDF
1016 : * @param salt_length Length of the salt
1017 : * @param info Optional info to use as input to the HKDF
1018 : * @param info_length Length of the info
1019 : * @param out_buffer Pointer to buffer to write output into.
1020 : * @param out_length Size of the underlying out_buffer. That length of output key material will be generated in out_buffer.
1021 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1022 : **/
1023 :
1024 : virtual CHIP_ERROR HKDF_SHA256(const uint8_t * secret, size_t secret_length, const uint8_t * salt, size_t salt_length,
1025 : const uint8_t * info, size_t info_length, uint8_t * out_buffer, size_t out_length);
1026 : };
1027 :
1028 : class HMAC_sha
1029 : {
1030 : public:
1031 : HMAC_sha() = default;
1032 92 : virtual ~HMAC_sha() = default;
1033 :
1034 : /**
1035 : * @brief A function that implements SHA-256 based HMAC per FIPS1981.
1036 : *
1037 : * This implements the CHIP_Crypto_HMAC() cryptographic primitive
1038 : * in the the specification.
1039 : *
1040 : * The `out_length` must be at least kSHA256_Hash_Length, and only
1041 : * kSHA256_Hash_Length bytes are written to out_buffer.
1042 : *
1043 : * Error values are:
1044 : * - CHIP_ERROR_INVALID_ARGUMENT: for any bad arguments or nullptr input on
1045 : * any pointer.
1046 : * - CHIP_ERROR_INTERNAL: for any unexpected error arising in the underlying
1047 : * cryptographic layers.
1048 : *
1049 : * @param key The key to use for the HMAC operation
1050 : * @param key_length Length of the key
1051 : * @param message Message over which to compute the HMAC
1052 : * @param message_length Length of the message over which to compute the HMAC
1053 : * @param out_buffer Pointer to buffer into which to write the output.
1054 : * @param out_length Underlying size of the `out_buffer`.
1055 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1056 : **/
1057 :
1058 : virtual CHIP_ERROR HMAC_SHA256(const uint8_t * key, size_t key_length, const uint8_t * message, size_t message_length,
1059 : uint8_t * out_buffer, size_t out_length);
1060 :
1061 : /**
1062 : * @brief A function that implements SHA-256 based HMAC per FIPS1981.
1063 : *
1064 : * This implements the CHIP_Crypto_HMAC() cryptographic primitive
1065 : * in the the specification.
1066 : *
1067 : * The `out_length` must be at least kSHA256_Hash_Length, and only
1068 : * kSHA256_Hash_Length bytes are written to out_buffer.
1069 : *
1070 : * Error values are:
1071 : * - CHIP_ERROR_INVALID_ARGUMENT: for any bad arguments or nullptr input on
1072 : * any pointer.
1073 : * - CHIP_ERROR_INTERNAL: for any unexpected error arising in the underlying
1074 : * cryptographic layers.
1075 : *
1076 : * @param key The HMAC Key handle to use for the HMAC operation
1077 : * @param message Message over which to compute the HMAC
1078 : * @param message_length Length of the message over which to compute the HMAC
1079 : * @param out_buffer Pointer to buffer into which to write the output.
1080 : * @param out_length Underlying size of the `out_buffer`.
1081 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1082 : **/
1083 : virtual CHIP_ERROR HMAC_SHA256(const Hmac128KeyHandle & key, const uint8_t * message, size_t message_length,
1084 : uint8_t * out_buffer, size_t out_length);
1085 : };
1086 :
1087 : /**
1088 : * @brief A cryptographically secure random number generator based on NIST SP800-90A
1089 : * @param out_buffer Buffer into which to write random bytes
1090 : * @param out_length Number of random bytes to generate
1091 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1092 : **/
1093 : CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, size_t out_length);
1094 :
1095 : /** @brief Entropy callback function
1096 : * @param data Callback-specific data pointer
1097 : * @param output Output data to fill
1098 : * @param len Length of output buffer
1099 : * @param olen The actual amount of data that was written to output buffer
1100 : * @return 0 if success
1101 : */
1102 : typedef int (*entropy_source)(void * data, uint8_t * output, size_t len, size_t * olen);
1103 :
1104 : /** @brief A function to add entropy sources to crypto library
1105 : *
1106 : * This function can be called multiple times to add multiple entropy sources. However,
1107 : * once the entropy source is added, it cannot be removed. Please make sure that the
1108 : * entropy source is valid for the lifetime of the application. Also, make sure that the
1109 : * same entropy source is not added multiple times, e.g.: by calling this function
1110 : * in class constructor or initialization function.
1111 : *
1112 : * @param fn_source Function pointer to the entropy source
1113 : * @param p_source Data that should be provided when fn_source is called
1114 : * @param threshold Minimum required from source before entropy is released
1115 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1116 : **/
1117 : CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold);
1118 :
1119 : class PBKDF2_sha256
1120 : {
1121 : public:
1122 : PBKDF2_sha256() = default;
1123 9 : virtual ~PBKDF2_sha256() = default;
1124 :
1125 : /** @brief Function to derive key using password. SHA256 hashing algorithm is used for calculating hmac.
1126 : * @param password password used for key derivation
1127 : * @param plen length of buffer containing password
1128 : * @param salt salt to use as input to the KDF
1129 : * @param slen length of salt
1130 : * @param iteration_count number of iterations to run
1131 : * @param key_length length of output key
1132 : * @param output output buffer where the key will be written
1133 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1134 : **/
1135 : virtual CHIP_ERROR pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen,
1136 : unsigned int iteration_count, uint32_t key_length, uint8_t * output);
1137 : };
1138 :
1139 : // TODO: Extract Spake2p to a separate header and replace the forward declaration with #include SessionKeystore.h
1140 : class SessionKeystore;
1141 :
1142 : /**
1143 : * The below class implements the draft 01 version of the Spake2+ protocol as
1144 : * defined in https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html.
1145 : *
1146 : * The following describes the protocol flows:
1147 : *
1148 : * Commissioner Accessory
1149 : * ------------ ---------
1150 : *
1151 : * Init
1152 : * BeginProver
1153 : * ComputeRoundOne ------------->
1154 : * Init
1155 : * BeginVerifier
1156 : * /- ComputeRoundOne
1157 : * <------------- ComputeRoundTwo
1158 : * ComputeRoundTwo ------------->
1159 : * KeyConfirm KeyConfirm
1160 : * GetKeys GetKeys
1161 : *
1162 : **/
1163 : class Spake2p
1164 : {
1165 : public:
1166 : Spake2p(size_t fe_size, size_t point_size, size_t hash_size);
1167 20 : virtual ~Spake2p() = default;
1168 :
1169 : /**
1170 : * @brief Initialize Spake2+ with some context specific information.
1171 : *
1172 : * @param context The context is arbitrary but should include information about the
1173 : * protocol being run, contain the transcript for negotiation, include
1174 : * the PKBDF parameters, etc.
1175 : * @param context_len The length of the context.
1176 : *
1177 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1178 : **/
1179 : virtual CHIP_ERROR Init(const uint8_t * context, size_t context_len);
1180 :
1181 : /**
1182 : * @brief Free Spake2+ underlying objects.
1183 : **/
1184 : virtual void Clear() = 0;
1185 :
1186 : /**
1187 : * @brief Start the Spake2+ process as a verifier (i.e. an accessory being provisioned).
1188 : *
1189 : * @param my_identity The verifier identity. May be NULL if identities are not established.
1190 : * @param my_identity_len The verifier identity length.
1191 : * @param peer_identity The peer identity. May be NULL if identities are not established.
1192 : * @param peer_identity_len The peer identity length.
1193 : * @param w0in The input w0 (a parameter baked into the device or computed with ComputeW0).
1194 : * @param w0in_len The input w0 length.
1195 : * @param Lin The input L (a parameter baked into the device or computed with ComputeL).
1196 : * @param Lin_len The input L length.
1197 : *
1198 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1199 : **/
1200 : virtual CHIP_ERROR BeginVerifier(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity,
1201 : size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * Lin,
1202 : size_t Lin_len);
1203 :
1204 : /**
1205 : * @brief Start the Spake2+ process as a prover (i.e. a commissioner).
1206 : *
1207 : * @param my_identity The prover identity. May be NULL if identities are not established.
1208 : * @param my_identity_len The prover identity length.
1209 : * @param peer_identity The peer identity. May be NULL if identities are not established.
1210 : * @param peer_identity_len The peer identity length.
1211 : * @param w0sin The input w0s (an output from the PBKDF).
1212 : * @param w0sin_len The input w0s length.
1213 : * @param w1sin The input w1s (an output from the PBKDF).
1214 : * @param w1sin_len The input w1s length.
1215 : *
1216 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1217 : **/
1218 : virtual CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity,
1219 : size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin,
1220 : size_t w1sin_len);
1221 :
1222 : /**
1223 : * @brief Compute the first round of the protocol.
1224 : *
1225 : * @param pab X value from commissioner.
1226 : * @param pab_len X length.
1227 : * @param out The output first round Spake2+ contribution.
1228 : * @param out_len The output first round Spake2+ contribution length.
1229 : *
1230 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1231 : **/
1232 : virtual CHIP_ERROR ComputeRoundOne(const uint8_t * pab, size_t pab_len, uint8_t * out, size_t * out_len);
1233 :
1234 : /**
1235 : * @brief Compute the second round of the protocol.
1236 : *
1237 : * @param in The peer first round Spake2+ contribution.
1238 : * @param in_len The peer first round Spake2+ contribution length.
1239 : * @param out The output second round Spake2+ contribution.
1240 : * @param out_len The output second round Spake2+ contribution length.
1241 : *
1242 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1243 : **/
1244 : virtual CHIP_ERROR ComputeRoundTwo(const uint8_t * in, size_t in_len, uint8_t * out, size_t * out_len);
1245 :
1246 : /**
1247 : * @brief Confirm that each party computed the same keys.
1248 : *
1249 : * @param in The peer second round Spake2+ contribution.
1250 : * @param in_len The peer second round Spake2+ contribution length.
1251 : *
1252 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1253 : **/
1254 : virtual CHIP_ERROR KeyConfirm(const uint8_t * in, size_t in_len);
1255 :
1256 : /**
1257 : * @brief Return the shared HKDF key.
1258 : *
1259 : * Returns the shared key established during the Spake2+ process, which can be used
1260 : * to derive application-specific keys using HKDF.
1261 : *
1262 : * @param keystore The session keystore for managing the HKDF key lifetime.
1263 : * @param key The output HKDF key.
1264 : *
1265 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1266 : **/
1267 : CHIP_ERROR GetKeys(SessionKeystore & keystore, HkdfKeyHandle & key);
1268 :
1269 : CHIP_ERROR InternalHash(const uint8_t * in, size_t in_len);
1270 : CHIP_ERROR WriteMN();
1271 : CHIP_ERROR GenerateKeys();
1272 :
1273 : /**
1274 : * @brief Load a field element.
1275 : *
1276 : * @param in The input big endian field element.
1277 : * @param in_len The size of the input buffer in bytes.
1278 : * @param fe A pointer to an initialized implementation dependant field element.
1279 : *
1280 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1281 : **/
1282 : virtual CHIP_ERROR FELoad(const uint8_t * in, size_t in_len, void * fe) = 0;
1283 :
1284 : /**
1285 : * @brief Write a field element in big-endian format.
1286 : *
1287 : * @param fe The field element to write.
1288 : * @param out The output buffer.
1289 : * @param out_len The length of the output buffer.
1290 : *
1291 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1292 : **/
1293 : virtual CHIP_ERROR FEWrite(const void * fe, uint8_t * out, size_t out_len) = 0;
1294 :
1295 : /**
1296 : * @brief Generate a field element.
1297 : *
1298 : * @param fe A pointer to an initialized implementation dependant field element.
1299 : *
1300 : * @note The implementation must generate a random element from [0, q) where q is the curve order.
1301 : *
1302 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1303 : **/
1304 : virtual CHIP_ERROR FEGenerate(void * fe) = 0;
1305 :
1306 : /**
1307 : * @brief Multiply two field elements, fer = fe1 * fe2.
1308 : *
1309 : * @param fer A pointer to an initialized implementation dependant field element.
1310 : * @param fe1 A pointer to an initialized implementation dependant field element.
1311 : * @param fe2 A pointer to an initialized implementation dependant field element.
1312 : *
1313 : * @note The result must be a field element (i.e. reduced by the curve order).
1314 : *
1315 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1316 : **/
1317 : virtual CHIP_ERROR FEMul(void * fer, const void * fe1, const void * fe2) = 0;
1318 :
1319 : /**
1320 : * @brief Load a point from 0x04 || X || Y format
1321 : *
1322 : * @param in Input buffer
1323 : * @param in_len Input buffer length
1324 : * @param R A pointer to an initialized implementation dependant point.
1325 : *
1326 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1327 : **/
1328 : virtual CHIP_ERROR PointLoad(const uint8_t * in, size_t in_len, void * R) = 0;
1329 :
1330 : /**
1331 : * @brief Write a point in 0x04 || X || Y format
1332 : *
1333 : * @param R A pointer to an initialized implementation dependant point.
1334 : * @param out Output buffer
1335 : * @param out_len Length of the output buffer
1336 : *
1337 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1338 : **/
1339 : virtual CHIP_ERROR PointWrite(const void * R, uint8_t * out, size_t out_len) = 0;
1340 :
1341 : /**
1342 : * @brief Scalar multiplication, R = fe1 * P1.
1343 : *
1344 : * @param R Resultant point
1345 : * @param P1 Input point
1346 : * @param fe1 Input field element.
1347 : *
1348 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1349 : **/
1350 : virtual CHIP_ERROR PointMul(void * R, const void * P1, const void * fe1) = 0;
1351 :
1352 : /**
1353 : * @brief Scalar multiplication with addition, R = fe1 * P1 + fe2 * P2.
1354 : *
1355 : * @param R Resultant point
1356 : * @param P1 Input point
1357 : * @param fe1 Input field element.
1358 : * @param P2 Input point
1359 : * @param fe2 Input field element.
1360 : *
1361 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1362 : **/
1363 : virtual CHIP_ERROR PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, const void * fe2) = 0;
1364 :
1365 : /**
1366 : * @brief Point inversion.
1367 : *
1368 : * @param R Input/Output point to point_invert
1369 : *
1370 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1371 : **/
1372 : virtual CHIP_ERROR PointInvert(void * R) = 0;
1373 :
1374 : /**
1375 : * @brief Multiply a point by the curve cofactor.
1376 : *
1377 : * @param R Input/Output point to point_invert
1378 : *
1379 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1380 : **/
1381 : virtual CHIP_ERROR PointCofactorMul(void * R) = 0;
1382 :
1383 : /*
1384 : * @synopsis Check if a point is on the curve.
1385 : *
1386 : * @param R Input point to check.
1387 : *
1388 : * @return CHIP_NO_ERROR if the point is valid, CHIP_ERROR otherwise.
1389 : */
1390 : virtual CHIP_ERROR PointIsValid(void * R) = 0;
1391 :
1392 : /*
1393 : * @synopsis Compute w0sin mod p
1394 : *
1395 : * @param w0out Output field element w0
1396 : * @param w0_len Output field element length
1397 : * @param w0sin Input field element
1398 : * @param w0sin_len Input field element length
1399 : *
1400 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1401 : **/
1402 : virtual CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) = 0;
1403 :
1404 : /*
1405 : * @synopsis Compute w1in*G where w1in is w1sin mod p
1406 : *
1407 : * @param Lout Output point in 0x04 || X || Y format.
1408 : * @param L_len Output point length
1409 : * @param w1sin Input field element
1410 : * @param w1sin_len Input field element size
1411 : *
1412 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1413 : **/
1414 : virtual CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) = 0;
1415 :
1416 : void * M;
1417 : void * N;
1418 : const void * G;
1419 : void * X;
1420 : void * Y;
1421 : void * L;
1422 : void * Z;
1423 : void * V;
1424 : void * w0;
1425 : void * w1;
1426 : void * xy;
1427 : void * order;
1428 : void * tempbn;
1429 :
1430 : protected:
1431 : /**
1432 : * @brief Initialize underlying implementation curve, points, field elements, etc.
1433 : *
1434 : * @details The implementation needs to:
1435 : * 1. Initialize each of the points below and set the relevant pointers on the class:
1436 : * a. M
1437 : * b. N
1438 : * c. G
1439 : * d. X
1440 : * e. Y
1441 : * f. L
1442 : * g. Z
1443 : * h. V
1444 : *
1445 : * As an example:
1446 : * this.M = implementation_alloc_point();
1447 : * 2. Initialize each of the field elements below and set the relevant pointers on the class:
1448 : * a. w0
1449 : * b. w1
1450 : * c. xy
1451 : * d. tempbn
1452 : * 3. The hashing context should be initialized
1453 : *
1454 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1455 : **/
1456 : virtual CHIP_ERROR InitImpl() = 0;
1457 :
1458 : /**
1459 : * @brief Hash in_len bytes of in into the internal hash context.
1460 : *
1461 : * @param in The input buffer.
1462 : * @param in_len Size of the input buffer in bytes.
1463 : *
1464 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1465 : **/
1466 : virtual CHIP_ERROR Hash(const uint8_t * in, size_t in_len) = 0;
1467 :
1468 : /**
1469 : * @brief Return the hash.
1470 : *
1471 : * @param out_span Output buffer. The size available must be >= the hash size. It gets resized
1472 : * to hash size on success.
1473 : *
1474 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1475 : **/
1476 : virtual CHIP_ERROR HashFinalize(MutableByteSpan & out_span) = 0;
1477 :
1478 : /**
1479 : * @brief Generate a message authentication code.
1480 : *
1481 : * @param key The MAC key buffer.
1482 : * @param key_len The size of the MAC key in bytes.
1483 : * @param in The input buffer.
1484 : * @param in_len The size of the input data to MAC in bytes.
1485 : * @param out_span The output MAC buffer span. Size must be >= the hash_size. Output size is updated to fit on success.
1486 : *
1487 : * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
1488 : **/
1489 : virtual CHIP_ERROR Mac(const uint8_t * key, size_t key_len, const uint8_t * in, size_t in_len, MutableByteSpan & out_span) = 0;
1490 :
1491 : /**
1492 : * @brief Verify a message authentication code.
1493 : *
1494 : * @param key The MAC key buffer.
1495 : * @param key_len The size of the MAC key in bytes.
1496 : * @param mac The input MAC buffer.
1497 : * @param mac_len The size of the MAC in bytes.
1498 : * @param in The input buffer to verify.
1499 : * @param in_len The size of the input data to verify in bytes.
1500 : *
1501 : * @return Returns a CHIP_ERROR when the MAC doesn't validate, CHIP_NO_ERROR otherwise.
1502 : **/
1503 : virtual CHIP_ERROR MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, const uint8_t * in,
1504 : size_t in_len) = 0;
1505 :
1506 : /**
1507 : * @brief Derive an key of length out_len.
1508 : *
1509 : * @param ikm The input key material buffer.
1510 : * @param ikm_len The input key material length.
1511 : * @param salt The optional salt. This may be NULL.
1512 : * @param salt_len The size of the salt in bytes.
1513 : * @param info The info.
1514 : * @param info_len The size of the info in bytes.
1515 : * @param out The output key
1516 : * @param out_len The output key length
1517 : *
1518 : * @return Returns a CHIP_ERROR when the MAC doesn't validate, CHIP_NO_ERROR otherwise.
1519 : **/
1520 : virtual CHIP_ERROR KDF(const uint8_t * ikm, size_t ikm_len, const uint8_t * salt, size_t salt_len, const uint8_t * info,
1521 : size_t info_len, uint8_t * out, size_t out_len) = 0;
1522 :
1523 : CHIP_SPAKE2P_ROLE role;
1524 : CHIP_SPAKE2P_STATE state = CHIP_SPAKE2P_STATE::PREINIT;
1525 : size_t fe_size;
1526 : size_t hash_size;
1527 : size_t point_size;
1528 : uint8_t Kcab[kMAX_Hash_Length];
1529 : uint8_t Kae[kMAX_Hash_Length];
1530 : uint8_t * Kca;
1531 : uint8_t * Kcb;
1532 : uint8_t * Ka;
1533 : uint8_t * Ke;
1534 : };
1535 :
1536 : struct alignas(size_t) Spake2pOpaqueContext
1537 : {
1538 : uint8_t mOpaque[kMAX_Spake2p_Context_Size];
1539 : };
1540 :
1541 : class Spake2p_P256_SHA256_HKDF_HMAC : public Spake2p
1542 : {
1543 : public:
1544 5 : Spake2p_P256_SHA256_HKDF_HMAC() : Spake2p(kP256_FE_Length, kP256_Point_Length, kSHA256_Hash_Length)
1545 : {
1546 5 : memset(&mSpake2pContext, 0, sizeof(mSpake2pContext));
1547 5 : }
1548 :
1549 20 : ~Spake2p_P256_SHA256_HKDF_HMAC() override { Spake2p_P256_SHA256_HKDF_HMAC::Clear(); }
1550 :
1551 : void Clear() override;
1552 : CHIP_ERROR Mac(const uint8_t * key, size_t key_len, const uint8_t * in, size_t in_len, MutableByteSpan & out_span) override;
1553 : CHIP_ERROR MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, const uint8_t * in,
1554 : size_t in_len) override;
1555 : CHIP_ERROR FELoad(const uint8_t * in, size_t in_len, void * fe) override;
1556 : CHIP_ERROR FEWrite(const void * fe, uint8_t * out, size_t out_len) override;
1557 : CHIP_ERROR FEGenerate(void * fe) override;
1558 : CHIP_ERROR FEMul(void * fer, const void * fe1, const void * fe2) override;
1559 :
1560 : CHIP_ERROR PointLoad(const uint8_t * in, size_t in_len, void * R) override;
1561 : CHIP_ERROR PointWrite(const void * R, uint8_t * out, size_t out_len) override;
1562 : CHIP_ERROR PointMul(void * R, const void * P1, const void * fe1) override;
1563 : CHIP_ERROR PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, const void * fe2) override;
1564 : CHIP_ERROR PointInvert(void * R) override;
1565 : CHIP_ERROR PointCofactorMul(void * R) override;
1566 : CHIP_ERROR PointIsValid(void * R) override;
1567 :
1568 : CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) override;
1569 : CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) override;
1570 :
1571 : protected:
1572 : CHIP_ERROR InitImpl() override;
1573 : CHIP_ERROR Hash(const uint8_t * in, size_t in_len) override;
1574 : CHIP_ERROR HashFinalize(MutableByteSpan & out_span) override;
1575 : CHIP_ERROR KDF(const uint8_t * secret, size_t secret_length, const uint8_t * salt, size_t salt_length, const uint8_t * info,
1576 : size_t info_length, uint8_t * out, size_t out_length) override;
1577 :
1578 : private:
1579 : CHIP_ERROR InitInternal();
1580 : Hash_SHA256_stream sha256_hash_ctx;
1581 :
1582 : Spake2pOpaqueContext mSpake2pContext;
1583 : };
1584 :
1585 : /**
1586 : * @brief Class used for verifying PASE secure sessions.
1587 : **/
1588 : class Spake2pVerifier
1589 : {
1590 : public:
1591 : uint8_t mW0[kP256_FE_Length];
1592 : uint8_t mL[kP256_Point_Length];
1593 :
1594 : CHIP_ERROR Serialize(MutableByteSpan & outSerialized) const;
1595 : CHIP_ERROR Deserialize(const ByteSpan & inSerialized);
1596 :
1597 : /**
1598 : * @brief Generate the Spake2+ verifier.
1599 : *
1600 : * @param pbkdf2IterCount Iteration count for PBKDF2 function
1601 : * @param salt Salt to be used for Spake2+ operation
1602 : * @param setupPin Provided setup PIN (passcode)
1603 : *
1604 : * @return CHIP_ERROR The result of Spake2+ verifier generation
1605 : */
1606 : CHIP_ERROR Generate(uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t setupPin);
1607 :
1608 : /**
1609 : * @brief Compute the initiator values (w0s, w1s) used for PAKE input.
1610 : *
1611 : * @param pbkdf2IterCount Iteration count for PBKDF2 function
1612 : * @param salt Salt to be used for Spake2+ operation
1613 : * @param setupPin Provided setup PIN (passcode)
1614 : * @param ws The output pair (w0s, w1s) stored sequentially
1615 : * @param ws_len The output length
1616 : *
1617 : * @return CHIP_ERROR The result from running PBKDF2
1618 : */
1619 : static CHIP_ERROR ComputeWS(uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t setupPin, uint8_t * ws, uint32_t ws_len);
1620 : };
1621 :
1622 : /**
1623 : * @brief Serialized format of the Spake2+ Verifier components.
1624 : *
1625 : * This is used when the Verifier should be presented in a serialized form.
1626 : * For example, when it is generated using PBKDF function, when stored in the
1627 : * memory or when sent over the wire.
1628 : * The serialized format is concatentation of 'W0' and 'L' verifier components:
1629 : * { Spake2pVerifier.mW0[kP256_FE_Length], Spake2pVerifier.mL[kP256_Point_Length] }
1630 : **/
1631 : typedef uint8_t Spake2pVerifierSerialized[kSpake2p_VerifierSerialized_Length];
1632 :
1633 : /**
1634 : * @brief Compute the compressed fabric identifier used for operational discovery service
1635 : * records from a Node's root public key and Fabric ID. On success, out_compressed_fabric_id
1636 : * will have a size of exactly kCompressedFabricIdentifierSize.
1637 : *
1638 : * Errors are:
1639 : * - CHIP_ERROR_INVALID_ARGUMENT if root_public_key is invalid
1640 : * - CHIP_ERROR_BUFFER_TOO_SMALL if out_compressed_fabric_id is too small for serialization
1641 : * - CHIP_ERROR_INTERNAL on any unexpected crypto or data conversion errors.
1642 : *
1643 : * @param[in] root_public_key The root public key associated with the node's fabric
1644 : * @param[in] fabric_id The fabric ID associated with the node's fabric
1645 : * @param[out] out_compressed_fabric_id Span where output will be written. Its size must be >= kCompressedFabricIdentifierSize.
1646 : * @returns a CHIP_ERROR (see above) on failure or CHIP_NO_ERROR otherwise.
1647 : */
1648 : CHIP_ERROR GenerateCompressedFabricId(const Crypto::P256PublicKey & root_public_key, uint64_t fabric_id,
1649 : MutableByteSpan & out_compressed_fabric_id);
1650 :
1651 : /**
1652 : * @brief Compute the compressed fabric identifier used for operational discovery service
1653 : * records from a Node's root public key and Fabric ID. This is a conveniance
1654 : * overload that writes to a uint64_t (CompressedFabricId) type.
1655 : *
1656 : * @param[in] rootPublicKey The root public key associated with the node's fabric
1657 : * @param[in] fabricId The fabric ID associated with the node's fabric
1658 : * @param[out] compressedFabricId output location for compressed fabric ID
1659 : * @returns a CHIP_ERROR on failure or CHIP_NO_ERROR otherwise.
1660 : */
1661 : CHIP_ERROR GenerateCompressedFabricId(const Crypto::P256PublicKey & rootPublicKey, uint64_t fabricId,
1662 : uint64_t & compressedFabricId);
1663 :
1664 : enum class CertificateChainValidationResult
1665 : {
1666 : kSuccess = 0,
1667 :
1668 : kRootFormatInvalid = 100,
1669 : kRootArgumentInvalid = 101,
1670 :
1671 : kICAFormatInvalid = 200,
1672 : kICAArgumentInvalid = 201,
1673 :
1674 : kLeafFormatInvalid = 300,
1675 : kLeafArgumentInvalid = 301,
1676 :
1677 : kChainInvalid = 400,
1678 :
1679 : kNoMemory = 500,
1680 :
1681 : kInternalFrameworkError = 600,
1682 : };
1683 :
1684 : CHIP_ERROR ValidateCertificateChain(const uint8_t * rootCertificate, size_t rootCertificateLen, const uint8_t * caCertificate,
1685 : size_t caCertificateLen, const uint8_t * leafCertificate, size_t leafCertificateLen,
1686 : CertificateChainValidationResult & result);
1687 :
1688 : enum class AttestationCertType
1689 : {
1690 : kPAA = 0,
1691 : kPAI = 1,
1692 : kDAC = 2,
1693 : };
1694 :
1695 : CHIP_ERROR VerifyAttestationCertificateFormat(const ByteSpan & cert, AttestationCertType certType);
1696 :
1697 : /**
1698 : * @brief Generate a VendorFabricBindingMessage as used by the Fabric Table Vendor ID Verification Procedure.
1699 : *
1700 : * @param[in] fabricBindingVersion - Version of binding payload to generate. outputSpan size requirements are based on this.
1701 : * @param[in] rootPublicKey - Root public key for the fabric in question
1702 : * @param[in] fabricId - Fabric ID for the fabric in question
1703 : * @param[in] vendorId - Vendor ID for the fabric in question
1704 : * @param[inout] outputSpan - Span that will receive the binding message. Must be large enough for the
1705 : * payload (otherwise CHIP_ERROR_BUFFER_TOO_SMALL) and will be resized to fit.
1706 : * @return CHIP_NO_ERROR on success, otherwise another CHIP_ERROR value representative of the failure.
1707 : */
1708 : CHIP_ERROR GenerateVendorFabricBindingMessage(FabricBindingVersion fabricBindingVersion, const P256PublicKey & rootPublicKey,
1709 : FabricId fabricId, uint16_t vendorId, MutableByteSpan & outputSpan);
1710 :
1711 : /**
1712 : * @brief Generate the message to be signed for the Fabric Table Vendor ID Verification Procedure.
1713 : *
1714 : * The Fabric Binding Version value will be recovered from the vendorFabricBindingMessage.
1715 : *
1716 : * @param fabricIndex - Fabric Index for the fabric in question
1717 : * @param clientChallenge - Client challenge to use
1718 : * @param attestationChallenge - Attestation challenge to use
1719 : * @param vendorFabricBindingMessage - The VendorFabricBindingMessage previously computed for the fabric
1720 : * @param vidVerificationStatement - The VID Verification Statement to include in signature (may be empty)
1721 : * @param outputSpan - Span that will receive the to-be-signed message. Must be large enough for the
1722 : * payload (otherwise CHIP_ERROR_BUFFER_TOO_SMALL) and will be resized to fit.
1723 : * @return CHIP_NO_ERROR on success, otherwise another CHIP_ERROR value representative of the failure.
1724 : */
1725 : CHIP_ERROR GenerateVendorIdVerificationToBeSigned(FabricIndex fabricIndex, const ByteSpan & clientChallenge,
1726 : const ByteSpan & attestationChallenge,
1727 : const ByteSpan & vendorFabricBindingMessage,
1728 : const ByteSpan & vidVerificationStatement, MutableByteSpan & outputSpan);
1729 :
1730 : /**
1731 : * @brief Validate notBefore timestamp of a certificate (candidateCertificate) against validity period of the
1732 : * issuer certificate (issuerCertificate).
1733 : *
1734 : * Errors are:
1735 : * - CHIP_ERROR_CERT_EXPIRED if the candidateCertificate timestamp does not satisfy the issuerCertificate's timestamp.
1736 : * - CHIP_ERROR_INVALID_ARGUMENT when passing an invalid argument.
1737 : * - CHIP_ERROR_INTERNAL on any unexpected crypto or data conversion errors.
1738 : *
1739 : * @param candidateCertificate A DER Certificate ByteSpan those notBefore timestamp to be evaluated.
1740 : * @param issuerCertificate A DER Certificate ByteSpan used to evaluate validity timestamp of the candidateCertificate.
1741 : *
1742 : * @returns a CHIP_ERROR (see above) on failure or CHIP_NO_ERROR otherwise.
1743 : **/
1744 : CHIP_ERROR IsCertificateValidAtIssuance(const ByteSpan & candidateCertificate, const ByteSpan & issuerCertificate);
1745 :
1746 : /**
1747 : * @brief Validate a certificate's validity date against current time.
1748 : *
1749 : * Errors are:
1750 : * - CHIP_ERROR_CERT_EXPIRED if the certificate has expired.
1751 : * - CHIP_ERROR_INVALID_ARGUMENT when passing an invalid argument.
1752 : * - CHIP_ERROR_INTERNAL on any unexpected crypto or data conversion errors.
1753 : *
1754 : * @param certificate A DER Certificate ByteSpan used as the validity reference to be checked against current time.
1755 : *
1756 : * @returns a CHIP_ERROR (see above) on failure or CHIP_NO_ERROR otherwise.
1757 : **/
1758 : CHIP_ERROR IsCertificateValidAtCurrentTime(const ByteSpan & certificate);
1759 :
1760 : CHIP_ERROR ExtractPubkeyFromX509Cert(const ByteSpan & certificate, Crypto::P256PublicKey & pubkey);
1761 :
1762 : /**
1763 : * @brief Extracts the Subject Key Identifier from an X509 Certificate.
1764 : **/
1765 : CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & skid);
1766 :
1767 : /**
1768 : * @brief Extracts the Authority Key Identifier from an X509 Certificate.
1769 : **/
1770 : CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid);
1771 :
1772 : /**
1773 : * @brief Extracts the CRL Distribution Point (CDP) extension from an X509 ASN.1 Encoded Certificate.
1774 : * The returned value only covers the URI of the CDP. Only a single URI distribution point
1775 : * GeneralName is supported, and only those that start with "http://" and "https://".
1776 : *
1777 : * @returns CHIP_ERROR_NOT_FOUND if not found or wrong format.
1778 : * CHIP_NO_ERROR otherwise.
1779 : **/
1780 : CHIP_ERROR ExtractCRLDistributionPointURIFromX509Cert(const ByteSpan & certificate, MutableCharSpan & cdpurl);
1781 :
1782 : /**
1783 : * @brief Extracts the CRL Distribution Point (CDP) extension's cRLIssuer Name from an X509 ASN.1 Encoded Certificate.
1784 : * The value is copied into buffer in a raw ASN.1 X.509 format. This format should be directly comparable
1785 : * with the result of ExtractSubjectFromX509Cert().
1786 : *
1787 : * @returns CHIP_ERROR_NOT_FOUND if not found or wrong format.
1788 : * CHIP_NO_ERROR otherwise.
1789 : **/
1790 : CHIP_ERROR ExtractCDPExtensionCRLIssuerFromX509Cert(const ByteSpan & certificate, MutableByteSpan & crlIssuer);
1791 :
1792 : /**
1793 : * @brief Extracts Serial Number from X509 Certificate.
1794 : **/
1795 : CHIP_ERROR ExtractSerialNumberFromX509Cert(const ByteSpan & certificate, MutableByteSpan & serialNumber);
1796 :
1797 : /**
1798 : * @brief Extracts Subject Distinguished Name from X509 Certificate. The value is copied into buffer in a raw ASN.1 X.509 format.
1799 : **/
1800 : CHIP_ERROR ExtractSubjectFromX509Cert(const ByteSpan & certificate, MutableByteSpan & subject);
1801 :
1802 : /**
1803 : * @brief Extracts Issuer Distinguished Name from X509 Certificate. The value is copied into buffer in a raw ASN.1 X.509 format.
1804 : **/
1805 : CHIP_ERROR ExtractIssuerFromX509Cert(const ByteSpan & certificate, MutableByteSpan & issuer);
1806 :
1807 : /**
1808 : * @brief Checks for resigned version of the certificate in the list and returns it.
1809 : *
1810 : * The following conditions SHOULD be satisfied for the certificate to qualify as
1811 : * a resigned version of a reference certificate:
1812 : * - SKID of the candidate and the reference certificate should match.
1813 : * - SubjectDN of the candidate and the reference certificate should match.
1814 : *
1815 : * If no resigned version is found then reference certificate itself is returned.
1816 : *
1817 : * @param referenceCertificate A DER certificate.
1818 : * @param candidateCertificates A pointer to the list of DER Certificates, which should be searched
1819 : * for the resigned version of `referenceCertificate`.
1820 : * @param candidateCertificatesCount Number of certificates in the `candidateCertificates` list.
1821 : * @param outCertificate A reference to the certificate or it's resigned version if found.
1822 : * Note that it points to either `referenceCertificate` or one of
1823 : * `candidateCertificates`, but it doesn't copy data.
1824 : *
1825 : * @returns error if there is certificate parsing/format issue or CHIP_NO_ERROR otherwise.
1826 : **/
1827 : CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates,
1828 : size_t candidateCertificatesCount, ByteSpan & outCertificate);
1829 :
1830 : /**
1831 : * Defines DN attribute types that can include endocing of VID/PID parameters.
1832 : */
1833 : enum class DNAttrType
1834 : {
1835 : kUnspecified = 0,
1836 : kCommonName = 1,
1837 : kMatterVID = 2,
1838 : kMatterPID = 3,
1839 : };
1840 :
1841 : /**
1842 : * @struct AttestationCertVidPid
1843 : *
1844 : * @brief
1845 : * A data structure representing Attestation Certificate VID and PID attributes.
1846 : */
1847 : struct AttestationCertVidPid
1848 : {
1849 : Optional<VendorId> mVendorId;
1850 : Optional<uint16_t> mProductId;
1851 :
1852 620 : bool Initialized() const { return (mVendorId.HasValue() || mProductId.HasValue()); }
1853 : };
1854 :
1855 : /**
1856 : * @brief Extracts VID and PID attributes from the DN Attribute string.
1857 : * If attribute is not present the corresponding output value stays uninitialized.
1858 : *
1859 : * @return CHIP_ERROR_INVALID_ARGUMENT if wrong input is provided.
1860 : * CHIP_ERROR_WRONG_CERT_DN if encoding of kMatterVID and kMatterPID attributes is wrong.
1861 : * CHIP_NO_ERROR otherwise.
1862 : **/
1863 : CHIP_ERROR ExtractVIDPIDFromAttributeString(DNAttrType attrType, const ByteSpan & attr,
1864 : AttestationCertVidPid & vidpidFromMatterAttr, AttestationCertVidPid & vidpidFromCNAttr);
1865 :
1866 : /**
1867 : * @brief Extracts VID and PID attributes from the Subject DN of an X509 Certificate.
1868 : * If attribute is not present the corresponding output value stays uninitialized.
1869 : **/
1870 : CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & x509Cert, AttestationCertVidPid & vidpid);
1871 :
1872 : /**
1873 : * @brief The set of credentials needed to operate group message security with symmetric keys.
1874 : */
1875 : typedef struct GroupOperationalCredentials
1876 : {
1877 : /// Validity start time in microseconds since 2000-01-01T00:00:00 UTC ("the Epoch")
1878 : uint64_t start_time;
1879 : /// Session Id
1880 : uint16_t hash;
1881 : /// Operational group key
1882 : uint8_t encryption_key[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES];
1883 : /// Privacy key
1884 : uint8_t privacy_key[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES];
1885 : } GroupOperationalCredentials;
1886 :
1887 : /**
1888 : * @brief Opaque context used to protect a symmetric key. The key operations must
1889 : * be performed without exposing the protected key value.
1890 : */
1891 : class SymmetricKeyContext
1892 : {
1893 : public:
1894 : /**
1895 : * @brief Returns the symmetric key hash
1896 : *
1897 : * TODO: Replace GetKeyHash() with DeriveGroupSessionId(SymmetricKeyContext &, uint16_t & session_id)
1898 : *
1899 : * @return Group Key Hash
1900 : */
1901 : virtual uint16_t GetKeyHash() = 0;
1902 :
1903 11 : virtual ~SymmetricKeyContext() = default;
1904 : /**
1905 : * @brief Perform the message encryption as described in 4.7.2. (Security Processing of Outgoing Messages)
1906 : * @param[in] plaintext Outgoing message payload.
1907 : * @param[in] aad Additional data (message header contents)
1908 : * @param[in] nonce Nonce (Security Flags | Message Counter | Source Node ID)
1909 : * @param[out] mic Outgoing Message Integrity Check
1910 : * @param[out] ciphertext Outgoing encrypted payload. Must be at least as big as plaintext. The same buffer may be used both
1911 : * for ciphertext, and plaintext.
1912 : * @return CHIP_ERROR
1913 : */
1914 : virtual CHIP_ERROR MessageEncrypt(const ByteSpan & plaintext, const ByteSpan & aad, const ByteSpan & nonce,
1915 : MutableByteSpan & mic, MutableByteSpan & ciphertext) const = 0;
1916 : /**
1917 : * @brief Perform the message decryption as described in 4.7.3.(Security Processing of Incoming Messages)
1918 : * @param[in] ciphertext Incoming encrypted payload
1919 : * @param[in] aad Additional data (message header contents)
1920 : * @param[in] nonce Nonce (Security Flags | Message Counter | Source Node ID)
1921 : * @param[in] mic Incoming Message Integrity Check
1922 : * @param[out] plaintext Incoming message payload. Must be at least as big as ciphertext. The same buffer may be used both
1923 : * for plaintext, and ciphertext.
1924 : * @return CHIP_ERROR
1925 : */
1926 : virtual CHIP_ERROR MessageDecrypt(const ByteSpan & ciphertext, const ByteSpan & aad, const ByteSpan & nonce,
1927 : const ByteSpan & mic, MutableByteSpan & plaintext) const = 0;
1928 :
1929 : /**
1930 : * @brief Perform privacy encoding as described in 4.8.2. (Privacy Processing of Outgoing Messages)
1931 : * @param[in] input Message header to privacy encrypt
1932 : * @param[in] nonce Privacy Nonce = session_id | mic
1933 : * @param[out] output Message header obfuscated
1934 : * @return CHIP_ERROR
1935 : */
1936 : virtual CHIP_ERROR PrivacyEncrypt(const ByteSpan & input, const ByteSpan & nonce, MutableByteSpan & output) const = 0;
1937 :
1938 : /**
1939 : * @brief Perform privacy decoding as described in 4.8.3. (Privacy Processing of Incoming Messages)
1940 : * @param[in] input Message header to privacy decrypt
1941 : * @param[in] nonce Privacy Nonce = session_id | mic
1942 : * @param[out] output Message header deobfuscated
1943 : * @return CHIP_ERROR
1944 : */
1945 : virtual CHIP_ERROR PrivacyDecrypt(const ByteSpan & input, const ByteSpan & nonce, MutableByteSpan & output) const = 0;
1946 :
1947 : /**
1948 : * @brief Release resources such as dynamic memory used to allocate this instance of the SymmetricKeyContext
1949 : */
1950 : virtual void Release() = 0;
1951 : };
1952 :
1953 : /**
1954 : * @brief Derives the Operational Group Key using the Key Derivation Function (KDF) from the given epoch key.
1955 : * @param[in] epoch_key The epoch key. Must be CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1956 : * @param[in] compressed_fabric_id The compressed fabric ID for the fabric (big endian byte string)
1957 : * @param[out] out_key Symmetric key used as the encryption key during message processing for group communication.
1958 : The buffer size must be at least CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1959 : * @return Returns a CHIP_NO_ERROR on succcess, or CHIP_ERROR_INTERNAL if the provided key is invalid.
1960 : **/
1961 : CHIP_ERROR DeriveGroupOperationalKey(const ByteSpan & epoch_key, const ByteSpan & compressed_fabric_id, MutableByteSpan & out_key);
1962 :
1963 : /**
1964 : * @brief Derives the Group Session ID from a given operational group key using
1965 : * the Key Derivation Function (Group Key Hash)
1966 : * @param[in] operational_key The operational group key. Must be CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1967 : * @param[out] session_id Output of the Group Key Hash
1968 : * @return Returns a CHIP_NO_ERROR on succcess, or CHIP_ERROR_INVALID_ARGUMENT if the provided key is invalid.
1969 : **/
1970 : CHIP_ERROR DeriveGroupSessionId(const ByteSpan & operational_key, uint16_t & session_id);
1971 :
1972 : /**
1973 : * @brief Derives the Privacy Group Key using the Key Derivation Function (KDF) from the given epoch key.
1974 : * @param[in] epoch_key The epoch key. Must be CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1975 : * @param[out] out_key Symmetric key used as the privacy key during message processing for group communication.
1976 : * The buffer size must be at least CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1977 : * @return Returns a CHIP_NO_ERROR on succcess, or CHIP_ERROR_INTERNAL if the provided key is invalid.
1978 : **/
1979 : CHIP_ERROR DeriveGroupPrivacyKey(const ByteSpan & epoch_key, MutableByteSpan & out_key);
1980 :
1981 : /**
1982 : * @brief Derives the complete set of credentials needed for group security.
1983 : *
1984 : * This function will derive the Encryption Key, Group Key Hash (Session Id), and Privacy Key
1985 : * for the given Epoch Key and Compressed Fabric Id.
1986 : * @param[in] epoch_key The epoch key. Must be CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES bytes length.
1987 : * @param[in] compressed_fabric_id The compressed fabric ID for the fabric (big endian byte string)
1988 : * @param[out] operational_credentials The set of Symmetric keys used during message processing for group communication.
1989 : * @return Returns a CHIP_NO_ERROR on succcess, or CHIP_ERROR_INTERNAL if the provided key is invalid.
1990 : **/
1991 : CHIP_ERROR DeriveGroupOperationalCredentials(const ByteSpan & epoch_key, const ByteSpan & compressed_fabric_id,
1992 : GroupOperationalCredentials & operational_credentials);
1993 : } // namespace Crypto
1994 : } // namespace chip
|