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

randombit / botan / 13274522654

11 Feb 2025 11:26PM UTC coverage: 91.645% (-0.007%) from 91.652%
13274522654

push

github

web-flow
Merge pull request #4647 from randombit/jack/internal-assert-and-mem-ops

Avoid using mem_ops.h or assert.h in public headers

94854 of 103501 relevant lines covered (91.65%)

11334975.77 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

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

21
namespace Botan {
22

23
namespace {
24

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

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

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

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

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

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

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

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

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

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

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

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

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

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

156
namespace Roughtime {
157

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

165
Nonce::Nonce(RandomNumberGenerator& rng) {
6✔
166
   rng.randomize(m_nonce.data(), m_nonce.size());
6✔
167
}
6✔
168

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

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

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

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

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

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

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

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

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

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

247
   return ret;
11✔
248
}
11✔
249

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

385
   const std::string ERROR_MESSAGE = "Line does not have at least 5 space separated fields";
12✔
386
   for(std::string s; std::getline(ss, s);) {
20✔
387
      size_t start = 0, 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