My Project 4.4.0
C++ Distributed Hash Table
Loading...
Searching...
No Matches
securedht.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "dht.h"
6#include "crypto.h"
7
8#include <map>
9#include <vector>
10#include <memory>
11#include <random>
12
13namespace dht {
14
15class OPENDHT_PUBLIC SecureDht final : public DhtInterface
16{
17public:
18 typedef std::function<void(bool)> SignatureCheckCallback;
19
20 using Config = SecureDhtConfig;
21
22 static dht::Config getConfig(const SecureDht::Config& conf)
23 {
24 auto c = conf.node_config;
25 if (not c.node_id and conf.id.second)
26 c.node_id = InfoHash::get("node:" + conf.id.second->getId().toString());
27 return c;
28 }
29
36 SecureDht(std::unique_ptr<DhtInterface> dht,
37 Config config,
38 IdentityAnnouncedCb iacb = {},
39 const std::shared_ptr<Logger>& l = {});
40
41 virtual ~SecureDht();
42
43 InfoHash getId() const { return key_ ? key_->getPublicKey().getId() : InfoHash(); }
44 PkId getLongId() const { return key_ ? key_->getPublicKey().getLongId() : PkId(); }
45 Sp<crypto::PublicKey> getPublicKey() const { return key_ ? key_->getSharedPublicKey() : Sp<crypto::PublicKey> {}; }
46
47 ValueType secureType(ValueType&& type);
48
49 ValueType secureType(const ValueType& type)
50 {
51 ValueType tmp_type = type;
52 return secureType(std::move(tmp_type));
53 }
54
55 void registerType(const ValueType& type) override
56 {
57 if (dht_)
58 dht_->registerType(secureType(type));
59 }
60 void registerType(ValueType&& type)
61 {
62 if (dht_)
63 dht_->registerType(secureType(std::forward<ValueType>(type)));
64 }
65 void registerInsecureType(const ValueType& type)
66 {
67 if (dht_)
68 dht_->registerType(type);
69 }
70
76 void get(const InfoHash& id, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& = {}, Where&& w = {}) override;
77 void get(const InfoHash& id,
78 GetCallback cb,
79 DoneCallbackSimple donecb = {},
80 Value::Filter&& f = {},
81 Where&& w = {}) override
82 {
83 get(id, cb, bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
84 }
85 void get(const InfoHash& key,
86 GetCallbackSimple cb,
87 DoneCallback donecb = {},
88 Value::Filter&& f = {},
89 Where&& w = {}) override
90 {
91 get(key, bindGetCb(cb), donecb, std::forward<Value::Filter>(f), std::forward<Where>(w));
92 }
93 void get(const InfoHash& key,
94 GetCallbackSimple cb,
95 DoneCallbackSimple donecb,
96 Value::Filter&& f = {},
97 Where&& w = {}) override
98 {
99 get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
100 }
101
105 void putSigned(const InfoHash& hash, Sp<Value> val, DoneCallback callback, bool permanent = false);
106 void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false)
107 {
108 putSigned(hash, std::make_shared<Value>(std::move(v)), callback, permanent);
109 }
110
116 void putEncrypted(const InfoHash& hash,
117 const crypto::PublicKey& to,
118 Sp<Value> val,
119 DoneCallback callback,
120 bool permanent = false);
121
122 [[deprecated("Use the shared_ptr version instead")]]
124 const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false)
125 {
126 putEncrypted(hash, to, std::make_shared<Value>(std::move(v)), callback, permanent);
127 }
128
129 void putEncrypted(const InfoHash& hash, const PkId& to, Sp<Value> val, DoneCallback callback, bool permanent = false);
130
134 void sign(Value& v) const;
135
136 Value encrypt(Value& v, const crypto::PublicKey& to) const;
137
138 Value decrypt(const Value& v);
139
140 void findCertificate(const PkId& id, const std::function<void(const Sp<crypto::Certificate>)>& cb);
141 void findPublicKey(const PkId& id, const std::function<void(const Sp<crypto::PublicKey>)>& cb);
142
143 void registerCertificate(const Sp<crypto::Certificate>& cert);
144
145 Sp<crypto::Certificate> getCertificate(const PkId& node) const;
146 Sp<crypto::PublicKey> getPublicKey(const PkId& node) const;
147
153 void setLocalCertificateStore(CertificateStoreQuery&& query_method) { localQueryMethod_ = std::move(query_method); }
154 void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { dht_->setOnPublicAddressChanged(cb); }
155
159 void shutdown(ShutdownCallback cb, bool stop = false) override { dht_->shutdown(cb, stop); }
160 void dumpTables() const override { dht_->dumpTables(); }
161 inline const InfoHash& getNodeId() const override { return dht_->getNodeId(); }
162
163 std::pair<size_t, size_t> getStoreSize() const override { return dht_->getStoreSize(); }
164 std::pair<size_t, size_t> getLocalStoreSize() const override { return dht_->getLocalStoreSize(); }
165 std::string getStorageLog() const override { return dht_->getStorageLog(); }
166 std::string getStorageLog(const InfoHash& h) const override { return dht_->getStorageLog(h); }
167 void setStorageLimit(size_t limit = 0) override { dht_->setStorageLimit(limit); }
168 size_t getStorageLimit() const override { return dht_->getStorageLimit(); }
169 void setLocalStorageLimit(size_t limit = 0) override { dht_->setLocalStorageLimit(limit); }
170 size_t getLocalStorageLimit() const override { return dht_->getLocalStorageLimit(); }
171
172 std::vector<NodeExport> exportNodes() const override { return dht_->exportNodes(); }
173 std::vector<ValuesExport> exportValues() const override { return dht_->exportValues(); }
174 void importValues(const std::vector<ValuesExport>& v) override { dht_->importValues(v); }
175 NodeStats getNodesStats(sa_family_t af) const override { return dht_->getNodesStats(af); }
176
177 NodeInfo getNodeInfo()
178 {
179 NodeInfo info;
180 info.id = getId();
181 info.node_id = getNodeId();
182 info.ipv4 = getNodesStats(AF_INET);
183 info.ipv6 = getNodesStats(AF_INET6);
184 std::tie(info.storage_size, info.storage_values) = getStoreSize();
185 std::tie(info.local_storage_size, info.local_storage_values) = getLocalStoreSize();
186 if (auto sock = getSocket()) {
187 info.bound4 = sock->getBoundRef(AF_INET).getPort();
188 info.bound6 = sock->getBoundRef(AF_INET6).getPort();
189 }
190 return info;
191 }
192
193 std::vector<unsigned> getNodeMessageStats(bool in = false) override { return dht_->getNodeMessageStats(in); }
194 std::string getRoutingTablesLog(sa_family_t af) const override { return dht_->getRoutingTablesLog(af); }
195 std::string getSearchesLog(sa_family_t af) const override { return dht_->getSearchesLog(af); }
196 std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override
197 {
198 return dht_->getSearchLog(h, af);
199 }
200 std::vector<SockAddr> getPublicAddress(sa_family_t family = 0) override { return dht_->getPublicAddress(family); }
201 time_point periodic(const uint8_t* buf, size_t buflen, SockAddr sa, const time_point& now) override
202 {
203 return dht_->periodic(buf, buflen, std::move(sa), now);
204 }
205 time_point periodic(
206 const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override
207 {
208 return dht_->periodic(buf, buflen, from, fromlen, now);
209 }
210 NodeStatus updateStatus(sa_family_t af) override { return dht_->updateStatus(af); }
211 NodeStatus getStatus(sa_family_t af) const override { return dht_->getStatus(af); }
212 NodeStatus getStatus() const override { return dht_->getStatus(); }
213 net::DatagramSocket* getSocket() const override { return dht_->getSocket(); };
214 bool isRunning(sa_family_t af = 0) const override { return dht_->isRunning(af); }
215 const ValueType& getType(ValueType::Id type_id) const override { return dht_->getType(type_id); }
216 void addBootstrap(const std::string& host, const std::string& service) override
217 {
218 dht_->addBootstrap(host, service);
219 }
220 void clearBootstrap() override { dht_->clearBootstrap(); }
221 void insertNode(const InfoHash& id, const SockAddr& sa) override { dht_->insertNode(id, sa); }
222 void insertNode(const NodeExport& n) override { dht_->insertNode(n); }
223 void pingNode(SockAddr sa, DoneCallbackSimple&& cb = {}) override { dht_->pingNode(std::move(sa), std::move(cb)); }
224 void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override
225 {
226 dht_->query(key, cb, done_cb, std::move(q));
227 }
228 void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override
229 {
230 dht_->query(key, cb, done_cb, std::move(q));
231 }
232 std::vector<Sp<Value>> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override
233 {
234 return dht_->getLocal(key, f);
235 }
236 Sp<Value> getLocalById(const InfoHash& key, Value::Id vid) const override { return dht_->getLocalById(key, vid); }
237 void put(const InfoHash& key,
238 Sp<Value> v,
239 DoneCallback cb = nullptr,
240 time_point created = time_point::max(),
241 bool permanent = false) override
242 {
243 dht_->put(key, v, cb, created, permanent);
244 }
245 void put(const InfoHash& key,
246 const Sp<Value>& v,
247 DoneCallbackSimple cb,
248 time_point created = time_point::max(),
249 bool permanent = false) override
250 {
251 dht_->put(key, v, cb, created, permanent);
252 }
253
254 void put(const InfoHash& key,
255 Value&& v,
256 DoneCallback cb = nullptr,
257 time_point created = time_point::max(),
258 bool permanent = false) override
259 {
260 dht_->put(key, std::move(v), cb, created, permanent);
261 }
262 void put(const InfoHash& key,
263 Value&& v,
264 DoneCallbackSimple cb,
265 time_point created = time_point::max(),
266 bool permanent = false) override
267 {
268 dht_->put(key, std::move(v), cb, created, permanent);
269 }
270 std::vector<Sp<Value>> getPut(const InfoHash& h) const override { return dht_->getPut(h); }
271 Sp<Value> getPut(const InfoHash& h, const Value::Id& vid) const override { return dht_->getPut(h, vid); }
272 bool cancelPut(const InfoHash& h, const Value::Id& vid) override { return dht_->cancelPut(h, vid); }
273
274 size_t listen(const InfoHash& key, ValueCallback, Value::Filter = {}, Where = {}) override;
275 size_t listen(const InfoHash& key, GetCallback cb, Value::Filter = {}, Where w = {}) override;
276 size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override
277 {
278 return listen(key, bindGetCb(cb), f, w);
279 }
280 bool cancelListen(const InfoHash& h, size_t token) override { return dht_->cancelListen(h, token); }
281 void connectivityChanged(sa_family_t af) override { dht_->connectivityChanged(af); }
282 void connectivityChanged() override { dht_->connectivityChanged(); }
283
284 void forwardAllMessages(bool forward) { forward_all_ = forward; }
285
286 void setPushNotificationToken(const std::string& token = "") override { dht_->setPushNotificationToken(token); }
287
292 PushNotificationResult pushNotificationReceived(const std::map<std::string, std::string>& notification) override
293 {
294 return dht_->pushNotificationReceived(notification);
295 }
296
297 void setLogger(const std::shared_ptr<Logger>& logger) override
298 {
299 DhtInterface::setLogger(logger);
300 dht_->setLogger(logger);
301 }
302
306 void setLogFilter(const InfoHash& f) override
307 {
309 dht_->setLogFilter(f);
310 }
311
312private:
313 std::unique_ptr<DhtInterface> dht_;
314 // prevent copy
315 SecureDht(const SecureDht&) = delete;
316 SecureDht& operator=(const SecureDht&) = delete;
317
318 Sp<Value> checkValue(const Sp<Value>& v);
319 ValueCallback getCallbackFilter(const ValueCallback&, Value::Filter&&);
320 GetCallback getCallbackFilter(const GetCallback&, Value::Filter&&);
321
322 Sp<crypto::Certificate> registerCertificate(const InfoHash& node, const Blob& cert);
323 Sp<crypto::Certificate> registerCertificate(const PkId& node, const Blob& cert);
324
325 Sp<crypto::PrivateKey> key_ {};
326 Sp<crypto::Certificate> certificate_ {};
327
328 // method to query the local certificate store
329 CertificateStoreQuery localQueryMethod_ {};
330
331 // our certificate cache
332 std::map<PkId, Sp<crypto::Certificate>> nodesCertificates_ {};
333 std::map<PkId, Sp<crypto::PublicKey>> nodesPubKeys_ {};
334
335 std::atomic_bool forward_all_ {false};
336 bool enableCache_ {false};
337};
338
339const ValueType CERTIFICATE_TYPE = {8,
340 "Certificate",
341 std::chrono::hours(24 * 7),
342 // A certificate can only be stored at its public key ID.
343 [](InfoHash id, Sp<Value>& v, const InfoHash&, const SockAddr&) {
344 try {
345 crypto::Certificate crt(v->data);
346 // TODO check certificate signature
347 return crt.getPublicKey().getId() == id
348 || InfoHash::get(crt.getPublicKey().getLongId()) == id;
349 } catch (const std::exception& e) {
350 }
351 return false;
352 },
353 [](InfoHash, const Sp<Value>& o, Sp<Value>& n, const InfoHash&, const SockAddr&) {
354 try {
355 return crypto::Certificate(o->data).getPublicKey().getLongId()
356 == crypto::Certificate(n->data).getPublicKey().getLongId();
357 } catch (const std::exception& e) {
358 }
359 return false;
360 }};
361
362} // namespace dht
virtual void setLogFilter(const InfoHash &f)
void putSigned(const InfoHash &hash, Sp< Value > val, DoneCallback callback, bool permanent=false)
size_t listen(const InfoHash &key, GetCallback cb, Value::Filter={}, Where w={}) override
bool isRunning(sa_family_t af=0) const override
Definition securedht.h:214
void insertNode(const InfoHash &id, const SockAddr &sa) override
Definition securedht.h:221
void setLocalStorageLimit(size_t limit=0) override
Definition securedht.h:169
void putEncrypted(const InfoHash &hash, const crypto::PublicKey &to, Sp< Value > val, DoneCallback callback, bool permanent=false)
void query(const InfoHash &key, QueryCallback cb, DoneCallback done_cb={}, Query &&q={}) override
Definition securedht.h:224
void get(const InfoHash &id, GetCallback cb, DoneCallback donecb={}, Value::Filter &&={}, Where &&w={}) override
void sign(Value &v) const
SecureDht(std::unique_ptr< DhtInterface > dht, Config config, IdentityAnnouncedCb iacb={}, const std::shared_ptr< Logger > &l={})
void setLogFilter(const InfoHash &f) override
Definition securedht.h:306
void shutdown(ShutdownCallback cb, bool stop=false) override
Definition securedht.h:159
void setStorageLimit(size_t limit=0) override
Definition securedht.h:167
std::vector< NodeExport > exportNodes() const override
Definition securedht.h:172
std::vector< Sp< Value > > getLocal(const InfoHash &key, const Value::Filter &f={}) const override
Definition securedht.h:232
void putEncrypted(const InfoHash &hash, const crypto::PublicKey &to, Value &&v, DoneCallback callback, bool permanent=false)
Definition securedht.h:123
bool cancelPut(const InfoHash &h, const Value::Id &vid) override
Definition securedht.h:272
std::vector< Sp< Value > > getPut(const InfoHash &h) const override
Definition securedht.h:270
void put(const InfoHash &key, Sp< Value > v, DoneCallback cb=nullptr, time_point created=time_point::max(), bool permanent=false) override
Definition securedht.h:237
std::pair< size_t, size_t > getStoreSize() const override
Definition securedht.h:163
Sp< Value > getLocalById(const InfoHash &key, Value::Id vid) const override
Definition securedht.h:236
Sp< Value > getPut(const InfoHash &h, const Value::Id &vid) const override
Definition securedht.h:271
const InfoHash & getNodeId() const override
Definition securedht.h:161
PushNotificationResult pushNotificationReceived(const std::map< std::string, std::string > &notification) override
Definition securedht.h:292
NodeStatus updateStatus(sa_family_t af) override
Definition securedht.h:210
void setLocalCertificateStore(CertificateStoreQuery &&query_method)
Definition securedht.h:153
void connectivityChanged(sa_family_t af) override
Definition securedht.h:281
std::vector< uint8_t > Blob
Definition utils.h:166
NodeStatus
Definition callbacks.h:24
InfoHash node_id
Definition callbacks.h:101
Describes a query destined to another peer.
Definition value.h:1006
Serializable dht::Value filter.
Definition value.h:868
const PkId & getLongId() const