i2pd/libi2pd/Reseed.cpp

799 lines
24 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2013-2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
2014-12-12 20:45:39 +00:00
#include <string.h>
#include <fstream>
2014-12-11 20:41:04 +00:00
#include <sstream>
2015-11-03 14:15:49 +00:00
#include <boost/asio.hpp>
2018-01-06 03:48:51 +00:00
#include <boost/asio/ssl.hpp>
2016-09-16 22:56:51 +00:00
#include <boost/algorithm/string.hpp>
2016-05-11 20:02:26 +00:00
#include <openssl/ssl.h>
#include <openssl/err.h>
2015-11-03 14:15:49 +00:00
#include <zlib.h>
2016-05-11 20:02:26 +00:00
#include "Crypto.h"
#include "I2PEndian.h"
#include "Reseed.h"
#include "FS.h"
#include "Log.h"
2014-12-09 21:44:58 +00:00
#include "Identity.h"
#include "NetDb.hpp"
2016-07-19 00:00:00 +00:00
#include "HTTP.h"
2016-07-21 01:44:17 +00:00
#include "util.h"
2016-08-12 14:33:53 +00:00
#include "Config.h"
namespace i2p
{
namespace data
{
2018-01-06 03:48:51 +00:00
Reseeder::Reseeder()
{
}
Reseeder::~Reseeder()
{
}
/**
@brief tries to bootstrap into I2P network (from local files and servers, with respect of options)
*/
void Reseeder::Bootstrap ()
{
std::string su3FileName; i2p::config::GetOption("reseed.file", su3FileName);
std::string zipFileName; i2p::config::GetOption("reseed.zipfile", zipFileName);
if (su3FileName.length() > 0) // bootstrap from SU3 file or URL
{
int num;
if (su3FileName.length() > 8 && su3FileName.substr(0, 8) == "https://")
{
num = ReseedFromSU3Url (su3FileName); // from https URL
}
else
{
num = ProcessSU3File (su3FileName.c_str ());
}
if (num == 0)
LogPrint (eLogWarning, "Reseed: Failed to reseed from ", su3FileName);
}
else if (zipFileName.length() > 0) // bootstrap from ZIP file
{
int num = ProcessZIPFile (zipFileName.c_str ());
if (num == 0)
LogPrint (eLogWarning, "Reseed: Failed to reseed from ", zipFileName);
}
else // bootstrap from reseed servers
{
int num = ReseedFromServers ();
if (num == 0)
LogPrint (eLogWarning, "Reseed: Failed to reseed from servers");
}
}
/**
* @brief bootstrap from random server, retry 10 times
* @return number of entries added to netDb
*/
2017-02-01 22:17:25 +00:00
int Reseeder::ReseedFromServers ()
2014-12-11 20:41:04 +00:00
{
bool ipv6; i2p::config::GetOption("ipv6", ipv6);
bool ipv4; i2p::config::GetOption("ipv4", ipv4);
bool yggdrasil; i2p::config::GetOption("meshnets.yggdrasil", yggdrasil);
std::vector<std::string> httpsReseedHostList;
if (ipv4 || ipv6)
{
std::string reseedURLs; i2p::config::GetOption("reseed.urls", reseedURLs);
if (!reseedURLs.empty ())
boost::split(httpsReseedHostList, reseedURLs, boost::is_any_of(","), boost::token_compress_on);
}
2021-01-26 00:48:33 +00:00
std::vector<std::string> yggReseedHostList;
if (yggdrasil && !i2p::util::net::GetYggdrasilAddress ().is_unspecified ())
2021-01-26 00:48:33 +00:00
{
LogPrint (eLogInfo, "Reseed: Yggdrasil is supported");
2021-01-26 00:48:33 +00:00
std::string yggReseedURLs; i2p::config::GetOption("reseed.yggurls", yggReseedURLs);
if (!yggReseedURLs.empty ())
boost::split(yggReseedHostList, yggReseedURLs, boost::is_any_of(","), boost::token_compress_on);
}
2021-01-26 00:48:33 +00:00
if (httpsReseedHostList.empty () && yggReseedHostList.empty())
{
LogPrint (eLogWarning, "Reseed: No reseed servers specified");
return 0;
}
int reseedRetries = 0;
while (reseedRetries < 10)
{
2021-01-26 00:48:33 +00:00
auto ind = rand () % (httpsReseedHostList.size () + yggReseedHostList.size ());
bool isHttps = ind < httpsReseedHostList.size ();
std::string reseedUrl = isHttps ? httpsReseedHostList[ind] :
2021-01-26 00:48:33 +00:00
yggReseedHostList[ind - httpsReseedHostList.size ()];
reseedUrl += "i2pseeds.su3";
auto num = ReseedFromSU3Url (reseedUrl, isHttps);
if (num > 0) return num; // success
reseedRetries++;
}
LogPrint (eLogWarning, "Reseed: Failed to reseed from servers after 10 attempts");
return 0;
2014-12-11 20:41:04 +00:00
}
/**
* @brief bootstrap from HTTPS URL with SU3 file
* @param url
* @return number of entries added to netDb
*/
2021-01-26 00:48:33 +00:00
int Reseeder::ReseedFromSU3Url (const std::string& url, bool isHttps)
2014-12-11 20:41:04 +00:00
{
LogPrint (eLogInfo, "Reseed: Downloading SU3 from ", url);
2021-01-26 00:48:33 +00:00
std::string su3 = isHttps ? HttpsRequest (url) : YggdrasilRequest (url);
2014-12-11 20:41:04 +00:00
if (su3.length () > 0)
{
std::stringstream s(su3);
return ProcessSU3Stream (s);
}
else
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogWarning, "Reseed: SU3 download failed");
2014-12-11 20:41:04 +00:00
return 0;
}
}
2018-01-06 03:48:51 +00:00
2014-12-12 15:34:50 +00:00
int Reseeder::ProcessSU3File (const char * filename)
2014-12-11 20:41:04 +00:00
{
std::ifstream s(filename, std::ifstream::binary);
2018-01-06 03:48:51 +00:00
if (s.is_open ())
2014-12-11 20:41:04 +00:00
return ProcessSU3Stream (s);
else
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: Can't open file ", filename);
2014-12-11 20:41:04 +00:00
return 0;
}
}
2017-01-31 00:31:01 +00:00
int Reseeder::ProcessZIPFile (const char * filename)
{
std::ifstream s(filename, std::ifstream::binary);
2018-01-06 03:48:51 +00:00
if (s.is_open ())
{
2017-01-31 00:31:01 +00:00
s.seekg (0, std::ios::end);
auto len = s.tellg ();
s.seekg (0, std::ios::beg);
return ProcessZIPStream (s, len);
2018-01-06 03:48:51 +00:00
}
2017-01-31 00:31:01 +00:00
else
{
LogPrint (eLogError, "Reseed: Can't open file ", filename);
return 0;
}
2018-01-06 03:48:51 +00:00
}
const char SU3_MAGIC_NUMBER[]="I2Psu3";
2014-12-12 15:34:50 +00:00
int Reseeder::ProcessSU3Stream (std::istream& s)
2014-11-20 19:29:22 +00:00
{
2014-12-11 20:41:04 +00:00
char magicNumber[7];
s.read (magicNumber, 7); // magic number and zero byte 6
if (strcmp (magicNumber, SU3_MAGIC_NUMBER))
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: Unexpected SU3 magic number");
2014-12-11 20:41:04 +00:00
return 0;
2018-01-06 03:48:51 +00:00
}
2014-12-11 20:41:04 +00:00
s.seekg (1, std::ios::cur); // su3 file format version
SigningKeyType signatureType;
s.read ((char *)&signatureType, 2); // signature type
2014-12-11 20:41:04 +00:00
signatureType = be16toh (signatureType);
uint16_t signatureLength;
s.read ((char *)&signatureLength, 2); // signature length
2014-12-11 20:41:04 +00:00
signatureLength = be16toh (signatureLength);
s.seekg (1, std::ios::cur); // unused
uint8_t versionLength;
s.read ((char *)&versionLength, 1); // version length
2014-12-11 20:41:04 +00:00
s.seekg (1, std::ios::cur); // unused
uint8_t signerIDLength;
s.read ((char *)&signerIDLength, 1); // signer ID length
2014-12-11 20:41:04 +00:00
uint64_t contentLength;
s.read ((char *)&contentLength, 8); // content length
2014-12-11 20:41:04 +00:00
contentLength = be64toh (contentLength);
s.seekg (1, std::ios::cur); // unused
uint8_t fileType;
s.read ((char *)&fileType, 1); // file type
if (fileType != 0x00) // zip file
2014-12-11 20:41:04 +00:00
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: Can't handle file type ", (int)fileType);
2014-12-11 20:41:04 +00:00
return 0;
}
s.seekg (1, std::ios::cur); // unused
uint8_t contentType;
s.read ((char *)&contentType, 1); // content type
2014-12-11 20:41:04 +00:00
if (contentType != 0x03) // reseed data
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: Unexpected content type ", (int)contentType);
2014-12-11 20:41:04 +00:00
return 0;
}
s.seekg (12, std::ios::cur); // unused
s.seekg (versionLength, std::ios::cur); // skip version
char signerID[256];
s.read (signerID, signerIDLength); // signerID
signerID[signerIDLength] = 0;
2018-01-06 03:48:51 +00:00
bool verify; i2p::config::GetOption("reseed.verify", verify);
if (verify)
2018-01-06 03:48:51 +00:00
{
//try to verify signature
auto it = m_SigningKeys.find (signerID);
if (it != m_SigningKeys.end ())
{
// TODO: implement all signature types
if (signatureType == SIGNING_KEY_TYPE_RSA_SHA512_4096)
2015-11-03 14:15:49 +00:00
{
size_t pos = s.tellg ();
size_t tbsLen = pos + contentLength;
uint8_t * tbs = new uint8_t[tbsLen];
s.seekg (0, std::ios::beg);
s.read ((char *)tbs, tbsLen);
uint8_t * signature = new uint8_t[signatureLength];
s.read ((char *)signature, signatureLength);
// RSA-raw
{
// calculate digest
uint8_t digest[64];
SHA512 (tbs, tbsLen, digest);
// encrypt signature
BN_CTX * bnctx = BN_CTX_new ();
BIGNUM * s = BN_new (), * n = BN_new ();
BN_bin2bn (signature, signatureLength, s);
2018-09-21 15:16:38 +00:00
BN_bin2bn (it->second, 512, n); // RSA 4096 assumed
2018-01-06 03:48:51 +00:00
BN_mod_exp (s, s, i2p::crypto::GetRSAE (), n, bnctx); // s = s^e mod n
uint8_t * enSigBuf = new uint8_t[signatureLength];
i2p::crypto::bn2buf (s, enSigBuf, signatureLength);
// digest is right aligned
// we can't use RSA_verify due wrong padding in SU3
if (memcmp (enSigBuf + (signatureLength - 64), digest, 64))
LogPrint (eLogWarning, "Reseed: SU3 signature verification failed");
else
verify = false; // verified
delete[] enSigBuf;
BN_free (s); BN_free (n);
BN_CTX_free (bnctx);
2018-01-06 03:48:51 +00:00
}
delete[] signature;
delete[] tbs;
s.seekg (pos, std::ios::beg);
}
else
LogPrint (eLogWarning, "Reseed: Signature type ", signatureType, " is not supported");
}
else
LogPrint (eLogWarning, "Reseed: Certificate for ", signerID, " not loaded");
}
if (verify) // not verified
{
LogPrint (eLogError, "Reseed: SU3 verification failed");
return 0;
2018-01-06 03:48:51 +00:00
}
2014-12-11 20:41:04 +00:00
// handle content
2017-01-31 00:31:01 +00:00
return ProcessZIPStream (s, contentLength);
}
const uint32_t ZIP_HEADER_SIGNATURE = 0x04034B50;
2018-01-06 03:48:51 +00:00
const uint32_t ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE = 0x02014B50;
2017-01-31 00:31:01 +00:00
const uint16_t ZIP_BIT_FLAG_DATA_DESCRIPTOR = 0x0008;
int Reseeder::ProcessZIPStream (std::istream& s, uint64_t contentLength)
2018-01-06 03:48:51 +00:00
{
2014-12-11 20:41:04 +00:00
int numFiles = 0;
size_t contentPos = s.tellg ();
while (!s.eof ())
2018-01-06 03:48:51 +00:00
{
2014-12-11 20:41:04 +00:00
uint32_t signature;
s.read ((char *)&signature, 4);
2014-12-12 15:34:50 +00:00
signature = le32toh (signature);
if (signature == ZIP_HEADER_SIGNATURE)
2014-12-09 21:44:58 +00:00
{
2014-12-11 20:41:04 +00:00
// next local file
2014-12-12 15:34:50 +00:00
s.seekg (2, std::ios::cur); // version
uint16_t bitFlag;
2018-01-06 03:48:51 +00:00
s.read ((char *)&bitFlag, 2);
2014-12-12 15:34:50 +00:00
bitFlag = le16toh (bitFlag);
2014-12-12 01:44:08 +00:00
uint16_t compressionMethod;
2018-01-06 03:48:51 +00:00
s.read ((char *)&compressionMethod, 2);
2014-12-12 01:44:08 +00:00
compressionMethod = le16toh (compressionMethod);
2014-12-16 17:48:42 +00:00
s.seekg (4, std::ios::cur); // skip fields we don't care about
2018-01-06 03:48:51 +00:00
uint32_t compressedSize, uncompressedSize;
2015-11-03 14:15:49 +00:00
uint32_t crc_32;
s.read ((char *)&crc_32, 4);
crc_32 = le32toh (crc_32);
2018-01-06 03:48:51 +00:00
s.read ((char *)&compressedSize, 4);
compressedSize = le32toh (compressedSize);
2014-12-11 20:41:04 +00:00
s.read ((char *)&uncompressedSize, 4);
2018-01-06 03:48:51 +00:00
uncompressedSize = le32toh (uncompressedSize);
uint16_t fileNameLength, extraFieldLength;
s.read ((char *)&fileNameLength, 2);
2014-12-12 01:44:08 +00:00
fileNameLength = le16toh (fileNameLength);
if ( fileNameLength > 255 ) {
// too big
LogPrint(eLogError, "Reseed: SU3 fileNameLength too large: ", fileNameLength);
return numFiles;
}
2014-12-11 20:41:04 +00:00
s.read ((char *)&extraFieldLength, 2);
2014-12-12 01:44:08 +00:00
extraFieldLength = le16toh (extraFieldLength);
2014-12-11 20:41:04 +00:00
char localFileName[255];
s.read (localFileName, fileNameLength);
localFileName[fileNameLength] = 0;
s.seekg (extraFieldLength, std::ios::cur);
2018-07-10 09:39:21 +00:00
// take care about data descriptor if presented
2014-12-12 18:36:02 +00:00
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
{
size_t pos = s.tellg ();
if (!FindZipDataDescriptor (s))
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: SU3 archive data descriptor not found");
2014-12-12 18:36:02 +00:00
return numFiles;
2018-01-06 03:48:51 +00:00
}
s.read ((char *)&crc_32, 4);
2015-11-03 14:15:49 +00:00
crc_32 = le32toh (crc_32);
2018-01-06 03:48:51 +00:00
s.read ((char *)&compressedSize, 4);
2014-12-12 18:36:02 +00:00
compressedSize = le32toh (compressedSize) + 4; // ??? we must consider signature as part of compressed data
s.read ((char *)&uncompressedSize, 4);
2018-01-06 03:48:51 +00:00
uncompressedSize = le32toh (uncompressedSize);
2014-12-12 18:36:02 +00:00
// now we know compressed and uncompressed size
s.seekg (pos, std::ios::beg); // back to compressed data
}
2017-12-07 13:26:28 +00:00
LogPrint (eLogDebug, "Reseed: Processing file ", localFileName, " ", compressedSize, " bytes");
2014-12-12 03:31:39 +00:00
if (!compressedSize)
{
2015-12-21 02:20:16 +00:00
LogPrint (eLogWarning, "Reseed: Unexpected size 0. Skipped");
2014-12-12 03:31:39 +00:00
continue;
2018-01-06 03:48:51 +00:00
}
2014-12-11 20:41:04 +00:00
uint8_t * compressed = new uint8_t[compressedSize];
s.read ((char *)compressed, compressedSize);
2014-12-12 01:44:08 +00:00
if (compressionMethod) // we assume Deflate
{
2015-11-03 14:15:49 +00:00
z_stream inflator;
memset (&inflator, 0, sizeof (inflator));
inflateInit2 (&inflator, -MAX_WBITS); // no zlib header
uint8_t * uncompressed = new uint8_t[uncompressedSize];
inflator.next_in = compressed;
inflator.avail_in = compressedSize;
inflator.next_out = uncompressed;
2018-01-06 03:48:51 +00:00
inflator.avail_out = uncompressedSize;
2015-11-03 14:15:49 +00:00
int err;
if ((err = inflate (&inflator, Z_SYNC_FLUSH)) >= 0)
2018-01-06 03:48:51 +00:00
{
2015-11-03 14:15:49 +00:00
uncompressedSize -= inflator.avail_out;
if (crc32 (0, uncompressed, uncompressedSize) == crc_32)
2014-12-16 17:48:42 +00:00
{
i2p::data::netdb.AddRouterInfo (uncompressed, uncompressedSize);
numFiles++;
2018-01-06 03:48:51 +00:00
}
2014-12-16 17:48:42 +00:00
else
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: CRC32 verification failed");
2018-01-06 03:48:51 +00:00
}
2014-12-12 01:44:08 +00:00
else
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: SU3 decompression error ", err);
2018-01-06 03:48:51 +00:00
delete[] uncompressed;
2015-11-03 14:15:49 +00:00
inflateEnd (&inflator);
}
2014-12-12 01:44:08 +00:00
else // no compression
2014-11-20 19:29:22 +00:00
{
2014-12-12 01:44:08 +00:00
i2p::data::netdb.AddRouterInfo (compressed, compressedSize);
2014-12-11 20:41:04 +00:00
numFiles++;
2018-01-06 03:48:51 +00:00
}
2014-12-12 01:44:08 +00:00
delete[] compressed;
2014-12-12 18:36:02 +00:00
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
s.seekg (12, std::ios::cur); // skip data descriptor section if presented (12 = 16 - 4)
2014-11-20 19:29:22 +00:00
}
2014-12-11 20:41:04 +00:00
else
2014-12-16 17:48:42 +00:00
{
if (signature != ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE)
2015-12-21 02:20:16 +00:00
LogPrint (eLogWarning, "Reseed: Missing zip central directory header");
2014-12-11 20:41:04 +00:00
break; // no more files
2014-12-16 17:48:42 +00:00
}
2014-12-11 20:41:04 +00:00
size_t end = s.tellg ();
if (end - contentPos >= contentLength)
break; // we are beyond contentLength
2014-11-20 19:29:22 +00:00
}
2019-04-08 19:22:42 +00:00
if (numFiles) // check if routers are not outdated
2016-11-14 18:13:57 +00:00
{
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
int numOutdated = 0;
i2p::data::netdb.VisitRouterInfos (
[&numOutdated, ts](std::shared_ptr<const RouterInfo> r)
{
2016-11-14 21:23:42 +00:00
if (r && ts > r->GetTimestamp () + 10*i2p::data::NETDB_MAX_EXPIRATION_TIMEOUT*1000LL) // 270 hours
2016-11-14 18:13:57 +00:00
{
LogPrint (eLogError, "Reseed: Router ", r->GetIdentHash().ToBase64 (), " is outdated by ", (ts - r->GetTimestamp ())/1000LL/3600LL, " hours");
2016-11-14 18:13:57 +00:00
numOutdated++;
}
});
if (numOutdated > numFiles/2) // more than half
{
LogPrint (eLogError, "Reseed: Mammoth's shit\n"
2016-11-14 19:38:35 +00:00
" *_____*\n"
" *_*****_*\n"
" *_(O)_(O)_*\n"
" **____V____**\n"
" **_________**\n"
" **_________**\n"
" *_________*\n"
" ***___***");
2016-11-14 21:23:42 +00:00
i2p::data::netdb.ClearRouterInfos ();
numFiles = 0;
}
2016-11-14 18:13:57 +00:00
}
2014-12-11 20:41:04 +00:00
return numFiles;
2014-11-20 19:29:22 +00:00
}
2014-12-12 18:36:02 +00:00
2018-01-06 03:48:51 +00:00
const uint8_t ZIP_DATA_DESCRIPTOR_SIGNATURE[] = { 0x50, 0x4B, 0x07, 0x08 };
2014-12-12 18:36:02 +00:00
bool Reseeder::FindZipDataDescriptor (std::istream& s)
{
2018-01-06 03:48:51 +00:00
size_t nextInd = 0;
2014-12-12 18:36:02 +00:00
while (!s.eof ())
{
uint8_t nextByte;
s.read ((char *)&nextByte, 1);
2018-01-06 03:48:51 +00:00
if (nextByte == ZIP_DATA_DESCRIPTOR_SIGNATURE[nextInd])
2014-12-12 18:36:02 +00:00
{
nextInd++;
if (nextInd >= sizeof (ZIP_DATA_DESCRIPTOR_SIGNATURE))
return true;
}
else
nextInd = 0;
}
2014-12-17 16:42:16 +00:00
return false;
2014-12-12 18:36:02 +00:00
}
2014-12-12 20:45:39 +00:00
void Reseeder::LoadCertificate (const std::string& filename)
{
2017-01-23 21:22:48 +00:00
SSL_CTX * ctx = SSL_CTX_new (TLS_method ());
2018-01-06 03:48:51 +00:00
int ret = SSL_CTX_use_certificate_file (ctx, filename.c_str (), SSL_FILETYPE_PEM);
2015-11-03 14:15:49 +00:00
if (ret)
2018-01-06 03:48:51 +00:00
{
2015-11-03 14:15:49 +00:00
SSL * ssl = SSL_new (ctx);
X509 * cert = SSL_get_certificate (ssl);
// verify
if (cert)
2018-01-06 03:48:51 +00:00
{
2015-11-03 14:15:49 +00:00
// extract issuer name
char name[100];
X509_NAME_oneline (X509_get_issuer_name(cert), name, 100);
2016-08-26 13:48:19 +00:00
char * cn = strstr (name, "CN=");
if (cn)
2018-01-06 03:48:51 +00:00
{
2016-08-26 13:48:19 +00:00
cn += 3;
char * terminator = strchr (cn, '/');
if (terminator) terminator[0] = 0;
2018-01-06 03:48:51 +00:00
}
2015-11-03 14:15:49 +00:00
// extract RSA key (we need n only, e = 65537)
2021-10-23 22:10:02 +00:00
const RSA * key = EVP_PKEY_get0_RSA (X509_get_pubkey (cert));
2016-11-10 17:51:39 +00:00
const BIGNUM * n, * e, * d;
RSA_get0_key(key, &n, &e, &d);
2015-11-03 14:15:49 +00:00
PublicKey value;
2016-11-10 17:51:39 +00:00
i2p::crypto::bn2buf (n, value, 512);
2016-08-26 13:48:19 +00:00
if (cn)
m_SigningKeys[cn] = value;
else
LogPrint (eLogError, "Reseed: Can't find CN field in ", filename);
2018-01-06 03:48:51 +00:00
}
SSL_free (ssl);
}
2014-12-12 20:45:39 +00:00
else
2015-12-21 02:20:16 +00:00
LogPrint (eLogError, "Reseed: Can't open certificate file ", filename);
2018-01-06 03:48:51 +00:00
SSL_CTX_free (ctx);
2014-12-12 20:45:39 +00:00
}
void Reseeder::LoadCertificates ()
{
std::string certDir = i2p::fs::GetCertsDir() + i2p::fs::dirSep + "reseed";
std::vector<std::string> files;
int numCertificates = 0;
if (!i2p::fs::ReadDir(certDir, files)) {
LogPrint(eLogWarning, "Reseed: Can't load reseed certificates from ", certDir);
return;
}
for (const std::string & file : files) {
if (file.compare(file.size() - 4, 4, ".crt") != 0) {
LogPrint(eLogWarning, "Reseed: Ignoring file ", file);
continue;
}
LoadCertificate (file);
numCertificates++;
2018-01-06 03:48:51 +00:00
}
2015-12-21 02:20:16 +00:00
LogPrint (eLogInfo, "Reseed: ", numCertificates, " certificates loaded");
2018-01-06 03:48:51 +00:00
}
2015-02-16 04:03:04 +00:00
2015-02-20 15:47:44 +00:00
std::string Reseeder::HttpsRequest (const std::string& address)
{
2017-11-18 14:50:05 +00:00
i2p::http::URL proxyUrl;
std::string proxy; i2p::config::GetOption("reseed.proxy", proxy);
// check for proxy url
if(proxy.size()) {
// parse
if(proxyUrl.parse(proxy)) {
if (proxyUrl.schema == "http" && !proxyUrl.port) {
proxyUrl.port = 80;
} else if (proxyUrl.schema == "socks" && !proxyUrl.port) {
proxyUrl.port = 1080;
}
// check for valid proxy url schema
if (proxyUrl.schema != "http" && proxyUrl.schema != "socks") {
LogPrint(eLogError, "Reseed: Bad proxy url: ", proxy);
2017-11-18 14:50:05 +00:00
return "";
}
} else {
LogPrint(eLogError, "Reseed: Bad proxy url: ", proxy);
2017-11-18 14:50:05 +00:00
return "";
}
}
2016-07-19 00:00:00 +00:00
i2p::http::URL url;
if (!url.parse(address)) {
LogPrint(eLogError, "Reseed: Failed to parse url: ", address);
2016-07-19 00:00:00 +00:00
return "";
}
url.schema = "https";
if (!url.port)
url.port = 443;
2015-11-03 14:15:49 +00:00
boost::asio::io_service service;
boost::system::error_code ecode;
2017-11-18 14:50:05 +00:00
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
2017-11-18 14:50:05 +00:00
ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> s(service, ctx);
if(proxyUrl.schema.size())
2015-11-03 14:15:49 +00:00
{
2017-11-18 14:50:05 +00:00
// proxy connection
auto it = boost::asio::ip::tcp::resolver(service).resolve (
boost::asio::ip::tcp::resolver::query (proxyUrl.host, std::to_string(proxyUrl.port)), ecode);
if(!ecode)
2015-04-02 00:23:06 +00:00
{
2017-11-18 14:50:05 +00:00
s.lowest_layer().connect(*it, ecode);
if(!ecode)
2015-11-03 14:15:49 +00:00
{
2017-11-18 14:50:05 +00:00
auto & sock = s.next_layer();
if(proxyUrl.schema == "http")
{
i2p::http::HTTPReq proxyReq;
i2p::http::HTTPRes proxyRes;
proxyReq.method = "CONNECT";
proxyReq.version = "HTTP/1.1";
proxyReq.uri = url.host + ":" + std::to_string(url.port);
2021-03-11 22:02:56 +00:00
auto auth = i2p::http::CreateBasicAuthorizationString (proxyUrl.user, proxyUrl.pass);
if (!auth.empty ())
proxyReq.AddHeader("Proxy-Authorization", auth);
2017-11-18 14:50:05 +00:00
boost::asio::streambuf writebuf, readbuf;
std::ostream out(&writebuf);
out << proxyReq.to_string();
boost::asio::write(sock, writebuf.data(), boost::asio::transfer_all(), ecode);
if (ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: HTTP CONNECT write error: ", ecode.message());
return "";
}
boost::asio::read_until(sock, readbuf, "\r\n\r\n", ecode);
if (ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: HTTP CONNECT read error: ", ecode.message());
return "";
}
if(proxyRes.parse(boost::asio::buffer_cast<const char *>(readbuf.data()), readbuf.size()) <= 0)
{
sock.close();
LogPrint(eLogError, "Reseed: HTTP CONNECT malformed reply");
return "";
}
if(proxyRes.code != 200)
{
sock.close();
LogPrint(eLogError, "Reseed: HTTP CONNECT got bad status: ", proxyRes.code);
return "";
}
2016-07-19 00:00:00 +00:00
}
2017-11-18 14:50:05 +00:00
else
{
// assume socks if not http, is checked before this for other types
// TODO: support username/password auth etc
uint8_t hs_writebuf[3] = {0x05, 0x01, 0x00};
uint8_t hs_readbuf[2];
boost::asio::write(sock, boost::asio::buffer(hs_writebuf, 3), boost::asio::transfer_all(), ecode);
if(ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake write failed: ", ecode.message());
return "";
}
boost::asio::read(sock, boost::asio::buffer(hs_readbuf, 2), ecode);
if(ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake read failed: ", ecode.message());
return "";
}
size_t sz = 0;
uint8_t buf[256];
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x00;
buf[3] = 0x03;
sz += 4;
size_t hostsz = url.host.size();
if(1 + 2 + hostsz + sz > sizeof(buf))
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake failed, hostname too big: ", url.host);
return "";
}
buf[4] = (uint8_t) hostsz;
memcpy(buf+5, url.host.c_str(), hostsz);
sz += hostsz + 1;
htobe16buf(buf+sz, url.port);
sz += 2;
boost::asio::write(sock, boost::asio::buffer(buf, sz), boost::asio::transfer_all(), ecode);
if(ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake failed writing: ", ecode.message());
return "";
}
boost::asio::read(sock, boost::asio::buffer(buf, 10), ecode);
if(ecode)
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake failed reading: ", ecode.message());
return "";
}
if(buf[1] != 0x00)
{
sock.close();
LogPrint(eLogError, "Reseed: SOCKS handshake bad reply code: ", std::to_string(buf[1]));
return "";
}
}
2015-11-03 14:15:49 +00:00
}
2017-11-18 14:50:05 +00:00
}
}
else
{
// direct connection
auto it = boost::asio::ip::tcp::resolver(service).resolve (
boost::asio::ip::tcp::resolver::query (url.host, std::to_string(url.port)), ecode);
2021-04-18 21:27:50 +00:00
if (!ecode)
{
2021-04-18 21:27:50 +00:00
bool connected = false;
boost::asio::ip::tcp::resolver::iterator end;
while (it != end)
{
2021-04-18 21:27:50 +00:00
boost::asio::ip::tcp::endpoint ep = *it;
if ((ep.address ().is_v4 () && i2p::context.SupportsV4 ()) ||
(ep.address ().is_v6 () && i2p::context.SupportsV6 ()))
{
2021-04-18 21:27:50 +00:00
s.lowest_layer().connect (ep, ecode);
if (!ecode)
{
connected = true;
break;
}
}
2021-04-18 21:27:50 +00:00
it++;
}
if (!connected)
{
LogPrint(eLogError, "Reseed: Failed to connect to ", url.host);
return "";
}
}
2017-11-18 14:50:05 +00:00
}
if (!ecode)
{
SSL_set_tlsext_host_name(s.native_handle(), url.host.c_str ());
s.handshake (boost::asio::ssl::stream_base::client, ecode);
if (!ecode)
{
LogPrint (eLogDebug, "Reseed: Connected to ", url.host, ":", url.port);
2021-01-26 00:48:33 +00:00
return ReseedRequest (s, url.to_string());
2015-04-02 00:23:06 +00:00
}
2015-11-03 14:15:49 +00:00
else
2017-11-18 14:50:05 +00:00
LogPrint (eLogError, "Reseed: SSL handshake failed: ", ecode.message ());
2015-04-01 18:41:36 +00:00
}
else
2017-11-18 14:50:05 +00:00
LogPrint (eLogError, "Reseed: Couldn't connect to ", url.host, ": ", ecode.message ());
2015-11-03 14:15:49 +00:00
return "";
2017-11-18 14:50:05 +00:00
}
2021-01-26 00:48:33 +00:00
template<typename Stream>
std::string Reseeder::ReseedRequest (Stream& s, const std::string& uri)
{
boost::system::error_code ecode;
i2p::http::HTTPReq req;
req.uri = uri;
req.AddHeader("User-Agent", "Wget/1.11.4");
req.AddHeader("Connection", "close");
s.write_some (boost::asio::buffer (req.to_string()));
// read response
std::stringstream rs;
char recv_buf[1024]; size_t l = 0;
do {
l = s.read_some (boost::asio::buffer (recv_buf, sizeof(recv_buf)), ecode);
if (l) rs.write (recv_buf, l);
} while (!ecode && l);
// process response
std::string data = rs.str();
i2p::http::HTTPRes res;
int len = res.parse(data);
if (len <= 0) {
LogPrint(eLogWarning, "Reseed: Incomplete/broken response from ", uri);
2021-01-26 00:48:33 +00:00
return "";
}
if (res.code != 200) {
LogPrint(eLogError, "Reseed: Failed to reseed from ", uri, ", http code ", res.code);
2021-01-26 00:48:33 +00:00
return "";
}
data.erase(0, len); /* drop http headers from response */
LogPrint(eLogDebug, "Reseed: Got ", data.length(), " bytes of data from ", uri);
2021-01-26 00:48:33 +00:00
if (res.is_chunked()) {
std::stringstream in(data), out;
if (!i2p::http::MergeChunkedResponse(in, out)) {
LogPrint(eLogWarning, "Reseed: Failed to merge chunked response from ", uri);
2021-01-26 00:48:33 +00:00
return "";
}
LogPrint(eLogDebug, "Reseed: Got ", data.length(), "(", out.tellg(), ") bytes of data from ", uri);
2021-01-26 00:48:33 +00:00
data = out.str();
}
return data;
}
2021-01-26 00:48:33 +00:00
std::string Reseeder::YggdrasilRequest (const std::string& address)
{
i2p::http::URL url;
if (!url.parse(address))
2021-01-26 00:48:33 +00:00
{
LogPrint(eLogError, "Reseed: Failed to parse url: ", address);
2021-01-26 00:48:33 +00:00
return "";
}
url.schema = "http";
if (!url.port) url.port = 80;
boost::system::error_code ecode;
boost::asio::io_service service;
2021-01-26 00:48:33 +00:00
boost::asio::ip::tcp::socket s(service, boost::asio::ip::tcp::v6());
if (url.host.length () < 2) return ""; // assume []
auto host = url.host.substr (1, url.host.length () - 2);
LogPrint (eLogDebug, "Reseed: Connecting to Yggdrasil ", url.host, ":", url.port);
s.connect (boost::asio::ip::tcp::endpoint (boost::asio::ip::address_v6::from_string (host), url.port), ecode);
2021-01-26 00:48:33 +00:00
if (!ecode)
{
LogPrint (eLogDebug, "Reseed: Connected to Yggdrasil ", url.host, ":", url.port);
2021-01-26 00:48:33 +00:00
return ReseedRequest (s, url.to_string());
}
else
LogPrint (eLogError, "Reseed: Couldn't connect to Yggdrasil ", url.host, ": ", ecode.message ());
2021-01-26 00:48:33 +00:00
return "";
}
}
}