Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions include/peer.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <cstdint>
#include <mutex>
#include <memory>
#include <optional>
#include <string>

#include <pb.h>
Expand Down Expand Up @@ -110,8 +111,8 @@ class Peer {
// Cryptographic operations
int construct_ad_buffer(Signatures_SignatureType signature_type, const char *vin, uint32_t expires_at,
pb_byte_t *output_buffer, size_t *output_length, uint32_t flags = 0,
const pb_byte_t *request_hash = nullptr, size_t request_hash_length = 0,
uint32_t fault = 0) const;
const pb_byte_t *request_hash = nullptr, size_t request_hash_length = 0, uint32_t fault = 0,
std::optional<uint32_t> counter = std::nullopt) const;

int encrypt(pb_byte_t *input_buffer, size_t input_buffer_length, pb_byte_t *output_buffer,
size_t output_buffer_length, size_t *output_length, pb_byte_t *signature_buffer, pb_byte_t *ad_buffer,
Expand All @@ -123,7 +124,8 @@ class Peer {

int decrypt_response(const pb_byte_t *input_buffer, size_t input_length, const pb_byte_t *nonce, const pb_byte_t *tag,
const pb_byte_t *request_hash, size_t request_hash_length, uint32_t flags, uint32_t fault,
pb_byte_t *output_buffer, size_t output_buffer_length, size_t *output_length) const;
uint32_t response_counter, pb_byte_t *output_buffer, size_t output_buffer_length,
size_t *output_length) const;

/**
* @brief Validate a response counter using sliding window anti-replay
Expand Down
4 changes: 2 additions & 2 deletions src/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,8 @@ int Client::parse_payload_car_server_response(
int return_code = session->decrypt_response(
input_buffer->bytes, input_buffer->size, signature_data->sig_type.AES_GCM_Response_data.nonce,
signature_data->sig_type.AES_GCM_Response_data.tag, last_request_hash_infotainment_.data(),
this->last_request_hash_infotainment_length_, response_flags, signed_message_fault, decrypt_buffer.bytes,
sizeof(decrypt_buffer.bytes), &decrypt_length);
this->last_request_hash_infotainment_length_, response_flags, signed_message_fault, counter,
decrypt_buffer.bytes, sizeof(decrypt_buffer.bytes), &decrypt_length);
if (return_code != 0) {
LOG_ERROR("[parse_payload_car_server_response] Failed to decrypt response");
return TeslaBLE_Status_E_ERROR_DECRYPT;
Expand Down
39 changes: 25 additions & 14 deletions src/peer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,8 @@ int Peer::force_update_session(Signatures_SessionInfo *session_info) {

int Peer::construct_ad_buffer(Signatures_SignatureType signature_type, const char *vin, uint32_t expires_at,
pb_byte_t *output_buffer, size_t *output_length, uint32_t flags,
const pb_byte_t *request_hash, size_t request_hash_length, uint32_t fault) const {
const pb_byte_t *request_hash, size_t request_hash_length, uint32_t fault,
std::optional<uint32_t> counter) const {
if (output_buffer == nullptr || output_length == nullptr || vin == nullptr) {
LOG_ERROR("Invalid parameters for AD buffer construction");
return TeslaBLE_Status_E_ERROR_INVALID_PARAMS;
Expand Down Expand Up @@ -367,9 +368,10 @@ int Peer::construct_ad_buffer(Signatures_SignatureType signature_type, const cha
}
}

// Counter (TLV format)
// Counter (TLV format). A response is authenticated with the counter the
// vehicle sent in it (AES_GCM_ResponseData.counter), not our request counter.
pb_byte_t counter_bytes[4];
write_uint32_be(counter_bytes, counter_);
write_uint32_be(counter_bytes, counter.value_or(counter_));
if (!append_tlv(Signatures_Tag_TAG_COUNTER, counter_bytes, sizeof(counter_bytes))) {
LOG_ERROR("Failed to append counter to AD buffer");
return TeslaBLE_Status_E_ERROR_INVALID_PARAMS;
Expand Down Expand Up @@ -450,8 +452,8 @@ int Peer::construct_request_hash(Signatures_SignatureType auth_type, const pb_by

int Peer::decrypt_response(const pb_byte_t *input_buffer, size_t input_length, const pb_byte_t *nonce,
const pb_byte_t *tag, const pb_byte_t *request_hash, size_t request_hash_length,
uint32_t flags, uint32_t fault, pb_byte_t *output_buffer, size_t output_buffer_length,
size_t *output_length) const {
uint32_t flags, uint32_t fault, uint32_t response_counter, pb_byte_t *output_buffer,
size_t output_buffer_length, size_t *output_length) const {
if (!is_private_key_initialized()) {
LOG_ERROR("[DecryptResponse] Private key not initialized");
return TeslaBLE_Status_E_ERROR_PRIVATE_KEY_NOT_INITIALIZED;
Expand All @@ -471,9 +473,10 @@ int Peer::decrypt_response(const pb_byte_t *input_buffer, size_t input_length, c
// Construct AD buffer for response (max 79 bytes)
pb_byte_t ad_buffer[80];
size_t ad_length;
return_code = construct_ad_buffer(Signatures_SignatureType_SIGNATURE_TYPE_AES_GCM_RESPONSE, vin_.c_str(),
0, // expires_at not used for responses
ad_buffer, &ad_length, flags, request_hash, request_hash_length, fault);
return_code =
construct_ad_buffer(Signatures_SignatureType_SIGNATURE_TYPE_AES_GCM_RESPONSE, vin_.c_str(),
0, // expires_at not used for responses
ad_buffer, &ad_length, flags, request_hash, request_hash_length, fault, response_counter);

if (return_code != 0) {
LOG_ERROR("[DecryptResponse] Failed to construct AD buffer");
Expand Down Expand Up @@ -507,15 +510,23 @@ int Peer::decrypt_response(const pb_byte_t *input_buffer, size_t input_length, c
return TeslaBLE_Status_E_ERROR_DECRYPT;
}

// Finalize and verify the tag
// Finalize and authenticate. In decrypt mode mbedtls_gcm_finish() only
// computes the tag; it never compares it with the received one, so the
// comparison is done here (constant-time).
size_t finish_length = 0;
pb_byte_t finish_buffer[16];
pb_byte_t tag_copy[16];
std::memcpy(tag_copy, tag, sizeof(tag_copy));
return_code = mbedtls_gcm_finish(&aes_context, finish_buffer, sizeof(finish_buffer), &finish_length, tag_copy,
sizeof(tag_copy)); // tag is always 16 bytes
pb_byte_t computed_tag[16];
return_code = mbedtls_gcm_finish(&aes_context, finish_buffer, sizeof(finish_buffer), &finish_length, computed_tag,
sizeof(computed_tag)); // tag is always 16 bytes
if (return_code != 0) {
LOG_ERROR("[DecryptResponse] Authentication failed in gcm_finish: -0x%04x", (unsigned int) -return_code);
LOG_ERROR("[DecryptResponse] Failed to compute tag in gcm_finish: -0x%04x", (unsigned int) -return_code);
mbedtls_gcm_free(&aes_context);
return TeslaBLE_Status_E_ERROR_DECRYPT;
}

if (!CryptoUtils::secure_memory_compare(tag, computed_tag, sizeof(computed_tag))) {
LOG_ERROR("[DecryptResponse] Authentication failed: response tag mismatch");
mbedtls_gcm_free(&aes_context);
return TeslaBLE_Status_E_ERROR_DECRYPT;
}

Expand Down
9 changes: 5 additions & 4 deletions src/vehicle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -868,10 +868,11 @@ void TeslaBLE::Vehicle::handle_vcsec_message_(const UniversalMessage_RoutableMes
}

size_t decrypt_length = 0;
int return_code = session->decrypt_response(
payload->bytes, payload->size, sig_data->sig_type.AES_GCM_Response_data.nonce,
sig_data->sig_type.AES_GCM_Response_data.tag, request_hash, request_hash_length, msg.flags, fault,
decrypt_buffer.bytes, sizeof(decrypt_buffer.bytes), &decrypt_length);
int return_code =
session->decrypt_response(payload->bytes, payload->size, sig_data->sig_type.AES_GCM_Response_data.nonce,
sig_data->sig_type.AES_GCM_Response_data.tag, request_hash, request_hash_length,
msg.flags, fault, sig_data->sig_type.AES_GCM_Response_data.counter,
decrypt_buffer.bytes, sizeof(decrypt_buffer.bytes), &decrypt_length);
if (return_code != 0) {
LOG_ERROR("Failed to decrypt VCSEC response: %d", return_code);
return;
Expand Down
109 changes: 84 additions & 25 deletions tests/test_encrypted_responses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <chrono>
#include <cstring>
#include <memory>
#include <optional>
#include <vector>

using TeslaBLE::Client;
Expand Down Expand Up @@ -117,10 +118,10 @@ std::array<pb_byte_t, 17> request_hash_from_frame(Client &parser, const std::vec
}

// Encrypt a payload the way the vehicle does for a response to request_frame:
// response AD (request hash, flags, fault) + AES-GCM with the session key.
// response AD (request hash, flags, fault, response counter) + AES-GCM with the session key.
std::vector<uint8_t> make_encrypted_response(Client &helper, UniversalMessage_Domain domain, uint32_t counter,
const std::vector<uint8_t> &request_frame, const pb_byte_t *payload,
size_t payload_length) {
size_t payload_length, std::optional<uint32_t> ad_counter_override = {}) {
if (request_frame.size() <= 2) {
return {};
}
Expand All @@ -141,9 +142,12 @@ std::vector<uint8_t> make_encrypted_response(Client &helper, UniversalMessage_Do
const uint32_t flags = 1u << UniversalMessage_Flags_FLAG_ENCRYPT_RESPONSE;
std::array<pb_byte_t, 80> ad{};
size_t ad_length = 0;
// The response is authenticated with the counter reported in
// AES_GCM_ResponseData; ad_counter_override lets tests sign with a
// different counter than the one the message reports.
if (peer->construct_ad_buffer(Signatures_SignatureType_SIGNATURE_TYPE_AES_GCM_RESPONSE, TEST_VIN, 0, ad.data(),
&ad_length, flags, request_hash.data(), request_hash.size(),
0) != TeslaBLE_Status_E_OK) {
&ad_length, flags, request_hash.data(), request_hash.size(), 0,
ad_counter_override.value_or(counter)) != TeslaBLE_Status_E_OK) {
return {};
}

Expand Down Expand Up @@ -209,41 +213,96 @@ class EncryptedResponseTest : public ::testing::Test {
std::shared_ptr<MockStorageAdapter> mock_storage_;
std::shared_ptr<Vehicle> vehicle_;
std::shared_ptr<Client> helper_;

// Sends the standard "Climate On" command with the preloaded session and
// returns the encrypted request frame that was written.
std::vector<uint8_t> send_climate_command(OperationOutcome *outcome) {
vehicle_->send_command_result(
UniversalMessage_Domain_DOMAIN_INFOTAINMENT, "Climate On",
[](Client *client, uint8_t *buff, size_t *len) {
bool enabled = true;
return client->build_car_server_vehicle_action_message(buff, len, CarServer_VehicleAction_hvacAutoAction_tag,
&enabled);
},
[outcome](TeslaBLE::OperationResult result) { *outcome = result.outcome(); });
vehicle_->loop();
vehicle_->loop();

const auto &writes = mock_ble_->get_written_data();
if (writes.size() != 1U) {
return {};
}
return writes.front();
}

// A CarServer OK response encrypted for request_frame.
std::vector<uint8_t> make_ok_infotainment_response(const std::vector<uint8_t> &request_frame, uint32_t counter,
std::optional<uint32_t> ad_counter_override = {}) {
CarServer_Response content = CarServer_Response_init_default;
content.has_actionStatus = true;
content.actionStatus.result = CarServer_OperationStatus_E_OPERATIONSTATUS_OK;
pb_byte_t payload[256];
size_t payload_length = sizeof(payload);
if (TeslaBLE::pb_encode_fields(payload, &payload_length, CarServer_Response_fields, &content) !=
TeslaBLE_Status_E_OK) {
return {};
}

return make_encrypted_response(*helper_, UniversalMessage_Domain_DOMAIN_INFOTAINMENT, counter, request_frame,
payload, payload_length, ad_counter_override);
}
};

TEST_F(EncryptedResponseTest, InfotainmentCommandCompletesWithEncryptedResponse) {
OperationOutcome outcome = OperationOutcome::FAILED;
vehicle_->send_command_result(
UniversalMessage_Domain_DOMAIN_INFOTAINMENT, "Climate On",
[](Client *client, uint8_t *buff, size_t *len) {
bool enabled = true;
return client->build_car_server_vehicle_action_message(buff, len, CarServer_VehicleAction_hvacAutoAction_tag,
&enabled);
},
[&](TeslaBLE::OperationResult result) { outcome = result.outcome(); });
auto request = send_climate_command(&outcome);
ASSERT_FALSE(request.empty()) << "Preloaded sessions should send the encrypted command directly";

vehicle_->loop();
auto response = make_ok_infotainment_response(request, 201);
ASSERT_FALSE(response.empty()) << "Encrypted response should be built";

vehicle_->on_rx_data(response);
vehicle_->loop();

const auto &writes = mock_ble_->get_written_data();
ASSERT_EQ(writes.size(), 1U) << "Preloaded sessions should send the encrypted command directly";
EXPECT_EQ(outcome, OperationOutcome::SUCCESS) << "Encrypted response should complete the command";
}

CarServer_Response content = CarServer_Response_init_default;
content.has_actionStatus = true;
content.actionStatus.result = CarServer_OperationStatus_E_OPERATIONSTATUS_OK;
pb_byte_t payload[256];
size_t payload_length = sizeof(payload);
ASSERT_EQ(TeslaBLE::pb_encode_fields(payload, &payload_length, CarServer_Response_fields, &content),
TEST_F(EncryptedResponseTest, TamperedResponseTagIsRejected) {
OperationOutcome outcome = OperationOutcome::FAILED;
auto request = send_climate_command(&outcome);
ASSERT_FALSE(request.empty());

auto response = make_ok_infotainment_response(request, 201);
ASSERT_FALSE(response.empty());

// Corrupt one byte of the response tag.
TeslaBLE::Client parser;
UniversalMessage_RoutableMessage parsed = UniversalMessage_RoutableMessage_init_default;
ASSERT_EQ(parser.parse_universal_message(const_cast<pb_byte_t *>(response.data() + 2), response.size() - 2, &parsed),
TeslaBLE_Status_E_OK);
parsed.sub_sigData.signature_data.sig_type.AES_GCM_Response_data.tag[0] ^= 0xFF;
auto tampered = frame_universal_message(parsed);
ASSERT_FALSE(tampered.empty());

auto response = make_encrypted_response(*helper_, UniversalMessage_Domain_DOMAIN_INFOTAINMENT, 201, writes.front(),
payload, payload_length);
ASSERT_FALSE(response.empty()) << "Encrypted response should be built";
vehicle_->on_rx_data(tampered);
vehicle_->loop();

EXPECT_EQ(outcome, OperationOutcome::FAILED) << "Tampered response must not complete the command";
}

TEST_F(EncryptedResponseTest, ResponseWithMismatchedCounterIsRejected) {
OperationOutcome outcome = OperationOutcome::FAILED;
auto request = send_climate_command(&outcome);
ASSERT_FALSE(request.empty());

// Sign with a different counter than the one reported in AES_GCM_ResponseData.
auto response = make_ok_infotainment_response(request, 201, /*ad_counter_override=*/202);
ASSERT_FALSE(response.empty());

