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

randombit / botan / 16399247596

19 Jul 2025 11:30PM UTC coverage: 90.635% (-0.07%) from 90.708%
16399247596

push

github

web-flow
Merge pull request #4998 from randombit/jack/fix-clang-tidy-readability-isolate-declaration

Enable and fix clang-tidy warning readability-isolate-declaration

99940 of 110266 relevant lines covered (90.64%)

12278552.1 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/mem_ops.h>
13
#include <botan/pubkey.h>
14
#include <botan/rng.h>
15
#include <botan/internal/socket_udp.h>
16
#include <botan/internal/stl_util.h>
17

18
#include <cmath>
19
#include <map>
20
#include <sstream>
21

22
namespace Botan {
23

24
namespace {
25

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

29
template <class T>
30
struct is_array : std::false_type {};
31

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

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

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

47
template <typename T>
48
T copy(const uint8_t* t)
142✔
49
   requires(is_array<T>::value)
50
{
51
   return typecast_copy<T>(t);  //arrays are endianess independent, so we do a memcpy
142✔
52
}
53

54
template <typename T>
55
T copy(const uint8_t* t)
92✔
56
   requires(!is_array<T>::value)
57
{
58
   //other types are arithmetic, so we account that roughtime serializes as little endian
59
   return from_little_endian<T>(t);
92✔
60
}
61

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

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

107
const std::vector<uint8_t>& get_v(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
87✔
108
   const auto& tag = map.find(label);
87✔
109
   if(tag == map.end()) {
87✔
110
      throw Roughtime::Roughtime_Error("Tag " + label + " not found");
2✔
111
   }
112
   return tag->second;
86✔
113
}
114

115
bool verify_signature(const std::array<uint8_t, 32>& pk,
27✔
116
                      const std::vector<uint8_t>& payload,
117
                      const std::array<uint8_t, 64>& signature) {
118
   constexpr std::string_view context("RoughTime v1 response signature\0", 32);
27✔
119
   Ed25519_PublicKey key(std::vector<uint8_t>(pk.data(), pk.data() + pk.size()));
27✔
120
   PK_Verifier verifier(key, "Pure");
27✔
121
   verifier.update(context);
27✔
122
   verifier.update(payload);
27✔
123
   return verifier.check_signature(signature.data(), signature.size());
54✔
124
}
27✔
125

126
std::array<uint8_t, 64> hashLeaf(const std::array<uint8_t, 64>& leaf) {
24✔
127
   std::array<uint8_t, 64> ret{};
24✔
128
   auto hash = HashFunction::create_or_throw("SHA-512");
24✔
129
   hash->update(0);
24✔
130
   hash->update(leaf.data(), leaf.size());
24✔
131
   hash->final(ret.data());
24✔
132
   return ret;
24✔
133
}
24✔
134

135
void hashNode(std::span<uint8_t, 64> hash, std::span<const uint8_t, 64> node, bool reverse) {
3✔
136
   auto h = HashFunction::create_or_throw("SHA-512");
3✔
137
   h->update(1);
3✔
138
   if(reverse) {
3✔
139
      h->update(node.data(), node.size());
2✔
140
      h->update(hash.data(), hash.size());
2✔
141
   } else {
142
      h->update(hash.data(), hash.size());
1✔
143
      h->update(node.data(), node.size());
1✔
144
   }
145
   h->final(hash.data());
6✔
146
}
3✔
147

148
template <size_t N, typename T>
149
std::array<uint8_t, N> vector_to_array(std::vector<uint8_t, T> vec) {
13✔
150
   if(vec.size() != N) {
13✔
151
      throw std::logic_error("Invalid vector size");
×
152
   }
153
   return typecast_copy<std::array<uint8_t, N>>(vec.data());
13✔
154
}
155
}  // namespace
156

157
namespace Roughtime {
158

159
Nonce::Nonce(const std::vector<uint8_t>& nonce) : m_nonce{} {
27✔
160
   if(nonce.size() != 64) {
27✔
161
      throw Invalid_Argument("Roughtime nonce must be 64 bytes long");
2✔
162
   }
163
   m_nonce = typecast_copy<std::array<uint8_t, 64>>(nonce.data());
25✔
164
}
25✔
165

166
Nonce::Nonce(RandomNumberGenerator& rng) : m_nonce(rng.random_array<64>()) {}
6✔
167

168
std::array<uint8_t, request_min_size> encode_request(const Nonce& nonce) {
8✔
169
   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✔
170
   std::memcpy(buf.data() + 16, nonce.get_nonce().data(), nonce.get_nonce().size());
8✔
171
   std::memset(buf.data() + 16 + nonce.get_nonce().size(), 0, buf.size() - 16 - nonce.get_nonce().size());
8✔
172
   return buf;
8✔
173
}
174

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

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

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

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

203
   BufferSlicer slicer(path);
24✔
204
   auto hash = hashLeaf(nonce.get_nonce());
24✔
205
   auto index = indx;
206
   for(std::size_t level = 0; level < levels; ++level) {
27✔
207
      hashNode(hash, slicer.take<64>(), index & 1);
3✔
208
      index >>= 1;
3✔
209
   }
210

211
   if(srep_root != hash) {
24✔
212
      throw Roughtime_Error("Nonce verification failed");
1✔
213
   }
214

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

228
bool Response::validate(const Ed25519_PublicKey& pk) const {
20✔
229
   constexpr std::string_view context("RoughTime v1 delegation signature--\0", 36);
20✔
230
   PK_Verifier verifier(pk, "Pure");
20✔
231
   verifier.update(context);
20✔
232
   verifier.update(m_cert_dele.data(), m_cert_dele.size());
20✔
233
   return verifier.check_signature(m_cert_sig.data(), m_cert_sig.size());
40✔
234
}
20✔
235

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

245
   return Nonce(ret);
11✔
246
}
11✔
247

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

263
      start = end + 1;
17✔
264
      end = s.find(' ', start);
17✔
265
      if(end == std::string::npos) {
17✔
266
         throw Decoding_Error(ERROR_MESSAGE);
1✔
267
      }
268
      const auto serverPublicKey = Ed25519_PublicKey(base64_decode(s.substr(start, end - start)));
38✔
269

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

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

288
      m_links.push_back({response, serverPublicKey, nonceOrBlind});
24✔
289
   }
