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

randombit / botan / 5230455705

10 Jun 2023 02:30PM UTC coverage: 91.715% (-0.03%) from 91.746%
5230455705

push

github

randombit
Merge GH #3584 Change clang-format AllowShortFunctionsOnASingleLine config from All to Inline

77182 of 84154 relevant lines covered (91.72%)

11975295.43 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 <bool B, class T = void>
28
using enable_if_t = typename std::enable_if<B, T>::type;
29

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

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

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

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

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

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

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

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

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

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

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

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

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

154
namespace Roughtime {
155

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

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

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

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

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

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

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

202
   auto hash = hashLeaf(nonce.get_nonce());
24✔
203
   auto index = indx;
204
   size_t level = 0;
205
   while(level < levels) {
27✔
206
      hashNode(hash, typecast_copy<std::array<uint8_t, 64>>(path.data() + level * 64), index & 1);
3✔
207
      ++level;
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) {
46✔
220
      throw Roughtime_Error("Midpoint earlier than delegation start");
1✔
221
   }
222
   if(srep_midp > cert_dele_maxt) {
44✔
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
   const char context[] = "RoughTime v1 delegation signature--";
20✔
230
   PK_Verifier verifier(pk, "Pure");
20✔
231
   verifier.update(cast_char_ptr_to_uint8(context), sizeof(context));  //add context including \0
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 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, end = 0;
19✔
253
      end = s.find(' ', start);
19✔
254
      if(end == std::string::npos) {
19✔
255
         throw Decoding_Error(ERROR_MESSAGE);
1✔
256
      }
257
      const auto publicKeyType = s.substr(start, end - start);
18✔
258
      if(publicKeyType != "ed25519") {
18✔
259
         throw Not_Implemented("Only ed25519 publicKeyType is implemented");
1✔
260
      }
261

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

440
      servers.push_back({name, publicKey, addresses});
16✔
441
   }
52✔
442
   return servers;
8✔
443
}
20✔
444

445
}  // namespace Roughtime
446

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