Skip to content

Commit

Permalink
Use HTTPS, support for HTTP missing
Browse files Browse the repository at this point in the history
  • Loading branch information
badaix committed May 7, 2024
1 parent 65f6bb4 commit cbe0a30
Show file tree
Hide file tree
Showing 14 changed files with 121 additions and 54 deletions.
1 change: 0 additions & 1 deletion server/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ endif()
# list(APPEND SERVER_LIBRARIES Boost::boost)
list(APPEND SERVER_LIBRARIES OpenSSL::Crypto OpenSSL::SSL)


include_directories(${SERVER_INCLUDE})
if(ANDROID)
add_executable(libsnapserver.so ${SERVER_SOURCES})
Expand Down
23 changes: 12 additions & 11 deletions server/control_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "common/json.hpp"
#include "control_session_http.hpp"
#include "control_session_tcp.hpp"
#include "server_settings.hpp"

// 3rd party headers

Expand All @@ -37,16 +38,16 @@ using json = nlohmann::json;
static constexpr auto LOG_TAG = "ControlServer";


ControlServer::ControlServer(boost::asio::io_context& io_context, const ServerSettings::Tcp& tcp_settings, const ServerSettings::Http& http_settings,
ControlMessageReceiver* controlMessageReceiver)
: io_context_(io_context), ssl_context_(boost::asio::ssl::context::sslv23), tcp_settings_(tcp_settings), http_settings_(http_settings),
ControlServer::ControlServer(boost::asio::io_context& io_context, const ServerSettings& settings, ControlMessageReceiver* controlMessageReceiver)
: io_context_(io_context), ssl_context_(boost::asio::ssl::context::sslv23), tcp_settings_(settings.tcp), http_settings_(settings.http),
controlMessageReceiver_(controlMessageReceiver)
{
const ServerSettings::Ssl& ssl = settings.ssl;
ssl_context_.set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use);
ssl_context_.set_password_callback(std::bind(&ControlServer::getPassword, this));
ssl_context_.use_certificate_chain_file("server.pem");
ssl_context_.use_private_key_file("server.pem", boost::asio::ssl::context::pem);
ssl_context_.use_tmp_dh_file("dh4096.pem");
ssl_context_.use_certificate_chain_file(ssl.certificate);
ssl_context_.use_private_key_file(ssl.private_key, boost::asio::ssl::context::pem);
// ssl_context_.use_tmp_dh_file("dh4096.pem");
}


Expand All @@ -58,6 +59,7 @@ ControlServer::~ControlServer()

std::string ControlServer::getPassword() const
{
LOG(DEBUG, LOG_TAG) << "getPassword\n";
return "test";
}

