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

randombit / botan / 26735862306

31 May 2026 11:43PM UTC coverage: 89.37%. Remained the same
26735862306

push

github

web-flow
Merge pull request #5631 from randombit/jack/overflow-checks

Systematically eliminate any possible integer overflows

110295 of 123414 relevant lines covered (89.37%)

11075877.11 hits per line

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

97.23
/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/buffer_slicer.h>
16
#include <botan/internal/int_utils.h>
17
#include <botan/internal/socket_udp.h>
18

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 endianness 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
      size_t end = bytes.size();
397✔
77
      if((i + 1) != num_tags) {
397✔
78
         const auto tag_end = checked_add(start_content, from_little_endian<uint32_t>(buf + 4 + i * 4));
831✔
79
         if(!tag_end.has_value()) {
277✔
80
            throw Roughtime::Roughtime_Error("Tag end index out of bounds");
×
81
         }
82
         end = tag_end.value();
277✔
83
      }
84
      if(end > bytes.size()) {
367✔
85
         throw Roughtime::Roughtime_Error("Tag end index out of bounds");
1✔
86
      }
87
      if(end < start) {
396✔
88
         throw Roughtime::Roughtime_Error("Tag offset must be more than previous tag offset");
1✔
89
      }
90
      const char* label_ptr = cast_uint8_ptr_to_char(buf) + (num_tags + i) * 4;
395✔
91
      const char label[] = {label_ptr[0], label_ptr[1], label_ptr[2], label_ptr[3], 0};
395✔
92
      auto ret = tags.emplace(label, std::vector<uint8_t>(buf + start, buf + end));
792✔
93
      if(!ret.second) {
395✔
94
         throw Roughtime::Roughtime_Error(std::string("Map has duplicated tag: ") + label);
×
95
      }
96
      start = static_cast<uint32_t>(end);
395✔
97
   }
98
   return tags;
120✔
99
}
2✔
100

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

113
const std::vector<uint8_t>& get_v(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
87✔
114
   const auto& tag = map.find(label);
87✔
115
   if(tag == map.end()) {
87✔
116
      throw Roughtime::Roughtime_Error("Tag " + label + " not found");
2✔
117
   }
118
   return tag->second;
86✔
119
}
120

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

132
std::array<uint8_t, 64> hashLeaf(const std::array<uint8_t, 64>& leaf) {
24✔
133
   std::array<uint8_t, 64> ret{};
24✔
134
   auto hash = HashFunction::create_or_throw("SHA-512");
24✔
135
   hash->update(0);
24✔
136
   hash->update(leaf.data(), leaf.size());
24✔
137
   hash->final(ret.data());
24✔
138
   return ret;
24✔
139
}
24✔
140

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

154
template <size_t N, typename T>
155
std::array<uint8_t, N> vector_to_array(std::vector<uint8_t, T> vec) {
13✔
156
   if(vec.size() != N) {
13✔
157
      throw std::logic_error("Invalid vector size");
×
158
   }
159
   return typecast_copy<std::array<uint8_t, N>>(vec.data());
13✔
160
}
161
}  // namespace
162

163
namespace Roughtime {
164

165
Nonce::Nonce(const std::vector<uint8_t>& nonce) : m_nonce{} {
27✔
166
   if(nonce.size() != 64) {
27✔
167
      throw Invalid_Argument("Roughtime nonce must be 64 bytes long");
2✔
168
   }
169
   m_nonce = typecast_copy<std::array<uint8_t, 64>>(nonce.data());
25✔
170
}
25✔
171

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

174
std::array<uint8_t, request_min_size> encode_request(const Nonce& nonce) {
8✔
175
   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✔
176
   std::memcpy(buf.data() + 16, nonce.get_nonce().data(), nonce.get_nonce().size());
8✔
177
   std::memset(buf.data() + 16 + nonce.get_nonce().size(), 0, buf.size() - 16 - nonce.get_nonce().size());
8✔
178
   return buf;
8✔
179
}
180

181
Response Response::from_bits(const std::vector<uint8_t>& response, const Nonce& nonce) {
34✔
182
   const auto response_v = unpack_roughtime_packet(response);
37✔
183
   const auto cert = unpack_roughtime_packet(get_v(response_v, "CERT"));
71✔
184
   const auto cert_dele = get<std::array<uint8_t, 72>>(cert, "DELE");
30✔
185
   const auto cert_sig = get<std::array<uint8_t, 64>>(cert, "SIG");
39✔
186
   const auto cert_dele_v = unpack_roughtime_packet(cert_dele);
30✔
187
   const auto srep = get_v(response_v, "SREP");
39✔
188
   const auto srep_v = unpack_roughtime_packet(srep);
39✔
189

190
   const auto cert_dele_pubk = get<std::array<uint8_t, 32>>(cert_dele_v, "PUBK");
29✔
191
   const auto sig = get<std::array<uint8_t, 64>>(response_v, "SIG");
31✔
192
   if(!verify_signature(cert_dele_pubk, srep, sig)) {
27✔
193
      throw Roughtime_Error("Response signature invalid");
1✔
194
   }
195

196
   const auto indx = get<uint32_t>(response_v, "INDX");
26✔
197
   const auto path = get_v(response_v, "PATH");
34✔
198
   const auto srep_root = get<std::array<uint8_t, 64>>(srep_v, "ROOT");
26✔
199
   const size_t size = path.size();
26✔
200
   const size_t levels = size / 64;
26✔
201

202
   if(size % 64 != 0) {
26✔
203
      throw Roughtime_Error("Merkle tree path size must be multiple of 64 bytes");
1✔
204
   }
205
   if(levels >= 32 || indx >= (uint32_t(1) << levels)) {
25✔
206
      throw Roughtime_Error("Merkle tree path is too short");
1✔
207
   }
208

209
   BufferSlicer slicer(path);
24✔
210
   auto hash = hashLeaf(nonce.get_nonce());
24✔
211
   auto index = indx;
212
   for(std::size_t level = 0; level < levels; ++level) {
27✔
213
      hashNode(hash, slicer.take<64>(), index % 2 == 1);
3✔
214
      index >>= 1;
3✔
215
   }
216

217
   if(srep_root != hash) {
24✔
218
      throw Roughtime_Error("Nonce verification failed");
1✔
219
   }
220

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

234
bool Response::validate(const Ed25519_PublicKey& pk) const {
20✔
235
   constexpr std::string_view context("RoughTime v1 delegation signature--\0", 36);
20✔
236
   PK_Verifier verifier(pk, "Pure");
20✔
237
   verifier.update(context);
20✔
238
   verifier.update(m_cert_dele.data(), m_cert_dele.size());
20✔
239
   return verifier.check_signature(m_cert_sig.data(), m_cert_sig.size());
40✔
240
}
20✔
241

242
Nonce nonce_from_blind(const std::vector<uint8_t>& previous_response, const Nonce& blind) {
11✔
243
   std::array<uint8_t, 64> ret{};
11✔
244
   const auto blind_arr = blind.get_nonce();
11✔
245
   auto hash = HashFunction::create_or_throw("SHA-512");
11✔
246
   hash->update(previous_response);
11✔
247
   hash->update(hash->final());
11✔
248
   hash->update(blind_arr.data(), blind_arr.size());
11✔
249
   hash->final(ret.data());
11✔
250

251
   return Nonce(ret);
11✔
252
}
11✔
253

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

269
      start = end + 1;
17✔
270
      end = s.find(' ', start);
17✔
271
      if(end == std::string::npos) {
17✔
272
         throw Decoding_Error(ERROR_MESSAGE);
1✔
273
      }
274
      const auto serverPublicKey = Ed25519_PublicKey(base64_decode(s.substr(start, end - start)));
38✔
275

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

287
      start = end + 1;
13✔
288
      end = s.find(' ', start);
13✔
289
      if(end != std::string::npos) {
13✔
290
         throw Decoding_Error(ERROR_MESSAGE);
1✔
291
      }
292
      const auto response = unlock(base64_decode(s.substr(start)));
37✔
293

294
      m_links.push_back({response, serverPublicKey, nonceOrBlind});
24✔
295
   }
46✔
296
}
20✔
297

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