vehicle_->on_rx_data(response);
vehicle_->loop();

EXPECT_EQ(outcome, OperationOutcome::SUCCESS) << "Encrypted response should complete the command";
EXPECT_EQ(outcome, OperationOutcome::FAILED) << "Response authenticated with a different counter must be rejected";
}

TEST_F(EncryptedResponseTest, VcsecCommandCompletesWithEncryptedResponse) {
Expand Down
46 changes: 32 additions & 14 deletions tests/test_protocol_handshake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,16 +215,12 @@ TEST_F(ProtocolHandshakeTest, ResponseDecryption) {
request_hash, sizeof(request_hash),
0, // flags
0, // fault
0, // response counter
decrypted, sizeof(decrypted), &decrypted_length);

// The exact result depends on the mock data being valid
// But we should get a meaningful response
EXPECT_TRUE(decrypt_result == TeslaBLE_Status_E_OK || decrypt_result != TeslaBLE_Status_E_OK)
<< "Decryption should either succeed or fail gracefully";

if (result == TeslaBLE_Status_E_OK) {
EXPECT_GT(decrypted_length, 0) << "Successful decryption should produce content";
}
// The mock data does not carry a valid tag for this session, so it must be
// rejected (before tag verification was added, decryption always "succeeded").
EXPECT_EQ(decrypt_result, TeslaBLE_Status_E_ERROR_DECRYPT) << "Decryption of unauthenticated data must fail";
}

