blob: afd823a6ad1287e8f23612f44c0babd8abd574dc [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"
8#include "timer_queue.hpp"
9#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010
Ed Tanouse0d918b2018-03-27 17:41:04 -070011#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070012#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080013#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080014#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070015#include <boost/asio/ssl/stream.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 Tanous57fce802019-05-21 13:00:34 -070019#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070020#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <ssl_key_handler.hpp>
22
Manojkiran Eda44250442020-06-16 12:51:38 +053023#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050024#include <chrono>
25#include <vector>
26
Ed Tanous1abe55e2018-09-05 08:30:59 -070027namespace crow
28{
Ed Tanous257f5792018-03-17 14:40:09 -070029
Ed Tanous1abe55e2018-09-05 08:30:59 -070030inline void prettyPrintJson(crow::Response& res)
31{
Ed Tanous57fce802019-05-21 13:00:34 -070032 json_html_util::dumpHtml(res.body(), res.jsonValue);
33
Ed Tanous93ef5802019-01-03 10:15:41 -080034 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070035}
36
Ed Tanous55c7b7a2018-05-22 15:27:24 -070037#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070038static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070039#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070040
Ed Tanous0260d9d2021-02-07 19:31:07 +000041// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060042constexpr unsigned int httpReqBodyLimit =
Ed Tanous0260d9d2021-02-07 19:31:07 +000043 1024 * 1024 * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070044
James Feist3909dc82020-04-03 10:58:55 -070045constexpr uint64_t loggedOutPostBodyLimit = 4096;
46
47constexpr uint32_t httpHeaderLimit = 8192;
48
49// drop all connections after 1 minute, this time limit was chosen
50// arbitrarily and can be adjusted later if needed
51static constexpr const size_t loggedInAttempts =
52 (60 / timerQueueTimeoutSeconds);
53
54static constexpr const size_t loggedOutAttempts =
55 (15 / timerQueueTimeoutSeconds);
56
Ed Tanous52cc1122020-07-18 13:51:21 -070057template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050058class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070059 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070060{
61 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070062 Connection(Handler* handlerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000063 std::function<std::string()>& getCachedDateStrF,
Ed Tanous271584a2019-07-09 16:24:22 -070064 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanous81ce6092020-12-17 16:54:55 +000066 handler(handlerIn), getCachedDateStr(getCachedDateStrF),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070067 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070068 {
69 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070071 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020072
73#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070074 prepareMutualTls();
75#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
76
77#ifdef BMCWEB_ENABLE_DEBUG
78 connectionCount++;
79 BMCWEB_LOG_DEBUG << this << " Connection open, total "
80 << connectionCount;
81#endif
82 }
83
84 ~Connection()
85 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070086 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070087 cancelDeadlineTimer();
88#ifdef BMCWEB_ENABLE_DEBUG
89 connectionCount--;
90 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
91 << connectionCount;
92#endif
93 }
94
95 void prepareMutualTls()
96 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080097 std::error_code error;
98 std::filesystem::path caPath(ensuressl::trustStorePath);
99 auto caAvailable = !std::filesystem::is_empty(caPath, error);
100 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700101 if (caAvailable && persistent_data::SessionStore::getInstance()
102 .getAuthMethodsConfig()
103 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100104 {
105 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700106 std::string id = "bmcweb";
107 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100108 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700109 reinterpret_cast<const unsigned char*>(id.c_str()),
110 static_cast<unsigned int>(id.length()));
111 if (ret == 0)
112 {
113 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
114 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100115 }
116
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100117 adaptor.set_verify_callback([this](
118 bool preverified,
119 boost::asio::ssl::verify_context& ctx) {
120 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700121 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100122 .getAuthMethodsConfig()
123 .tls)
124 {
125 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200126 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100127 }
128
129 // We always return true to allow full auth flow
130 if (!preverified)
131 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100132 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100133 return true;
134 }
135
136 X509_STORE_CTX* cts = ctx.native_handle();
137 if (cts == nullptr)
138 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100139 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100140 return true;
141 }
142
143 // Get certificate
144 X509* peerCert =
145 X509_STORE_CTX_get_current_cert(ctx.native_handle());
146 if (peerCert == nullptr)
147 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100148 BMCWEB_LOG_DEBUG << this
149 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100150 return true;
151 }
152
153 // Check if certificate is OK
154 int error = X509_STORE_CTX_get_error(cts);
155 if (error != X509_V_OK)
156 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100157 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158 return true;
159 }
160 // Check that we have reached final certificate in chain
161 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
162 if (depth != 0)
163
164 {
165 BMCWEB_LOG_DEBUG
166 << this << " Certificate verification in progress (depth "
167 << depth << "), waiting to reach final depth";
168 return true;
169 }
170
171 BMCWEB_LOG_DEBUG << this
172 << " Certificate verification of final depth";
173
174 // Verify KeyUsage
175 bool isKeyUsageDigitalSignature = false;
176 bool isKeyUsageKeyAgreement = false;
177
178 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000179 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100180
181 if (usage == nullptr)
182 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100183 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100184 return true;
185 }
186
187 for (int i = 0; i < usage->length; i++)
188 {
189 if (KU_DIGITAL_SIGNATURE & usage->data[i])
190 {
191 isKeyUsageDigitalSignature = true;
192 }
193 if (KU_KEY_AGREEMENT & usage->data[i])
194 {
195 isKeyUsageKeyAgreement = true;
196 }
197 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700198 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100199
200 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
201 {
202 BMCWEB_LOG_DEBUG << this
203 << " Certificate ExtendedKeyUsage does "
204 "not allow provided certificate to "
205 "be used for user authentication";
206 return true;
207 }
208
209 // Determine that ExtendedKeyUsage includes Client Auth
210
Ed Tanous23a21a12020-07-25 04:45:05 +0000211 stack_st_ASN1_OBJECT* extUsage =
212 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
213 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100214
215 if (extUsage == nullptr)
216 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100217 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100218 return true;
219 }
220
221 bool isExKeyUsageClientAuth = false;
222 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
223 {
224 if (NID_client_auth ==
225 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
226 {
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);
Sunitha Harishd3239222021-02-24 15:33:29 +0530264 std::string unsupportedClientId = "";
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700265 userSession = persistent_data::SessionStore::getInstance()
266 .generateUserSession(
267 sslUser, req->ipAddress.to_string(),
268 unsupportedClientId,
269 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 Tanous7045c8d2017-04-03 10:04:37 -0700287
James Feist3909dc82020-04-03 10:58:55 -0700288 startDeadline(0);
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500289
Ed Tanousceac6f72018-12-02 11:58:47 -0800290 // TODO(ed) Abstract this to a more clever class with the idea of an
291 // asynchronous "start"
292 if constexpr (std::is_same_v<Adaptor,
293 boost::beast::ssl_stream<
294 boost::asio::ip::tcp::socket>>)
295 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000296 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
297 [this, self(shared_from_this())](
298 const boost::system::error_code& ec) {
299 if (ec)
300 {
301 return;
302 }
303 doReadHeaders();
304 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800305 }
306 else
307 {
308 doReadHeaders();
309 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700310 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700311
Ed Tanous1abe55e2018-09-05 08:30:59 -0700312 void handle()
313 {
314 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700315
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000316 // Fetch the client IP address
317 readClientIp();
318
Ed Tanous1abe55e2018-09-05 08:30:59 -0700319 // Check for HTTP version 1.1.
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700320 if (parser->get().version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700322 if (parser->get()[boost::beast::http::field::host].empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700323 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700324 res.result(boost::beast::http::status::bad_request);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700325 completeRequest();
326 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 }
328 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700329
Ed Tanouse278c182019-03-13 16:23:37 -0700330 BMCWEB_LOG_INFO << "Request: "
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700331 << " " << this << " HTTP/"
332 << parser->get().version() / 10 << "."
333 << parser->get().version() % 10 << ' '
334 << parser->get().method_string() << " "
335 << parser->get().target() << " " << req->ipAddress;
336 req.emplace(parser->release());
337 req->session = userSession;
338 try
339 {
340 // causes life time issue
341 req->urlView = boost::urls::url_view(req->target());
342 req->url = req->urlView.encoded_path();
343 }
344 catch (std::exception& p)
345 {
346 BMCWEB_LOG_ERROR << p.what();
347 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700348
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700349 res.setCompleteRequestHandler(nullptr);
350 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700351
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700352 req->ioService = static_cast<decltype(req->ioService)>(
353 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200354
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700355 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 {
357 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700358 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 }
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700360 res.setCompleteRequestHandler([self(shared_from_this())] {
361 boost::asio::post(self->adaptor.get_executor(),
362 [self] { self->completeRequest(); });
363 });
364
365 if (req->isUpgrade() &&
366 boost::iequals(
367 req->getHeaderValue(boost::beast::http::field::upgrade),
368 "websocket"))
369 {
370 handler->handleUpgrade(*req, res, std::move(adaptor));
371 // delete lambda with self shared_ptr
372 // to enable connection destruction
373 res.setCompleteRequestHandler(nullptr);
374 return;
375 }
376 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
377 handler->handle(*req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700378 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700379
Ed Tanouse278c182019-03-13 16:23:37 -0700380 bool isAlive()
381 {
Ed Tanouse278c182019-03-13 16:23:37 -0700382 if constexpr (std::is_same_v<Adaptor,
383 boost::beast::ssl_stream<
384 boost::asio::ip::tcp::socket>>)
385 {
386 return adaptor.next_layer().is_open();
387 }
388 else
389 {
390 return adaptor.is_open();
391 }
392 }
393 void close()
394 {
Ed Tanouse278c182019-03-13 16:23:37 -0700395 if constexpr (std::is_same_v<Adaptor,
396 boost::beast::ssl_stream<
397 boost::asio::ip::tcp::socket>>)
398 {
399 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200400#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700401 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200402 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700403 BMCWEB_LOG_DEBUG
404 << this
405 << " Removing TLS session: " << userSession->uniqueId;
406 persistent_data::SessionStore::getInstance().removeSession(
407 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200408 }
409#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700410 }
411 else
412 {
413 adaptor.close();
414 }
415 }
416
Ed Tanous1abe55e2018-09-05 08:30:59 -0700417 void completeRequest()
418 {
419 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
420 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700421
Ed Tanous0260d9d2021-02-07 19:31:07 +0000422 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700423
Ed Tanouscf099fa2021-08-25 12:37:31 -0700424 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425
Ed Tanouse278c182019-03-13 16:23:37 -0700426 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 {
428 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
429 // isReading
430 // << ' ' << isWriting;
431 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000432
433 // delete lambda with self shared_ptr
434 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700435 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 return;
437 }
438 if (res.body().empty() && !res.jsonValue.empty())
439 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700440 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 {
442 prettyPrintJson(res);
443 }
444 else
445 {
446 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800447 res.body() = res.jsonValue.dump(
448 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700449 }
450 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700451
Ed Tanous1abe55e2018-09-05 08:30:59 -0700452 if (res.resultInt() >= 400 && res.body().empty())
453 {
454 res.body() = std::string(res.reason());
455 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700456
457 if (res.result() == boost::beast::http::status::no_content)
458 {
459 // Boost beast throws if content is provided on a no-content
460 // response. Ideally, this would never happen, but in the case that
461 // it does, we don't want to throw.
462 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100463 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700464 res.body().clear();
465 }
466
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
468
469 res.keepAlive(req->keepAlive());
470
471 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000472
473 // delete lambda with self shared_ptr
474 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700475 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700476 }
477
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500478 void readClientIp()
479 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700480 boost::asio::ip::address ip;
481 boost::system::error_code ec = getClientIp(ip);
482 if (ec)
483 {
484 return;
485 }
486 req->ipAddress = ip;
487 }
488
489 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
490 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500491 boost::system::error_code ec;
492 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
493 boost::asio::ip::tcp::endpoint endpoint =
494 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
495
496 if (ec)
497 {
498 // If remote endpoint fails keep going. "ClientOriginIPAddress"
499 // will be empty.
500 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
501 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700502 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500503 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700504 ip = endpoint.address();
505 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500506 }
507
Ed Tanous1abe55e2018-09-05 08:30:59 -0700508 private:
509 void doReadHeaders()
510 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700511 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
512
513 // Clean up any previous Connection.
514 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800515 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000516 [this,
517 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000518 std::size_t bytesTransferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700519 BMCWEB_LOG_ERROR << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000520 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700521 bool errorWhileReading = false;
522 if (ec)
523 {
524 errorWhileReading = true;
525 BMCWEB_LOG_ERROR
526 << this << " Error while reading: " << ec.message();
527 }
528 else
529 {
530 // if the adaptor isn't open anymore, and wasn't handed to a
531 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700532 if (!isAlive() &&
533 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700534 {
535 errorWhileReading = true;
536 }
537 }
538
James Feist3909dc82020-04-03 10:58:55 -0700539 cancelDeadlineTimer();
540
Ed Tanous1abe55e2018-09-05 08:30:59 -0700541 if (errorWhileReading)
542 {
Ed Tanouse278c182019-03-13 16:23:37 -0700543 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700544 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545 return;
546 }
547
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700548 boost::beast::http::verb method = parser->get().method();
549 readClientIp();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700550 try
551 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700552 req->urlView =
553 boost::urls::url_view(parser->get().target());
Ed Tanousdc7a7932020-08-17 15:04:58 -0700554 req->url = req->urlView.encoded_path();
555 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700556 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700557 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700558 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700559 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700560
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700561 boost::asio::ip::address ip;
562 if (getClientIp(ip))
563 {
564 BMCWEB_LOG_DEBUG << "Unable to get client IP";
565 }
566 userSession = crow::authorization::authenticate(
567 req->url, ip, res, method, parser->get().base(),
568 userSession);
569 bool loggedIn = userSession != nullptr;
James Feist3909dc82020-04-03 10:58:55 -0700570 if (loggedIn)
571 {
572 startDeadline(loggedInAttempts);
573 BMCWEB_LOG_DEBUG << "Starting slow deadline";
574
James Feist5a7e8772020-07-22 09:08:38 -0700575 req->urlParams = req->urlView.params();
576
577#ifdef BMCWEB_ENABLE_DEBUG
578 std::string paramList = "";
579 for (const auto param : req->urlParams)
580 {
581 paramList += param->key() + " " + param->value() + " ";
582 }
583 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
584#endif
James Feist3909dc82020-04-03 10:58:55 -0700585 }
586 else
587 {
588 const boost::optional<uint64_t> contentLength =
589 parser->content_length();
590 if (contentLength &&
591 *contentLength > loggedOutPostBodyLimit)
592 {
593 BMCWEB_LOG_DEBUG << "Content length greater than limit "
594 << *contentLength;
595 close();
596 return;
597 }
598
599 startDeadline(loggedOutAttempts);
600 BMCWEB_LOG_DEBUG << "Starting quick deadline";
601 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700602 doRead();
603 });
604 }
605
606 void doRead()
607 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 BMCWEB_LOG_DEBUG << this << " doRead";
609
610 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800611 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000612 [this,
613 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000614 std::size_t bytesTransferred) {
615 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617
618 bool errorWhileReading = false;
619 if (ec)
620 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100621 BMCWEB_LOG_ERROR
622 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 errorWhileReading = true;
624 }
625 else
626 {
James Feist3909dc82020-04-03 10:58:55 -0700627 if (isAlive())
628 {
629 cancelDeadlineTimer();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700630 if (userSession != nullptr)
James Feist3909dc82020-04-03 10:58:55 -0700631 {
632 startDeadline(loggedInAttempts);
633 }
634 else
635 {
636 startDeadline(loggedOutAttempts);
637 }
638 }
639 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 {
641 errorWhileReading = true;
642 }
643 }
644 if (errorWhileReading)
645 {
646 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700647 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 return;
650 }
651 handle();
652 });
653 }
654
655 void doWrite()
656 {
James Feist3909dc82020-04-03 10:58:55 -0700657 bool loggedIn = req && req->session;
658 if (loggedIn)
659 {
660 startDeadline(loggedInAttempts);
661 }
662 else
663 {
664 startDeadline(loggedOutAttempts);
665 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100666 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700667 res.preparePayload();
668 serializer.emplace(*res.stringResponse);
669 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800670 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000671 [this,
672 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000673 std::size_t bytesTransferred) {
674 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 << " bytes";
676
James Feist54d8bb12020-07-20 13:28:59 -0700677 cancelDeadlineTimer();
678
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 if (ec)
680 {
681 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700682 return;
683 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800684 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 {
Ed Tanouse278c182019-03-13 16:23:37 -0700686 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700687 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700688 return;
689 }
690
691 serializer.reset();
692 BMCWEB_LOG_DEBUG << this << " Clearing response";
693 res.clear();
694 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500695 parser->body_limit(httpReqBodyLimit); // reset body limit for
696 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700697 buffer.consume(buffer.size());
698
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700699 req.emplace(parser->release());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700700 doReadHeaders();
701 });
702 }
703
Ed Tanous1abe55e2018-09-05 08:30:59 -0700704 void cancelDeadlineTimer()
705 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000706 if (timerCancelKey)
707 {
708 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
709 << ' ' << *timerCancelKey;
710 timerQueue.cancel(*timerCancelKey);
711 timerCancelKey.reset();
712 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700713 }
714
James Feist3909dc82020-04-03 10:58:55 -0700715 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700716 {
717 cancelDeadlineTimer();
718
James Feist3909dc82020-04-03 10:58:55 -0700719 if (timerIterations)
720 {
721 timerIterations--;
722 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100723
James Feist3909dc82020-04-03 10:58:55 -0700724 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700725 timerQueue.add([self(shared_from_this()), timerIterations,
726 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700727 // Mark timer as not active to avoid canceling it during
728 // Connection destructor which leads to double free issue
729 self->timerCancelKey.reset();
730 if (!self->isAlive())
731 {
732 return;
733 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100734
James Feistbe5dfca2020-07-22 08:54:59 -0700735 bool loggedIn = self->req && self->req->session;
736 // allow slow uploads for logged in users
737 if (loggedIn && self->parser->get().body().size() > readCount)
738 {
739 BMCWEB_LOG_DEBUG << self.get()
740 << " restart timer - read in progress";
741 self->startDeadline(timerIterations);
742 return;
743 }
744
James Feist3909dc82020-04-03 10:58:55 -0700745 // Threshold can be used to drop slow connections
746 // to protect against slow-rate DoS attack
747 if (timerIterations)
748 {
James Feistbe5dfca2020-07-22 08:54:59 -0700749 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700750 self->startDeadline(timerIterations);
751 return;
752 }
753
754 self->close();
755 });
James Feistcb6cb492020-04-03 13:36:17 -0700756
757 if (!timerCancelKey)
758 {
759 close();
760 return;
761 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000763 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700764 }
765
766 private:
767 Adaptor adaptor;
768 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800769 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700770 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800771 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700772 boost::beast::http::request_parser<boost::beast::http::string_body>>
773 parser;
774
Ed Tanous3112a142018-11-29 15:45:10 -0800775 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776
Ed Tanousa24526d2018-12-10 15:17:59 -0800777 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700778 boost::beast::http::string_body>>
779 serializer;
780
Ed Tanousa24526d2018-12-10 15:17:59 -0800781 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700783
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700784 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000786 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700787
Ed Tanous1abe55e2018-09-05 08:30:59 -0700788 std::function<std::string()>& getCachedDateStr;
789 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000790
791 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700792 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800793};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700794} // namespace crow