Botan 3.9.0
Crypto and TLS for C&
roughtime.cpp
Go to the documentation of this file.
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
22namespace Botan {
23
24namespace {
25
26// This exists to work around a LGTM false positive
27static_assert(Roughtime::request_min_size == 1024, "Expected minimum size");
28
29template <class T>
30struct is_array : std::false_type {};
31
32template <class T, std::size_t N>
33struct is_array<std::array<T, N>> : std::true_type {};
34
35template <typename T>
36T impl_from_little_endian(const uint8_t* t, const size_t i)
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));
40}
41
42template <typename T>
43T from_little_endian(const uint8_t* t) {
44 return impl_from_little_endian<T>(t, sizeof(T) - 1);
45}
46
47template <typename T>
48T copy(const uint8_t* t)
49 requires(is_array<T>::value)
50{
51 return typecast_copy<T>(t); //arrays are endianess independent, so we do a memcpy
52}
53
54template <typename T>
55T copy(const uint8_t* t)
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);
60}
61
62template <typename T>
63std::map<std::string, std::vector<uint8_t>> unpack_roughtime_packet(T bytes) {
64 if(bytes.size() < 8) {
65 throw Roughtime::Roughtime_Error("Map length is under minimum of 8 bytes");
66 }
67 const auto buf = bytes.data();
68 const uint32_t num_tags = buf[0];
69 const uint32_t start_content = num_tags * 8;
70 if(start_content > bytes.size()) {
71 throw Roughtime::Roughtime_Error("Map length too small to contain all tags");
72 }
73 uint32_t start = start_content;
74 std::map<std::string, std::vector<uint8_t>> tags;
75 for(uint32_t i = 0; i < num_tags; ++i) {
76 const size_t end =
77 ((i + 1) == num_tags) ? bytes.size() : start_content + from_little_endian<uint32_t>(buf + 4 + i * 4);
78 if(end > bytes.size()) {
79 throw Roughtime::Roughtime_Error("Tag end index out of bounds");
80 }
81 if(end < start) {
82 throw Roughtime::Roughtime_Error("Tag offset must be more than previous tag offset");
83 }
84 const char* label_ptr = cast_uint8_ptr_to_char(buf) + (num_tags + i) * 4;
85 const char label[] = {label_ptr[0], label_ptr[1], label_ptr[2], label_ptr[3], 0};
86 auto ret = tags.emplace(label, std::vector<uint8_t>(buf + start, buf + end));
87 if(!ret.second) {
88 throw Roughtime::Roughtime_Error(std::string("Map has duplicated tag: ") + label);
89 }
90 start = static_cast<uint32_t>(end);
91 }
92 return tags;
93}
94
95template <typename T>
96T get(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
97 const auto& tag = map.find(label);
98 if(tag == map.end()) {
99 throw Roughtime::Roughtime_Error("Tag " + label + " not found");
100 }
101 if(tag->second.size() != sizeof(T)) {
102 throw Roughtime::Roughtime_Error("Tag " + label + " has unexpected size");
103 }
104 return copy<T>(tag->second.data());
105}
106
107const std::vector<uint8_t>& get_v(const std::map<std::string, std::vector<uint8_t>>& map, const std::string& label) {
108 const auto& tag = map.find(label);
109 if(tag == map.end()) {
110 throw Roughtime::Roughtime_Error("Tag " + label + " not found");
111 }
112 return tag->second;
113}
114
115bool verify_signature(const std::array<uint8_t, 32>& pk,
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);
119 Ed25519_PublicKey key(std::vector<uint8_t>(pk.data(), pk.data() + pk.size()));
120 PK_Verifier verifier(key, "Pure");
121 verifier.update(context);
122 verifier.update(payload);
123 return verifier.check_signature(signature.data(), signature.size());
124}
125
126std::array<uint8_t, 64> hashLeaf(const std::array<uint8_t, 64>& leaf) {
127 std::array<uint8_t, 64> ret{};
128 auto hash = HashFunction::create_or_throw("SHA-512");
129 hash->update(0);
130 hash->update(leaf.data(), leaf.size());
131 hash->final(ret.data());
132 return ret;
133}
134
135void hashNode(std::span<uint8_t, 64> hash, std::span<const uint8_t, 64> node, bool reverse) {
136 auto h = HashFunction::create_or_throw("SHA-512");
137 h->update(1);
138 if(reverse) {
139 h->update(node.data(), node.size());
140 h->update(hash.data(), hash.size());
141 } else {
142 h->update(hash.data(), hash.size());
143 h->update(node.data(), node.size());
144 }
145 h->final(hash.data());
146}
147
148template <size_t N, typename T>
149std::array<uint8_t, N> vector_to_array(std::vector<uint8_t, T> vec) {
150 if(vec.size() != N) {
151 throw std::logic_error("Invalid vector size");
152 }
153 return typecast_copy<std::array<uint8_t, N>>(vec.data());
154}
155} // namespace
156
157namespace Roughtime {
158
159Nonce::Nonce(const std::vector<uint8_t>& nonce) : m_nonce{} {
160 if(nonce.size() != 64) {
161 throw Invalid_Argument("Roughtime nonce must be 64 bytes long");
162 }
163 m_nonce = typecast_copy<std::array<uint8_t, 64>>(nonce.data());
164}
165
166Nonce::Nonce(RandomNumberGenerator& rng) : m_nonce(rng.random_array<64>()) {}
167
168std::array<uint8_t, request_min_size> encode_request(const Nonce& nonce) {
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}};
170 std::memcpy(buf.data() + 16, nonce.get_nonce().data(), nonce.get_nonce().size());
171 std::memset(buf.data() + 16 + nonce.get_nonce().size(), 0, buf.size() - 16 - nonce.get_nonce().size());
172 return buf;
173}
174
175Response Response::from_bits(const std::vector<uint8_t>& response, const Nonce& nonce) {
176 const auto response_v = unpack_roughtime_packet(response);
177 const auto cert = unpack_roughtime_packet(get_v(response_v, "CERT"));
178 const auto cert_dele = get<std::array<uint8_t, 72>>(cert, "DELE");
179 const auto cert_sig = get<std::array<uint8_t, 64>>(cert, "SIG");
180 const auto cert_dele_v = unpack_roughtime_packet(cert_dele);
181 const auto srep = get_v(response_v, "SREP");
182 const auto srep_v = unpack_roughtime_packet(srep);
183
184 const auto cert_dele_pubk = get<std::array<uint8_t, 32>>(cert_dele_v, "PUBK");
185 const auto sig = get<std::array<uint8_t, 64>>(response_v, "SIG");
186 if(!verify_signature(cert_dele_pubk, srep, sig)) {
187 throw Roughtime_Error("Response signature invalid");
188 }
189
190 const auto indx = get<uint32_t>(response_v, "INDX");
191 const auto path = get_v(response_v, "PATH");
192 const auto srep_root = get<std::array<uint8_t, 64>>(srep_v, "ROOT");
193 const size_t size = path.size();
194 const size_t levels = size / 64;
195
196 if(size % 64 != 0) {
197 throw Roughtime_Error("Merkle tree path size must be multiple of 64 bytes");
198 }
199 if(indx >= (1U << levels)) {
200 throw Roughtime_Error("Merkle tree path is too short");
201 }
202
203 BufferSlicer slicer(path);
204 auto hash = hashLeaf(nonce.get_nonce());
205 auto index = indx;
206 for(std::size_t level = 0; level < levels; ++level) {
207 hashNode(hash, slicer.take<64>(), index % 2 == 1);
208 index >>= 1;
209 }
210
211 if(srep_root != hash) {
212 throw Roughtime_Error("Nonce verification failed");
213 }
214
215 const auto cert_dele_maxt = sys_microseconds64(get<microseconds64>(cert_dele_v, "MAXT"));
216 const auto cert_dele_mint = sys_microseconds64(get<microseconds64>(cert_dele_v, "MINT"));
217 const auto srep_midp = sys_microseconds64(get<microseconds64>(srep_v, "MIDP"));
218 const auto srep_radi = get<microseconds32>(srep_v, "RADI");
219 if(srep_midp < cert_dele_mint) {
220 throw Roughtime_Error("Midpoint earlier than delegation start");
221 }
222 if(srep_midp > cert_dele_maxt) {
223 throw Roughtime_Error("Midpoint later than delegation end");
224 }
225 return {cert_dele, cert_sig, srep_midp, srep_radi};
226}
227
229 constexpr std::string_view context("RoughTime v1 delegation signature--\0", 36);
230 PK_Verifier verifier(pk, "Pure");
231 verifier.update(context);
232 verifier.update(m_cert_dele.data(), m_cert_dele.size());
233 return verifier.check_signature(m_cert_sig.data(), m_cert_sig.size());
234}
235
236Nonce nonce_from_blind(const std::vector<uint8_t>& previous_response, const Nonce& blind) {
237 std::array<uint8_t, 64> ret{};
238 const auto blind_arr = blind.get_nonce();
239 auto hash = HashFunction::create_or_throw("SHA-512");
240 hash->update(previous_response);
241 hash->update(hash->final());
242 hash->update(blind_arr.data(), blind_arr.size());
243 hash->final(ret.data());
244
245 return Nonce(ret);
246}
247
248Chain::Chain(std::string_view str) {
249 std::istringstream ss{std::string(str)}; // FIXME C++23 avoid copy
250 const std::string ERROR_MESSAGE = "Line does not have 4 space separated fields";
251 for(std::string s; std::getline(ss, s);) {
252 size_t start = 0;
253 size_t end = 0;
254 end = s.find(' ', start);
255 if(end == std::string::npos) {
256 throw Decoding_Error(ERROR_MESSAGE);
257 }
258 const auto publicKeyType = s.substr(start, end - start);
259 if(publicKeyType != "ed25519") {
260 throw Not_Implemented("Only ed25519 publicKeyType is implemented");
261 }
262
263 start = end + 1;
264 end = s.find(' ', start);
265 if(end == std::string::npos) {
266 throw Decoding_Error(ERROR_MESSAGE);
267 }
268 const auto serverPublicKey = Ed25519_PublicKey(base64_decode(s.substr(start, end - start)));
269
270 start = end + 1;
271 end = s.find(' ', start);
272 if(end == std::string::npos) {
273 throw Decoding_Error(ERROR_MESSAGE);
274 }
275 if((end - start) != 88) {
276 throw Decoding_Error("Nonce has invalid length");
277 }
278 const auto vec = base64_decode(s.substr(start, end - start));
279 const auto nonceOrBlind = Nonce(vector_to_array<64>(base64_decode(s.substr(start, end - start))));
280
281 start = end + 1;
282 end = s.find(' ', start);
283 if(end != std::string::npos) {
284 throw Decoding_Error(ERROR_MESSAGE);
285 }
286 const auto response = unlock(base64_decode(s.substr(start)));
287
288 m_links.push_back({response, serverPublicKey, nonceOrBlind});
289 }
290}
291
292std::vector<Response> Chain::responses() const {
293 std::vector<Response> responses;
294 for(size_t i = 0; i < m_links.size(); ++i) {
295 const auto& l = m_links[i];
296 const auto nonce = i > 0 ? nonce_from_blind(m_links[i - 1].response(), l.nonce_or_blind()) : l.nonce_or_blind();
297 const auto response = Response::from_bits(l.response(), nonce);
298 if(!response.validate(l.public_key())) {
299 throw Roughtime_Error("Invalid signature or public key");
300 }
301 responses.push_back(response);
302 }
303 return responses;
304}
305
306Nonce Chain::next_nonce(const Nonce& blind) const {
307 return m_links.empty() ? blind : nonce_from_blind(m_links.back().response(), blind);
308}
309
310void Chain::append(const Link& new_link, size_t max_chain_size) {
311 if(max_chain_size <= 0) {
312 throw Invalid_Argument("Max chain size must be positive");
313 }
314
315 while(m_links.size() >= max_chain_size) {
316 if(m_links.size() == 1) {
317 auto new_link_updated = new_link;
318 new_link_updated.nonce_or_blind() =
319 nonce_from_blind(m_links[0].response(), new_link.nonce_or_blind()); //we need to convert blind to nonce
320 m_links.clear();
321 m_links.push_back(new_link_updated);
322 return;
323 }
324 if(m_links.size() >= 2) {
325 m_links[1].nonce_or_blind() =
326 nonce_from_blind(m_links[0].response(), m_links[1].nonce_or_blind()); //we need to convert blind to nonce
327 }
328 m_links.erase(m_links.begin());
329 }
330 m_links.push_back(new_link);
331}
332
333std::string Chain::to_string() const {
334 std::string s;
335 s.reserve((7 + 1 + 88 + 1 + 44 + 1 + 480) * m_links.size());
336 for(const auto& link : m_links) {
337 s += "ed25519";
338 s += ' ';
339 s += base64_encode(link.public_key().get_public_key());
340 s += ' ';
341 s += base64_encode(link.nonce_or_blind().get_nonce().data(), link.nonce_or_blind().get_nonce().size());
342 s += ' ';
343 s += base64_encode(link.response());
344 s += '\n';
345 }
346 return s;
347}
348
349std::vector<uint8_t> online_request(std::string_view uri, const Nonce& nonce, std::chrono::milliseconds timeout) {
350 const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
351 auto socket = OS::open_socket_udp(uri, timeout);
352 if(!socket) {
353 throw Not_Implemented("No socket support enabled in build");
354 }
355
356 const auto encoded = encode_request(nonce);
357 socket->write(encoded.data(), encoded.size());
358
359 if(std::chrono::system_clock::now() - start_time > timeout) {
360 throw System_Error("Timeout during socket write");
361 }
362
363 std::vector<uint8_t> buffer;
364 buffer.resize(360 + 64 * 10 + 1); //response basic size is 360 bytes + 64 bytes for each level of merkle tree
365 //add one additional byte to be able to differentiate if datagram got truncated
366 const auto n = socket->read(buffer.data(), buffer.size());
367
368 if(n == 0 || std::chrono::system_clock::now() - start_time > timeout) {
369 throw System_Error("Timeout waiting for response");
370 }
371
372 if(n == buffer.size()) {
373 throw System_Error("Buffer too small");
374 }
375
376 buffer.resize(n);
377 return buffer;
378}
379
380std::vector<Server_Information> servers_from_str(std::string_view str) {
381 std::vector<Server_Information> servers;
382 std::istringstream ss{std::string(str)}; // FIXME C++23 avoid copy
383
384 const std::string ERROR_MESSAGE = "Line does not have at least 5 space separated fields";
385 for(std::string s; std::getline(ss, s);) {
386 size_t start = 0;
387 size_t end = 0;
388 end = s.find(' ', start);
389 if(end == std::string::npos) {
390 throw Decoding_Error(ERROR_MESSAGE);
391 }
392 const auto name = s.substr(start, end - start);
393
394 start = end + 1;
395 end = s.find(' ', start);
396 if(end == std::string::npos) {
397 throw Decoding_Error(ERROR_MESSAGE);
398 }
399 const auto publicKeyType = s.substr(start, end - start);
400 if(publicKeyType != "ed25519") {
401 throw Not_Implemented("Only ed25519 publicKeyType is implemented");
402 }
403
404 start = end + 1;
405 end = s.find(' ', start);
406
407 if(end == std::string::npos) {
408 throw Decoding_Error(ERROR_MESSAGE);
409 }
410 const auto publicKeyBase64 = s.substr(start, end - start);
411 const auto publicKey = Ed25519_PublicKey(base64_decode(publicKeyBase64));
412
413 start = end + 1;
414 end = s.find(' ', start);
415 if(end == std::string::npos) {
416 throw Decoding_Error(ERROR_MESSAGE);
417 }
418 const auto protocol = s.substr(start, end - start);
419 if(protocol != "udp") {
420 throw Not_Implemented("Only UDP protocol is implemented");
421 }
422
423 const auto addresses = [&]() {
424 std::vector<std::string> addr;
425 for(;;) {
426 start = end + 1;
427 end = s.find(' ', start);
428 const auto address = s.substr(start, (end == std::string::npos) ? std::string::npos : end - start);
429 if(address.empty()) {
430 return addr;
431 }
432 addr.push_back(address);
433 if(end == std::string::npos) {
434 return addr;
435 }
436 }
437 }();
438 if(addresses.empty()) {
439 throw Decoding_Error(ERROR_MESSAGE);
440 }
441
442 servers.push_back({name, publicKey, addresses});
443 }
444 return servers;
445}
446
447} // namespace Roughtime
448
449} // namespace Botan
std::span< const uint8_t > take(const size_t count)
Definition stl_util.h:90
static std::unique_ptr< HashFunction > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition hash.cpp:298
void update(uint8_t in)
Definition pubkey.h:334
bool check_signature(const uint8_t sig[], size_t length)
Definition pubkey.cpp:458
void append(const Link &new_link, size_t max_chain_size)
std::string to_string() const
Nonce next_nonce(const Nonce &blind) const
std::vector< Response > responses() const
const std::array< uint8_t, 64 > & get_nonce() const
Definition roughtime.h:42
std::chrono::time_point< std::chrono::system_clock, microseconds64 > sys_microseconds64
Definition roughtime.h:61
static Response from_bits(const std::vector< uint8_t > &response, const Nonce &nonce)
bool validate(const Ed25519_PublicKey &pk) const
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout)
std::vector< Server_Information > servers_from_str(std::string_view str)
std::vector< uint8_t > online_request(std::string_view uri, const Nonce &nonce, std::chrono::milliseconds timeout)
Nonce nonce_from_blind(const std::vector< uint8_t > &previous_response, const Nonce &blind)
std::array< uint8_t, request_min_size > encode_request(const Nonce &nonce)
const unsigned request_min_size
Definition roughtime.h:23
size_t base64_encode(char out[], const uint8_t in[], size_t input_length, size_t &input_consumed, bool final_inputs)
Definition base64.cpp:160
size_t base64_decode(uint8_t out[], const char in[], size_t input_length, size_t &input_consumed, bool final_inputs, bool ignore_ws)
Definition base64.cpp:168
std::vector< T > unlock(const secure_vector< T > &in)
Definition secmem.h:86
bool verify_signature(std::span< const uint8_t, ED448_LEN > pk, bool phflag, std::span< const uint8_t > context, std::span< const uint8_t > sig, std::span< const uint8_t > msg)
Verify a signature(RFC 8032 5.2.7)
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition mem_ops.h:282
constexpr void typecast_copy(ToR &&out, const FromR &in)
Definition mem_ops.h:177