/** * link_secure.h - the SECURE envelope of the A <-> B link (see automotive_data.h). * * THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS, like automotive_data.h. * * payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner) * * Both cores ship mbedtls (2.28 on Controller B's IDF 4.4, 3.x on Controller * A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs. */ #ifndef LINK_SECURE_H #define LINK_SECURE_H #include "automotive_data.h" #include #include #include #if __has_include() #include #else #include // IDF 4.4: esp_random / esp_fill_random live here #endif /** First two bytes of SHA-256(key), never 0 (0 means "unpaired" on the wire). */ static inline uint16_t link_key_fingerprint(const uint8_t key[LINK_KEY_LEN]) { uint8_t h[32]; #if MBEDTLS_VERSION_MAJOR >= 3 mbedtls_sha256(key, LINK_KEY_LEN, h, 0); #else mbedtls_sha256_ret(key, LINK_KEY_LEN, h, 0); #endif uint16_t fp = (uint16_t)((h[0] << 8) | h[1]); return fp ? fp : 1; } /** * Seal inner_type + inner into a SECURE payload. * @param out buffer of PACKET_MAX_PAYLOAD bytes * @return payload length, or 0 on error / oversize */ static inline size_t link_secure_seal(const uint8_t key[LINK_KEY_LEN], uint8_t inner_type, const void* inner, size_t inner_len, uint8_t* out) { if (inner_len + 1 > LINK_SECURE_MAX_INNER) return 0; uint8_t plain[LINK_SECURE_MAX_INNER]; plain[0] = inner_type; memcpy(&plain[1], inner, inner_len); size_t n = inner_len + 1; uint8_t* nonce = out; uint8_t* tag = out + LINK_NONCE_LEN; uint8_t* ct = out + LINK_SECURE_OVERHEAD; esp_fill_random(nonce, LINK_NONCE_LEN); mbedtls_gcm_context g; mbedtls_gcm_init(&g); int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8); if (rc == 0) { rc = mbedtls_gcm_crypt_and_tag(&g, MBEDTLS_GCM_ENCRYPT, n, nonce, LINK_NONCE_LEN, NULL, 0, plain, ct, LINK_TAG_LEN, tag); } mbedtls_gcm_free(&g); return rc == 0 ? LINK_SECURE_OVERHEAD + n : 0; } /** * Open a SECURE payload. On success *inner_type and inner (LINK_SECURE_MAX_INNER * bytes) are filled; *inner_len excludes the type byte. */ static inline bool link_secure_open(const uint8_t key[LINK_KEY_LEN], const uint8_t* payload, size_t len, uint8_t* inner_type, uint8_t* inner, size_t* inner_len) { if (len < LINK_SECURE_OVERHEAD + 1 || len > PACKET_MAX_PAYLOAD) return false; size_t n = len - LINK_SECURE_OVERHEAD; uint8_t plain[LINK_SECURE_MAX_INNER]; mbedtls_gcm_context g; mbedtls_gcm_init(&g); int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8); if (rc == 0) { rc = mbedtls_gcm_auth_decrypt(&g, n, payload, LINK_NONCE_LEN, NULL, 0, payload + LINK_NONCE_LEN, LINK_TAG_LEN, payload + LINK_SECURE_OVERHEAD, plain); } mbedtls_gcm_free(&g); if (rc != 0) return false; *inner_type = plain[0]; *inner_len = n - 1; memcpy(inner, &plain[1], n - 1); return true; } #endif // LINK_SECURE_H