008eb35f95
The IDE include checker got to the point where it is actually useful and this removes a lot of unneeded includes. Naturally, especially for headers like util.h, this may mean we need to re-add includes in consuming cpp files that bloats the diff a bit.
283 lines
9.1 KiB
C++
283 lines
9.1 KiB
C++
/*
|
|
* This file is part of the Flowee project
|
|
* Copyright (c) 2015 The Bitcoin Core developers
|
|
* Copyright (c) 2019 Tom Zander <tom@flowee.org>
|
|
*
|
|
* This program is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU General Public License as published by
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
* (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
#include "httprpc.h"
|
|
|
|
#include "httpserver.h"
|
|
#include "rpcprotocol.h"
|
|
#include "rpcserver.h"
|
|
#include "random.h"
|
|
#include "util.h"
|
|
#include "utilstrencodings.h"
|
|
#include <hmac_sha256.h>
|
|
#include "utilstrencodings.h"
|
|
#include "utiltime.h"
|
|
#include "netbase.h"
|
|
|
|
#include <boost/algorithm/string.hpp> // boost::trim
|
|
#include <boost/foreach.hpp> //BOOST_FOREACH
|
|
#include <fstream>
|
|
|
|
/** WWW-Authenticate to present with 401 Unauthorized response */
|
|
static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
|
|
|
|
/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
|
|
* re-lock the wellet.
|
|
*/
|
|
class HTTPRPCTimer : public RPCTimerBase
|
|
{
|
|
public:
|
|
HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :
|
|
ev(eventBase, false, func)
|
|
{
|
|
struct timeval tv;
|
|
tv.tv_sec = millis/1000;
|
|
tv.tv_usec = (millis%1000)*1000;
|
|
ev.trigger(&tv);
|
|
}
|
|
private:
|
|
HTTPEvent ev;
|
|
};
|
|
|
|
class HTTPRPCTimerInterface : public RPCTimerInterface
|
|
{
|
|
public:
|
|
HTTPRPCTimerInterface(struct event_base* base) : base(base)
|
|
{
|
|
}
|
|
const char* Name()
|
|
{
|
|
return "HTTP";
|
|
}
|
|
RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)
|
|
{
|
|
return new HTTPRPCTimer(base, func, millis);
|
|
}
|
|
private:
|
|
struct event_base* base;
|
|
};
|
|
|
|
|
|
/* Pre-base64-encoded authentication token */
|
|
static std::string strRPCUserColonPass;
|
|
/* Stored RPC timer interface (for unregistration) */
|
|
static HTTPRPCTimerInterface* httpRPCTimerInterface = nullptr;
|
|
|
|
static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
|
|
{
|
|
// Send error reply from json-rpc error object
|
|
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
|
|
int code = find_value(objError, "code").get_int();
|
|
|
|
if (code == RPC_INVALID_REQUEST)
|
|
nStatus = HTTP_BAD_REQUEST;
|
|
else if (code == RPC_METHOD_NOT_FOUND)
|
|
nStatus = HTTP_NOT_FOUND;
|
|
|
|
std::string strReply = JSONRPCReply(NullUniValue, objError, id);
|
|
|
|
req->WriteHeader("Content-Type", "application/json");
|
|
req->WriteReply(nStatus, strReply);
|
|
}
|
|
|
|
//This function checks username and password against -rpcauth
|
|
//entries from config file.
|
|
static bool multiUserAuthorized(std::string strUserPass)
|
|
{
|
|
if (strUserPass.find(":") == std::string::npos) {
|
|
return false;
|
|
}
|
|
std::string strUser = strUserPass.substr(0, strUserPass.find(":"));
|
|
std::string strPass = strUserPass.substr(strUserPass.find(":") + 1);
|
|
|
|
if (mapMultiArgs.count("-rpcauth") > 0) {
|
|
//Search for multi-user login/pass "rpcauth" from config
|
|
BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs["-rpcauth"])
|
|
{
|
|
std::vector<std::string> vFields;
|
|
boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
|
|
if (vFields.size() != 3) {
|
|
//Incorrect formatting in config file
|
|
continue;
|
|
}
|
|
|
|
std::string strName = vFields[0];
|
|
if (!TimingResistantEqual(strName, strUser)) {
|
|
continue;
|
|
}
|
|
|
|
std::string strSalt = vFields[1];
|
|
std::string strHash = vFields[2];
|
|
|
|
unsigned int KEY_SIZE = 32;
|
|
unsigned char *out = new unsigned char[KEY_SIZE];
|
|
|
|
CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).finalize(out);
|
|
std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
|
|
std::string strHashFromPass = HexStr(hexvec);
|
|
|
|
if (TimingResistantEqual(strHashFromPass, strHash)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool RPCAuthorized(const std::string& strAuth)
|
|
{
|
|
if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
|
|
return false;
|
|
if (strAuth.substr(0, 6) != "Basic ")
|
|
return false;
|
|
std::string strUserPass64 = strAuth.substr(6);
|
|
boost::trim(strUserPass64);
|
|
std::string strUserPass = DecodeBase64(strUserPass64);
|
|
|
|
//Check if authorized under single-user field
|
|
if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
|
|
return true;
|
|
}
|
|
return multiUserAuthorized(strUserPass);
|
|
}
|
|
|
|
static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
|
|
{
|
|
// JSONRPC handles only POST
|
|
if (req->GetRequestMethod() != HTTPRequest::POST) {
|
|
req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
|
|
return false;
|
|
}
|
|
// Check authorization
|
|
std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
|
|
if (!authHeader.first) {
|
|
req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
|
|
req->WriteReply(HTTP_UNAUTHORIZED);
|
|
return false;
|
|
}
|
|
|
|
if (!RPCAuthorized(authHeader.second)) {
|
|
logCritical(Log::RPC) << "ThreadRPCServer incorrect password attempt from" << req->GetPeer();
|
|
|
|
/* Deter brute-forcing
|
|
If this results in a DoS the user really
|
|
shouldn't have their RPC port exposed. */
|
|
MilliSleep(250);
|
|
|
|
req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
|
|
req->WriteReply(HTTP_UNAUTHORIZED);
|
|
return false;
|
|
}
|
|
|
|
JSONRequest jreq;
|
|
try {
|
|
// Parse request
|
|
UniValue valRequest;
|
|
if (!valRequest.read(req->ReadBody()))
|
|
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
|
|
|
|
std::string strReply;
|
|
// singleton request
|
|
if (valRequest.isObject()) {
|
|
jreq.parse(valRequest);
|
|
|
|
UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);
|
|
|
|
// Send reply
|
|
strReply = JSONRPCReply(result, NullUniValue, jreq.id);
|
|
|
|
// array of requests
|
|
} else if (valRequest.isArray())
|
|
strReply = JSONRPCExecBatch(valRequest.get_array());
|
|
else
|
|
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
|
|
|
|
req->WriteHeader("Content-Type", "application/json");
|
|
req->WriteReply(HTTP_OK, strReply);
|
|
} catch (const UniValue& objError) {
|
|
JSONErrorReply(req, objError, jreq.id);
|
|
return false;
|
|
} catch (const std::exception& e) {
|
|
JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static bool InitRPCAuthentication()
|
|
{
|
|
if (!mapArgs["-rpcpassword"].empty()) {
|
|
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
|
|
}
|
|
else {
|
|
boost::filesystem::path tokenFilePath = GetAuthCookieFile();
|
|
std::ifstream tokenFile;
|
|
tokenFile.open(tokenFilePath.string().c_str());
|
|
if (!tokenFile.is_open()) {
|
|
logCritical(Log::RPC) << "No rpcpassword set - using random cookie authentication";
|
|
|
|
unsigned char rand_pwd[32];
|
|
GetRandBytes(rand_pwd, 32);
|
|
// prefix with username for debugging / logging purposes.
|
|
strRPCUserColonPass = "__cookie__:" + EncodeBase64(&rand_pwd[0],32);
|
|
|
|
std::ofstream file;
|
|
file.open(tokenFilePath.string().c_str());
|
|
if (!file.is_open()) {
|
|
logFatal(Log::RPC) << "Unable to open cookie authentication file" << tokenFilePath.string() << "for writing";
|
|
return false;
|
|
}
|
|
file << strRPCUserColonPass;
|
|
file.close();
|
|
logCritical(Log::RPC) << "Generated RPC authentication cookie" << tokenFilePath.string();
|
|
}
|
|
else {
|
|
logCritical(Log::RPC) << "Reading RPC cookie" << tokenFilePath.string();
|
|
tokenFile >> strRPCUserColonPass;
|
|
tokenFile.close();
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool StartHTTPRPC()
|
|
{
|
|
logCritical(Log::RPC) << "Starting HTTP RPC server";
|
|
if (!InitRPCAuthentication())
|
|
return false;
|
|
|
|
RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
|
|
|
|
assert(EventBase());
|
|
httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
|
|
RPCRegisterTimerInterface(httpRPCTimerInterface);
|
|
return true;
|
|
}
|
|
|
|
void StopHTTPRPC()
|
|
{
|
|
UnregisterHTTPHandler("/", true);
|
|
if (httpRPCTimerInterface) {
|
|
logCritical(Log::RPC) << "Stopping HTTP RPC server";
|
|
RPCUnregisterTimerInterface(httpRPCTimerInterface);
|
|
delete httpRPCTimerInterface;
|
|
httpRPCTimerInterface = nullptr;
|
|
}
|
|
}
|