xrpld
Loading...
Searching...
No Matches
Handshake.cpp
1#include <xrpld/overlay/detail/Handshake.h>
2
3#include <xrpld/app/ledger/LedgerMaster.h>
4#include <xrpld/app/main/Application.h>
5#include <xrpld/overlay/detail/ProtocolVersion.h>
6
7#include <xrpl/basics/Log.h>
8#include <xrpl/basics/Slice.h>
9#include <xrpl/basics/StringUtilities.h>
10#include <xrpl/basics/base64.h>
11#include <xrpl/basics/base_uint.h>
12#include <xrpl/basics/strHex.h>
13#include <xrpl/beast/core/LexicalCast.h>
14#include <xrpl/beast/net/IPAddress.h>
15#include <xrpl/beast/rfc2616.h>
16#include <xrpl/beast/utility/Journal.h>
17#include <xrpl/beast/utility/Zero.h>
18#include <xrpl/protocol/BuildInfo.h>
19#include <xrpl/protocol/KeyType.h>
20#include <xrpl/protocol/PublicKey.h>
21#include <xrpl/protocol/SecretKey.h>
22#include <xrpl/protocol/digest.h>
23#include <xrpl/protocol/tokens.h>
24
25#include <boost/asio/ip/address.hpp>
26#include <boost/beast/http/status.hpp>
27#include <boost/beast/http/verb.hpp>
28#include <boost/regex/v5/regex.hpp>
29#include <boost/regex/v5/regex_search.hpp>
30#include <boost/system/detail/error_code.hpp>
31
32#include <openssl/crypto.h>
33#include <openssl/sha.h>
34#include <openssl/ssl.h>
35
36#include <chrono>
37#include <cstddef>
38#include <cstdint>
39#include <optional>
40#include <sstream>
41#include <stdexcept>
42#include <string>
43#include <string_view>
44
45// VFALCO Shouldn't we have to include the OpenSSL
46// headers or something for SSL_get_finished?
47
48namespace xrpl {
49
50std::optional<std::string>
51getFeatureValue(boost::beast::http::fields const& headers, std::string const& feature)
52{
53 auto const header = headers.find("X-Protocol-Ctl");
54 if (header == headers.end())
55 return {};
56 boost::smatch match;
57 boost::regex const rx(feature + "=([^;\\s]+)");
58 std::string const allFeatures(header->value());
59 if (boost::regex_search(allFeatures, match, rx))
60 return {match[1]};
61 return {};
62}
63
64bool
66 boost::beast::http::fields const& headers,
67 std::string const& feature,
68 std::string const& value)
69{
70 if (auto const fvalue = getFeatureValue(headers, feature))
71 return beast::rfc2616::tokenInList(fvalue.value(), value);
72
73 return false;
74}
75
76bool
77featureEnabled(boost::beast::http::fields const& headers, std::string const& feature)
78{
79 return isFeatureValue(headers, feature, "1");
80}
81
84 bool comprEnabled,
85 bool ledgerReplayEnabled,
86 bool txReduceRelayEnabled,
87 bool vpReduceRelayEnabled)
88{
90 if (comprEnabled)
91 str << kFeatureCompr << "=lz4" << kDelimFeature;
92 if (ledgerReplayEnabled)
93 str << kFeatureLedgerReplay << "=1" << kDelimFeature;
94 if (txReduceRelayEnabled)
95 str << kFeatureTxrr << "=1" << kDelimFeature;
96 if (vpReduceRelayEnabled)
97 str << kFeatureVprr << "=1" << kDelimFeature;
98 return str.str();
99}
100
103 http_request_type const& headers,
104 bool comprEnabled,
105 bool ledgerReplayEnabled,
106 bool txReduceRelayEnabled,
107 bool vpReduceRelayEnabled)
108{
110 if (comprEnabled && isFeatureValue(headers, kFeatureCompr, "lz4"))
111 str << kFeatureCompr << "=lz4" << kDelimFeature;
112 if (ledgerReplayEnabled && featureEnabled(headers, kFeatureLedgerReplay))
113 str << kFeatureLedgerReplay << "=1" << kDelimFeature;
114 if (txReduceRelayEnabled && featureEnabled(headers, kFeatureTxrr))
115 str << kFeatureTxrr << "=1" << kDelimFeature;
116 if (vpReduceRelayEnabled && featureEnabled(headers, kFeatureVprr))
117 str << kFeatureVprr << "=1" << kDelimFeature;
118 return str.str();
119}
120
137hashLastMessage(SSL const* ssl, size_t (*get)(const SSL*, void*, size_t))
138{
139 static constexpr std::size_t kSslMinimumFinishedLength = 12;
140
141 unsigned char buf[1024];
142 size_t const len = get(ssl, buf, sizeof(buf));
143
144 if (len < kSslMinimumFinishedLength)
145 return std::nullopt;
146
147 sha512_hasher const h;
148
149 BaseUInt<512> cookie;
150 SHA512(buf, len, cookie.data());
151 return cookie;
152}
153
156{
157 auto const cookie1 = hashLastMessage(ssl.native_handle(), SSL_get_finished);
158 if (!cookie1)
159 {
160 JLOG(journal.error()) << "Cookie generation: local setup not complete";
161 return std::nullopt;
162 }
163
164 auto const cookie2 = hashLastMessage(ssl.native_handle(), SSL_get_peer_finished);
165 if (!cookie2)
166 {
167 JLOG(journal.error()) << "Cookie generation: peer setup not complete";
168 return std::nullopt;
169 }
170
171 auto const result = (*cookie1 ^ *cookie2);
172
173 // Both messages hash to the same value and the cookie
174 // is 0. Don't allow this.
175 if (result == beast::kZero)
176 {
177 JLOG(journal.error()) << "Cookie generation: identical finished messages";
178 return std::nullopt;
179 }
180
181 return sha512Half(Slice(result.data(), result.size()));
182}
183
184void
186 boost::beast::http::fields& h,
187 xrpl::uint256 const& sharedValue,
189 beast::ip::Address publicIp,
190 beast::ip::Address remoteIp,
191 Application& app)
192{
193 if (networkID)
194 {
195 // The network identifier, if configured, can be used to specify
196 // what network we intend to connect to and detect if the remote
197 // end connects to the same network.
198 h.insert("Network-ID", std::to_string(*networkID));
199 }
200
201 h.insert("Network-Time", std::to_string(app.getTimeKeeper().now().time_since_epoch().count()));
202
203 h.insert("Public-Key", toBase58(TokenType::NodePublic, app.nodeIdentity().first));
204
205 {
206 auto const sig =
207 signDigest(app.nodeIdentity().first, app.nodeIdentity().second, sharedValue);
208 h.insert("Session-Signature", base64Encode(sig.data(), sig.size()));
209 }
210
211 h.insert("Instance-Cookie", std::to_string(app.instanceID()));
212
213 if (!app.config().serverDomain.empty())
214 h.insert("Server-Domain", app.config().serverDomain);
215
216 if (beast::ip::isPublic(remoteIp))
217 h.insert("Remote-IP", remoteIp.to_string());
218
219 if (!publicIp.is_unspecified())
220 h.insert("Local-IP", publicIp.to_string());
221
222 if (auto const cl = app.getLedgerMaster().getClosedLedger())
223 {
224 h.insert("Closed-Ledger", strHex(cl->header().hash));
225 h.insert("Previous-Ledger", strHex(cl->header().parentHash));
226 }
227}
228
229PublicKey
231 boost::beast::http::fields const& headers,
232 xrpl::uint256 const& sharedValue,
234 beast::ip::Address publicIp,
235 beast::ip::Address remote,
236 Application& app)
237{
238 if (auto const iter = headers.find("Server-Domain"); iter != headers.end())
239 {
240 if (!isProperlyFormedTomlDomain(iter->value()))
241 throw std::runtime_error("Invalid server domain");
242 }
243
244 if (auto const iter = headers.find("Network-ID"); iter != headers.end())
245 {
246 std::uint32_t nid = 0;
247
248 if (!beast::lexicalCastChecked(nid, iter->value()))
249 throw std::runtime_error("Invalid peer network identifier");
250
251 if (networkID && nid != *networkID)
252 throw std::runtime_error("Peer is on a different network");
253 }
254
255 if (auto const iter = headers.find("Network-Time"); iter != headers.end())
256 {
257 auto const netTime = [str = iter->value()]() -> TimeKeeper::time_point {
258 TimeKeeper::duration::rep val = 0;
259
260 if (beast::lexicalCastChecked(val, str))
262
263 // It's not an error for the header field to not be present but if
264 // it is present and it contains junk data, that is an error.
265 throw std::runtime_error("Invalid peer clock timestamp");
266 }();
267
268 using namespace std::chrono;
269
270 auto const ourTime = app.getTimeKeeper().now();
271 auto const tolerance = 20s;
272
273 // We can't blindly "return a-b;" because TimeKeeper::time_point
274 // uses an unsigned integer for representing durations, which is
275 // a problem when trying to subtract time points.
276 auto calculateOffset = [](TimeKeeper::time_point a, TimeKeeper::time_point b) {
277 if (a > b)
280 };
281
282 auto const offset = calculateOffset(netTime, ourTime);
283
284 if (abs(offset) > tolerance)
285 throw std::runtime_error("Peer clock is too far off");
286 }
287
288 PublicKey const publicKey = [&headers] {
289 if (auto const iter = headers.find("Public-Key"); iter != headers.end())
290 {
291 auto pk = parseBase58<PublicKey>(TokenType::NodePublic, iter->value());
292
293 if (pk)
294 {
296 throw std::runtime_error("Unsupported public key type");
297
298 return *pk;
299 }
300 }
301
302 throw std::runtime_error("Bad node public key");
303 }();
304
305 // This check gets two birds with one stone:
306 //
307 // 1) it verifies that the node we are talking to has access to the
308 // private key corresponding to the public node identity it claims.
309 // 2) it verifies that our SSL session is end-to-end with that node
310 // and not through a proxy that establishes two separate sessions.
311 {
312 auto const iter = headers.find("Session-Signature");
313
314 if (iter == headers.end())
315 throw std::runtime_error("No session signature specified");
316
317 auto sig = base64Decode(iter->value());
318
319 if (!verifyDigest(publicKey, sharedValue, makeSlice(sig), false))
320 throw std::runtime_error("Failed to verify session");
321 }
322
323 if (publicKey == app.nodeIdentity().first)
324 throw std::runtime_error("Self connection");
325
326 if (auto const iter = headers.find("Local-IP"); iter != headers.end())
327 {
328 boost::system::error_code ec;
329 auto const localIp = boost::asio::ip::make_address(std::string_view(iter->value()), ec);
330
331 if (ec)
332 throw std::runtime_error("Invalid Local-IP");
333
334 if (beast::ip::isPublic(remote) && remote != localIp)
335 {
336 throw std::runtime_error(
337 "Incorrect Local-IP: " + remote.to_string() + " instead of " + localIp.to_string());
338 }
339 }
340
341 if (auto const iter = headers.find("Remote-IP"); iter != headers.end())
342 {
343 boost::system::error_code ec;
344 auto const remoteIp = boost::asio::ip::make_address(std::string_view(iter->value()), ec);
345
346 if (ec)
347 throw std::runtime_error("Invalid Remote-IP");
348
349 if (beast::ip::isPublic(remote) && !beast::ip::isUnspecified(publicIp))
350 {
351 // We know our public IP and peer reports our connection came
352 // from some other IP.
353 if (remoteIp != publicIp)
354 {
355 throw std::runtime_error(
356 "Incorrect Remote-IP: " + publicIp.to_string() + " instead of " +
357 remoteIp.to_string());
358 }
359 }
360 }
361
362 return publicKey;
363}
364
365auto
367 bool crawlPublic,
368 bool comprEnabled,
369 bool ledgerReplayEnabled,
370 bool txReduceRelayEnabled,
371 bool vpReduceRelayEnabled) -> request_type
372{
373 request_type m;
374 m.method(boost::beast::http::verb::get);
375 m.target("/");
376 m.version(11);
377 m.insert("User-Agent", build_info::getFullVersionString());
378 m.insert("Upgrade", supportedProtocolVersions());
379 m.insert("Connection", "Upgrade");
380 m.insert("Connect-As", "Peer");
381 m.insert("Crawl", crawlPublic ? "public" : "private");
382 m.insert(
383 "X-Protocol-Ctl",
385 comprEnabled, ledgerReplayEnabled, txReduceRelayEnabled, vpReduceRelayEnabled));
386 return m;
387}
388
391 bool crawlPublic,
392 http_request_type const& req,
393 beast::ip::Address publicIp,
394 beast::ip::Address remoteIp,
395 uint256 const& sharedValue,
398 Application& app)
399{
401 resp.result(boost::beast::http::status::switching_protocols);
402 resp.version(req.version());
403 resp.insert("Connection", "Upgrade");
404 resp.insert("Upgrade", to_string(protocol));
405 resp.insert("Connect-As", "Peer");
406 resp.insert("Server", build_info::getFullVersionString());
407 resp.insert("Crawl", crawlPublic ? "public" : "private");
408 resp.insert(
409 "X-Protocol-Ctl",
411 req,
412 app.config().compression,
413 app.config().ledgerReplay,
416
417 buildHandshake(resp, sharedValue, networkID, publicIp, remoteIp, app);
418
419 return resp;
420}
421
422} // namespace xrpl
NetClock::time_point time_point
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
virtual Config & config()=0
virtual std::uint64_t instanceID() const =0
Returns a 64-bit instance identifier, generated at startup.
virtual std::pair< PublicKey, SecretKey > const & nodeIdentity()=0
Integers of any length that is a multiple of 32-bits.
Definition base_uint.h:82
pointer data()
Definition base_uint.h:117
bool txReduceRelayEnable
////////////// END OF TEMPORARY CODE BLOCK /////////////////////
std::shared_ptr< Ledger const > getClosedLedger()
A public key.
Definition PublicKey.h:53
virtual LedgerMaster & getLedgerMaster()=0
virtual TimeKeeper & getTimeKeeper()=0
An immutable linear range of bytes.
Definition Slice.h:28
time_point now() const override
Returns the current time, using the server's clock.
Definition TimeKeeper.h:48
T duration_cast(T... args)
T empty(T... args)
boost::asio::ip::address Address
Definition IPAddress.h:20
bool isPublic(Address const &addr)
Returns true if the address is a public routable address.
Definition IPAddress.h:71
bool isUnspecified(Address const &addr)
Returns true if the address is unspecified.
Definition IPAddress.h:44
bool tokenInList(boost::string_ref const &value, boost::string_ref const &token)
Returns true if the specified token exists in the list.
Definition rfc2616.h:353
constexpr bool lexicalCastChecked(Out &out, In in)
Intelligently convert from one type to another.
constexpr Zero kZero
Definition Zero.h:30
std::string const & getFullVersionString()
Full server version string.
Definition BuildInfo.cpp:82
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
std::string base64Decode(std::string_view data)
static constexpr char kDelimFeature[]
Definition Handshake.h:132
bool featureEnabled(boost::beast::http::fields const &headers, std::string const &feature)
Check if a feature is enabled.
Definition Handshake.cpp:77
static std::optional< BaseUInt< 512 > > hashLastMessage(SSL const *ssl, size_t(*get)(const SSL *, void *, size_t))
Hashes the latest finished message from an SSL stream.
bool verifyDigest(PublicKey const &publicKey, uint256 const &digest, Slice const &sig, bool mustBeFullyCanonical=true) noexcept
Verify a secp256k1 signature on the digest of a message.
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:215
std::optional< uint256 > makeSharedValue(stream_type &ssl, beast::Journal journal)
Computes a shared value based on the SSL connection state.
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
bool isProperlyFormedTomlDomain(std::string_view domain)
Determines if the given string looks like a TOML-file hosting domain.
T get(Section const &section, std::string const &name, T const &defaultValue=T{})
Retrieve a key/value pair from a section.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
static constexpr char kFeatureLedgerReplay[]
Definition Handshake.h:131
boost::beast::http::request< boost::beast::http::empty_body > request_type
Definition Handshake.h:25
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:651
auto makeRequest(bool crawlPublic, bool comprEnabled, bool ledgerReplayEnabled, bool txReduceRelayEnabled, bool vpReduceRelayEnabled) -> request_type
Make outbound http request.
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
static constexpr char kFeatureTxrr[]
Definition Handshake.h:129
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
std::string base64Encode(std::uint8_t const *data, std::size_t len)
std::string makeFeaturesRequestHeader(bool comprEnabled, bool ledgerReplayEnabled, bool txReduceRelayEnabled, bool vpReduceRelayEnabled)
Make request header X-Protocol-Ctl value with supported features.
Definition Handshake.cpp:83
Buffer signDigest(PublicKey const &pk, SecretKey const &sk, uint256 const &digest)
Generate a signature for a message digest.
OpensslSha512Hasher sha512_hasher
Definition digest.h:103
constexpr Number abs(Number x) noexcept
Definition Number.h:876
void buildHandshake(boost::beast::http::fields &h, xrpl::uint256 const &sharedValue, std::optional< std::uint32_t > networkID, beast::ip::Address publicIp, beast::ip::Address remoteIp, Application &app)
Insert fields headers necessary for upgrading the link to the peer protocol.
http_response_type makeResponse(bool crawlPublic, http_request_type const &req, beast::ip::Address publicIp, beast::ip::Address remoteIp, uint256 const &sharedValue, std::optional< std::uint32_t > networkID, ProtocolVersion protocol, Application &app)
Make http response.
std::string const & supportedProtocolVersions()
The list of all the protocol versions we support.
std::optional< std::string > getFeatureValue(boost::beast::http::fields const &headers, std::string const &feature)
Get feature's header value.
Definition Handshake.cpp:51
std::pair< std::uint16_t, std::uint16_t > ProtocolVersion
Represents a particular version of the peer-to-peer protocol.
boost::beast::ssl_stream< socket_type > stream_type
Definition Handshake.h:24
boost::beast::http::request< boost::beast::http::dynamic_body > http_request_type
Definition Handoff.h:12
std::string makeFeaturesResponseHeader(http_request_type const &headers, bool comprEnabled, bool ledgerReplayEnabled, bool txReduceRelayEnabled, bool vpReduceRelayEnabled)
Make response header X-Protocol-Ctl value with supported features.
static constexpr char kFeatureCompr[]
Definition Handshake.h:125
BaseUInt< 256 > uint256
Definition base_uint.h:580
PublicKey verifyHandshake(boost::beast::http::fields const &headers, xrpl::uint256 const &sharedValue, std::optional< std::uint32_t > networkID, beast::ip::Address publicIp, beast::ip::Address remote, Application &app)
Validate header fields necessary for upgrading the link to the peer protocol.
static constexpr char kFeatureVprr[]
Definition Handshake.h:127
bool isFeatureValue(boost::beast::http::fields const &headers, std::string const &feature, std::string const &value)
Check if a feature's value is equal to the specified value.
Definition Handshake.cpp:65
boost::beast::http::response< boost::beast::http::dynamic_body > http_response_type
Definition Handoff.h:14
T str(T... args)
T to_string(T... args)