1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_bluetooth_sapphire/internal/host/sm/security_manager.h"
16
17 #include <cinttypes>
18 #include <memory>
19 #include <optional>
20 #include <type_traits>
21 #include <utility>
22 #include <variant>
23
24 #include "lib/fit/function.h"
25 #include "pw_bluetooth_sapphire/internal/host/common/assert.h"
26 #include "pw_bluetooth_sapphire/internal/host/common/byte_buffer.h"
27 #include "pw_bluetooth_sapphire/internal/host/common/device_address.h"
28 #include "pw_bluetooth_sapphire/internal/host/common/log.h"
29 #include "pw_bluetooth_sapphire/internal/host/common/random.h"
30 #include "pw_bluetooth_sapphire/internal/host/common/uint128.h"
31 #include "pw_bluetooth_sapphire/internal/host/gap/gap.h"
32 #include "pw_bluetooth_sapphire/internal/host/hci-spec/link_key.h"
33 #include "pw_bluetooth_sapphire/internal/host/hci/low_energy_connection.h"
34 #include "pw_bluetooth_sapphire/internal/host/sm/error.h"
35 #include "pw_bluetooth_sapphire/internal/host/sm/packet.h"
36 #include "pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h"
37 #include "pw_bluetooth_sapphire/internal/host/sm/phase_1.h"
38 #include "pw_bluetooth_sapphire/internal/host/sm/phase_2_legacy.h"
39 #include "pw_bluetooth_sapphire/internal/host/sm/phase_2_secure_connections.h"
40 #include "pw_bluetooth_sapphire/internal/host/sm/phase_3.h"
41 #include "pw_bluetooth_sapphire/internal/host/sm/security_request_phase.h"
42 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
43 #include "pw_bluetooth_sapphire/internal/host/sm/types.h"
44 #include "pw_bluetooth_sapphire/internal/host/sm/util.h"
45 #include "pw_bluetooth_sapphire/internal/host/transport/error.h"
46
47 namespace bt::sm {
48
49 namespace {
50
FeaturesToProperties(const PairingFeatures & features)51 SecurityProperties FeaturesToProperties(const PairingFeatures& features) {
52 return SecurityProperties(features.method == PairingMethod::kJustWorks
53 ? SecurityLevel::kEncrypted
54 : SecurityLevel::kAuthenticated,
55 features.encryption_key_size,
56 features.secure_connections);
57 }
58 } // namespace
59
60 class SecurityManagerImpl final : public SecurityManager,
61 public PairingPhase::Listener,
62 public PairingChannel::Handler {
63 public:
64 ~SecurityManagerImpl() override;
65 SecurityManagerImpl(hci::LowEnergyConnection::WeakPtr link,
66 l2cap::Channel::WeakPtr smp,
67 IOCapability io_capability,
68 Delegate::WeakPtr delegate,
69 BondableMode bondable_mode,
70 gap::LESecurityMode security_mode,
71 pw::async::Dispatcher& dispatcher);
72 // SecurityManager overrides:
73 bool AssignLongTermKey(const LTK& ltk) override;
74 void UpgradeSecurity(SecurityLevel level, PairingCallback callback) override;
75 void Reset(IOCapability io_capability) override;
76 void Abort(ErrorCode ecode) override;
77
78 private:
79 // Represents a pending request to update the security level.
80 struct PendingRequest {
81 PendingRequest(SecurityLevel level_in, PairingCallback callback_in);
82 PendingRequest(PendingRequest&&) = default;
83 PendingRequest& operator=(PendingRequest&&) = default;
84
85 SecurityLevel level;
86 PairingCallback callback;
87 };
88
89 // Called when we receive a peer security request as initiator, will start
90 // Phase 1.
91 void OnSecurityRequest(AuthReqField auth_req);
92
93 // Called when we receive a peer pairing request as responder, will start
94 // Phase 1.
95 void OnPairingRequest(const PairingRequestParams& req_params);
96
97 // Pulls the next PendingRequest off |request_queue_| and starts a security
98 // upgrade to that |level| by either sending a Pairing Request as initiator or
99 // a Security Request as responder.
100 void UpgradeSecurityInternal();
101
102 // Creates the pairing phase responsible for sending the security upgrade
103 // request to the peer (a PairingRequest if we are initiator, otherwise a
104 // SecurityRequest). Returns fit::error(ErrorCode::
105 // kAuthenticationRequirements) if the local IOCapabilities are insufficient
106 // for SecurityLevel, otherwise returns fit::ok().
107 [[nodiscard]] fit::result<ErrorCode> RequestSecurityUpgrade(
108 SecurityLevel level);
109
110 // Called when the feature exchange (Phase 1) completes and the relevant
111 // features of both sides have been resolved into `features`. `preq` and
112 // `pres` need to be retained for cryptographic calculations in Phase 2.
113 // Causes a state transition from Phase 1 to Phase 2
114 void OnFeatureExchange(PairingFeatures features,
115 PairingRequestParams preq,
116 PairingResponseParams pres);
117
118 // Called when Phase 2 generates an encryption key, so the link can be
119 // encrypted with it.
120 void OnPhase2EncryptionKey(const UInt128& new_key);
121
122 // Check if encryption using `current_ltk` will satisfy the current security
123 // requirements.
124 static bool CurrentLtkInsufficientlySecureForEncryption(
125 std::optional<LTK> current_ltk,
126 SecurityRequestPhase* security_request_phase,
127 gap::LESecurityMode mode);
128
129 // Called when the encryption state of the LE link changes.
130 void OnEncryptionChange(hci::Result<bool> enabled_result);
131
132 // Called when the link is encrypted at the end of pairing Phase 2.
133 void EndPhase2();
134
135 // Cleans up pairing state, updates the current security level, and notifies
136 // parties that requested security of the link's updated security properties.
137 void OnPairingComplete(PairingData data);
138
139 // After a call to UpgradeSecurity results in an increase of the link security
140 // level (through pairing completion or SMP Security Requested encryption),
141 // this method notifies all the callbacks associated with SecurityUpgrade
142 // requests.
143 void NotifySecurityCallbacks();
144
145 // Assign the current security properties and notify the delegate of the
146 // change.
147 void SetSecurityProperties(const SecurityProperties& sec);
148
149 // Directly assigns the current |ltk_| and the underlying |le_link_|'s link
150 // key. This function does not initiate link layer encryption and can be
151 // called during and outside of pairing.
152 void OnNewLongTermKey(const LTK& ltk);
153
154 // PairingPhase::Listener overrides:
155 void OnPairingFailed(Error error) override;
156 std::optional<IdentityInfo> OnIdentityRequest() override;
157 void ConfirmPairing(ConfirmCallback confirm) override;
158 void DisplayPasskey(uint32_t passkey,
159 Delegate::DisplayMethod method,
160 ConfirmCallback cb) override;
161 void RequestPasskey(PasskeyResponseCallback respond) override;
162
163 // PairingChannel::Handler overrides. SecurityManagerImpl is only the fallback
164 // handler, meaning these methods are only called by PairingChannel when no
165 // security upgrade is in progress:
166 void OnRxBFrame(ByteBufferPtr sdu) override;
167 void OnChannelClosed() override;
168
169 // Starts the SMP timer. Stops and cancels any in-progress timers.
170 void StartNewTimer();
171 // Stops and resets the SMP Pairing Timer.
172 void StopTimer();
173 // Called when the pairing timer expires, forcing the pairing process to stop
174 void OnPairingTimeout();
175
176 // Returns a std::pair<InitiatorAddress, ResponderAddress>. Will assert if
177 // called outside active pairing or before Phase 1 is complete.
178 std::pair<DeviceAddress, DeviceAddress> LEPairingAddresses();
179
180 // Puts the class into a non-pairing state.
181 void ResetState();
182
183 // Returns true if the pairing state machine is currently in Phase 2 of
184 // pairing.
InPhase2() const185 bool InPhase2() const {
186 return std::holds_alternative<Phase2Legacy>(current_phase_) ||
187 std::holds_alternative<Phase2SecureConnections>(current_phase_);
188 }
189
SecurityUpgradeInProgress() const190 bool SecurityUpgradeInProgress() const {
191 return !std::holds_alternative<std::monostate>(current_phase_);
192 }
193
194 // Validates that both SM and the link have stored LTKs, and that these values
195 // match. Disconnects the link if it finds an issue. Should only be called
196 // when an LTK is expected to exist.
197 Result<> ValidateExistingLocalLtk();
198
199 pw::async::Dispatcher& pw_dispatcher_;
200
201 // The ID that will be assigned to the next pairing operation.
202 PairingProcedureId next_pairing_id_;
203
204 // The higher-level class acting as a delegate for operations outside of SMP.
205 Delegate::WeakPtr delegate_;
206
207 // Data for the currently registered LE-U link, if any.
208 hci::LowEnergyConnection::WeakPtr le_link_;
209
210 // The IO capabilities of the device
211 IOCapability io_cap_;
212
213 // The current LTK assigned to this connection. This can be assigned directly
214 // by calling AssignLongTermKey() or as a result of a pairing procedure.
215 std::optional<LTK> ltk_;
216
217 // If a pairing is in progress and Phase 1 (feature exchange) has completed,
218 // this will store the result of that feature exchange. Otherwise, this will
219 // be std::nullopt.
220 std::optional<PairingFeatures> features_;
221
222 // The pending security requests added via UpgradeSecurity().
223 std::queue<PendingRequest> request_queue_;
224
225 // Fixed SMP Channel used to send/receive packets
226 std::unique_ptr<PairingChannel> sm_chan_;
227
228 // The role of the local device in pairing.
229 Role role_;
230
231 SmartTask timeout_task_{pw_dispatcher_};
232
233 // The presence of a particular phase in this variant indicates that a
234 // security upgrade is in progress at the stored phase. No security upgrade is
235 // in progress if std::monostate is present.
236 std::variant<std::monostate,
237 SecurityRequestPhase,
238 std::unique_ptr<Phase1>,
239 Phase2Legacy,
240 Phase2SecureConnections,
241 Phase3>
242 current_phase_;
243
244 WeakSelf<SecurityManagerImpl> weak_self_;
245 WeakSelf<PairingPhase::Listener> weak_listener_;
246 WeakSelf<PairingChannel::Handler> weak_handler_;
247
248 BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(SecurityManagerImpl);
249 };
250
PendingRequest(SecurityLevel level_in,PairingCallback callback_in)251 SecurityManagerImpl::PendingRequest::PendingRequest(SecurityLevel level_in,
252 PairingCallback callback_in)
253 : level(level_in), callback(std::move(callback_in)) {}
254
~SecurityManagerImpl()255 SecurityManagerImpl::~SecurityManagerImpl() {
256 if (le_link_.is_alive()) {
257 le_link_->set_encryption_change_callback({});
258 }
259 }
260
SecurityManagerImpl(hci::LowEnergyConnection::WeakPtr link,l2cap::Channel::WeakPtr smp,IOCapability io_capability,Delegate::WeakPtr delegate,BondableMode bondable_mode,gap::LESecurityMode security_mode,pw::async::Dispatcher & dispatcher)261 SecurityManagerImpl::SecurityManagerImpl(hci::LowEnergyConnection::WeakPtr link,
262 l2cap::Channel::WeakPtr smp,
263 IOCapability io_capability,
264 Delegate::WeakPtr delegate,
265 BondableMode bondable_mode,
266 gap::LESecurityMode security_mode,
267 pw::async::Dispatcher& dispatcher)
268 : SecurityManager(bondable_mode, security_mode),
269 pw_dispatcher_(dispatcher),
270 next_pairing_id_(0),
271 delegate_(std::move(delegate)),
272 le_link_(std::move(link)),
273 io_cap_(io_capability),
274 sm_chan_(std::make_unique<PairingChannel>(
275 smp, fit::bind_member<&SecurityManagerImpl::StartNewTimer>(this))),
276 role_(le_link_->role() == pw::bluetooth::emboss::ConnectionRole::CENTRAL
277 ? Role::kInitiator
278 : Role::kResponder),
279 weak_self_(this),
280 weak_listener_(this),
281 weak_handler_(this) {
282 PW_CHECK(delegate_.is_alive());
283 PW_CHECK(le_link_.is_alive());
284 PW_CHECK(smp.is_alive());
285 PW_CHECK(le_link_->handle() == smp->link_handle());
286 PW_CHECK(smp->id() == l2cap::kLESMPChannelId);
287 // `current_phase_` is default constructed into std::monostate in the
288 // initializer list as no security upgrade is in progress upon construction.
289
290 // Set up HCI encryption event.
291 le_link_->set_encryption_change_callback(
292 fit::bind_member<&SecurityManagerImpl::OnEncryptionChange>(this));
293 sm_chan_->SetChannelHandler(weak_handler_.GetWeakPtr());
294
295 timeout_task_.set_function(
296 [this](pw::async::Context /*ctx*/, pw::Status status) {
297 if (status.ok()) {
298 OnPairingTimeout();
299 }
300 });
301 }
302
OnSecurityRequest(AuthReqField auth_req)303 void SecurityManagerImpl::OnSecurityRequest(AuthReqField auth_req) {
304 PW_CHECK(!SecurityUpgradeInProgress());
305
306 if (role_ != Role::kInitiator) {
307 bt_log(
308 INFO,
309 "sm",
310 "Received spurious Security Request while not acting as SM initiator");
311 sm_chan_->SendMessageNoTimerReset(kPairingFailed,
312 ErrorCode::kCommandNotSupported);
313 return;
314 }
315
316 SecurityLevel requested_level;
317 // inclusive-language: ignore
318 if (auth_req & AuthReq::kMITM) {
319 requested_level = SecurityLevel::kAuthenticated;
320 } else {
321 requested_level = SecurityLevel::kEncrypted;
322 }
323
324 // If we already have a LTK and its security properties satisfy the request,
325 // then we start link layer encryption (which will either encrypt the link or
326 // perform a key refresh). See Vol 3, Part H, Figure 2.7 for the algorithm.
327 if (ltk_ && (ltk_->security().level() >= requested_level) &&
328 (!(auth_req & AuthReq::kSC) || ltk_->security().secure_connections())) {
329 if (bt_is_error(
330 ValidateExistingLocalLtk(),
331 ERROR,
332 "sm",
333 "disconnecting link as it cannot be encrypted with LTK status")) {
334 return;
335 }
336 le_link_->StartEncryption();
337 return;
338 }
339 // V5.1 Vol. 3 Part H Section 3.4: "Upon [...] reception of the Security
340 // Request command, the Security Manager Timer shall be [...] restarted."
341 StartNewTimer();
342 if (fit::result result = RequestSecurityUpgrade(requested_level);
343 result.is_error()) {
344 // Per v5.3 Vol. 3 Part H 2.4.6, "When a Central receives a Security Request
345 // command it may
346 // [...] reject the request.", which we do here as we know we are unable to
347 // fulfill it.
348 sm_chan_->SendMessageNoTimerReset(kPairingFailed, result.error_value());
349 // If we fail to start pairing, we need to stop the timer.
350 StopTimer();
351 }
352 }
353
UpgradeSecurity(SecurityLevel level,PairingCallback callback)354 void SecurityManagerImpl::UpgradeSecurity(SecurityLevel level,
355 PairingCallback callback) {
356 if (SecurityUpgradeInProgress()) {
357 bt_log(TRACE,
358 "sm",
359 "LE security upgrade in progress; request for %s security queued",
360 LevelToString(level));
361 request_queue_.emplace(level, std::move(callback));
362 return;
363 }
364
365 if (level <= security().level()) {
366 callback(fit::ok(), security());
367 return;
368 }
369
370 // Secure Connections only mode only permits Secure Connections authenticated
371 // pairing with a 128- bit encryption key, so we force all security upgrade
372 // requests to that level.
373 if (security_mode() == gap::LESecurityMode::SecureConnectionsOnly) {
374 level = SecurityLevel::kSecureAuthenticated;
375 }
376
377 // |request_queue| must be empty if there is no active security upgrade
378 // request, which is equivalent to being in idle phase with no pending
379 // security request.
380 PW_CHECK(request_queue_.empty());
381 request_queue_.emplace(level, std::move(callback));
382 UpgradeSecurityInternal();
383 }
384
OnPairingRequest(const PairingRequestParams & req_params)385 void SecurityManagerImpl::OnPairingRequest(
386 const PairingRequestParams& req_params) {
387 // Only the initiator may send the Pairing Request (V5.0 Vol. 3 Part H 3.5.1).
388 if (role_ != Role::kResponder) {
389 bt_log(INFO, "sm", "rejecting \"Pairing Request\" as initiator");
390 sm_chan_->SendMessageNoTimerReset(kPairingFailed,
391 ErrorCode::kCommandNotSupported);
392 return;
393 }
394 // V5.1 Vol. 3 Part H Section 3.4: "Upon [...] reception of the Pairing
395 // Request command, the Security Manager Timer shall be reset and started."
396 StartNewTimer();
397
398 // We only require authentication as Responder if there is a pending Security
399 // Request for it.
400 SecurityRequestPhase* security_req_phase =
401 std::get_if<SecurityRequestPhase>(¤t_phase_);
402 auto required_level = security_req_phase
403 ? security_req_phase->pending_security_request()
404 : SecurityLevel::kEncrypted;
405
406 // Secure Connections only mode only permits Secure Connections authenticated
407 // pairing with a 128- bit encryption key, so we force all security upgrade
408 // requests to that level.
409 if (security_mode() == gap::LESecurityMode::SecureConnectionsOnly) {
410 required_level = SecurityLevel::kSecureAuthenticated;
411 }
412
413 current_phase_ = Phase1::CreatePhase1Responder(
414 sm_chan_->GetWeakPtr(),
415 weak_listener_.GetWeakPtr(),
416 req_params,
417 io_cap_,
418 bondable_mode(),
419 required_level,
420 fit::bind_member<&SecurityManagerImpl::OnFeatureExchange>(this));
421 std::get<std::unique_ptr<Phase1>>(current_phase_)->Start();
422 }
423
UpgradeSecurityInternal()424 void SecurityManagerImpl::UpgradeSecurityInternal() {
425 PW_CHECK(
426 !SecurityUpgradeInProgress(),
427 "cannot upgrade security while security upgrade already in progress!");
428 const PendingRequest& next_req = request_queue_.front();
429 if (fit::result result = RequestSecurityUpgrade(next_req.level);
430 result.is_error()) {
431 next_req.callback(ToResult(result.error_value()), security());
432 request_queue_.pop();
433 if (!request_queue_.empty()) {
434 UpgradeSecurityInternal();
435 }
436 }
437 }
438
RequestSecurityUpgrade(SecurityLevel level)439 fit::result<ErrorCode> SecurityManagerImpl::RequestSecurityUpgrade(
440 SecurityLevel level) {
441 if (level >= SecurityLevel::kAuthenticated &&
442 io_cap_ == IOCapability::kNoInputNoOutput) {
443 bt_log(WARN,
444 "sm",
445 "cannot fulfill authenticated security request as IOCapabilities "
446 "are NoInputNoOutput");
447 return fit::error(ErrorCode::kAuthenticationRequirements);
448 }
449
450 if (role_ == Role::kInitiator) {
451 current_phase_ = Phase1::CreatePhase1Initiator(
452 sm_chan_->GetWeakPtr(),
453 weak_listener_.GetWeakPtr(),
454 io_cap_,
455 bondable_mode(),
456 level,
457 fit::bind_member<&SecurityManagerImpl::OnFeatureExchange>(this));
458 std::get<std::unique_ptr<Phase1>>(current_phase_)->Start();
459 } else {
460 current_phase_.emplace<SecurityRequestPhase>(
461 sm_chan_->GetWeakPtr(),
462 weak_listener_.GetWeakPtr(),
463 level,
464 bondable_mode(),
465 fit::bind_member<&SecurityManagerImpl::OnPairingRequest>(this));
466 std::get<SecurityRequestPhase>(current_phase_).Start();
467 }
468 return fit::ok();
469 }
470
OnFeatureExchange(PairingFeatures features,PairingRequestParams preq,PairingResponseParams pres)471 void SecurityManagerImpl::OnFeatureExchange(PairingFeatures features,
472 PairingRequestParams preq,
473 PairingResponseParams pres) {
474 PW_CHECK(std::holds_alternative<std::unique_ptr<Phase1>>(current_phase_));
475 bt_log(TRACE, "sm", "obtained LE Pairing features");
476 next_pairing_id_++;
477 features_ = features;
478
479 const auto [initiator_addr, responder_addr] = LEPairingAddresses();
480 auto self = weak_listener_.GetWeakPtr();
481 if (!features.secure_connections) {
482 auto preq_pdu = util::NewPdu(sizeof(PairingRequestParams)),
483 pres_pdu = util::NewPdu(sizeof(PairingResponseParams));
484 PacketWriter preq_writer(kPairingRequest, preq_pdu.get()),
485 pres_writer(kPairingResponse, pres_pdu.get());
486 *preq_writer.mutable_payload<PairingRequestParams>() = preq;
487 *pres_writer.mutable_payload<PairingRequestParams>() = pres;
488 current_phase_.emplace<Phase2Legacy>(
489 sm_chan_->GetWeakPtr(),
490 self,
491 role_,
492 features,
493 *preq_pdu,
494 *pres_pdu,
495 initiator_addr,
496 responder_addr,
497 fit::bind_member<&SecurityManagerImpl::OnPhase2EncryptionKey>(this));
498 std::get<Phase2Legacy>(current_phase_).Start();
499 } else {
500 current_phase_.emplace<Phase2SecureConnections>(
501 sm_chan_->GetWeakPtr(),
502 self,
503 role_,
504 features,
505 preq,
506 pres,
507 initiator_addr,
508 responder_addr,
509 fit::bind_member<&SecurityManagerImpl::OnPhase2EncryptionKey>(this));
510 std::get<Phase2SecureConnections>(current_phase_).Start();
511 }
512 }
513
OnPhase2EncryptionKey(const UInt128 & new_key)514 void SecurityManagerImpl::OnPhase2EncryptionKey(const UInt128& new_key) {
515 PW_CHECK(le_link_.is_alive());
516 PW_CHECK(features_);
517 PW_CHECK(InPhase2());
518 // EDiv and Rand values are 0 for Phase 2 keys generated by Legacy or Secure
519 // Connections (Vol 3, Part H, 2.4.4 / 2.4.4.1). Secure Connections generates
520 // an LTK, while Legacy generates an STK.
521 auto new_link_key = hci_spec::LinkKey(new_key, 0, 0);
522
523 if (features_->secure_connections) {
524 OnNewLongTermKey(LTK(FeaturesToProperties(*features_), new_link_key));
525 } else {
526 // `set_le_ltk` sets the encryption key of the LE link (which is the STK for
527 // Legacy), not the long-term key that results from pairing (which is
528 // generated in Phase 3 for Legacy).
529 le_link_->set_ltk(new_link_key);
530 }
531 // If we're the initiator, we encrypt the link. If we're the responder, we
532 // wait for the initiator to encrypt the link with the new key.|le_link_| will
533 // respond to the HCI "LTK request" event with the `new_link_key` assigned
534 // above, which should trigger OnEncryptionChange.
535 if (role_ == Role::kInitiator) {
536 if (!le_link_->StartEncryption()) {
537 bt_log(ERROR, "sm", "failed to start encryption");
538 Abort(ErrorCode::kUnspecifiedReason);
539 }
540 }
541 }
542
CurrentLtkInsufficientlySecureForEncryption(std::optional<LTK> current_ltk,SecurityRequestPhase * security_request_phase,gap::LESecurityMode mode)543 bool SecurityManagerImpl::CurrentLtkInsufficientlySecureForEncryption(
544 std::optional<LTK> current_ltk,
545 SecurityRequestPhase* security_request_phase,
546 gap::LESecurityMode mode) {
547 SecurityLevel current_ltk_sec = current_ltk ? current_ltk->security().level()
548 : SecurityLevel::kNoSecurity;
549 return (security_request_phase &&
550 security_request_phase->pending_security_request() >
551 current_ltk_sec) ||
552 (mode == gap::LESecurityMode::SecureConnectionsOnly &&
553 current_ltk_sec != SecurityLevel::kSecureAuthenticated);
554 }
555
OnEncryptionChange(hci::Result<bool> enabled_result)556 void SecurityManagerImpl::OnEncryptionChange(hci::Result<bool> enabled_result) {
557 // First notify the delegate in case of failure.
558 if (bt_is_error(
559 enabled_result, ERROR, "sm", "link layer authentication failed")) {
560 PW_CHECK(delegate_.is_alive());
561 delegate_->OnAuthenticationFailure(
562 fit::error(enabled_result.error_value()));
563 }
564
565 if (enabled_result.is_error() || !enabled_result.value()) {
566 bt_log(WARN,
567 "sm",
568 "encryption of link (handle: %#.4x) %s%s!",
569 le_link_->handle(),
570 enabled_result.is_error()
571 ? bt_lib_cpp_string::StringPrintf("failed with %s",
572 bt_str(enabled_result))
573 .c_str()
574 : "disabled",
575 SecurityUpgradeInProgress() ? "" : " during security upgrade");
576 SetSecurityProperties(sm::SecurityProperties());
577 if (SecurityUpgradeInProgress()) {
578 Abort(ErrorCode::kUnspecifiedReason);
579 }
580 return;
581 }
582
583 SecurityRequestPhase* security_request_phase =
584 std::get_if<SecurityRequestPhase>(¤t_phase_);
585 if (CurrentLtkInsufficientlySecureForEncryption(
586 ltk_, security_request_phase, security_mode())) {
587 bt_log(WARN,
588 "sm",
589 "peer encrypted link with insufficiently secure key, disconnecting");
590 delegate_->OnAuthenticationFailure(
591 ToResult(HostError::kInsufficientSecurity));
592 sm_chan_->SignalLinkError();
593 return;
594 }
595
596 if (!SecurityUpgradeInProgress() || security_request_phase) {
597 bt_log(DEBUG, "sm", "encryption enabled while not pairing");
598 if (bt_is_error(
599 ValidateExistingLocalLtk(),
600 ERROR,
601 "sm",
602 "disconnecting link as it cannot be encrypted with LTK status")) {
603 return;
604 }
605 // If encryption is enabled while not pairing, we update the security
606 // properties to those of `ltk_`. Otherwise, we let the EndPhase2 pairing
607 // function determine the security properties.
608 SetSecurityProperties(ltk_->security());
609 if (security_request_phase) {
610 PW_CHECK(role_ == Role::kResponder);
611 PW_CHECK(!request_queue_.empty());
612 NotifySecurityCallbacks();
613 }
614 return;
615 }
616
617 if (InPhase2()) {
618 bt_log(DEBUG, "sm", "link encrypted with phase 2 generated key");
619 EndPhase2();
620 }
621 }
622
EndPhase2()623 void SecurityManagerImpl::EndPhase2() {
624 PW_CHECK(features_.has_value());
625 PW_CHECK(InPhase2());
626
627 SetSecurityProperties(FeaturesToProperties(*features_));
628 // If there are no keys to distribute, don't bother creating Phase 3
629 if (!HasKeysToDistribute(*features_)) {
630 OnPairingComplete(PairingData());
631 return;
632 }
633 auto self = weak_listener_.GetWeakPtr();
634 current_phase_.emplace<Phase3>(
635 sm_chan_->GetWeakPtr(),
636 self,
637 role_,
638 *features_,
639 security(),
640 fit::bind_member<&SecurityManagerImpl::OnPairingComplete>(this));
641 std::get<Phase3>(current_phase_).Start();
642 }
643
OnPairingComplete(PairingData pairing_data)644 void SecurityManagerImpl::OnPairingComplete(PairingData pairing_data) {
645 // We must either be in Phase3 or Phase 2 with no keys to distribute if
646 // pairing has completed.
647 if (!std::holds_alternative<Phase3>(current_phase_)) {
648 PW_CHECK(InPhase2());
649 PW_CHECK(!HasKeysToDistribute(*features_));
650 }
651 PW_CHECK(delegate_.is_alive());
652 PW_CHECK(features_.has_value());
653 bt_log(DEBUG, "sm", "LE pairing complete");
654 delegate_->OnPairingComplete(fit::ok());
655 // In Secure Connections, the LTK will be generated in Phase 2, not exchanged
656 // in Phase 3, so we want to ensure that it is still put in the pairing_data.
657 if (features_->secure_connections) {
658 PW_CHECK(ltk_.has_value());
659 pairing_data.peer_ltk = pairing_data.local_ltk = ltk_;
660 } else {
661 // The SM-internal LTK is used to validate future encryption events on the
662 // existing link. Encryption with LTKs generated by LE legacy pairing uses
663 // the key received by the link-layer central - so as initiator, this is the
664 // peer key, and as responder, this is the local key.
665 const std::optional<LTK>& new_ltk = role_ == Role::kInitiator
666 ? pairing_data.peer_ltk
667 : pairing_data.local_ltk;
668 if (new_ltk.has_value()) {
669 OnNewLongTermKey(*new_ltk);
670 }
671 }
672
673 if (features_->generate_ct_key.has_value()) {
674 // If we are generating the CT key, we must be using secure connections, and
675 // as such the peer and local LTKs will be equivalent.
676 PW_CHECK(features_->secure_connections);
677 PW_CHECK(pairing_data.peer_ltk == pairing_data.local_ltk);
678 std::optional<UInt128> ct_key_value = util::LeLtkToBrEdrLinkKey(
679 ltk_->key().value(), features_->generate_ct_key.value());
680 if (ct_key_value) {
681 pairing_data.cross_transport_key =
682 sm::LTK(ltk_->security(), hci_spec::LinkKey(*ct_key_value, 0, 0));
683 } else {
684 bt_log(WARN, "sm", "failed to generate cross-transport key");
685 }
686 }
687
688 if (features_->will_bond) {
689 delegate_->OnNewPairingData(pairing_data);
690 } else {
691 bt_log(INFO,
692 "gap-le",
693 " %s pairing complete in non-bondable mode with [%s%s%s%s%s]",
694 features_->secure_connections ? "secure connections" : "legacy",
695 pairing_data.peer_ltk ? "peer_ltk " : "",
696 pairing_data.local_ltk ? "local_ltk " : "",
697 pairing_data.irk ? "irk " : "",
698 pairing_data.identity_address
699 ? bt_lib_cpp_string::StringPrintf(
700 "(identity: %s) ", bt_str(*pairing_data.identity_address))
701 .c_str()
702 : "",
703 pairing_data.csrk ? "csrk " : "");
704 }
705 // So we can pair again if need be.
706 ResetState();
707
708 NotifySecurityCallbacks();
709 }
710
NotifySecurityCallbacks()711 void SecurityManagerImpl::NotifySecurityCallbacks() {
712 // Separate out the requests that are satisfied by the current security level
713 // from those that require a higher level. We'll retry pairing for the latter.
714 std::queue<PendingRequest> satisfied;
715 std::queue<PendingRequest> unsatisfied;
716 while (!request_queue_.empty()) {
717 auto& request = request_queue_.front();
718 if (request.level <= security().level()) {
719 satisfied.push(std::move(request));
720 } else {
721 unsatisfied.push(std::move(request));
722 }
723 request_queue_.pop();
724 }
725
726 request_queue_ = std::move(unsatisfied);
727
728 // Notify the satisfied requests with success.
729 while (!satisfied.empty()) {
730 satisfied.front().callback(fit::ok(), security());
731 satisfied.pop();
732 }
733
734 if (!request_queue_.empty()) {
735 UpgradeSecurityInternal();
736 }
737 }
738
Reset(IOCapability io_capability)739 void SecurityManagerImpl::Reset(IOCapability io_capability) {
740 Abort(ErrorCode::kUnspecifiedReason);
741 io_cap_ = io_capability;
742 ResetState();
743 }
744
ResetState()745 void SecurityManagerImpl::ResetState() {
746 StopTimer();
747 features_.reset();
748 sm_chan_->SetChannelHandler(weak_handler_.GetWeakPtr());
749 current_phase_ = std::monostate{};
750 }
751
AssignLongTermKey(const LTK & ltk)752 bool SecurityManagerImpl::AssignLongTermKey(const LTK& ltk) {
753 if (SecurityUpgradeInProgress()) {
754 bt_log(
755 DEBUG, "sm", "Cannot directly assign LTK while pairing is in progress");
756 return false;
757 }
758
759 OnNewLongTermKey(ltk);
760
761 // The initiatior starts encryption when it receives a new LTK from GAP.
762 if (role_ == Role::kInitiator && !le_link_->StartEncryption()) {
763 bt_log(ERROR, "sm", "Failed to initiate authentication procedure");
764 return false;
765 }
766
767 return true;
768 }
769
SetSecurityProperties(const SecurityProperties & sec)770 void SecurityManagerImpl::SetSecurityProperties(const SecurityProperties& sec) {
771 if (sec != security()) {
772 bt_log(DEBUG,
773 "sm",
774 "security properties changed - handle: %#.4x, new: %s, old: %s",
775 le_link_->handle(),
776 bt_str(sec),
777 bt_str(security()));
778 set_security(sec);
779 delegate_->OnNewSecurityProperties(security());
780 }
781 }
782
Abort(ErrorCode ecode)783 void SecurityManagerImpl::Abort(ErrorCode ecode) {
784 std::visit(
785 [=](auto& arg) {
786 using T = std::decay_t<decltype(arg)>;
787 if constexpr (std::is_same_v<std::unique_ptr<Phase1>, T>) {
788 arg->Abort(ecode);
789 } else if constexpr (std::is_base_of_v<PairingPhase, T>) {
790 arg.Abort(ecode);
791 } else {
792 bt_log(DEBUG,
793 "sm",
794 "Attempted to abort security upgrade while not in progress");
795 }
796 },
797 current_phase_);
798 // "Abort" should trigger OnPairingFailed.
799 }
800
OnIdentityRequest()801 std::optional<IdentityInfo> SecurityManagerImpl::OnIdentityRequest() {
802 // This is called by the bearer to determine if we have local identity
803 // information to distribute.
804 PW_CHECK(delegate_.is_alive());
805 return delegate_->OnIdentityInformationRequest();
806 }
807
ConfirmPairing(ConfirmCallback confirm)808 void SecurityManagerImpl::ConfirmPairing(ConfirmCallback confirm) {
809 PW_CHECK(delegate_.is_alive());
810 delegate_->ConfirmPairing([id = next_pairing_id_,
811 self = weak_self_.GetWeakPtr(),
812 cb = std::move(confirm)](bool is_confirmed) {
813 if (!self.is_alive() || self->next_pairing_id_ != id) {
814 bt_log(TRACE,
815 "sm",
816 "ignoring user confirmation for expired pairing: id = %" PRIu64,
817 id);
818 return;
819 }
820 cb(is_confirmed);
821 });
822 }
823
DisplayPasskey(uint32_t passkey,Delegate::DisplayMethod method,ConfirmCallback confirm)824 void SecurityManagerImpl::DisplayPasskey(uint32_t passkey,
825 Delegate::DisplayMethod method,
826 ConfirmCallback confirm) {
827 PW_CHECK(delegate_.is_alive());
828 delegate_->DisplayPasskey(
829 passkey,
830 method,
831 [id = next_pairing_id_,
832 self = weak_self_.GetWeakPtr(),
833 method,
834 cb = std::move(confirm)](bool is_confirmed) {
835 if (!self.is_alive() || self->next_pairing_id_ != id) {
836 bt_log(TRACE,
837 "sm",
838 "ignoring %s response for expired pairing: id = %" PRIu64,
839 util::DisplayMethodToString(method).c_str(),
840 id);
841 return;
842 }
843 cb(is_confirmed);
844 });
845 }
846
RequestPasskey(PasskeyResponseCallback respond)847 void SecurityManagerImpl::RequestPasskey(PasskeyResponseCallback respond) {
848 PW_CHECK(delegate_.is_alive());
849 delegate_->RequestPasskey([id = next_pairing_id_,
850 self = weak_self_.GetWeakPtr(),
851 cb = std::move(respond)](int64_t passkey) {
852 if (!self.is_alive() || self->next_pairing_id_ != id) {
853 bt_log(
854 TRACE,
855 "sm",
856 "ignoring passkey input response for expired pairing: id = %" PRIx64,
857 id);
858 return;
859 }
860 cb(passkey);
861 });
862 }
863
OnRxBFrame(ByteBufferPtr sdu)864 void SecurityManagerImpl::OnRxBFrame(ByteBufferPtr sdu) {
865 fit::result<ErrorCode, ValidPacketReader> maybe_reader =
866 ValidPacketReader::ParseSdu(sdu);
867 if (maybe_reader.is_error()) {
868 bt_log(INFO,
869 "sm",
870 "dropped SMP packet: %s",
871 bt_str(ToResult(maybe_reader.error_value())));
872 return;
873 }
874 ValidPacketReader reader = maybe_reader.value();
875 Code smp_code = reader.code();
876
877 if (smp_code == kPairingRequest) {
878 OnPairingRequest(reader.payload<PairingRequestParams>());
879 } else if (smp_code == kSecurityRequest) {
880 OnSecurityRequest(reader.payload<AuthReqField>());
881 } else {
882 bt_log(INFO,
883 "sm",
884 "dropped unexpected SMP code %#.2X when not pairing",
885 smp_code);
886 }
887 }
888
OnChannelClosed()889 void SecurityManagerImpl::OnChannelClosed() {
890 bt_log(DEBUG, "sm", "SMP channel closed while not pairing");
891 }
892
OnPairingFailed(Error error)893 void SecurityManagerImpl::OnPairingFailed(Error error) {
894 std::string phase_status = std::visit(
895 [=](auto& arg) {
896 using T = std::decay_t<decltype(arg)>;
897 std::string s;
898 if constexpr (std::is_same_v<std::unique_ptr<Phase1>, T>) {
899 s = arg->ToString();
900 } else if constexpr (std::is_base_of_v<PairingPhase, T>) {
901 s = arg.ToString();
902 } else {
903 BT_PANIC(
904 "security upgrade cannot fail when current_phase_ is "
905 "std::monostate!");
906 }
907 return s;
908 },
909 current_phase_);
910 bt_log(ERROR,
911 "sm",
912 "LE pairing failed: %s. Current pairing phase: %s",
913 bt_str(error),
914 phase_status.c_str());
915 StopTimer();
916 // TODO(fxbug.dev/42172514): implement "waiting interval" to prevent repeated
917 // attempts as described in Vol 3, Part H, 2.3.6.
918
919 PW_CHECK(delegate_.is_alive());
920 delegate_->OnPairingComplete(fit::error(error));
921
922 auto requests = std::move(request_queue_);
923 while (!requests.empty()) {
924 requests.front().callback(fit::error(error), security());
925 requests.pop();
926 }
927
928 if (SecurityUpgradeInProgress()) {
929 PW_CHECK(le_link_.is_alive());
930 le_link_->set_ltk(hci_spec::LinkKey());
931 }
932 ResetState();
933 // Reset state before potentially disconnecting link to avoid causing pairing
934 // phase to fail twice.
935 if (error.is(HostError::kTimedOut)) {
936 // Per v5.2 Vol. 3 Part H 3.4, after a pairing timeout "No further SMP
937 // commands shall be sent over the L2CAP Security Manager Channel. A new
938 // Pairing process shall only be performed when a new physical link has been
939 // established."
940 bt_log(WARN, "sm", "pairing timed out! disconnecting link");
941 sm_chan_->SignalLinkError();
942 }
943 }
944
StartNewTimer()945 void SecurityManagerImpl::StartNewTimer() {
946 if (timeout_task_.is_pending()) {
947 PW_CHECK(timeout_task_.Cancel());
948 }
949 timeout_task_.PostAfter(kPairingTimeout);
950 }
951
StopTimer()952 void SecurityManagerImpl::StopTimer() {
953 if (timeout_task_.is_pending() && !timeout_task_.Cancel()) {
954 bt_log(TRACE, "sm", "smp: failed to stop timer");
955 }
956 }
957
OnPairingTimeout()958 void SecurityManagerImpl::OnPairingTimeout() {
959 std::visit(
960 [=](auto& arg) {
961 using T = std::decay_t<decltype(arg)>;
962 if constexpr (std::is_same_v<std::unique_ptr<Phase1>, T>) {
963 arg->OnFailure(Error(HostError::kTimedOut));
964 } else if constexpr (std::is_base_of_v<PairingPhase, T>) {
965 arg.OnFailure(Error(HostError::kTimedOut));
966 } else {
967 BT_PANIC("cannot timeout when current_phase_ is std::monostate!");
968 }
969 },
970 current_phase_);
971 }
972
973 std::pair<DeviceAddress, DeviceAddress>
LEPairingAddresses()974 SecurityManagerImpl::LEPairingAddresses() {
975 PW_CHECK(SecurityUpgradeInProgress());
976 const DeviceAddress *initiator = &le_link_->local_address(),
977 *responder = &le_link_->peer_address();
978 if (role_ == Role::kResponder) {
979 std::swap(initiator, responder);
980 }
981 return std::make_pair(*initiator, *responder);
982 }
983
OnNewLongTermKey(const LTK & ltk)984 void SecurityManagerImpl::OnNewLongTermKey(const LTK& ltk) {
985 ltk_ = ltk;
986 le_link_->set_ltk(ltk.key());
987 }
988
ValidateExistingLocalLtk()989 Result<> SecurityManagerImpl::ValidateExistingLocalLtk() {
990 Result<> status = fit::ok();
991 if (!ltk_.has_value()) {
992 // Should always be present when this method is called.
993 bt_log(ERROR, "sm", "SM LTK not found");
994 status = fit::error(Error(HostError::kNotFound));
995 } else if (!le_link_->ltk().has_value()) {
996 // Should always be present when this method is called.
997 bt_log(ERROR, "sm", "Link LTK not found");
998 status = fit::error(Error(HostError::kNotFound));
999 } else if (le_link_->ltk().value() != ltk_->key()) {
1000 // As only SM should ever change the LE Link encryption key, these two
1001 // values should always be in sync, i.e. something in the system is acting
1002 // unreliably if they get out of sync.
1003 bt_log(ERROR, "sm", "SM LTK differs from LE link LTK");
1004 status = fit::error(Error(HostError::kNotReliable));
1005 }
1006 if (status.is_error()) {
1007 // SM does not own the link, so although the checks above should never fail,
1008 // disconnecting the link (vs. ASSERTing these checks) is safer against
1009 // non-SM code potentially touching the key.
1010 delegate_->OnAuthenticationFailure(
1011 ToResult(pw::bluetooth::emboss::StatusCode::PIN_OR_KEY_MISSING));
1012 sm_chan_->SignalLinkError();
1013 }
1014 return status;
1015 }
1016
Create(hci::LowEnergyConnection::WeakPtr link,l2cap::Channel::WeakPtr smp,IOCapability io_capability,Delegate::WeakPtr delegate,BondableMode bondable_mode,gap::LESecurityMode security_mode,pw::async::Dispatcher & dispatcher)1017 std::unique_ptr<SecurityManager> SecurityManager::Create(
1018 hci::LowEnergyConnection::WeakPtr link,
1019 l2cap::Channel::WeakPtr smp,
1020 IOCapability io_capability,
1021 Delegate::WeakPtr delegate,
1022 BondableMode bondable_mode,
1023 gap::LESecurityMode security_mode,
1024 pw::async::Dispatcher& dispatcher) {
1025 return std::make_unique<SecurityManagerImpl>(std::move(link),
1026 std::move(smp),
1027 io_capability,
1028 std::move(delegate),
1029 bondable_mode,
1030 security_mode,
1031 dispatcher);
1032 }
1033
SecurityManager(BondableMode bondable_mode,gap::LESecurityMode security_mode)1034 SecurityManager::SecurityManager(BondableMode bondable_mode,
1035 gap::LESecurityMode security_mode)
1036 : bondable_mode_(bondable_mode), security_mode_(security_mode) {}
1037
1038 } // namespace bt::sm
1039