• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 5841327280

12 Aug 2023 12:33PM UTC coverage: 91.709% (-0.01%) from 91.719%
5841327280

push

github

web-flow
Merge pull request #3668 from randombit/enable_if_t_cxx20

roughtime remove redefinition of enable_if_t helper

78552 of 85654 relevant lines covered (91.71%)

12230962.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.54
/src/lib/misc/roughtime/roughtime.cpp
1
/*
2
* Roughtime
3
* (C) 2019 Nuno Goncalves <nunojpg@gmail.com>
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include <botan/roughtime.h>
9

10
#include <botan/base64.h>
11
#include <botan/hash.h>
12
#include <botan/pubkey.h>
13
#include <botan/rng.h>
14
#include <botan/internal/socket_udp.h>
15

16
#include <cmath>
17
#include <map>
18
#include <sstream>
19

20
namespace Botan {
21

22
namespace {
23

24
// This exists to work around a LGTM false positive
25
static_assert(Roughtime::request_min_size == 1024, "Expected minimum size");
26

27
template <class T>
28
struct is_array : std::false_type {};
29

30
template <class T, std::size_t N>
31
struct is_array<std::array<T, N>> : std::true_type {};
32

33
template <typename T>
34
T impl_from_little_endian(const uint8_t* t, const size_t i)
921✔
35
   requires(sizeof(T) <= sizeof(int64_t))
36
{
37
   return T(static_cast<int64_t>(t[i]) << i * 8) + (i == 0 ? T(0) : impl_from_little_endian<T>(t, i - 1));
1,856✔
38
}
39

40
template <typename T>
41
T from_little_endian(const uint8_t* t) {
369✔
42
   return impl_from_little_endian<T>(t, sizeof(T) - 1);
369✔
43
}
44

45
template <typename T, std::enable_if_t<is_array<T>::value>* = nullptr>
46
T copy(const uint8_t* t) {
142✔
47
   return typecast_copy<T>(t);  //arrays are endianess indepedent, so we do a memcpy
142✔
48
}
49

50
template <typename T, std::enable_if_t<!is_array<T>::value>* = nullptr>
51
T copy(const uint8_t* t) {
92✔
52
   return from_little_endian<T>(
92✔
53
      t);  //other types are arithmetic, so we account that roughtime serializes as little endian
54
}
55

56
template <typename T>
57
std::map<std::string, std::vector<uint8_t>> unpack_roughtime_packet(T bytes) {
124✔
58
   if(bytes.size() < 8) {
94✔
59
      throw Roughtime::Roughtime_Error("Map length is under minimum of 8 bytes");
1✔
60
   }
61
   const auto buf = bytes.data();
123✔
62
   const uint32_t num_tags = buf[0];
123✔
63
   const uint32_t start_content = num_tags * 8;
123✔
64
   if(start_content > bytes.size()) {
123✔
65
      throw Roughtime::Roughtime_Error("Map length too small to contain all tags");
1✔
66
   }
67
   uint32_t start = start_content;
122✔
68
   std::map<std::string, std::vector<uint8_t>> tags;
122✔
69
   for(uint32_t i = 0; i < num_tags; ++i) {
517✔
70
      const size_t end =
457✔
71
         ((i + 1) == num_tags) ? bytes.size() : start_content + from_little_endian<uint32_t>(buf + 4 + i * 4);
614✔
72
      if(end > bytes.size()) {
367✔
73
         throw Roughtime::Roughtime_Error("Tag end index out of bounds");
1✔
74
      }
75
      if(end < start) {
396✔
76
         throw Roughtime::Roughtime_Error("Tag offset must be more than previous tag offset");
1✔
77
      }
78
      const char* label_ptr = cast_uint8_ptr_to_char(buf) + (num_tags + i) * 4;
395✔
79
      const char label[] = {label_ptr[0], label_ptr[1], label_ptr[2], label_ptr[3], 0};
395✔
80
      auto ret = tags.emplace(label, std::vector<uint8_t>(buf + start, buf + end));
792✔
81
      if(!ret.second) {
395✔
82
         throw Roughtime::Roughtime_Error(std::string("Map has duplicated tag: ") + label);
×
83
      }
84
      start = static_cast<uint32_t>(end);
395✔
85
   }
86
   return tags;
120✔
87
}
2✔
88

89
template <typename T>
90
T get(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
262✔
91
   const auto& tag = map.find(label);
262✔
92
   if(tag == map.end()) {
262✔
93
      throw Roughtime::Roughtime_Error("Tag " + label + " not found");
2✔
94
   }
95
   if(tag->second.size() != sizeof(T)) {
261✔
96
      throw Roughtime::Roughtime_Error("Tag " + label + " has unexpected size");
2✔
97
   }
98
   return copy<T>(tag->second.data());
260✔
99
}
100

101
const std::vector<uint8_t>& get_v(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
87✔
102
   const auto& tag = map.find(label);
87✔
103
   if(tag == map.end()) {
87✔
104
      throw Roughtime::Roughtime_Error("Tag " + label + " not found");
2✔
105
   }
106
   return tag->second;
86✔
107
}
108

109
bool verify_signature(const std::array<uint8_t, 32>& pk,
27✔
110
                      const std::vector<uint8_t>& payload,
111
                      const std::array<uint8_t, 64>& signature) {
112
   const char context[] = "RoughTime v1 response signature";
27✔
113
   Ed25519_PublicKey key(std::vector<uint8_t>(pk.data(), pk.data() + pk.size()));
54✔
114
   PK_Verifier verifier(key, "Pure");
27✔
115
   verifier.update(cast_char_ptr_to_uint8(context), sizeof(context));  //add context including \0
27✔
116
   verifier.update(payload);
27✔
117
   return verifier.check_signature(signature.data(), signature.size());
54✔
118
}
27✔
119

120
std::array<uint8_t, 64> hashLeaf(const std::array<uint8_t, 64>& leaf) {
24✔
121
   std::array<uint8_t, 64> ret{};
24✔
122
   auto hash = HashFunction::create_or_throw("SHA-512");
24✔
123
   hash->update(0);
24✔
124
   hash->update(leaf.data(), leaf.size());
24✔
125
   hash->final(ret.data());
24✔
126
   return ret;
24✔
127
}
24✔
128

129
void hashNode(std::array<uint8_t, 64>& hash, const std::array<uint8_t, 64>& node, bool reverse) {
3✔
130
   auto h = HashFunction::create_or_throw("SHA-512");
3✔
131
   h->update(1);
3✔
132
   if(reverse) {
3✔
133
      h->update(node.data(), node.size());
2✔
134
      h->update(hash.data(), hash.size());
2✔
135
   } else {
136
      h->update(hash.data(), hash.size());
1✔
137
      h->update(node.data(), node.size());
1✔
138
   }
139
   h->final(hash.data());
3✔
140
}
3✔
141

142
template <size_t N, typename T>
143
std::array<uint8_t, N> vector_to_array(std::vector<uint8_t, T> vec) {
13✔
144
   if(vec.size() != N) {
13✔
145
      throw std::logic_error("Invalid vector size");
×
146
   }
147
   return typecast_copy<std::array<uint8_t, N>>(vec.data());
13✔
148
}
149
}  // namespace
150

151
namespace Roughtime {
152

153
Nonce::Nonce(const std::vector<uint8_t>& nonce) {
27✔
154
   if(nonce.size() != 64) {
27✔
155
      throw Invalid_Argument("Roughtime nonce must be 64 bytes long");
2✔
156
   }
157
   m_nonce = typecast_copy<std::array<uint8_t, 64>>(nonce.data());
25✔
158
}
25✔
159

160
Nonce::Nonce(RandomNumberGenerator& rng) {
6✔
161
   rng.randomize(m_nonce.data(), m_nonce.size());
6✔
162
}
6✔
163

164
std::array<uint8_t, request_min_size> encode_request(const Nonce& nonce) {
8✔
165
   std::array<uint8_t, request_min_size> buf = {{2, 0, 0, 0, 64, 0, 0, 0, 'N', 'O', 'N', 'C', 'P', 'A', 'D', 0xff}};
8✔
166
   std::memcpy(buf.data() + 16, nonce.get_nonce().data(), nonce.get_nonce().size());
8✔
167
   std::memset(buf.data() + 16 + nonce.get_nonce().size(), 0, buf.size() - 16 - nonce.get_nonce().size());
8✔
168
   return buf;
8✔
169
}
170

171
Response Response::from_bits(const std::vector<uint8_t>& response, const Nonce& nonce) {
34✔
172
   const auto response_v = unpack_roughtime_packet(response);
34✔
173
   const auto cert = unpack_roughtime_packet(get_v(response_v, "CERT"));
71✔
174
   const auto cert_dele = get<std::array<uint8_t, 72>>(cert, "DELE");
30✔
175
   const auto cert_sig = get<std::array<uint8_t, 64>>(cert, "SIG");
39✔
176
   const auto cert_dele_v = unpack_roughtime_packet(cert_dele);
30✔
177
   const auto srep = get_v(response_v, "SREP");
39✔
178
   const auto srep_v = unpack_roughtime_packet(srep);
39✔
179

180
   const auto cert_dele_pubk = get<std::array<uint8_t, 32>>(cert_dele_v, "PUBK");
29✔
181
   const auto sig = get<std::array<uint8_t, 64>>(response_v, "SIG");
31✔
182
   if(!verify_signature(cert_dele_pubk, srep, sig)) {
27✔
183
      throw Roughtime_Error("Response signature invalid");
1✔
184
   }
185

186
   const auto indx = get<uint32_t>(response_v, "INDX");
26✔
187
   const auto path = get_v(response_v, "PATH");
34✔
188
   const auto srep_root = get<std::array<uint8_t, 64>>(srep_v, "ROOT");
26✔
189
   const size_t size = path.size();
26✔
190
   const size_t levels = size / 64;
26✔
191

192
   if(size % 64) {
26✔
193
      throw Roughtime_Error("Merkle tree path size must be multiple of 64 bytes");
1✔
194
   }
195
   if(indx >= (1U << levels)) {
25✔
196
      throw Roughtime_Error("Merkle tree path is too short");
1✔
197
   }
198

199
   auto hash = hashLeaf(nonce.get_nonce());
24✔
200
   auto index = indx;
201
   size_t level = 0;
202
   while(level < levels) {
27✔
203
      hashNode(hash, typecast_copy<std::array<uint8_t, 64>>(path.data() + level * 64), index & 1);
3✔
204
      ++level;
3✔
205
      index >>= 1;
3✔
206
   }
207

208
   if(srep_root != hash) {
24✔
209
      throw Roughtime_Error("Nonce verification failed");
1✔
210
   }
211

212
   const auto cert_dele_maxt = sys_microseconds64(get<microseconds64>(cert_dele_v, "MAXT"));
23✔
213
   const auto cert_dele_mint = sys_microseconds64(get<microseconds64>(cert_dele_v, "MINT"));
23✔
214
   const auto srep_midp = sys_microseconds64(get<microseconds64>(srep_v, "MIDP"));
23✔
215
   const auto srep_radi = get<microseconds32>(srep_v, "RADI");
28✔
216
   if(srep_midp < cert_dele_mint) {
46✔
217
      throw Roughtime_Error("Midpoint earlier than delegation start");
1✔
218
   }
219
   if(srep_midp > cert_dele_maxt) {
44✔
220
      throw Roughtime_Error("Midpoint later than delegation end");
1✔
221
   }
222
   return {cert_dele, cert_sig, srep_midp, srep_radi};
21✔
223
}
82✔
224

225
bool Response::validate(const Ed25519_PublicKey& pk) const {
20✔
226
   const char context[] = "RoughTime v1 delegation signature--";
20✔
227
   PK_Verifier verifier(pk, "Pure");
20✔
228
   verifier.update(cast_char_ptr_to_uint8(context), sizeof(context));  //add context including \0
20✔
229
   verifier.update(m_cert_dele.data(), m_cert_dele.size());
20✔
230
   return verifier.check_signature(m_cert_sig.data(), m_cert_sig.size());
40✔
231
}
20✔
232

233
Nonce nonce_from_blind(const std::vector<uint8_t>& previous_response, const Nonce& blind) {
11✔
234
   std::array<uint8_t, 64> ret{};
11✔
235
   const auto blind_arr = blind.get_nonce();
11✔
236
   auto hash = HashFunction::create_or_throw("SHA-512");
11✔
237
   hash->update(previous_response);
11✔
238
   hash->update(hash->final());
11✔
239
   hash->update(blind_arr.data(), blind_arr.size());
11✔
240
   hash->final(ret.data());
11✔
241

242
   return ret;
11✔
243
}
11✔
244

245
Chain::Chain(std::string_view str) {
13✔
246
   std::istringstream ss{std::string(str)};  // FIXME C++23 avoid copy
26✔
247
   const std::string ERROR_MESSAGE = "Line does not have 4 space separated fields";
13✔
248
   for(std::string s; std::getline(ss, s);) {
25✔
249
      size_t start = 0, end = 0;
19✔
250
      end = s.find(' ', start);
19✔
251
      if(end == std::string::npos) {
19✔
252
         throw Decoding_Error(ERROR_MESSAGE);
1✔
253
      }
254
      const auto publicKeyType = s.substr(start, end - start);
18✔
255
      if(publicKeyType != "ed25519") {
18✔
256
         throw Not_Implemented("Only ed25519 publicKeyType is implemented");
1✔
257
      }
258

259
      start = end + 1;
17✔
260
      end = s.find(' ', start);
17✔
261
      if(end == std::string::npos) {
17✔
262
         throw Decoding_Error(ERROR_MESSAGE);
1✔
263
      }
264
      const auto serverPublicKey = Ed25519_PublicKey(base64_decode(s.substr(start, end - start)));
53✔
265

266
      start = end + 1;
15✔
267
      end = s.find(' ', start);
15✔
268
      if(end == std::string::npos) {
15✔
269
         throw Decoding_Error(ERROR_MESSAGE);
1✔
270
      }
271
      if((end - start) != 88) {
14✔
272
         throw Decoding_Error("Nonce has invalid length");
1✔
273
      }
274
      const auto vec = base64_decode(s.substr(start, end - start));
13✔
275
      const auto nonceOrBlind = Nonce(vector_to_array<64>(base64_decode(s.substr(start, end - start))));
26✔
276

277
      start = end + 1;
13✔
278
      end = s.find(' ', start);
13✔
279
      if(end != std::string::npos) {
13✔
280
         throw Decoding_Error(ERROR_MESSAGE);
1✔
281
      }
282
      const auto response = unlock(base64_decode(s.substr(start)));
37✔
283

284
      m_links.push_back({response, serverPublicKey, nonceOrBlind});
24✔
285
   }
46✔
286
}
20✔
287

288
std::vector<Response> Chain::responses() const {
7✔
289
   std::vector<Response> responses;
7✔
290
   for(unsigned i = 0; i < m_links.size(); ++i) {
17✔
291
      const auto& l = m_links[i];
11✔
292
      const auto nonce = i ? nonce_from_blind(m_links[i - 1].response(), l.nonce_or_blind()) : l.nonce_or_blind();
11✔
293
      const auto response = Response::from_bits(l.response(), nonce);
11✔
294
      if(!response.validate(l.public_key())) {
11✔
295
         throw Roughtime_Error("Invalid signature or public key");
1✔
296
      }
297
      responses.push_back(response);
10✔
298
   }
299
   return responses;
6✔
300
}
1✔
301

302
Nonce Chain::next_nonce(const Nonce& blind) const {
4✔
303
   return m_links.empty() ? blind : nonce_from_blind(m_links.back().response(), blind);
4✔
304
}
305

306
void Chain::append(const Link& new_link, size_t max_chain_size) {
6✔
307
   if(max_chain_size <= 0) {
6✔
308
      throw Invalid_Argument("Max chain size must be positive");
1✔
309
   }
310

311
   while(m_links.size() >= max_chain_size) {
6✔
312
      if(m_links.size() == 1) {
2✔
313
         auto new_link_updated = new_link;
1✔
314
         new_link_updated.nonce_or_blind() =
1✔
315
            nonce_from_blind(m_links[0].response(), new_link.nonce_or_blind());  //we need to convert blind to nonce
1✔
316
         m_links.clear();
1✔
317
         m_links.push_back(new_link_updated);
1✔
318
         return;
1✔
319
      }
1✔
320
      if(m_links.size() >= 2) {
1✔
321
         m_links[1].nonce_or_blind() =
1✔
322
            nonce_from_blind(m_links[0].response(), m_links[1].nonce_or_blind());  //we need to convert blind to nonce
1✔
323
      }
324
      m_links.erase(m_links.begin());
1✔
325
   }
326
   m_links.push_back(new_link);
4✔
327
}
328

329
std::string Chain::to_string() const {
4✔
330
   std::string s;
4✔
331
   s.reserve((7 + 1 + 88 + 1 + 44 + 1 + 480) * m_links.size());
4✔
332
   for(const auto& link : m_links) {
11✔
333
      s += "ed25519";
7✔
334
      s += ' ';
7✔
335
      s += base64_encode(link.public_key().get_public_key());
14✔
336
      s += ' ';
7✔
337
      s += base64_encode(link.nonce_or_blind().get_nonce().data(), link.nonce_or_blind().get_nonce().size());
14✔
338
      s += ' ';
7✔
339
      s += base64_encode(link.response());
14✔
340
      s += '\n';
14✔
341
   }
342
   return s;
4✔
343
}
×
344

345
std::vector<uint8_t> online_request(std::string_view uri, const Nonce& nonce, std::chrono::milliseconds timeout) {
6✔
346
   const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
6✔
347
   auto socket = OS::open_socket_udp(uri, timeout);
6✔
348
   if(!socket) {
6✔
349
      throw Not_Implemented("No socket support enabled in build");
×
350
   }
351

352
   const auto encoded = encode_request(nonce);
6✔
353
   socket->write(encoded.data(), encoded.size());
6✔
354

355
   if(std::chrono::system_clock::now() - start_time > timeout) {
12✔
356
      throw System_Error("Timeout during socket write");
×
357
   }
358

359
   std::vector<uint8_t> buffer;
6✔
360
   buffer.resize(360 + 64 * 10 + 1);  //response basic size is 360 bytes + 64 bytes for each level of merkle tree
6✔
361
                                      //add one additional byte to be able to differentiate if datagram got truncated
362
   const auto n = socket->read(buffer.data(), buffer.size());
6✔
363

364
   if(!n || std::chrono::system_clock::now() - start_time > timeout) {
12✔
365
      throw System_Error("Timeout waiting for response");
×
366
   }
367

368
   if(n == buffer.size()) {
6✔
369
      throw System_Error("Buffer too small");
×
370
   }
371

372
   buffer.resize(n);
6✔
373
   return buffer;
6✔
374
}
6✔
375

376
std::vector<Server_Information> servers_from_str(std::string_view str) {
12✔
377
   std::vector<Server_Information> servers;
12✔
378
   std::istringstream ss{std::string(str)};  // FIXME C++23 avoid copy
24✔
379

380
   const std::string ERROR_MESSAGE = "Line does not have at least 5 space separated fields";
12✔
381
   for(std::string s; std::getline(ss, s);) {
20✔
382
      size_t start = 0, end = 0;
16✔
383
      end = s.find(' ', start);
16✔
384
      if(end == std::string::npos) {
16✔
385
         throw Decoding_Error(ERROR_MESSAGE);
1✔
386
      }
387
      const auto name = s.substr(start, end - start);
15✔
388

389
      start = end + 1;
15✔
390
      end = s.find(' ', start);
15✔
391
      if(end == std::string::npos) {
15✔
392
         throw Decoding_Error(ERROR_MESSAGE);
1✔
393
      }
394
      const auto publicKeyType = s.substr(start, end - start);
14✔
395
      if(publicKeyType != "ed25519") {
14✔
396
         throw Not_Implemented("Only ed25519 publicKeyType is implemented");
1✔
397
      }
398

399
      start = end + 1;
13✔
400
      end = s.find(' ', start);
13✔
401

402
      if(end == std::string::npos) {
13✔
403
         throw Decoding_Error(ERROR_MESSAGE);
1✔
404
      }
405
      const auto publicKeyBase64 = s.substr(start, end - start);
12✔
406
      const auto publicKey = Ed25519_PublicKey(base64_decode(publicKeyBase64));
27✔
407

408
      start = end + 1;
11✔
409
      end = s.find(' ', start);
11✔
410
      if(end == std::string::npos) {
11✔
411
         throw Decoding_Error(ERROR_MESSAGE);
1✔
412
      }
413
      const auto protocol = s.substr(start, end - start);
10✔
414
      if(protocol != "udp") {
10✔
415
         throw Not_Implemented("Only UDP protocol is implemented");
1✔
416
      }
417

418
      const auto addresses = [&]() {
18✔
419
         std::vector<std::string> addr;
9✔
420
         for(;;) {
9✔
421
            start = end + 1;
17✔
422
            end = s.find(' ', start);
9✔
423
            const auto address = s.substr(start, (end == std::string::npos) ? std::string::npos : end - start);
9✔
424
            if(address.empty()) {
9✔
425
               return addr;
426
            }
427
            addr.push_back(address);
8✔
428
            if(end == std::string::npos) {
8✔
429
               return addr;
430
            }
431
         }
9✔
432
      }();
11✔
433
      if(addresses.empty()) {
9✔
434
         throw Decoding_Error(ERROR_MESSAGE);
1✔
435
      }
436

437
      servers.push_back({name, publicKey, addresses});
16✔
438
   }
52✔
439
   return servers;
8✔
440
}
20✔
441

442
}  // namespace Roughtime
443

444
}  // namespace Botan
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc