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 #pragma once
16 #include <lib/fit/function.h>
17
18 #include <optional>
19 #include <string>
20 #include <unordered_map>
21
22 #include "pw_bluetooth_sapphire/internal/host/common/inspect.h"
23 #include "pw_bluetooth_sapphire/internal/host/common/uint128.h"
24 #include "pw_bluetooth_sapphire/internal/host/hci-spec/constants.h"
25 #include "pw_bluetooth_sapphire/internal/host/hci-spec/link_key.h"
26 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
27
28 namespace bt::sm {
29
30 const std::unordered_map<Code, size_t> kCodeToPayloadSize{
31 {kSecurityRequest, sizeof(AuthReqField)},
32 {kPairingRequest, sizeof(PairingRequestParams)},
33 {kPairingResponse, sizeof(PairingResponseParams)},
34 {kPairingConfirm, sizeof(PairingConfirmValue)},
35 {kPairingRandom, sizeof(PairingRandomValue)},
36 {kPairingFailed, sizeof(PairingFailedParams)},
37 {kEncryptionInformation, sizeof(EncryptionInformationParams)},
38 {kCentralIdentification, sizeof(CentralIdentificationParams)},
39 {kIdentityInformation, sizeof(IRK)},
40 {kIdentityAddressInformation, sizeof(IdentityAddressInformationParams)},
41 {kPairingPublicKey, sizeof(PairingPublicKeyParams)},
42 {kPairingDHKeyCheck, sizeof(PairingDHKeyCheckValueE)},
43 };
44
45 // The available algorithms used to generate the cross-transport key during
46 // pairing.
47 enum CrossTransportKeyAlgo {
48 // Use only the H6 function during cross-transport derivation (v5.2 Vol. 3
49 // Part H 2.2.10).
50 kUseH6,
51
52 // Use the H7 function during cross-transport derivation (v5.2 Vol. 3 Part
53 // H 2.2.11).
54 kUseH7
55 };
56
57 // Represents the features exchanged during Pairing Phase 1.
58 struct PairingFeatures final {
59 // True if the local device is in the "initiator" role.
60 bool initiator = false;
61
62 // True if LE Secure Connections pairing should be used. Otherwise, LE Legacy
63 // Pairing should be used.
64 bool secure_connections = false;
65
66 // True if pairing is to be performed with bonding, false if not
67 bool will_bond = false;
68
69 // If present, prescribes the algorithm to use during cross-transport key
70 // derivation. If not present, cross-transport key derivation should not take
71 // place.
72 std::optional<CrossTransportKeyAlgo> generate_ct_key;
73
74 // Indicates the key generation model used for Phase 2.
75 PairingMethod method = PairingMethod::kJustWorks;
76
77 // The negotiated encryption key size.
78 uint8_t encryption_key_size = 0;
79
80 // The keys that we must distribute to the peer.
81 KeyDistGenField local_key_distribution = 0;
82
83 // The keys that will be distributed to us by the peer.
84 KeyDistGenField remote_key_distribution = 0;
85 };
86
DistributableKeys(KeyDistGenField keys)87 constexpr KeyDistGenField DistributableKeys(KeyDistGenField keys) {
88 // The link key field never affects the distributed keys. It only has meaning
89 // when the devices use LE Secure Connections, where it means the devices
90 // should generate the BR/EDR Link Key locally.
91 return keys & ~KeyDistGen::kLinkKey;
92 }
93
94 // Returns a bool indicating whether `features` calls for the devices to
95 // exchange key information during the Key Distribution/Generation Phase 3.
96 bool HasKeysToDistribute(PairingFeatures features);
97
98 // Each enum variant corresponds to either:
99 // 1) a LE security mode 1 level (Core Spec v5.4, Vol 3, Part C 10.2.1)
100 // 2) a BR/EDR security mode 4 level (Core Spec v5.4, Vol 3, Part C, 5.2.2.8)
101 // Fuchsia only supports encryption based security
102 // TODO(fxbug.dev/42113587): Implement BR/EDR security database
103 enum class SecurityLevel {
104 // No encryption
105 kNoSecurity = 1,
106
107 // inclusive-language: ignore
108 // Encrypted without MITM protection (unauthenticated)
109 kEncrypted = 2,
110
111 // inclusive-language: ignore
112 // Encrypted with MITM protection (authenticated)
113 kAuthenticated = 3,
114
115 // inclusive-language: ignore
116 // Encrypted with MITM protection, Secure Connections, and a 128-bit
117 // encryption key.
118 kSecureAuthenticated = 4,
119 };
120
121 // Returns a string representation of |level| for debug messages.
122 const char* LevelToString(SecurityLevel level);
123
124 // Represents the security properties of a key. The security properties of a
125 // connection's LTK defines the security properties of the connection.
126 class SecurityProperties final {
127 public:
128 SecurityProperties();
129 SecurityProperties(SecurityLevel level,
130 size_t enc_key_size,
131 bool secure_connections);
132 SecurityProperties(bool encrypted,
133 bool authenticated,
134 bool secure_connections,
135 size_t enc_key_size);
136 // Build from a BR/EDR Link Key that resulted from pairing. |lk_type| should
137 // not be kChangedCombination, because that means that the link key is the
138 // same type as before it was changed, which this has no knowledge of.
139 //
140 // Legacy pairing keys will be considered to have security level kNoSecurity
141 // because legacy pairing is superseded by Secure Simple Pairing in Core Spec
142 // v2.1 + EDR in 2007. Backwards compatiblity is optional per v5.0, Vol 3,
143 // Part C, Section 5. Furthermore, the last Core Spec with only legacy pairing
144 // (v2.0 + EDR) was withdrawn by Bluetooth SIG on 2019-01-28.
145 //
146 // TODO(fxbug.dev/42111880): SecurityProperties will treat kDebugCombination
147 // keys as "encrypted, unauthenticated, and no Secure Connections" to
148 // potentially allow their use as valid link keys, but does not store the fact
149 // that they originate from a controller in pairing debug mode, a potential
150 // hazard. Care should be taken at the controller interface to enforce
151 // particular policies regarding debug keys.
152 explicit SecurityProperties(hci_spec::LinkKeyType lk_type);
153
154 ~SecurityProperties() = default;
155
156 // Copy constructors that ignore InspectProperties
157 SecurityProperties(const SecurityProperties& other);
158 SecurityProperties& operator=(const SecurityProperties& other);
159
160 SecurityLevel level() const;
enc_key_size()161 size_t enc_key_size() const { return enc_key_size_; }
encrypted()162 bool encrypted() const { return properties_ & Property::kEncrypted; }
secure_connections()163 bool secure_connections() const {
164 return properties_ & Property::kSecureConnections;
165 }
authenticated()166 bool authenticated() const { return properties_ & Property::kAuthenticated; }
167
168 // Returns the BR/EDR link key type that produces the current security
169 // properties. Returns kCombination if the current security level is
170 // kNoSecurity since it is the key type generated by legacy pairing.
171 //
172 // SecurityProperties does not encode the use of
173 // LinkKeyType::kDebugCombination keys (see Core Spec v5.0 Vol 2, Part E
174 // Section 7.6.4), produced when a controller is in debug mode, so
175 // SecurityProperties constructed from LinkKeyType::kDebugCombination returns
176 // LinkKeyType::kUnauthenticatedCombination192 from this method.
177 hci_spec::LinkKeyType GetLinkKeyType() const;
178
179 // Returns a string representation of these properties.
180 std::string ToString() const;
181
182 // Returns whether `this` SecurityProperties is at least as secure as |other|.
183 // This checks the encryption/authentication level of `this` vs. other, that
184 // `this` used secure connections if |other| did, and that `this` encryption
185 // key size is at least as large as |others|.
186 bool IsAsSecureAs(const SecurityProperties& other) const;
187
188 // Attach pairing state inspect node named |name| as a child of |parent|.
189 void AttachInspect(inspect::Node& parent, std::string name);
190
191 // Compare two properties for equality.
192 bool operator==(const SecurityProperties& other) const {
193 return properties_ == other.properties_ &&
194 enc_key_size_ == other.enc_key_size_;
195 }
196
197 bool operator!=(const SecurityProperties& other) const {
198 return !(*this == other);
199 }
200
201 private:
202 struct InspectProperties {
203 inspect::StringProperty level;
204 inspect::BoolProperty encrypted;
205 inspect::BoolProperty secure_connections;
206 inspect::BoolProperty authenticated;
207 inspect::StringProperty key_type;
208 };
209 InspectProperties inspect_properties_;
210 inspect::Node inspect_node_;
211
212 // Possible security properties for a link.
213 enum Property : uint8_t {
214 kEncrypted = (1 << 0),
215 kAuthenticated = (1 << 1),
216 kSecureConnections = (1 << 2)
217 };
218 using PropertiesField = uint8_t;
219 PropertiesField properties_;
220 size_t enc_key_size_;
221 };
222
223 // Represents a reusable long term key for a specific transport.
224 class LTK final {
225 public:
226 LTK() = default;
227 LTK(const SecurityProperties& security, const hci_spec::LinkKey& key);
228
security()229 const SecurityProperties& security() const { return security_; }
key()230 const hci_spec::LinkKey& key() const { return key_; }
231
232 bool operator==(const LTK& other) const {
233 return security() == other.security() && key() == other.key();
234 }
235
236 bool operator!=(const LTK& other) const { return !(*this == other); }
237
238 // Attach |security_| as child node of |parent| with specified |name|.
239 void AttachInspect(inspect::Node& parent, std::string name);
240
241 private:
242 SecurityProperties security_;
243 hci_spec::LinkKey key_;
244 };
245
246 // Represents a 128-bit key.
247 class Key final {
248 public:
249 Key() = default;
250 Key(const SecurityProperties& security, const UInt128& value);
251
security()252 const SecurityProperties& security() const { return security_; }
value()253 const UInt128& value() const { return value_; }
254
255 bool operator==(const Key& other) const {
256 return security() == other.security() && value() == other.value();
257 }
258
259 private:
260 SecurityProperties security_;
261 UInt128 value_;
262 };
263
264 // Container for LE pairing data.
265 struct PairingData final {
266 // The identity address.
267 std::optional<DeviceAddress> identity_address;
268
269 // The long term link encryption key generated by the local device. For LTKs
270 // generated by Secure Connections, this will be the same as peer_ltk.
271 std::optional<sm::LTK> local_ltk;
272
273 // The long term link encryption key generated by the peer device. For LTKs
274 // generated by Secure Connections, this will be the same as local_ltk.
275 std::optional<sm::LTK> peer_ltk;
276
277 // The cross-transport key for pairing-free encryption on the other transport.
278 std::optional<sm::LTK> cross_transport_key;
279
280 // The identity resolving key used to resolve RPAs to |identity|.
281 std::optional<sm::Key> irk;
282
283 // The connection signature resolving key used in LE security mode 2.
284 std::optional<sm::Key> csrk;
285
286 bool operator==(const PairingData& other) const {
287 return identity_address == other.identity_address &&
288 local_ltk == other.local_ltk && peer_ltk == other.peer_ltk &&
289 irk == other.irk && csrk == other.csrk;
290 }
291 };
292
293 // Container for identity information for distribution.
294 struct IdentityInfo {
295 UInt128 irk;
296 DeviceAddress address;
297 };
298
299 // Enum for the possible values of the SM Bondable Mode as defined in spec V5.1
300 // Vol 3 Part C Section 9.4
301 enum class BondableMode {
302 // Allows pairing which results in bonding, as well as pairing which does not
303 Bondable,
304 // Does not allow pairing which results in bonding
305 NonBondable,
306 };
307
308 // Represents the local device's settings for easy mapping to
309 // Pairing(Request|Response)Parameters.
310 struct LocalPairingParams {
311 // The local I/O capability.
312 IOCapability io_capability;
313 // Whether or not OOB authentication data is available locally. Defaults to no
314 // OOB data.
315 OOBDataFlag oob_data_flag = OOBDataFlag::kNotPresent;
316 // The local requested security properties (Vol 3, Part H, 2.3.1). Defaults to
317 // no Authentication Requirements.
318 AuthReqField auth_req = 0u;
319 // Maximum encryption key size supported by the local device. Valid values are
320 // 7-16. Defaults to maximum allowed encryption key size.
321 uint8_t max_encryption_key_size = kMaxEncryptionKeySize;
322 // The keys that the local system is able to distribute. Defaults to
323 // distributing no keys.
324 KeyDistGenField local_keys = 0u;
325 // The keys that are desired from the peer. Defaults to distributing no keys.
326 KeyDistGenField remote_keys = 0u;
327 };
328
329 // These roles correspond to the device which starts pairing.
330 enum class Role {
331 // The LMP Central device is always kInitiator (V5.0 Vol. 3 Part H Appendix
332 // C.1).
333 kInitiator,
334
335 // The LMP Peripheral device is always kResponder (V5.0 Vol. 3 Part H Appendix
336 // C.1).
337 kResponder
338 };
339
340 using PairingProcedureId = uint64_t;
341
342 // Used by Phase 2 classes to notify their owner that a new encryption key is
343 // ready. For Legacy Pairing, this is the STK which may only be used for the
344 // current session. For Secure Connections, this is the LTK which may be
345 // persisted.
346 using OnPhase2KeyGeneratedCallback = fit::function<void(const UInt128&)>;
347
348 // Used to notify classes of peer Pairing Requests.
349 using PairingRequestCallback = fit::function<void(PairingRequestParams)>;
350
351 } // namespace bt::sm
352