Expand Down Expand Up @@ -127,11 +129,10 @@ void ControlServer::startAccept()
{
if (!ec)
{
handleAccept<ControlSessionHttp>(std::move(socket), http_settings_);
// auto session = make_shared<ControlSessionHttp<boost::asio::ssl::stream<tcp::socket>>>(
// this, boost::asio::ssl::stream<tcp::socket>(std::move(socket), ssl_context_), http_settings_);
// onNewSession(std::move(session));
// startAccept();
// handleAccept<ControlSessionHttp>(std::move(socket), http_settings_);
auto session = make_shared<ControlSessionHttp>(this, std::move(socket), ssl_context_, http_settings_);
onNewSession(std::move(session));
startAccept();
}
else
LOG(ERROR, LOG_TAG) << "Error while accepting socket connection: " << ec.message() << "\n";
Expand Down
3 changes: 1 addition & 2 deletions server/control_server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ using acceptor_ptr = std::unique_ptr<tcp::acceptor>;
class ControlServer : public ControlMessageReceiver
{
public:
ControlServer(boost::asio::io_context& io_context, const ServerSettings::Tcp& tcp_settings, const ServerSettings::Http& http_settings,
ControlMessageReceiver* controlMessageReceiver = nullptr);
ControlServer(boost::asio::io_context& io_context, const ServerSettings& settings, ControlMessageReceiver* controlMessageReceiver = nullptr);
virtual ~ControlServer();

void start();
Expand Down
56 changes: 44 additions & 12 deletions server/control_session_http.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@

// standard headers
#include <iostream>
#include <memory>

// 3rd party headers
#include <boost/asio/ssl/stream.hpp>
#include <boost/beast/http/buffer_body.hpp>
#include <boost/beast/http/file_body.hpp>

// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"
#include "common/utils/file_utils.hpp"
#include "control_session_ws.hpp"
#include "stream_session_ws.hpp"
Expand Down Expand Up @@ -146,10 +147,11 @@ std::string path_cat(boost::beast::string_view base, boost::beast::string_view p
}
} // namespace

ControlSessionHttp::ControlSessionHttp(ControlMessageReceiver* receiver, tcp::socket&& socket, const ServerSettings::Http& settings)
: ControlSession(receiver), socket_(std::move(socket)), settings_(settings)
ControlSessionHttp::ControlSessionHttp(ControlMessageReceiver* receiver, tcp_socket&& socket, boost::asio::ssl::context& ssl_context,
const ServerSettings::Http& settings)
: ControlSession(receiver), socket_(ssl_socket(std::move(socket), ssl_context)), ssl_context_(ssl_context), settings_(settings)
{
LOG(DEBUG, LOG_TAG) << "ControlSessionHttp, Local IP: " << socket_.local_endpoint().address().to_string() << "\n";
LOG(DEBUG, LOG_TAG) << "ControlSessionHttp, Local IP: " << socket_.next_layer().local_endpoint().address().to_string() << "\n";
}


Expand All @@ -160,9 +162,31 @@ ControlSessionHttp::~ControlSessionHttp()
}


void ControlSessionHttp::doHandshake()
{
LOG(DEBUG, LOG_TAG) << "doHandshake\n";
socket_.async_handshake(boost::asio::ssl::stream_base::server,
[this, self = shared_from_this()](const boost::system::error_code& error)
{
LOG(DEBUG, LOG_TAG) << "async_handshake\n";
if (error)
{
LOG(ERROR, LOG_TAG) << "async_handshake error: " << error.message() << "\n";
}
else
{
http::async_read(socket_, buffer_, req_,
[this, self = shared_from_this()](boost::system::error_code ec, std::size_t bytes) { on_read(ec, bytes); });
}
});
}


void ControlSessionHttp::start()
{
http::async_read(socket_, buffer_, req_, [this, self = shared_from_this()](boost::system::error_code ec, std::size_t bytes) { on_read(ec, bytes); });
LOG(DEBUG, LOG_TAG) << "start\n";
doHandshake();
// http::async_read(socket_, buffer_, req_, [this, self = shared_from_this()](boost::system::error_code ec, std::size_t bytes) { on_read(ec, bytes); });
}


