Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/src/HttpServer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ using namespace drogon;
using namespace trantor;

static inline bool isWebSocket(const HttpRequestImplPtr &req);
static bool isValidWebSocketKey(std::string_view key);
static inline HttpResponsePtr tryDecompressRequest(
const HttpRequestImplPtr &req);
static inline bool passSyncAdvices(
Expand Down Expand Up @@ -736,6 +737,14 @@ void HttpServer::websocketRequestRouting(
std::function<void(const HttpResponsePtr &)> &&callback,
WebSocketConnectionImplPtr &&wsConnPtr)
{
if (!isValidWebSocketKey(req->getHeaderBy("sec-websocket-key")))
{
auto resp = HttpResponse::newHttpResponse(k400BadRequest, CT_NONE);
resp->setCloseConnection(true);
callback(resp);
return;
}

RouteResult result = HttpControllersRouter::instance().routeWs(req);

if (result.result == RouteResult::Success)
Expand Down Expand Up @@ -1157,6 +1166,15 @@ void HttpServer::sendResponses(
buffer.retrieveAll();
}

static bool isValidWebSocketKey(std::string_view key)
{
if (key.size() != 24 || !drogon::utils::isBase64(key))
return false;

const auto decoded = drogon::utils::base64Decode(key);
return decoded.size() == 16 && drogon::utils::base64Encode(decoded) == key;
}

static inline bool isWebSocket(const HttpRequestImplPtr &req)
{
if (req->method() != Get)
Expand Down
5 changes: 3 additions & 2 deletions lib/src/Utilities.cc
Original file line number Diff line number Diff line change
Expand Up @@ -911,8 +911,9 @@ std::string urlDecode(const char *begin, const char *end)
result += ' ';
break;
case '%':
if ((i + 2) < len && isxdigit(begin[i + 1]) &&
isxdigit(begin[i + 2]))
if ((i + 2) < len &&
isxdigit(static_cast<unsigned char>(begin[i + 1])) &&
isxdigit(static_cast<unsigned char>(begin[i + 2])))
{
unsigned int x1 = begin[i + 1];
if (x1 >= '0' && x1 <= '9')
Expand Down
3 changes: 3 additions & 0 deletions lib/src/WebSocketClientImpl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ void WebSocketClientImpl::onRecvMessage(
auto acceptStr = resp->getHeaderBy("sec-websocket-accept");

if (resp->statusCode() != k101SwitchingProtocols ||
!drogon::utils::ci_equals(resp->getHeaderBy("upgrade"),
"websocket") ||
!containsHttpToken(resp->getHeaderBy("connection"), "upgrade") ||
acceptStr != wsAccept_)
{
requestCallback_(ReqResult::BadResponse,
Expand Down
Loading