1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2021 Gothel Software e.K.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <cstdio>
#include "SMPKeyBin.hpp"
// #define USE_CXX17lib_FS 1
#if USE_CXX17lib_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif
using namespace direct_bt;
static bool file_exists(const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
SMPKeyBin SMPKeyBin::create(const BTDevice& device) {
const BTSecurityLevel sec_lvl = device.getConnSecurityLevel();
const SMPPairingState pstate = device.getPairingState();
const PairingMode pmode = device.getPairingMode(); // Skip PairingMode::PRE_PAIRED (write again)
SMPKeyBin smpKeyBin(device.getAddressAndType(),
device.getConnSecurityLevel(), device.getConnIOCapability());
if( ( BTSecurityLevel::NONE < sec_lvl && SMPPairingState::COMPLETED == pstate && PairingMode::NEGOTIATING < pmode ) ||
( BTSecurityLevel::NONE == sec_lvl && SMPPairingState::NONE == pstate && PairingMode::NONE == pmode ) )
{
const SMPKeyType keys_resp = device.getAvailableSMPKeys(true /* responder */);
const SMPKeyType keys_init = device.getAvailableSMPKeys(false /* responder */);
if( ( SMPKeyType::ENC_KEY & keys_init ) != SMPKeyType::NONE ) {
smpKeyBin.setLTKInit( device.getLongTermKeyInfo(false /* responder */) );
}
if( ( SMPKeyType::ENC_KEY & keys_resp ) != SMPKeyType::NONE ) {
smpKeyBin.setLTKResp( device.getLongTermKeyInfo(true /* responder */) );
}
if( ( SMPKeyType::SIGN_KEY & keys_init ) != SMPKeyType::NONE ) {
smpKeyBin.setCSRKInit( device.getSignatureResolvingKeyInfo(false /* responder */) );
}
if( ( SMPKeyType::SIGN_KEY & keys_resp ) != SMPKeyType::NONE ) {
smpKeyBin.setCSRKResp( device.getSignatureResolvingKeyInfo(true /* responder */) );
}
} else {
smpKeyBin.size = 0; // explicitly mark invalid
}
return smpKeyBin;
}
bool SMPKeyBin::createAndWrite(const BTDevice& device, const std::string& path, const bool overwrite, const bool verbose_) {
SMPKeyBin smpKeyBin = SMPKeyBin::create(device);
if( smpKeyBin.isValid() ) {
smpKeyBin.setVerbose( verbose_ );
return smpKeyBin.write( getFilename(path, device.getAddressAndType()), overwrite );
} else {
if( verbose_ ) {
jau::fprintf_td(stderr, "Create SMPKeyBin: Invalid %s, %s\n", smpKeyBin.toString().c_str(), device.toString().c_str());
}
return false;
}
}
std::string SMPKeyBin::toString() const noexcept {
std::string res = "SMPKeyBin["+addrAndType.toString()+", sec "+to_string(sec_level)+
", io "+to_string(io_cap)+
", ";
if( isVersionValid() ) {
res += "Init[";
if( hasLTKInit() ) {
res += ltk_init.toString();
}
if( hasCSRKInit() ) {
if( hasLTKInit() ) {
res += ", ";
}
res += csrk_init.toString();
}
res += "], Resp[";
if( hasLTKResp() ) {
res += ltk_resp.toString();
}
if( hasCSRKResp() ) {
if( hasLTKResp() ) {
res += ", ";
}
res += csrk_resp.toString();
}
res += "], ";
}
res += "ver["+jau::to_hexstring(version)+", ok "+std::to_string( isVersionValid() )+
"], size["+std::to_string(size);
if( verbose ) {
res += ", calc "+std::to_string( calcSize() );
}
res += ", valid "+std::to_string( isSizeValid() )+
"], ";
{
std::time_t t0 = static_cast<std::time_t>(ts_creation_sec);
struct std::tm tm_0;
if( nullptr == ::gmtime_r( &t0, &tm_0 ) ) {
res += "1970-01-01 00:00:00"; // 19 + 1
} else {
char b[20];
strftime(b, sizeof(b), "%Y-%m-%d %H:%M:%S", &tm_0);
res += std::string(b);
}
}
res += ", valid "+std::to_string( isValid() )+"]";
return res;
}
std::string SMPKeyBin::getFileBasename() const noexcept {
std::string r("bd_"+addrAndType.address.toString()+":"+std::to_string(number(addrAndType.type))+"-smpkey.bin");
std::replace( r.begin(), r.end(), ':', '_');
return r;
}
std::string SMPKeyBin::getFileBasename(const BDAddressAndType& addrAndType_) {
std::string r("bd_"+addrAndType_.address.toString()+":"+std::to_string(number(addrAndType_.type))+"-smpkey.bin");
std::replace( r.begin(), r.end(), ':', '_');
return r;
}
bool SMPKeyBin::remove_impl(const std::string& fname) {
#if USE_CXX17lib_FS
const fs::path fname2 = fname;
return fs::remove(fname);
#else
return 0 == std::remove( fname.c_str() );
#endif
}
bool SMPKeyBin::write(const std::string& fname, const bool overwrite) const noexcept {
if( !isValid() ) {
if( verbose ) {
jau::fprintf_td(stderr, "Write SMPKeyBin: Invalid (skipped) %s\n", toString().c_str());
}
return false;
}
if( file_exists(fname) ) {
if( overwrite ) {
if( !remove_impl(fname) ) {
jau::fprintf_td(stderr, "Write SMPKeyBin: Failed deletion of existing file %s, %s\n", fname.c_str(), toString().c_str());
return false;
}
} else {
jau::fprintf_td(stderr, "Write SMPKeyBin: Not overwriting existing file %s, %s\n", fname.c_str(), toString().c_str());
return false;
}
}
std::ofstream file(fname, std::ios::out | std::ios::binary);
if ( !file.good() || !file.is_open() ) {
if( verbose ) {
jau::fprintf_td(stderr, "Write SMPKeyBin: Failed: File not open %s: %s\n", fname.c_str(), toString().c_str());
}
return false;
}
uint8_t buffer[8];
jau::put_uint16(buffer, 0, version, true /* littleEndian */);
file.write((char*)buffer, sizeof(version));
jau::put_uint16(buffer, 0, size, true /* littleEndian */);
file.write((char*)buffer, sizeof(size));
jau::put_uint64(buffer, 0, ts_creation_sec, true /* littleEndian */);
file.write((char*)buffer, sizeof(ts_creation_sec));
file.write((char*)&addrAndType.address, sizeof(addrAndType.address));
file.write((char*)&addrAndType.type, sizeof(addrAndType.type));
file.write((char*)&sec_level, sizeof(sec_level));
file.write((char*)&io_cap, sizeof(io_cap));
file.write((char*)&keys_init, sizeof(keys_init));
file.write((char*)&keys_resp, sizeof(keys_resp));
if( hasLTKInit() ) {
file.write((char*)<k_init, sizeof(ltk_init));
}
if( hasCSRKInit() ) {
file.write((char*)&csrk_init, sizeof(csrk_init));
}
if( hasLTKResp() ) {
file.write((char*)<k_resp, sizeof(ltk_resp));
}
if( hasCSRKResp() ) {
file.write((char*)&csrk_resp, sizeof(csrk_resp));
}
const bool res = file.good() && file.is_open();
if( verbose ) {
if( res ) {
jau::fprintf_td(stderr, "Write SMPKeyBin: Success: %s: %s\n", fname.c_str(), toString().c_str());
} else {
jau::fprintf_td(stderr, "Write SMPKeyBin: Failed: %s: %s\n", fname.c_str(), toString().c_str());
}
}
file.close();
return res;
}
bool SMPKeyBin::read(const std::string& fname, const bool removeInvalidFile) {
std::ifstream file(fname, std::ios::binary);
if ( !file.is_open() ) {
if( verbose ) {
jau::fprintf_td(stderr, "Read SMPKeyBin failed: %s\n", fname.c_str());
}
size = 0; // explicitly mark invalid
return false;
}
bool err = false;
uint8_t buffer[8];
file.read((char*)buffer, sizeof(version));
version = jau::get_uint16(buffer, 0, true /* littleEndian */);
err = file.fail();
if( !err ) {
file.read((char*)buffer, sizeof(size));
size = jau::get_uint16(buffer, 0, true /* littleEndian */);
err = file.fail();
}
uint16_t remaining = size - sizeof(version) - sizeof(size);
if( !err && 8 <= remaining ) {
file.read((char*)buffer, sizeof(ts_creation_sec));
ts_creation_sec = jau::get_uint64(buffer, 0, true /* littleEndian */);
remaining -= 8;
err = file.fail();
} else {
err = true;
}
if( !err && 11 <= remaining ) {
file.read((char*)&addrAndType.address, sizeof(addrAndType.address));
file.read((char*)&addrAndType.type, sizeof(addrAndType.type));
file.read((char*)&sec_level, sizeof(sec_level));
file.read((char*)&io_cap, sizeof(io_cap));
file.read((char*)&keys_init, sizeof(keys_init));
file.read((char*)&keys_resp, sizeof(keys_resp));
remaining -= 11;
err = file.fail();
} else {
err = true;
}
addrAndType.clearHash();
if( !err && hasLTKInit() ) {
if( sizeof(ltk_init) <= remaining ) {
file.read((char*)<k_init, sizeof(ltk_init));
remaining -= sizeof(ltk_init);
err = file.fail();
} else {
err = true;
}
}
if( !err && hasCSRKInit() ) {
if( sizeof(csrk_init) <= remaining ) {
file.read((char*)&csrk_init, sizeof(csrk_init));
remaining -= sizeof(csrk_init);
err = file.fail();
} else {
err = true;
}
}
if( !err && hasLTKResp() ) {
if( sizeof(ltk_resp) <= remaining ) {
file.read((char*)<k_resp, sizeof(ltk_resp));
remaining -= sizeof(ltk_resp);
err = file.fail();
} else {
err = true;
}
}
if( !err && hasCSRKResp() ) {
if( sizeof(csrk_resp) <= remaining ) {
file.read((char*)&csrk_resp, sizeof(csrk_resp));
remaining -= sizeof(csrk_resp);
err = file.fail();
} else {
err = true;
}
}
if( !err ) {
err = !isValid();
}
file.close();
if( err ) {
if( removeInvalidFile ) {
remove_impl( fname );
}
if( verbose ) {
jau::fprintf_td(stderr, "Read SMPKeyBin: Failed %s (removed %d): %s, remaining %u\n",
fname.c_str(), removeInvalidFile, toString().c_str(), remaining);
}
size = 0; // explicitly mark invalid
} else {
if( verbose ) {
jau::fprintf_td(stderr, "Read SMPKeyBin: OK %s: %s, remaining %u\n",
fname.c_str(), toString().c_str(), remaining);
}
}
return err;
}
HCIStatusCode SMPKeyBin::apply(BTDevice & device) const noexcept {
HCIStatusCode res = HCIStatusCode::SUCCESS;
// Must be a valid SMPKeyBin instance and at least one LTK key if using encryption.
if( !isValid() || ( BTSecurityLevel::NONE != sec_level && !hasLTKInit() && !hasLTKResp() ) ) {
res = HCIStatusCode::INVALID_PARAMS;
if( verbose ) {
jau::fprintf_td(stderr, "Apply SMPKeyBin failed: SMPKeyBin Status: %s, %s\n",
to_string(res).c_str(), this->toString().c_str());
}
return res;
}
if( !device.isValid() ) {
res = HCIStatusCode::INVALID_PARAMS;
if( verbose ) {
jau::fprintf_td(stderr, "Apply SMPKeyBin failed: Device Invalid: %s, %s, %s\n",
to_string(res).c_str(), this->toString().c_str(), device.toString().c_str());
}
return res;
}
// Allow no encryption at all, i.e. BTSecurityLevel::NONE
const BTSecurityLevel applySecLevel = BTSecurityLevel::NONE == sec_level ?
BTSecurityLevel::NONE : BTSecurityLevel::ENC_ONLY;
if( !device.setConnSecurity(applySecLevel, SMPIOCapability::NO_INPUT_NO_OUTPUT) ) {
res = HCIStatusCode::CONNECTION_ALREADY_EXISTS;
if( verbose ) {
jau::fprintf_td(stderr, "Apply SMPKeyBin failed: Device Connected/ing: %s, %s, %s\n",
to_string(res).c_str(), this->toString().c_str(), device.toString().c_str());
}
return res;
}
if( hasLTKInit() ) {
res = device.setLongTermKeyInfo( getLTKInit() );
if( HCIStatusCode::SUCCESS != res && verbose ) {
jau::fprintf_td(stderr, "Apply SMPKeyBin failed: Init-LTK Upload: %s, %s, %s\n",
to_string(res).c_str(), this->toString().c_str(), device.toString().c_str());
}
}
if( HCIStatusCode::SUCCESS == res && hasLTKResp() ) {
res = device.setLongTermKeyInfo( getLTKResp() );
if( HCIStatusCode::SUCCESS != res && verbose ) {
jau::fprintf_td(stderr, "Apply SMPKeyBin failed: Resp-LTK Upload: %s, %s, %s\n",
to_string(res).c_str(), this->toString().c_str(), device.toString().c_str());
}
}
return res;
}
|