Expand Down Expand Up @@ -331,7 +355,11 @@ void ControlSessionHttp::on_read(beast::error_code ec, std::size_t bytes_transfe
// This means they closed the connection
if (ec == http::error::end_of_stream)
{
socket_.shutdown(tcp::socket::shutdown_send, ec);
boost::system::error_code res;
res = socket_.shutdown(res);
// auto res = socket_.lowest_layer().shutdown(tcp_socket::shutdown_send, ec);
if (res.failed())
LOG(ERROR, LOG_TAG) << "Failed to shudown socket: " << res << "\n";
return;
}

Expand All @@ -352,14 +380,14 @@ void ControlSessionHttp::on_read(beast::error_code ec, std::size_t bytes_transfe
if (req_.target() == "/jsonrpc")
{
// Create a WebSocket session by transferring the socket
// std::make_shared<websocket_session>(std::move(socket_), state_)->run(std::move(req_));
auto ws = std::make_shared<websocket::stream<beast::tcp_stream>>(std::move(socket_));
auto ws = std::make_shared<websocket::stream<ssl_socket>>(std::move(socket_));
// Accept the websocket handshake
ws->async_accept(req_,
[this, ws, self = shared_from_this()](beast::error_code ec)
[this, ws, self = shared_from_this()](beast::error_code ec) mutable
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error during WebSocket handshake (control): " << ec.message() << "\n";
LOG(ERROR, LOG_TAG) << "Error during WebSocket accept (control): " << ec.message() << "\n";
}
else
{
Expand All @@ -372,7 +400,7 @@ void ControlSessionHttp::on_read(beast::error_code ec, std::size_t bytes_transfe
{
// Create a WebSocket session by transferring the socket
// std::make_shared<websocket_session>(std::move(socket_), state_)->run(std::move(req_));
auto ws = std::make_shared<websocket::stream<beast::tcp_stream>>(std::move(socket_));
auto ws = std::make_shared<websocket::stream<ssl_socket>>(std::move(socket_));
ws->async_accept(req_,
[this, ws, self = shared_from_this()](beast::error_code ec)
{
Expand Down Expand Up @@ -422,7 +450,11 @@ void ControlSessionHttp::on_write(beast::error_code ec, std::size_t bytes, bool
{
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
socket_.shutdown(tcp::socket::shutdown_send, ec);
boost::system::error_code res;
res = socket_.shutdown(res);
// auto res = socket_.lowest_layer().shutdown(tcp::socket::shutdown_send, ec);
if (res.failed())
LOG(ERROR, LOG_TAG) << "Failed to shudown socket: " << res << "\n";
return;
}

Expand Down
18 changes: 14 additions & 4 deletions server/control_session_http.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
#include "server_settings.hpp"

// 3rd party headers
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/ssl.hpp>

#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
Expand All @@ -37,12 +40,13 @@

// standard headers
#include <deque>

using boost::asio::ip::tcp;
// #include <variant>

namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>

using tcp_socket = boost::asio::ip::tcp::socket;
using ssl_socket = boost::asio::ssl::stream<tcp_socket>;

/// Endpoint for a connected control client.
/**
Expand All @@ -54,7 +58,7 @@ class ControlSessionHttp : public ControlSession
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSessionHttp(ControlMessageReceiver* receiver, tcp::socket&& socket, const ServerSettings::Http& settings);
ControlSessionHttp(ControlMessageReceiver* receiver, tcp_socket&& socket, boost::asio::ssl::context& ssl_context, const ServerSettings::Http& settings);
~ControlSessionHttp() override;
void start() override;
void stop() override;
Expand All @@ -72,8 +76,14 @@ class ControlSessionHttp : public ControlSession

http::request<http::string_body> req_;

// do SSL handshake
void doHandshake();

protected:
tcp::socket socket_;
// tcp_socket socket_;
ssl_socket socket_;
// std::variant<tcp_socket, ssl_socket> sock_;
boost::asio::ssl::context& ssl_context_;
beast::flat_buffer buffer_;
ServerSettings::Http settings_;
std::deque<std::string> messages_;
Expand Down
13 changes: 6 additions & 7 deletions server/control_session_ws.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"

// 3rd party headers

Expand All @@ -33,8 +32,8 @@ using namespace std;
static constexpr auto LOG_TAG = "ControlSessionWS";


ControlSessionWebsocket::ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket)
: ControlSession(receiver), ws_(std::move(socket)), strand_(boost::asio::make_strand(ws_.get_executor()))
ControlSessionWebsocket::ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<ssl_socket>&& wss)
: ControlSession(receiver), wss_(std::move(wss)), strand_(boost::asio::make_strand(wss_.get_executor()))
{
LOG(DEBUG, LOG_TAG) << "ControlSessionWebsocket\n";
}
Expand Down Expand Up @@ -85,9 +84,9 @@ void ControlSessionWebsocket::sendAsync(const std::string& message)
void ControlSessionWebsocket::send_next()
{
const std::string& message = messages_.front();
ws_.async_write(boost::asio::buffer(message),
[this, self = shared_from_this()](std::error_code ec, std::size_t length)
{
wss_.async_write(boost::asio::buffer(message),
[this, self = shared_from_this()](std::error_code ec, std::size_t length)
{
messages_.pop_front();
if (ec)
{
Expand All @@ -106,7 +105,7 @@ void ControlSessionWebsocket::send_next()
void ControlSessionWebsocket::do_read_ws()
{
// Read a message into our buffer
ws_.async_read(buffer_, [this, self = shared_from_this()](beast::error_code ec, std::size_t bytes_transferred) { on_read_ws(ec, bytes_transferred); });
wss_.async_read(buffer_, [this, self = shared_from_this()](beast::error_code ec, std::size_t bytes_transferred) { on_read_ws(ec, bytes_transferred); });
}


Expand Down
7 changes: 5 additions & 2 deletions server/control_session_ws.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#endif
#include <boost/beast/core.hpp>
#pragma GCC diagnostic pop
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>

// standard headers
Expand All @@ -40,6 +41,8 @@

namespace beast = boost::beast; // from <boost/beast.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
using tcp_socket = boost::asio::ip::tcp::socket;
using ssl_socket = boost::asio::ssl::stream<tcp_socket>;


/// Endpoint for a connected control client.
Expand All @@ -52,7 +55,7 @@ class ControlSessionWebsocket : public ControlSession
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket);
ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<ssl_socket>&& wss);
~ControlSessionWebsocket() override;
void start() override;
void stop() override;
Expand All @@ -66,7 +69,7 @@ class ControlSessionWebsocket : public ControlSession
void do_read_ws();
void send_next();

websocket::stream<beast::tcp_stream> ws_;
websocket::stream<ssl_socket> wss_;

protected:
beast::flat_buffer buffer_;
Expand Down
12 changes: 12 additions & 0 deletions server/etc/snapserver.conf
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@
###############################################################################


# Secure Socket Layer #########################################################
#
[ssl]
# https://deliciousbrains.com/ssl-certificate-authority-for-local-https-development/
# https://gist.github.com/fntlnz/cf14feb5a46b2eda428e000157447309
certificate = certs/snapserver.crt
private_key = certs/snapserver.key

#
###############################################################################


# HTTP RPC ####################################################################
#
[http]
Expand Down
2 changes: 1 addition & 1 deletion server/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -871,7 +871,7 @@ void Server::start()
{
try
{
controlServer_ = std::make_unique<ControlServer>(io_context_, settings_.tcp, settings_.http, this);
controlServer_ = std::make_unique<ControlServer>(io_context_, settings_, this);
streamServer_ = std::make_unique<StreamServer>(io_context_, settings_, this);
streamManager_ = std::make_unique<StreamManager>(this, io_context_, settings_);

Expand Down
7 changes: 7 additions & 0 deletions server/server_settings.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ struct ServerSettings
std::string data_dir{""};
};

struct Ssl
{
std::string certificate{""};
std::string private_key{""};
};

struct Http
{
bool enabled{true};
Expand Down Expand Up @@ -79,6 +85,7 @@ struct ServerSettings
};

Server server;
Ssl ssl;
Http http;
Tcp tcp;
Stream stream;
Expand Down
4 changes: 4 additions & 0 deletions server/snapserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ int main(int argc, char* argv[])
conf.add<Implicit<string>>("", "server.group", "the group to run as when daemonized", settings.server.group, &settings.server.group);
conf.add<Implicit<string>>("", "server.datadir", "directory where persistent data is stored", settings.server.data_dir, &settings.server.data_dir);

// SSL settings
conf.add<Value<string>>("", "ssl.certificate", "certificate file (PEM format)", settings.ssl.certificate, &settings.ssl.certificate);
conf.add<Value<string>>("", "ssl.private_key", "private key file (PEM format)", settings.ssl.private_key, &settings.ssl.private_key);

// HTTP RPC settings
conf.add<Value<bool>>("", "http.enabled", "enable HTTP Json RPC (HTTP POST and websockets)", settings.http.enabled, &settings.http.enabled);
conf.add<Value<size_t>>("", "http.port", "which port the server should listen on", settings.http.port, &settings.http.port);
Expand Down
Loading

0 comments on commit cbe0a30

Please sign in to comment.