fido_cable_device_unittest.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/fido/cable/fido_cable_device.h"
  5. #include <array>
  6. #include <limits>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include "base/bind.h"
  11. #include "base/command_line.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/test/task_environment.h"
  14. #include "base/threading/sequenced_task_runner_handle.h"
  15. #include "crypto/aead.h"
  16. #include "device/bluetooth/test/bluetooth_test.h"
  17. #include "device/bluetooth/test/mock_bluetooth_adapter.h"
  18. #include "device/fido/cable/mock_fido_ble_connection.h"
  19. #include "device/fido/fido_parsing_utils.h"
  20. #include "device/fido/test_callback_receiver.h"
  21. #include "testing/gmock/include/gmock/gmock.h"
  22. #include "testing/gtest/include/gtest/gtest.h"
  23. #include "third_party/abseil-cpp/absl/types/optional.h"
  24. namespace device {
  25. namespace {
  26. using ::testing::_;
  27. using ::testing::Invoke;
  28. using ::testing::Test;
  29. using TestDeviceCallbackReceiver =
  30. test::ValueCallbackReceiver<absl::optional<std::vector<uint8_t>>>;
  31. using NiceMockBluetoothAdapter = ::testing::NiceMock<MockBluetoothAdapter>;
  32. // Sufficiently large test control point length as we are not interested
  33. // in testing fragmentations of BLE messages. All Cable messages are encrypted
  34. // and decrypted per request frame, not fragment.
  35. constexpr auto kControlPointLength = std::numeric_limits<uint16_t>::max();
  36. // Counter value that is larger than FidoCableDevice::kMaxCounter.
  37. constexpr uint32_t kInvalidCounter = 1 << 24;
  38. constexpr std::array<uint8_t, 32> kTestSessionKey = {0};
  39. constexpr std::array<uint8_t, 8> kTestEncryptionNonce = {
  40. {1, 1, 1, 1, 1, 1, 1, 1}};
  41. constexpr uint8_t kTestData[] = {'T', 'E', 'S', 'T'};
  42. // kCTAPFramingLength is the number of bytes of framing data at the beginning
  43. // of transmitted BLE messages. See
  44. // https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#ble-client-to-authenticator
  45. constexpr size_t kCTAPFramingLength = 3;
  46. std::vector<uint8_t> ConstructSerializedOutgoingFragment(
  47. base::span<const uint8_t> data) {
  48. FidoBleFrame response_frame(FidoBleDeviceCommand::kMsg,
  49. fido_parsing_utils::Materialize(data));
  50. const auto response_fragment =
  51. std::get<0>(response_frame.ToFragments(kControlPointLength));
  52. std::vector<uint8_t> outgoing_message;
  53. response_fragment.Serialize(&outgoing_message);
  54. return outgoing_message;
  55. }
  56. class FakeCableAuthenticator {
  57. public:
  58. // Returns encrypted message of the ciphertext received from the client.
  59. std::vector<uint8_t> ReplyWithSameMessage(base::span<const uint8_t> message) {
  60. auto decrypted_message = DecryptMessage(message);
  61. auto message_to_send = EncryptMessage(std::move(decrypted_message));
  62. return std::vector<uint8_t>(message_to_send.begin(), message_to_send.end());
  63. }
  64. void SetSessionKey(const std::string& session_key) {
  65. session_key_ = session_key;
  66. }
  67. void SetAuthenticatorCounter(uint32_t authenticator_counter) {
  68. authenticator_counter_ = authenticator_counter;
  69. }
  70. private:
  71. std::string EncryptMessage(std::string message) {
  72. crypto::Aead aead(crypto::Aead::AES_256_GCM);
  73. DCHECK_EQ(session_key_.size(), aead.KeyLength());
  74. aead.Init(&session_key_);
  75. auto encryption_nonce = fido_parsing_utils::Materialize(nonce_);
  76. encryption_nonce.push_back(0x01);
  77. encryption_nonce.push_back(authenticator_counter_ >> 16 & 0xFF);
  78. encryption_nonce.push_back(authenticator_counter_ >> 8 & 0xFF);
  79. encryption_nonce.push_back(authenticator_counter_ & 0xFF);
  80. DCHECK(encryption_nonce.size() == aead.NonceLength());
  81. std::string ciphertext;
  82. aead.Seal(
  83. message, fido_parsing_utils::ConvertToStringPiece(encryption_nonce),
  84. std::string(1, base::strict_cast<uint8_t>(FidoBleDeviceCommand::kMsg)),
  85. &ciphertext);
  86. authenticator_counter_++;
  87. return ciphertext;
  88. }
  89. std::string DecryptMessage(base::span<const uint8_t> message) {
  90. crypto::Aead aead(crypto::Aead::AES_256_GCM);
  91. DCHECK_EQ(session_key_.size(), aead.KeyLength());
  92. aead.Init(&session_key_);
  93. auto encryption_nonce = fido_parsing_utils::Materialize(nonce_);
  94. encryption_nonce.push_back(0x00);
  95. encryption_nonce.push_back(expected_client_counter_ >> 16 & 0xFF);
  96. encryption_nonce.push_back(expected_client_counter_ >> 8 & 0xFF);
  97. encryption_nonce.push_back(expected_client_counter_ & 0xFF);
  98. DCHECK(encryption_nonce.size() == aead.NonceLength());
  99. std::string ciphertext;
  100. aead.Open(
  101. fido_parsing_utils::ConvertToStringPiece(message),
  102. fido_parsing_utils::ConvertToStringPiece(encryption_nonce),
  103. std::string(1, base::strict_cast<uint8_t>(FidoBleDeviceCommand::kMsg)),
  104. &ciphertext);
  105. expected_client_counter_++;
  106. return ciphertext;
  107. }
  108. std::array<uint8_t, 8> nonce_ = kTestEncryptionNonce;
  109. std::string session_key_{
  110. reinterpret_cast<const char*>(kTestSessionKey.data()),
  111. kTestSessionKey.size()};
  112. uint32_t expected_client_counter_ = 0;
  113. uint32_t authenticator_counter_ = 0;
  114. };
  115. } // namespace
  116. class FidoCableDeviceTest : public Test {
  117. public:
  118. FidoCableDeviceTest() {
  119. auto connection = std::make_unique<MockFidoBleConnection>(
  120. adapter_.get(), BluetoothTestBase::kTestDeviceAddress1);
  121. connection_ = connection.get();
  122. device_ = std::make_unique<FidoCableDevice>(std::move(connection));
  123. device_->SetV1EncryptionData(kTestSessionKey, kTestEncryptionNonce);
  124. connection_->read_callback() = device_->GetReadCallbackForTesting();
  125. }
  126. void ConnectWithLength(uint16_t length) {
  127. EXPECT_CALL(*connection(), ConnectPtr).WillOnce(Invoke([](auto* callback) {
  128. std::move(*callback).Run(true);
  129. }));
  130. EXPECT_CALL(*connection(), ReadControlPointLengthPtr(_))
  131. .WillOnce(Invoke([length](auto* cb) { std::move(*cb).Run(length); }));
  132. device()->Connect();
  133. }
  134. FidoCableDevice* device() { return device_.get(); }
  135. MockFidoBleConnection* connection() { return connection_; }
  136. FakeCableAuthenticator* authenticator() { return &authenticator_; }
  137. protected:
  138. base::test::TaskEnvironment task_environment_{
  139. base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  140. private:
  141. scoped_refptr<MockBluetoothAdapter> adapter_ =
  142. base::MakeRefCounted<NiceMockBluetoothAdapter>();
  143. FakeCableAuthenticator authenticator_;
  144. raw_ptr<MockFidoBleConnection> connection_;
  145. std::unique_ptr<FidoCableDevice> device_;
  146. };
  147. TEST_F(FidoCableDeviceTest, ConnectionFailureTest) {
  148. EXPECT_CALL(*connection(), ConnectPtr).WillOnce(Invoke([](auto* callback) {
  149. std::move(*callback).Run(false);
  150. }));
  151. device()->Connect();
  152. }
  153. TEST_F(FidoCableDeviceTest, StaticGetIdTest) {
  154. std::string address = BluetoothTestBase::kTestDeviceAddress1;
  155. EXPECT_EQ("ble-" + address, FidoCableDevice::GetIdForAddress(address));
  156. }
  157. TEST_F(FidoCableDeviceTest, GetIdTest) {
  158. EXPECT_EQ(std::string("ble-") + BluetoothTestBase::kTestDeviceAddress1,
  159. device()->GetId());
  160. }
  161. TEST_F(FidoCableDeviceTest, Timeout) {
  162. EXPECT_CALL(*connection(), ConnectPtr);
  163. TestDeviceCallbackReceiver callback_receiver;
  164. device()->SendPing(std::vector<uint8_t>(), callback_receiver.callback());
  165. task_environment_.FastForwardUntilNoTasksRemain();
  166. EXPECT_EQ(FidoDevice::State::kDeviceError, device()->state_for_testing());
  167. EXPECT_TRUE(callback_receiver.was_called());
  168. EXPECT_FALSE(callback_receiver.value());
  169. }
  170. TEST_F(FidoCableDeviceTest, TestCaBleDeviceSendData) {
  171. ConnectWithLength(kControlPointLength);
  172. EXPECT_CALL(*connection(), WriteControlPointPtr(_, _))
  173. .WillRepeatedly(Invoke([this](const auto& data, auto* cb) {
  174. base::SequencedTaskRunnerHandle::Get()->PostTask(
  175. FROM_HERE, base::BindOnce(std::move(*cb), true));
  176. const auto authenticator_reply = authenticator()->ReplyWithSameMessage(
  177. base::make_span(data).subspan(kCTAPFramingLength));
  178. base::SequencedTaskRunnerHandle::Get()->PostTask(
  179. FROM_HERE, base::BindOnce(connection()->read_callback(),
  180. ConstructSerializedOutgoingFragment(
  181. authenticator_reply)));
  182. }));
  183. for (size_t i = 0; i < 3; i++) {
  184. SCOPED_TRACE(i);
  185. TestDeviceCallbackReceiver callback_receiver;
  186. device()->DeviceTransact(fido_parsing_utils::Materialize(kTestData),
  187. callback_receiver.callback());
  188. callback_receiver.WaitForCallback();
  189. const auto& value = callback_receiver.value();
  190. ASSERT_TRUE(value);
  191. EXPECT_THAT(*value, ::testing::ElementsAreArray(kTestData));
  192. }
  193. }
  194. TEST_F(FidoCableDeviceTest, TestCableDeviceFailOnIncorrectSessionKey) {
  195. constexpr char kIncorrectSessionKey[] = "11111111111111111111111111111111";
  196. ConnectWithLength(kControlPointLength);
  197. EXPECT_CALL(*connection(), WriteControlPointPtr(_, _))
  198. .WillOnce(Invoke([this, &kIncorrectSessionKey](const auto& data,
  199. auto* cb) {
  200. base::SequencedTaskRunnerHandle::Get()->PostTask(
  201. FROM_HERE, base::BindOnce(std::move(*cb), true));
  202. authenticator()->SetSessionKey(kIncorrectSessionKey);
  203. const auto authenticator_reply = authenticator()->ReplyWithSameMessage(
  204. base::make_span(data).subspan(kCTAPFramingLength));
  205. base::SequencedTaskRunnerHandle::Get()->PostTask(
  206. FROM_HERE, base::BindOnce(connection()->read_callback(),
  207. ConstructSerializedOutgoingFragment(
  208. authenticator_reply)));
  209. }));
  210. TestDeviceCallbackReceiver callback_receiver;
  211. device()->DeviceTransact(fido_parsing_utils::Materialize(kTestData),
  212. callback_receiver.callback());
  213. callback_receiver.WaitForCallback();
  214. const auto& value = callback_receiver.value();
  215. EXPECT_FALSE(value);
  216. }
  217. TEST_F(FidoCableDeviceTest, TestCableDeviceFailOnUnexpectedCounter) {
  218. constexpr uint32_t kIncorrectAuthenticatorCounter = 1;
  219. ConnectWithLength(kControlPointLength);
  220. EXPECT_CALL(*connection(), WriteControlPointPtr(_, _))
  221. .WillOnce(Invoke([this](const auto& data, auto* cb) {
  222. base::SequencedTaskRunnerHandle::Get()->PostTask(
  223. FROM_HERE, base::BindOnce(std::move(*cb), true));
  224. authenticator()->SetAuthenticatorCounter(
  225. kIncorrectAuthenticatorCounter);
  226. const auto authenticator_reply = authenticator()->ReplyWithSameMessage(
  227. base::make_span(data).subspan(kCTAPFramingLength));
  228. base::SequencedTaskRunnerHandle::Get()->PostTask(
  229. FROM_HERE, base::BindOnce(connection()->read_callback(),
  230. ConstructSerializedOutgoingFragment(
  231. authenticator_reply)));
  232. }));
  233. TestDeviceCallbackReceiver callback_receiver;
  234. device()->DeviceTransact(fido_parsing_utils::Materialize(kTestData),
  235. callback_receiver.callback());
  236. callback_receiver.WaitForCallback();
  237. const auto& value = callback_receiver.value();
  238. EXPECT_FALSE(value);
  239. }
  240. // Test the unlikely event that the authenticator and client has sent/received
  241. // requests more than FidoCableDevice::kMaxCounter amount of times. As we are
  242. // only using 3 bytes to encapsulate counter during encryption, any counter
  243. // value that is above FidoCableDevice::kMaxCounter -- even though it may be
  244. // the expected counter value -- should return an error.
  245. TEST_F(FidoCableDeviceTest, TestCableDeviceErrorOnMaxCounter) {
  246. ConnectWithLength(kControlPointLength);
  247. EXPECT_CALL(*connection(), WriteControlPointPtr(_, _))
  248. .WillOnce(Invoke([this](const auto& data, auto* cb) {
  249. base::SequencedTaskRunnerHandle::Get()->PostTask(
  250. FROM_HERE, base::BindOnce(std::move(*cb), true));
  251. authenticator()->SetAuthenticatorCounter(kInvalidCounter);
  252. const auto authenticator_reply = authenticator()->ReplyWithSameMessage(
  253. base::make_span(data).subspan(kCTAPFramingLength));
  254. base::SequencedTaskRunnerHandle::Get()->PostTask(
  255. FROM_HERE, base::BindOnce(connection()->read_callback(),
  256. ConstructSerializedOutgoingFragment(
  257. authenticator_reply)));
  258. }));
  259. TestDeviceCallbackReceiver callback_receiver;
  260. device()->SetSequenceNumbersForTesting(kInvalidCounter, 0);
  261. device()->DeviceTransact(fido_parsing_utils::Materialize(kTestData),
  262. callback_receiver.callback());
  263. callback_receiver.WaitForCallback();
  264. const auto& value = callback_receiver.value();
  265. EXPECT_FALSE(value);
  266. }
  267. } // namespace device