46✔
290
}
20✔
291

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

306
Nonce Chain::next_nonce(const Nonce& blind) const {
4✔
307
   return m_links.empty() ? blind : nonce_from_blind(m_links.back().response(), blind);
4✔
308
}
309

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

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

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

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

356
   const auto encoded = encode_request(nonce);
6✔
357
   socket->write(encoded.data(), encoded.size());
6✔
358

359
   if(std::chrono::system_clock::now() - start_time > timeout) {
6✔
360
      throw System_Error("Timeout during socket write");
×
361
   }
362

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

368
   if(!n || std::chrono::system_clock::now() - start_time > timeout) {
6✔
369
      throw System_Error("Timeout waiting for response");
×
370
   }
371

372
   if(n == buffer.size()) {
6✔
373
      throw System_Error("Buffer too small");
×
374
   }
375

376
   buffer.resize(n);
6✔
377
   return buffer;
6✔
378
}
6✔
379

380
std::vector<Server_Information> servers_from_str(std::string_view str) {
12✔
381
   std::vector<Server_Information> servers;
12✔
382
   std::istringstream ss{std::string(str)};  // FIXME C++23 avoid copy
24✔
383

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

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

404
      start = end + 1;
13✔
405
      end = s.find(' ', start);
13✔
406

407
      if(end == std::string::npos) {
13✔
408
         throw Decoding_Error(ERROR_MESSAGE);
1✔
409
      }
410
      const auto publicKeyBase64 = s.substr(start, end - start);
12✔
411
      const auto publicKey = Ed25519_PublicKey(base64_decode(publicKeyBase64));
16✔
412

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

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

442
      servers.push_back({name, publicKey, addresses});
16✔
443
   }
37✔
444
   return servers;
8✔
445
}
20✔
446

447
}  // namespace Roughtime
448

449
}  // 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

© 2026 Coveralls, Inc