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