blob: 4482f8d8e542519867d86d93e1923cad14883c17 [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);
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020073
74#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Jonathan Doman83deb7d2020-11-16 17:00:22 -080075 std::error_code error;
76 std::filesystem::path caPath(ensuressl::trustStorePath);
77 auto caAvailable = !std::filesystem::is_empty(caPath, error);
78 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070079 if (caAvailable && persistent_data::SessionStore::getInstance()
80 .getAuthMethodsConfig()
81 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010082 {
83 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070084 std::string id = "bmcweb";
85 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010086 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070087 reinterpret_cast<const unsigned char*>(id.c_str()),
88 static_cast<unsigned int>(id.length()));
89 if (ret == 0)
90 {
91 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
92 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010093 }
94
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010095 adaptor.set_verify_callback([this](
96 bool preverified,
97 boost::asio::ssl::verify_context& ctx) {
98 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070099 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100100 .getAuthMethodsConfig()
101 .tls)
102 {
103 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200104 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100105 }
106
107 // We always return true to allow full auth flow
108 if (!preverified)
109 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100110 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100111 return true;
112 }
113
114 X509_STORE_CTX* cts = ctx.native_handle();
115 if (cts == nullptr)
116 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100117 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 return true;
119 }
120
121 // Get certificate
122 X509* peerCert =
123 X509_STORE_CTX_get_current_cert(ctx.native_handle());
124 if (peerCert == nullptr)
125 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100126 BMCWEB_LOG_DEBUG << this
127 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100128 return true;
129 }
130
131 // Check if certificate is OK
132 int error = X509_STORE_CTX_get_error(cts);
133 if (error != X509_V_OK)
134 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100135 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100136 return true;
137 }
138 // Check that we have reached final certificate in chain
139 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
140 if (depth != 0)
141
142 {
143 BMCWEB_LOG_DEBUG
144 << this << " Certificate verification in progress (depth "
145 << depth << "), waiting to reach final depth";
146 return true;
147 }
148
149 BMCWEB_LOG_DEBUG << this
150 << " Certificate verification of final depth";
151
152 // Verify KeyUsage
153 bool isKeyUsageDigitalSignature = false;
154 bool isKeyUsageKeyAgreement = false;
155
156 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000157 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158
159 if (usage == nullptr)
160 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100161 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100162 return true;
163 }
164
165 for (int i = 0; i < usage->length; i++)
166 {
167 if (KU_DIGITAL_SIGNATURE & usage->data[i])
168 {
169 isKeyUsageDigitalSignature = true;
170 }
171 if (KU_KEY_AGREEMENT & usage->data[i])
172 {
173 isKeyUsageKeyAgreement = true;
174 }
175 }
176
177 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
178 {
179 BMCWEB_LOG_DEBUG << this
180 << " Certificate ExtendedKeyUsage does "
181 "not allow provided certificate to "
182 "be used for user authentication";
183 return true;
184 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200185 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100186
187 // Determine that ExtendedKeyUsage includes Client Auth
188
Ed Tanous23a21a12020-07-25 04:45:05 +0000189 stack_st_ASN1_OBJECT* extUsage =
190 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
191 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192
193 if (extUsage == nullptr)
194 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100195 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100196 return true;
197 }
198
199 bool isExKeyUsageClientAuth = false;
200 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
201 {
202 if (NID_client_auth ==
203 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
204 {
205 isExKeyUsageClientAuth = true;
206 break;
207 }
208 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200209 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100210
211 // Certificate has to have proper key usages set
212 if (!isExKeyUsageClientAuth)
213 {
214 BMCWEB_LOG_DEBUG << this
215 << " Certificate ExtendedKeyUsage does "
216 "not allow provided certificate to "
217 "be used for user authentication";
218 return true;
219 }
220 std::string sslUser;
221 // Extract username contained in CommonName
222 sslUser.resize(256, '\0');
223
224 int status = X509_NAME_get_text_by_NID(
225 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
226 static_cast<int>(sslUser.size()));
227
228 if (status == -1)
229 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100230 BMCWEB_LOG_DEBUG
231 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100232 return true;
233 }
234
235 size_t lastChar = sslUser.find('\0');
236 if (lastChar == std::string::npos || lastChar == 0)
237 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100238 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100239 return true;
240 }
241 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530242 std::string unsupportedClientId = "";
243 session = persistent_data::SessionStore::getInstance()
244 .generateUserSession(
245 sslUser, req->ipAddress.to_string(),
246 unsupportedClientId,
247 persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100248 if (auto sp = session.lock())
249 {
250 BMCWEB_LOG_DEBUG << this
251 << " Generating TLS session: " << sp->uniqueId;
252 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100253 return true;
254 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200255#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
256
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700257#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700258 connectionCount++;
259 BMCWEB_LOG_DEBUG << this << " Connection open, total "
260 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700261#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700263
Ed Tanous1abe55e2018-09-05 08:30:59 -0700264 ~Connection()
265 {
266 res.completeRequestHandler = nullptr;
267 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700268#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700269 connectionCount--;
270 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
271 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700272#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700273 }
274
Ed Tanousceac6f72018-12-02 11:58:47 -0800275 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700276 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800277 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700278 }
279
Ed Tanous1abe55e2018-09-05 08:30:59 -0700280 void start()
281 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700282
James Feist3909dc82020-04-03 10:58:55 -0700283 startDeadline(0);
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500284
285 // Fetch the client IP address
286 readClientIp();
287
Ed Tanousceac6f72018-12-02 11:58:47 -0800288 // TODO(ed) Abstract this to a more clever class with the idea of an
289 // asynchronous "start"
290 if constexpr (std::is_same_v<Adaptor,
291 boost::beast::ssl_stream<
292 boost::asio::ip::tcp::socket>>)
293 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000294 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
295 [this, self(shared_from_this())](
296 const boost::system::error_code& ec) {
297 if (ec)
298 {
299 return;
300 }
301 doReadHeaders();
302 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800303 }
304 else
305 {
306 doReadHeaders();
307 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700308 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700309
Ed Tanous1abe55e2018-09-05 08:30:59 -0700310 void handle()
311 {
312 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700313
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315
Ed Tanous1abe55e2018-09-05 08:30:59 -0700316 // Check for HTTP version 1.1.
317 if (req->version() == 11)
318 {
319 if (req->getHeaderValue(boost::beast::http::field::host).empty())
320 {
321 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700322 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700323 }
324 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700325
Ed Tanouse278c182019-03-13 16:23:37 -0700326 BMCWEB_LOG_INFO << "Request: "
327 << " " << this << " HTTP/" << req->version() / 10 << "."
328 << req->version() % 10 << ' ' << req->methodString()
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500329 << " " << req->target() << " " << req->ipAddress;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700332
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 if (!isInvalidRequest)
334 {
335 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700336 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanouse278c182019-03-13 16:23:37 -0700338 req->ioService = static_cast<decltype(req->ioService)>(
339 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200340
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 if (!res.completed)
342 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000343 needToCallAfterHandlers = true;
344 res.completeRequestHandler = [self(shared_from_this())] {
Wludzik, Jozefc7d34222020-10-19 12:59:41 +0200345 boost::asio::post(self->adaptor.get_executor(),
346 [self] { self->completeRequest(); });
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000347 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700348 if (req->isUpgrade() &&
349 boost::iequals(
350 req->getHeaderValue(boost::beast::http::field::upgrade),
351 "websocket"))
352 {
353 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000354 // delete lambda with self shared_ptr
355 // to enable connection destruction
356 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700357 return;
358 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700360 }
361 else
362 {
363 completeRequest();
364 }
365 }
366 else
367 {
368 completeRequest();
369 }
370 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700371
Ed Tanouse278c182019-03-13 16:23:37 -0700372 bool isAlive()
373 {
374
375 if constexpr (std::is_same_v<Adaptor,
376 boost::beast::ssl_stream<
377 boost::asio::ip::tcp::socket>>)
378 {
379 return adaptor.next_layer().is_open();
380 }
381 else
382 {
383 return adaptor.is_open();
384 }
385 }
386 void close()
387 {
Ed Tanouse278c182019-03-13 16:23:37 -0700388 if constexpr (std::is_same_v<Adaptor,
389 boost::beast::ssl_stream<
390 boost::asio::ip::tcp::socket>>)
391 {
392 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200393#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
394 if (auto sp = session.lock())
395 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100396 BMCWEB_LOG_DEBUG << this
397 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200398 persistent_data::SessionStore::getInstance().removeSession(sp);
399 }
400#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700401 }
402 else
403 {
404 adaptor.close();
405 }
406 }
407
Ed Tanous1abe55e2018-09-05 08:30:59 -0700408 void completeRequest()
409 {
410 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
411 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700412
Ed Tanous0260d9d2021-02-07 19:31:07 +0000413 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700414
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 if (needToCallAfterHandlers)
416 {
James Feist3909dc82020-04-03 10:58:55 -0700417 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700419
Ed Tanouse278c182019-03-13 16:23:37 -0700420 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 {
422 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
423 // isReading
424 // << ' ' << isWriting;
425 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000426
427 // delete lambda with self shared_ptr
428 // to enable connection destruction
429 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700430 return;
431 }
432 if (res.body().empty() && !res.jsonValue.empty())
433 {
434 if (http_helpers::requestPrefersHtml(*req))
435 {
436 prettyPrintJson(res);
437 }
438 else
439 {
440 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800441 res.body() = res.jsonValue.dump(
442 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700443 }
444 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700445
Ed Tanous1abe55e2018-09-05 08:30:59 -0700446 if (res.resultInt() >= 400 && res.body().empty())
447 {
448 res.body() = std::string(res.reason());
449 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700450
451 if (res.result() == boost::beast::http::status::no_content)
452 {
453 // Boost beast throws if content is provided on a no-content
454 // response. Ideally, this would never happen, but in the case that
455 // it does, we don't want to throw.
456 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100457 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700458 res.body().clear();
459 }
460
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
462
463 res.keepAlive(req->keepAlive());
464
465 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000466
467 // delete lambda with self shared_ptr
468 // to enable connection destruction
469 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700470 }
471
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500472 void readClientIp()
473 {
474 boost::system::error_code ec;
475 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
476 boost::asio::ip::tcp::endpoint endpoint =
477 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
478
479 if (ec)
480 {
481 // If remote endpoint fails keep going. "ClientOriginIPAddress"
482 // will be empty.
483 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
484 << ec;
485 }
486 else
487 {
488 req->ipAddress = endpoint.address();
489 }
490 }
491
Ed Tanous1abe55e2018-09-05 08:30:59 -0700492 private:
493 void doReadHeaders()
494 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700495 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
496
497 // Clean up any previous Connection.
498 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800499 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000500 [this,
501 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000502 std::size_t bytesTransferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 BMCWEB_LOG_ERROR << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000504 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700505 bool errorWhileReading = false;
506 if (ec)
507 {
508 errorWhileReading = true;
509 BMCWEB_LOG_ERROR
510 << this << " Error while reading: " << ec.message();
511 }
512 else
513 {
514 // if the adaptor isn't open anymore, and wasn't handed to a
515 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700516 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 {
518 errorWhileReading = true;
519 }
520 }
521
James Feist3909dc82020-04-03 10:58:55 -0700522 cancelDeadlineTimer();
523
Ed Tanous1abe55e2018-09-05 08:30:59 -0700524 if (errorWhileReading)
525 {
Ed Tanouse278c182019-03-13 16:23:37 -0700526 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700527 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528 return;
529 }
530
James Feist3909dc82020-04-03 10:58:55 -0700531 if (!req)
532 {
533 close();
534 return;
535 }
536
Ed Tanousdc7a7932020-08-17 15:04:58 -0700537 // Note, despite the bmcweb coding policy on use of exceptions
538 // for error handling, this one particular use of exceptions is
539 // deemed acceptible, as it solved a significant error handling
540 // problem that resulted in seg faults, the exact thing that the
541 // exceptions rule is trying to avoid. If at some point,
542 // boost::urls makes the parser object public (or we port it
543 // into bmcweb locally) this will be replaced with
544 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700545
Ed Tanousdc7a7932020-08-17 15:04:58 -0700546 try
547 {
548 req->urlView = boost::urls::url_view(req->target());
549 req->url = req->urlView.encoded_path();
550 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700551 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700552 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700553 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700554 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700555
James Feist6964c982020-07-28 16:10:23 -0700556 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700557
558 bool loggedIn = req && req->session;
559 if (loggedIn)
560 {
561 startDeadline(loggedInAttempts);
562 BMCWEB_LOG_DEBUG << "Starting slow deadline";
563
James Feist5a7e8772020-07-22 09:08:38 -0700564 req->urlParams = req->urlView.params();
565
566#ifdef BMCWEB_ENABLE_DEBUG
567 std::string paramList = "";
568 for (const auto param : req->urlParams)
569 {
570 paramList += param->key() + " " + param->value() + " ";
571 }
572 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
573#endif
James Feist3909dc82020-04-03 10:58:55 -0700574 }
575 else
576 {
577 const boost::optional<uint64_t> contentLength =
578 parser->content_length();
579 if (contentLength &&
580 *contentLength > loggedOutPostBodyLimit)
581 {
582 BMCWEB_LOG_DEBUG << "Content length greater than limit "
583 << *contentLength;
584 close();
585 return;
586 }
587
588 startDeadline(loggedOutAttempts);
589 BMCWEB_LOG_DEBUG << "Starting quick deadline";
590 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700591 doRead();
592 });
593 }
594
595 void doRead()
596 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 BMCWEB_LOG_DEBUG << this << " doRead";
598
599 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800600 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000601 [this,
602 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000603 std::size_t bytesTransferred) {
604 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700606
607 bool errorWhileReading = false;
608 if (ec)
609 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100610 BMCWEB_LOG_ERROR
611 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 errorWhileReading = true;
613 }
614 else
615 {
James Feist3909dc82020-04-03 10:58:55 -0700616 if (isAlive())
617 {
618 cancelDeadlineTimer();
619 bool loggedIn = req && req->session;
620 if (loggedIn)
621 {
622 startDeadline(loggedInAttempts);
623 }
624 else
625 {
626 startDeadline(loggedOutAttempts);
627 }
628 }
629 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 {
631 errorWhileReading = true;
632 }
633 }
634 if (errorWhileReading)
635 {
636 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700637 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 return;
640 }
641 handle();
642 });
643 }
644
645 void doWrite()
646 {
James Feist3909dc82020-04-03 10:58:55 -0700647 bool loggedIn = req && req->session;
648 if (loggedIn)
649 {
650 startDeadline(loggedInAttempts);
651 }
652 else
653 {
654 startDeadline(loggedOutAttempts);
655 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100656 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 res.preparePayload();
658 serializer.emplace(*res.stringResponse);
659 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800660 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000661 [this,
662 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000663 std::size_t bytesTransferred) {
664 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700665 << " bytes";
666
James Feist54d8bb12020-07-20 13:28:59 -0700667 cancelDeadlineTimer();
668
Ed Tanous1abe55e2018-09-05 08:30:59 -0700669 if (ec)
670 {
671 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700672 return;
673 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800674 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 {
Ed Tanouse278c182019-03-13 16:23:37 -0700676 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 return;
679 }
680
681 serializer.reset();
682 BMCWEB_LOG_DEBUG << this << " Clearing response";
683 res.clear();
684 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500685 parser->body_limit(httpReqBodyLimit); // reset body limit for
686 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700687 buffer.consume(buffer.size());
688
689 req.emplace(parser->get());
690 doReadHeaders();
691 });
692 }
693
Ed Tanous1abe55e2018-09-05 08:30:59 -0700694 void cancelDeadlineTimer()
695 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000696 if (timerCancelKey)
697 {
698 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
699 << ' ' << *timerCancelKey;
700 timerQueue.cancel(*timerCancelKey);
701 timerCancelKey.reset();
702 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700703 }
704
James Feist3909dc82020-04-03 10:58:55 -0700705 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700706 {
707 cancelDeadlineTimer();
708
James Feist3909dc82020-04-03 10:58:55 -0700709 if (timerIterations)
710 {
711 timerIterations--;
712 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100713
James Feist3909dc82020-04-03 10:58:55 -0700714 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700715 timerQueue.add([self(shared_from_this()), timerIterations,
716 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700717 // Mark timer as not active to avoid canceling it during
718 // Connection destructor which leads to double free issue
719 self->timerCancelKey.reset();
720 if (!self->isAlive())
721 {
722 return;
723 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100724
James Feistbe5dfca2020-07-22 08:54:59 -0700725 bool loggedIn = self->req && self->req->session;
726 // allow slow uploads for logged in users
727 if (loggedIn && self->parser->get().body().size() > readCount)
728 {
729 BMCWEB_LOG_DEBUG << self.get()
730 << " restart timer - read in progress";
731 self->startDeadline(timerIterations);
732 return;
733 }
734
James Feist3909dc82020-04-03 10:58:55 -0700735 // Threshold can be used to drop slow connections
736 // to protect against slow-rate DoS attack
737 if (timerIterations)
738 {
James Feistbe5dfca2020-07-22 08:54:59 -0700739 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700740 self->startDeadline(timerIterations);
741 return;
742 }
743
744 self->close();
745 });
James Feistcb6cb492020-04-03 13:36:17 -0700746
747 if (!timerCancelKey)
748 {
749 close();
750 return;
751 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000753 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754 }
755
756 private:
757 Adaptor adaptor;
758 Handler* handler;
759
Ed Tanousa24526d2018-12-10 15:17:59 -0800760 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700761 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800762 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700763 boost::beast::http::request_parser<boost::beast::http::string_body>>
764 parser;
765
Ed Tanous3112a142018-11-29 15:45:10 -0800766 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700767
Ed Tanousa24526d2018-12-10 15:17:59 -0800768 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 boost::beast::http::string_body>>
770 serializer;
771
Ed Tanousa24526d2018-12-10 15:17:59 -0800772 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700773 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700774
775 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000777 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700778
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779 bool needToCallAfterHandlers{};
780 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700781
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782 std::function<std::string()>& getCachedDateStr;
783 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000784
785 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700786 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800787};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700788} // namespace crow