blob: 4df9300c1499903ffac83397968c688271028d76 [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
Ed Tanous40aa0582021-07-14 13:24:40 -070075 prepareMutualTls();
76#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
77
78#ifdef BMCWEB_ENABLE_DEBUG
79 connectionCount++;
80 BMCWEB_LOG_DEBUG << this << " Connection open, total "
81 << connectionCount;
82#endif
83 }
84
85 ~Connection()
86 {
87 res.completeRequestHandler = nullptr;
88 cancelDeadlineTimer();
89#ifdef BMCWEB_ENABLE_DEBUG
90 connectionCount--;
91 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
92 << connectionCount;
93#endif
94 }
95
96 void prepareMutualTls()
97 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080098 std::error_code error;
99 std::filesystem::path caPath(ensuressl::trustStorePath);
100 auto caAvailable = !std::filesystem::is_empty(caPath, error);
101 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700102 if (caAvailable && persistent_data::SessionStore::getInstance()
103 .getAuthMethodsConfig()
104 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100105 {
106 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700107 std::string id = "bmcweb";
108 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100109 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700110 reinterpret_cast<const unsigned char*>(id.c_str()),
111 static_cast<unsigned int>(id.length()));
112 if (ret == 0)
113 {
114 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
115 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100116 }
117
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 adaptor.set_verify_callback([this](
119 bool preverified,
120 boost::asio::ssl::verify_context& ctx) {
121 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700122 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100123 .getAuthMethodsConfig()
124 .tls)
125 {
126 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200127 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100128 }
129
130 // We always return true to allow full auth flow
131 if (!preverified)
132 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100133 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100134 return true;
135 }
136
137 X509_STORE_CTX* cts = ctx.native_handle();
138 if (cts == nullptr)
139 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100140 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100141 return true;
142 }
143
144 // Get certificate
145 X509* peerCert =
146 X509_STORE_CTX_get_current_cert(ctx.native_handle());
147 if (peerCert == nullptr)
148 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100149 BMCWEB_LOG_DEBUG << this
150 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100151 return true;
152 }
153
154 // Check if certificate is OK
155 int error = X509_STORE_CTX_get_error(cts);
156 if (error != X509_V_OK)
157 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100158 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100159 return true;
160 }
161 // Check that we have reached final certificate in chain
162 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
163 if (depth != 0)
164
165 {
166 BMCWEB_LOG_DEBUG
167 << this << " Certificate verification in progress (depth "
168 << depth << "), waiting to reach final depth";
169 return true;
170 }
171
172 BMCWEB_LOG_DEBUG << this
173 << " Certificate verification of final depth";
174
175 // Verify KeyUsage
176 bool isKeyUsageDigitalSignature = false;
177 bool isKeyUsageKeyAgreement = false;
178
179 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000180 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100181
182 if (usage == nullptr)
183 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100184 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100185 return true;
186 }
187
188 for (int i = 0; i < usage->length; i++)
189 {
190 if (KU_DIGITAL_SIGNATURE & usage->data[i])
191 {
192 isKeyUsageDigitalSignature = true;
193 }
194 if (KU_KEY_AGREEMENT & usage->data[i])
195 {
196 isKeyUsageKeyAgreement = true;
197 }
198 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700199 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100200
201 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
202 {
203 BMCWEB_LOG_DEBUG << this
204 << " Certificate ExtendedKeyUsage does "
205 "not allow provided certificate to "
206 "be used for user authentication";
207 return true;
208 }
209
210 // Determine that ExtendedKeyUsage includes Client Auth
211
Ed Tanous23a21a12020-07-25 04:45:05 +0000212 stack_st_ASN1_OBJECT* extUsage =
213 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
214 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100215
216 if (extUsage == nullptr)
217 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100218 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100219 return true;
220 }
221
222 bool isExKeyUsageClientAuth = false;
223 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
224 {
225 if (NID_client_auth ==
226 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
227 {
228 isExKeyUsageClientAuth = true;
229 break;
230 }
231 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200232 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100233
234 // Certificate has to have proper key usages set
235 if (!isExKeyUsageClientAuth)
236 {
237 BMCWEB_LOG_DEBUG << this
238 << " Certificate ExtendedKeyUsage does "
239 "not allow provided certificate to "
240 "be used for user authentication";
241 return true;
242 }
243 std::string sslUser;
244 // Extract username contained in CommonName
245 sslUser.resize(256, '\0');
246
247 int status = X509_NAME_get_text_by_NID(
248 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
249 static_cast<int>(sslUser.size()));
250
251 if (status == -1)
252 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100253 BMCWEB_LOG_DEBUG
254 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100255 return true;
256 }
257
258 size_t lastChar = sslUser.find('\0');
259 if (lastChar == std::string::npos || lastChar == 0)
260 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100261 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100262 return true;
263 }
264 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530265 std::string unsupportedClientId = "";
266 session = persistent_data::SessionStore::getInstance()
267 .generateUserSession(
268 sslUser, req->ipAddress.to_string(),
269 unsupportedClientId,
270 persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100271 if (auto sp = session.lock())
272 {
273 BMCWEB_LOG_DEBUG << this
274 << " Generating TLS session: " << sp->uniqueId;
275 }
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 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700320
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 // Check for HTTP version 1.1.
322 if (req->version() == 11)
323 {
324 if (req->getHeaderValue(boost::beast::http::field::host).empty())
325 {
326 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700327 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 }
329 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanouse278c182019-03-13 16:23:37 -0700331 BMCWEB_LOG_INFO << "Request: "
332 << " " << this << " HTTP/" << req->version() / 10 << "."
333 << req->version() % 10 << ' ' << req->methodString()
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500334 << " " << req->target() << " " << req->ipAddress;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700335
Ed Tanous1abe55e2018-09-05 08:30:59 -0700336 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 if (!isInvalidRequest)
339 {
340 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700341 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700342
Ed Tanouse278c182019-03-13 16:23:37 -0700343 req->ioService = static_cast<decltype(req->ioService)>(
344 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200345
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 if (!res.completed)
347 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000348 needToCallAfterHandlers = true;
349 res.completeRequestHandler = [self(shared_from_this())] {
Wludzik, Jozefc7d34222020-10-19 12:59:41 +0200350 boost::asio::post(self->adaptor.get_executor(),
351 [self] { self->completeRequest(); });
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000352 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700353 if (req->isUpgrade() &&
354 boost::iequals(
355 req->getHeaderValue(boost::beast::http::field::upgrade),
356 "websocket"))
357 {
358 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000359 // delete lambda with self shared_ptr
360 // to enable connection destruction
361 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700362 return;
363 }
zhanghch058d1b46d2021-04-01 11:18:24 +0800364 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
365 handler->handle(*req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700366 }
367 else
368 {
369 completeRequest();
370 }
371 }
372 else
373 {
374 completeRequest();
375 }
376 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700377
Ed Tanouse278c182019-03-13 16:23:37 -0700378 bool isAlive()
379 {
380
381 if constexpr (std::is_same_v<Adaptor,
382 boost::beast::ssl_stream<
383 boost::asio::ip::tcp::socket>>)
384 {
385 return adaptor.next_layer().is_open();
386 }
387 else
388 {
389 return adaptor.is_open();
390 }
391 }
392 void close()
393 {
Ed Tanouse278c182019-03-13 16:23:37 -0700394 if constexpr (std::is_same_v<Adaptor,
395 boost::beast::ssl_stream<
396 boost::asio::ip::tcp::socket>>)
397 {
398 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200399#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
400 if (auto sp = session.lock())
401 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100402 BMCWEB_LOG_DEBUG << this
403 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200404 persistent_data::SessionStore::getInstance().removeSession(sp);
405 }
406#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700407 }
408 else
409 {
410 adaptor.close();
411 }
412 }
413
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 void completeRequest()
415 {
416 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
417 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700418
Ed Tanous0260d9d2021-02-07 19:31:07 +0000419 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700420
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 if (needToCallAfterHandlers)
422 {
James Feist3909dc82020-04-03 10:58:55 -0700423 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700424 }
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
435 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 return;
437 }
438 if (res.body().empty() && !res.jsonValue.empty())
439 {
440 if (http_helpers::requestPrefersHtml(*req))
441 {
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
475 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700476 }
477
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500478 void readClientIp()
479 {
480 boost::system::error_code ec;
481 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
482 boost::asio::ip::tcp::endpoint endpoint =
483 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
484
485 if (ec)
486 {
487 // If remote endpoint fails keep going. "ClientOriginIPAddress"
488 // will be empty.
489 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
490 << ec;
491 }
492 else
493 {
494 req->ipAddress = endpoint.address();
495 }
496 }
497
Ed Tanous1abe55e2018-09-05 08:30:59 -0700498 private:
499 void doReadHeaders()
500 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700501 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
502
503 // Clean up any previous Connection.
504 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800505 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000506 [this,
507 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000508 std::size_t bytesTransferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700509 BMCWEB_LOG_ERROR << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000510 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700511 bool errorWhileReading = false;
512 if (ec)
513 {
514 errorWhileReading = true;
515 BMCWEB_LOG_ERROR
516 << this << " Error while reading: " << ec.message();
517 }
518 else
519 {
520 // if the adaptor isn't open anymore, and wasn't handed to a
521 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700522 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 {
524 errorWhileReading = true;
525 }
526 }
527
James Feist3909dc82020-04-03 10:58:55 -0700528 cancelDeadlineTimer();
529
Ed Tanous1abe55e2018-09-05 08:30:59 -0700530 if (errorWhileReading)
531 {
Ed Tanouse278c182019-03-13 16:23:37 -0700532 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700533 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700534 return;
535 }
536
James Feist3909dc82020-04-03 10:58:55 -0700537 if (!req)
538 {
539 close();
540 return;
541 }
542
Ed Tanousdc7a7932020-08-17 15:04:58 -0700543 // Note, despite the bmcweb coding policy on use of exceptions
544 // for error handling, this one particular use of exceptions is
545 // deemed acceptible, as it solved a significant error handling
546 // problem that resulted in seg faults, the exact thing that the
547 // exceptions rule is trying to avoid. If at some point,
548 // boost::urls makes the parser object public (or we port it
549 // into bmcweb locally) this will be replaced with
550 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700551
Ed Tanousdc7a7932020-08-17 15:04:58 -0700552 try
553 {
554 req->urlView = boost::urls::url_view(req->target());
555 req->url = req->urlView.encoded_path();
556 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700557 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700558 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700559 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700560 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700561
James Feist6964c982020-07-28 16:10:23 -0700562 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700563
564 bool loggedIn = req && req->session;
565 if (loggedIn)
566 {
567 startDeadline(loggedInAttempts);
568 BMCWEB_LOG_DEBUG << "Starting slow deadline";
569
James Feist5a7e8772020-07-22 09:08:38 -0700570 req->urlParams = req->urlView.params();
571
572#ifdef BMCWEB_ENABLE_DEBUG
573 std::string paramList = "";
574 for (const auto param : req->urlParams)
575 {
576 paramList += param->key() + " " + param->value() + " ";
577 }
578 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
579#endif
James Feist3909dc82020-04-03 10:58:55 -0700580 }
581 else
582 {
583 const boost::optional<uint64_t> contentLength =
584 parser->content_length();
585 if (contentLength &&
586 *contentLength > loggedOutPostBodyLimit)
587 {
588 BMCWEB_LOG_DEBUG << "Content length greater than limit "
589 << *contentLength;
590 close();
591 return;
592 }
593
594 startDeadline(loggedOutAttempts);
595 BMCWEB_LOG_DEBUG << "Starting quick deadline";
596 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 doRead();
598 });
599 }
600
601 void doRead()
602 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700603 BMCWEB_LOG_DEBUG << this << " doRead";
604
605 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800606 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000607 [this,
608 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000609 std::size_t bytesTransferred) {
610 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612
613 bool errorWhileReading = false;
614 if (ec)
615 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100616 BMCWEB_LOG_ERROR
617 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 errorWhileReading = true;
619 }
620 else
621 {
James Feist3909dc82020-04-03 10:58:55 -0700622 if (isAlive())
623 {
624 cancelDeadlineTimer();
625 bool loggedIn = req && req->session;
626 if (loggedIn)
627 {
628 startDeadline(loggedInAttempts);
629 }
630 else
631 {
632 startDeadline(loggedOutAttempts);
633 }
634 }
635 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 {
637 errorWhileReading = true;
638 }
639 }
640 if (errorWhileReading)
641 {
642 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700643 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 return;
646 }
647 handle();
648 });
649 }
650
651 void doWrite()
652 {
James Feist3909dc82020-04-03 10:58:55 -0700653 bool loggedIn = req && req->session;
654 if (loggedIn)
655 {
656 startDeadline(loggedInAttempts);
657 }
658 else
659 {
660 startDeadline(loggedOutAttempts);
661 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100662 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700663 res.preparePayload();
664 serializer.emplace(*res.stringResponse);
665 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800666 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000667 [this,
668 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000669 std::size_t bytesTransferred) {
670 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 << " bytes";
672
James Feist54d8bb12020-07-20 13:28:59 -0700673 cancelDeadlineTimer();
674
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 if (ec)
676 {
677 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 return;
679 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800680 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 {
Ed Tanouse278c182019-03-13 16:23:37 -0700682 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700683 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 return;
685 }
686
687 serializer.reset();
688 BMCWEB_LOG_DEBUG << this << " Clearing response";
689 res.clear();
690 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500691 parser->body_limit(httpReqBodyLimit); // reset body limit for
692 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700693 buffer.consume(buffer.size());
694
695 req.emplace(parser->get());
696 doReadHeaders();
697 });
698 }
699
Ed Tanous1abe55e2018-09-05 08:30:59 -0700700 void cancelDeadlineTimer()
701 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000702 if (timerCancelKey)
703 {
704 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
705 << ' ' << *timerCancelKey;
706 timerQueue.cancel(*timerCancelKey);
707 timerCancelKey.reset();
708 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700709 }
710
James Feist3909dc82020-04-03 10:58:55 -0700711 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700712 {
713 cancelDeadlineTimer();
714
James Feist3909dc82020-04-03 10:58:55 -0700715 if (timerIterations)
716 {
717 timerIterations--;
718 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100719
James Feist3909dc82020-04-03 10:58:55 -0700720 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700721 timerQueue.add([self(shared_from_this()), timerIterations,
722 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700723 // Mark timer as not active to avoid canceling it during
724 // Connection destructor which leads to double free issue
725 self->timerCancelKey.reset();
726 if (!self->isAlive())
727 {
728 return;
729 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100730
James Feistbe5dfca2020-07-22 08:54:59 -0700731 bool loggedIn = self->req && self->req->session;
732 // allow slow uploads for logged in users
733 if (loggedIn && self->parser->get().body().size() > readCount)
734 {
735 BMCWEB_LOG_DEBUG << self.get()
736 << " restart timer - read in progress";
737 self->startDeadline(timerIterations);
738 return;
739 }
740
James Feist3909dc82020-04-03 10:58:55 -0700741 // Threshold can be used to drop slow connections
742 // to protect against slow-rate DoS attack
743 if (timerIterations)
744 {
James Feistbe5dfca2020-07-22 08:54:59 -0700745 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700746 self->startDeadline(timerIterations);
747 return;
748 }
749
750 self->close();
751 });
James Feistcb6cb492020-04-03 13:36:17 -0700752
753 if (!timerCancelKey)
754 {
755 close();
756 return;
757 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000759 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760 }
761
762 private:
763 Adaptor adaptor;
764 Handler* handler;
765
Ed Tanousa24526d2018-12-10 15:17:59 -0800766 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700767 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800768 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 boost::beast::http::request_parser<boost::beast::http::string_body>>
770 parser;
771
Ed Tanous3112a142018-11-29 15:45:10 -0800772 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700773
Ed Tanousa24526d2018-12-10 15:17:59 -0800774 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700775 boost::beast::http::string_body>>
776 serializer;
777
Ed Tanousa24526d2018-12-10 15:17:59 -0800778 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700780
781 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000783 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700784
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785 bool needToCallAfterHandlers{};
786 bool needToStartReadAfterComplete{};
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