312
Nonce Chain::next_nonce(const Nonce& blind) const {
4✔
313
   return m_links.empty() ? blind : nonce_from_blind(m_links.back().response(), blind);
4✔
314
}
315

316
void Chain::append(const Link& new_link, size_t max_chain_size) {
6✔
317
   if(max_chain_size <= 0) {
6✔
318
      throw Invalid_Argument("Max chain size must be positive");
1✔
319
   }
320

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

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

355
std::vector<uint8_t> online_request(std::string_view uri, const Nonce& nonce, std::chrono::milliseconds timeout) {
6✔
356
   const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
6✔
357
   auto socket = OS::open_socket_udp(uri, timeout);
6✔
358
   if(!socket) {
6✔
359
      throw Not_Implemented("No socket support enabled in build");
×
360
   }
361

362
   const auto encoded = encode_request(nonce);
6✔
363
   socket->write(encoded.data(), encoded.size());
6✔
364

365
   if(std::chrono::system_clock::now() - start_time > timeout) {
6✔
366
      throw System_Error("Timeout during socket write");
×
367
   }
368

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

374
   if(n == 0 || std::chrono::system_clock::now() - start_time > timeout) {
6✔
375
      throw System_Error("Timeout waiting for response");
×
376
   }
377

378
   if(n == buffer.size()) {
6✔
379
      throw System_Error("Buffer too small");
×
380
   }
381

382
   buffer.resize(n);
6✔
383
   return buffer;
6✔
384
}
6✔
385

386
std::vector<Server_Information> servers_from_str(std::string_view str) {
12✔
387
   std::vector<Server_Information> servers;
12✔
388
   std::istringstream ss{std::string(str)};  // FIXME C++23 avoid copy
24✔
389

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

400
      start = end + 1;
15✔
401
      end = s.find(' ', start);
15✔
402
      if(end == std::string::npos) {
15✔
403
         throw Decoding_Error(ERROR_MESSAGE);
1✔
404
      }
405
      const auto publicKeyType = s.substr(start, end - start);
14✔
406
      if(publicKeyType != "ed25519") {
14✔
407
         throw Not_Implemented("Only ed25519 publicKeyType is implemented");
1✔
408
      }
409

410
      start = end + 1;
13✔
411
      end = s.find(' ', start);
13✔
412

413
      if(end == std::string::npos) {
13✔
414
         throw Decoding_Error(ERROR_MESSAGE);
1✔
415
      }
416
      const auto publicKeyBase64 = s.substr(start, end - start);
12✔
417
      const auto publicKey = Ed25519_PublicKey(base64_decode(publicKeyBase64));
16✔
418

419
      start = end + 1;
11✔
420
      end = s.find(' ', start);
11✔
421
      if(end == std::string::npos) {
11✔
422
         throw Decoding_Error(ERROR_MESSAGE);
1✔
423
      }
424
      const auto protocol = s.substr(start, end - start);
10✔
425
      if(protocol != "udp") {
10✔
426
         throw Not_Implemented("Only UDP protocol is implemented");
1✔
427
      }
428

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

448
      servers.push_back({name, publicKey, addresses});
16✔
449
   }
37✔
450
   return servers;
8✔
451
}
20✔
452

453
}  // namespace Roughtime
454

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