TEST_F(ProtocolHandshakeTest, VcsecResponseDecryptRoundTrip) {
Expand Down Expand Up @@ -259,9 +255,12 @@ TEST_F(ProtocolHandshakeTest, VcsecResponseDecryptRoundTrip) {
size_t ad_length = 0;
uint32_t flags = (1u << UniversalMessage_Flags_FLAG_ENCRYPT_RESPONSE);
uint32_t fault = 0;
auto ad_result =
peer.construct_ad_buffer(Signatures_SignatureType_SIGNATURE_TYPE_AES_GCM_RESPONSE, TestConstants::TEST_VIN, 0,
ad_buffer.data(), &ad_length, flags, request_hash.data(), request_hash_length, fault);
// The vehicle authenticates its response with the counter it sends in
// AES_GCM_ResponseData, which in general differs from our request counter.
const uint32_t response_counter = 0x2a;
auto ad_result = peer.construct_ad_buffer(Signatures_SignatureType_SIGNATURE_TYPE_AES_GCM_RESPONSE,
TestConstants::TEST_VIN, 0, ad_buffer.data(), &ad_length, flags,
request_hash.data(), request_hash_length, fault, response_counter);
ASSERT_EQ(ad_result, TeslaBLE_Status_E_OK) << "Failed to construct AD buffer";

unsigned char ad_hash[32];
Expand Down Expand Up @@ -294,13 +293,32 @@ TEST_F(ProtocolHandshakeTest, VcsecResponseDecryptRoundTrip) {

std::array<pb_byte_t, 32> decrypted{};
size_t decrypted_length = 0;
int decrypt_result =
peer.decrypt_response(ciphertext.data(), ciphertext_length, nonce.data(), tag.data(), request_hash.data(),
request_hash_length, flags, fault, decrypted.data(), decrypted.size(), &decrypted_length);
int decrypt_result = peer.decrypt_response(ciphertext.data(), ciphertext_length, nonce.data(), tag.data(),
request_hash.data(), request_hash_length, flags, fault, response_counter,
decrypted.data(), decrypted.size(), &decrypted_length);
ASSERT_EQ(decrypt_result, TeslaBLE_Status_E_OK) << "Failed to decrypt VCSEC response";
ASSERT_EQ(decrypted_length, plaintext.size()) << "Decrypted length mismatch";
EXPECT_TRUE(std::equal(plaintext.begin(), plaintext.end(), decrypted.begin()))
<< "Decrypted payload should match plaintext";

// Authentication is only accepted when the tag verifies: a different counter
// changes the authenticated data, so decryption must fail.
std::array<pb_byte_t, 32> rejected{};
size_t rejected_length = 0;
EXPECT_NE(peer.decrypt_response(ciphertext.data(), ciphertext_length, nonce.data(), tag.data(), request_hash.data(),
request_hash_length, flags, fault, response_counter + 1, rejected.data(),
rejected.size(), &rejected_length),
TeslaBLE_Status_E_OK)
<< "Response with a mismatched counter must not authenticate";

// A tampered tag must also be rejected.
std::array<pb_byte_t, Peer::TAG_SIZE_BYTES> tampered_tag = tag;
tampered_tag[0] ^= 0xFF;
EXPECT_NE(peer.decrypt_response(ciphertext.data(), ciphertext_length, nonce.data(), tampered_tag.data(),
request_hash.data(), request_hash_length, flags, fault, response_counter,
rejected.data(), rejected.size(), &rejected_length),
TeslaBLE_Status_E_OK)
<< "Response with a tampered tag must not authenticate";
}

// Test 5: Domain-Specific Behavior
Expand Down
Loading