blob: 339294ce558cf1ffd1bde4a90e3a8b84e18e2b52 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08002#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06003
James Feist3909dc82020-04-03 10:58:55 -07004#include "authorization.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07005#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07006#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "logging.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanouse0d918b2018-03-27 17:41:04 -070010#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070011#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080012#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080013#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070014#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080015#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/beast/core/flat_static_buffer.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053017#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070019#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070020#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070021#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Ed Tanous57fce802019-05-21 13:00:34 -070033 json_html_util::dumpHtml(res.body(), res.jsonValue);
34
Ed Tanous93ef5802019-01-03 10:15:41 -080035 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070036}
37
Ed Tanous6fbdbca2021-12-06 14:36:06 -080038static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070039
Ed Tanous0260d9d2021-02-07 19:31:07 +000040// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080041constexpr uint64_t httpReqBodyLimit =
42 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
James Feist3909dc82020-04-03 10:58:55 -070044constexpr uint64_t loggedOutPostBodyLimit = 4096;
45
46constexpr uint32_t httpHeaderLimit = 8192;
47
Ed Tanous52cc1122020-07-18 13:51:21 -070048template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050049class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070050 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070051{
52 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080053 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000054 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 handler(handlerIn), timer(std::move(timerIn)),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
60 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070062 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020063
64#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070065 prepareMutualTls();
66#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
67
Ed Tanous40aa0582021-07-14 13:24:40 -070068 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080069
Ed Tanous40aa0582021-07-14 13:24:40 -070070 BMCWEB_LOG_DEBUG << this << " Connection open, total "
71 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070072 }
73
74 ~Connection()
75 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070076 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount--;
80 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
Ed Tanousecd6a3a2022-01-07 09:18:40 -080084 Connection(const Connection&) = delete;
85 Connection(Connection&&) = delete;
86 Connection& operator=(const Connection&) = delete;
87 Connection& operator=(Connection&&) = delete;
88
Ed Tanous40aa0582021-07-14 13:24:40 -070089 void prepareMutualTls()
90 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080091 std::error_code error;
92 std::filesystem::path caPath(ensuressl::trustStorePath);
93 auto caAvailable = !std::filesystem::is_empty(caPath, error);
94 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070095 if (caAvailable && persistent_data::SessionStore::getInstance()
96 .getAuthMethodsConfig()
97 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010098 {
99 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700100 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800101
Ed Tanous9eb808c2022-01-25 10:19:23 -0800102 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800103 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800104 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700105 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800106 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700107 static_cast<unsigned int>(id.length()));
108 if (ret == 0)
109 {
110 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
111 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100112 }
113
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100114 adaptor.set_verify_callback([this](
115 bool preverified,
116 boost::asio::ssl::verify_context& ctx) {
117 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700118 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100119 .getAuthMethodsConfig()
120 .tls)
121 {
122 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200123 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100124 }
125
126 // We always return true to allow full auth flow
127 if (!preverified)
128 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100129 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100130 return true;
131 }
132
133 X509_STORE_CTX* cts = ctx.native_handle();
134 if (cts == nullptr)
135 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100136 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100137 return true;
138 }
139
140 // Get certificate
141 X509* peerCert =
142 X509_STORE_CTX_get_current_cert(ctx.native_handle());
143 if (peerCert == nullptr)
144 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100145 BMCWEB_LOG_DEBUG << this
146 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100147 return true;
148 }
149
150 // Check if certificate is OK
151 int error = X509_STORE_CTX_get_error(cts);
152 if (error != X509_V_OK)
153 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100154 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100155 return true;
156 }
157 // Check that we have reached final certificate in chain
158 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
159 if (depth != 0)
160
161 {
162 BMCWEB_LOG_DEBUG
163 << this << " Certificate verification in progress (depth "
164 << depth << "), waiting to reach final depth";
165 return true;
166 }
167
168 BMCWEB_LOG_DEBUG << this
169 << " Certificate verification of final depth";
170
171 // Verify KeyUsage
172 bool isKeyUsageDigitalSignature = false;
173 bool isKeyUsageKeyAgreement = false;
174
175 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000176 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100177
178 if (usage == nullptr)
179 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100180 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100181 return true;
182 }
183
184 for (int i = 0; i < usage->length; i++)
185 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800186 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
187 unsigned char usageChar = usage->data[i];
188 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100189 {
190 isKeyUsageDigitalSignature = true;
191 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800192 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100193 {
194 isKeyUsageKeyAgreement = true;
195 }
196 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700197 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100198
199 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
200 {
201 BMCWEB_LOG_DEBUG << this
202 << " Certificate ExtendedKeyUsage does "
203 "not allow provided certificate to "
204 "be used for user authentication";
205 return true;
206 }
207
208 // Determine that ExtendedKeyUsage includes Client Auth
209
Ed Tanous23a21a12020-07-25 04:45:05 +0000210 stack_st_ASN1_OBJECT* extUsage =
211 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
212 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100213
214 if (extUsage == nullptr)
215 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100216 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100217 return true;
218 }
219
220 bool isExKeyUsageClientAuth = false;
221 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
222 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800223 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
224 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
225 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100226 {
227 isExKeyUsageClientAuth = true;
228 break;
229 }
230 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200231 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100232
233 // Certificate has to have proper key usages set
234 if (!isExKeyUsageClientAuth)
235 {
236 BMCWEB_LOG_DEBUG << this
237 << " Certificate ExtendedKeyUsage does "
238 "not allow provided certificate to "
239 "be used for user authentication";
240 return true;
241 }
242 std::string sslUser;
243 // Extract username contained in CommonName
244 sslUser.resize(256, '\0');
245
246 int status = X509_NAME_get_text_by_NID(
247 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
248 static_cast<int>(sslUser.size()));
249
250 if (status == -1)
251 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100252 BMCWEB_LOG_DEBUG
253 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100254 return true;
255 }
256
257 size_t lastChar = sslUser.find('\0');
258 if (lastChar == std::string::npos || lastChar == 0)
259 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100260 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100261 return true;
262 }
263 sslUser.resize(lastChar);
Ed Tanouse05aec52022-01-25 10:28:56 -0800264 std::string unsupportedClientId;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700265 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700266 userSession = persistent_data::SessionStore::getInstance()
267 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800268 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700269 persistent_data::PersistenceType::TIMEOUT);
270 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100271 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700272 BMCWEB_LOG_DEBUG
273 << this
274 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100275 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100276 return true;
277 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700278 }
279
Ed Tanousceac6f72018-12-02 11:58:47 -0800280 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700283 }
284
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 void start()
286 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800287 if (connectionCount >= 100)
288 {
289 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
290 return;
291 }
292
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800293 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500294
Ed Tanousceac6f72018-12-02 11:58:47 -0800295 // TODO(ed) Abstract this to a more clever class with the idea of an
296 // asynchronous "start"
297 if constexpr (std::is_same_v<Adaptor,
298 boost::beast::ssl_stream<
299 boost::asio::ip::tcp::socket>>)
300 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000301 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
302 [this, self(shared_from_this())](
303 const boost::system::error_code& ec) {
304 if (ec)
305 {
306 return;
307 }
308 doReadHeaders();
309 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800310 }
311 else
312 {
313 doReadHeaders();
314 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700316
Ed Tanous1abe55e2018-09-05 08:30:59 -0700317 void handle()
318 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700319 std::error_code reqEc;
320 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
321 if (reqEc)
322 {
323 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
324 return;
325 }
Ed Tanous596b2032021-09-13 10:32:22 -0700326 thisReq.session = userSession;
327
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000328 // Fetch the client IP address
329 readClientIp();
330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700332 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 {
Ed Tanous596b2032021-09-13 10:32:22 -0700334 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700336 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800337 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700338 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700339 }
340 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700341
Ed Tanouse278c182019-03-13 16:23:37 -0700342 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700343 << " " << this << " HTTP/" << thisReq.version() / 10
344 << "." << thisReq.version() % 10 << ' '
345 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800346 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700347
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700348 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700349
Ed Tanous596b2032021-09-13 10:32:22 -0700350 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700351 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200352
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700353 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800355 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700356 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700357 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800358#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700359 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700360 thisReq.session == nullptr)
361 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800362 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700363 forward_unauthorized::sendUnauthorized(
364 req->url, req->getHeaderValue("User-Agent"),
365 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800366 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700367 return;
368 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800369#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Nan Zhou72374eb2022-01-27 17:06:51 -0800370 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
371 BMCWEB_LOG_DEBUG << "Setting completion handler";
372 asyncResp->res.setCompleteRequestHandler(
373 [self(shared_from_this())](crow::Response& thisRes) {
374 self->completeRequest(thisRes);
375 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700376
Ed Tanous596b2032021-09-13 10:32:22 -0700377 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700378 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700379 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700380 "websocket"))
381 {
Ed Tanous596b2032021-09-13 10:32:22 -0700382 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700383 // delete lambda with self shared_ptr
384 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800385 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700386 return;
387 }
Ed Tanous596b2032021-09-13 10:32:22 -0700388 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700389 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700390
Ed Tanouse278c182019-03-13 16:23:37 -0700391 bool isAlive()
392 {
Ed Tanouse278c182019-03-13 16:23:37 -0700393 if constexpr (std::is_same_v<Adaptor,
394 boost::beast::ssl_stream<
395 boost::asio::ip::tcp::socket>>)
396 {
397 return adaptor.next_layer().is_open();
398 }
399 else
400 {
401 return adaptor.is_open();
402 }
403 }
404 void close()
405 {
Ed Tanouse278c182019-03-13 16:23:37 -0700406 if constexpr (std::is_same_v<Adaptor,
407 boost::beast::ssl_stream<
408 boost::asio::ip::tcp::socket>>)
409 {
410 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800411 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200412 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700413 BMCWEB_LOG_DEBUG
414 << this
415 << " Removing TLS session: " << userSession->uniqueId;
416 persistent_data::SessionStore::getInstance().removeSession(
417 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200418 }
Ed Tanouse278c182019-03-13 16:23:37 -0700419 }
420 else
421 {
422 adaptor.close();
423 }
424 }
425
Nan Zhou72374eb2022-01-27 17:06:51 -0800426 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700428 if (!req)
429 {
430 return;
431 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800432 res = std::move(thisRes);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
434 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700435
Ed Tanous0260d9d2021-02-07 19:31:07 +0000436 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700437
Ed Tanouscf099fa2021-08-25 12:37:31 -0700438 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700439
Ed Tanouse278c182019-03-13 16:23:37 -0700440 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 {
442 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
443 // isReading
444 // << ' ' << isWriting;
445 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000446
447 // delete lambda with self shared_ptr
448 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700449 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 return;
451 }
452 if (res.body().empty() && !res.jsonValue.empty())
453 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700454 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700455 {
456 prettyPrintJson(res);
457 }
458 else
459 {
460 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800461 res.body() = res.jsonValue.dump(
462 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 }
464 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700465
Ed Tanous1abe55e2018-09-05 08:30:59 -0700466 if (res.resultInt() >= 400 && res.body().empty())
467 {
468 res.body() = std::string(res.reason());
469 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700470
471 if (res.result() == boost::beast::http::status::no_content)
472 {
473 // Boost beast throws if content is provided on a no-content
474 // response. Ideally, this would never happen, but in the case that
475 // it does, we don't want to throw.
476 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100477 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700478 res.body().clear();
479 }
480
Ed Tanous1abe55e2018-09-05 08:30:59 -0700481 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
482
483 res.keepAlive(req->keepAlive());
484
Nan Zhou72374eb2022-01-27 17:06:51 -0800485 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000486
487 // delete lambda with self shared_ptr
488 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700489 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 }
491
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500492 void readClientIp()
493 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700494 boost::asio::ip::address ip;
495 boost::system::error_code ec = getClientIp(ip);
496 if (ec)
497 {
498 return;
499 }
500 req->ipAddress = ip;
501 }
502
503 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
504 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500505 boost::system::error_code ec;
506 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
507 boost::asio::ip::tcp::endpoint endpoint =
508 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
509
510 if (ec)
511 {
512 // If remote endpoint fails keep going. "ClientOriginIPAddress"
513 // will be empty.
514 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
515 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700516 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500517 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700518 ip = endpoint.address();
519 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500520 }
521
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 private:
523 void doReadHeaders()
524 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
526
527 // Clean up any previous Connection.
528 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800529 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000530 [this,
531 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000532 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500533 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000534 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700535 bool errorWhileReading = false;
536 if (ec)
537 {
538 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500539 if (ec == boost::asio::error::eof)
540 {
541 BMCWEB_LOG_WARNING
542 << this << " Error while reading: " << ec.message();
543 }
544 else
545 {
546 BMCWEB_LOG_ERROR
547 << this << " Error while reading: " << ec.message();
548 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700549 }
550 else
551 {
552 // if the adaptor isn't open anymore, and wasn't handed to a
553 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700554 if (!isAlive() &&
555 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556 {
557 errorWhileReading = true;
558 }
559 }
560
James Feist3909dc82020-04-03 10:58:55 -0700561 cancelDeadlineTimer();
562
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 if (errorWhileReading)
564 {
Ed Tanouse278c182019-03-13 16:23:37 -0700565 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 return;
568 }
569
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700570 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700571
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700572 boost::asio::ip::address ip;
573 if (getClientIp(ip))
574 {
575 BMCWEB_LOG_DEBUG << "Unable to get client IP";
576 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700577 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800578#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
579 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700580 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700581 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800582
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700583 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800584 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700585 {
586 const boost::optional<uint64_t> contentLength =
587 parser->content_length();
588 if (contentLength &&
589 *contentLength > loggedOutPostBodyLimit)
590 {
591 BMCWEB_LOG_DEBUG << "Content length greater than limit "
592 << *contentLength;
593 close();
594 return;
595 }
596
James Feist3909dc82020-04-03 10:58:55 -0700597 BMCWEB_LOG_DEBUG << "Starting quick deadline";
598 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800599#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800600
Ed Tanous1abe55e2018-09-05 08:30:59 -0700601 doRead();
602 });
603 }
604
605 void doRead()
606 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700607 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800608 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800610 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000611 [this,
612 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000613 std::size_t bytesTransferred) {
614 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700615 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800616 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617 if (ec)
618 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100619 BMCWEB_LOG_ERROR
620 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700621 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 return;
624 }
625 handle();
626 });
627 }
628
Nan Zhou72374eb2022-01-27 17:06:51 -0800629 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100631 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800632 thisRes.preparePayload();
633 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800634 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800636 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000637 [this,
638 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000639 std::size_t bytesTransferred) {
640 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 << " bytes";
642
James Feist54d8bb12020-07-20 13:28:59 -0700643 cancelDeadlineTimer();
644
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 if (ec)
646 {
647 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 return;
649 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800650 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 {
Ed Tanouse278c182019-03-13 16:23:37 -0700652 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 return;
655 }
656
657 serializer.reset();
658 BMCWEB_LOG_DEBUG << this << " Clearing response";
659 res.clear();
660 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500661 parser->body_limit(httpReqBodyLimit); // reset body limit for
662 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700663 buffer.consume(buffer.size());
664
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700665 // If the session was built from the transport, we don't need to
666 // clear it. All other sessions are generated per request.
667 if (!sessionIsFromTransport)
668 {
669 userSession = nullptr;
670 }
671
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700672 // Destroy the Request via the std::optional
673 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700674 doReadHeaders();
675 });
676 }
677
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 void cancelDeadlineTimer()
679 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 }
682
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800683 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 {
685 cancelDeadlineTimer();
686
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 std::chrono::seconds timeout(15);
688 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800689 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800690 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700691 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800692 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700693 return;
694 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800695
696 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
697 timer.expires_after(timeout);
698 timer.async_wait([weakSelf](const boost::system::error_code ec) {
699 // Note, we are ignoring other types of errors here; If the timer
700 // failed for any reason, we should still close the connection
701
702 std::shared_ptr<Connection<Adaptor, Handler>> self =
703 weakSelf.lock();
704 if (!self)
705 {
706 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
707 return;
708 }
709 if (ec == boost::asio::error::operation_aborted)
710 {
711 // Canceled wait means the path succeeeded.
712 return;
713 }
714 if (ec)
715 {
716 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
717 }
718
719 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
720
721 self->close();
722 });
723
724 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725 }
726
Ed Tanous1abe55e2018-09-05 08:30:59 -0700727 Adaptor adaptor;
728 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800729 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800731 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700732 boost::beast::http::request_parser<boost::beast::http::string_body>>
733 parser;
734
Ed Tanous3112a142018-11-29 15:45:10 -0800735 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736
Ed Tanousa24526d2018-12-10 15:17:59 -0800737 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 boost::beast::http::string_body>>
739 serializer;
740
Ed Tanousa24526d2018-12-10 15:17:59 -0800741 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700743
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700744 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700745 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800747 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000750
751 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700752 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800753
754 using std::enable_shared_from_this<
755 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800756};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757} // namespace crow