From 5b5de37a172afd8361b273b97d73ef24eaa59492 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Sun, 20 Sep 2026 23:13:54 +0800 Subject: [PATCH] =?UTF-8?q?fix(security):=20=E9=98=B2=E6=AD=A2HTTP?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E5=A4=B4=E6=B3=A8=E5=85=A5=E6=BC=8F=E6=B4=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/WebApi.cpp | 27 ++++++++++++++++++++++++++- src/Http/HttpSession.cpp | 8 +++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/server/WebApi.cpp b/server/WebApi.cpp index 7c948c0c..8b1ecced 100755 --- a/server/WebApi.cpp +++ b/server/WebApi.cpp @@ -117,6 +117,26 @@ static void responseApi(int code, const string &msg, const HttpSession::HttpResp invoker(200, headerOut, res.toStyledString()); } +// 消毒用于 HTTP 响应头 quoted-string 的用户输入:去除 CR/LF 及其它控制字符以防止响应头注入(CWE-113), +// 并转义双引号以防止跳出引号范围。 +// Sanitize user input intended for an HTTP response header quoted-string value: strip CR/LF and other +// control characters to prevent response header injection (CWE-113), and escape double-quotes so the +// value cannot break out of the quoted-string. +static string sanitizeHeaderQuotedValue(const string &value) { + string ret; + ret.reserve(value.size()); + for (unsigned char c : value) { + if (c >= 0x20 && c != 0x7f) { + if (c == '"') { + ret += '\\'; + } + ret += static_cast(c); + } + // CR(0x0d), LF(0x0a) and other control chars are silently dropped + } + return ret; +} + static HttpApi toApi(const function &cb) { return [cb](const Parser &parser, const HttpSession::HttpResponseInvoker &invoker, SockInfo &sender) { GET_CONFIG(string, charSet, Http::kCharSet); @@ -2444,7 +2464,12 @@ void installWebApi() { StrCaseMap res_header; auto save_name = allArgs["save_name"]; if (!save_name.empty()) { - res_header.emplace("Content-Disposition", "attachment;filename=\"" + save_name + "\""); + // 消毒后再拼入 Content-Disposition,防止响应头注入(CWE-113) + // Sanitize before embedding into Content-Disposition to prevent header injection (CWE-113) + auto safe_name = sanitizeHeaderQuotedValue(save_name); + if (!safe_name.empty()) { + res_header.emplace("Content-Disposition", "attachment;filename=\"" + safe_name + "\""); + } } invoker.responseFile(allArgs.parser.getHeader(), res_header, allArgs["file_path"]); } diff --git a/src/Http/HttpSession.cpp b/src/Http/HttpSession.cpp index 2ef9b747..d80e3cb0 100644 --- a/src/Http/HttpSession.cpp +++ b/src/Http/HttpSession.cpp @@ -814,7 +814,13 @@ void HttpSession::sendResponse(int code, for (auto &pr : header) { str += pr.first; str += ": "; - str += pr.second; + // Strip CR and LF from header values to prevent HTTP response splitting (CWE-113). + // Any injected \r or \n is silently removed; other characters pass through unchanged. + for (char c : pr.second) { + if (c != '\r' && c != '\n') { + str += c; + } + } str += "\r\n"; } str += "\r\n";