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