blob: 3720d9d35545520575e8074dce3b6e88c5185959 [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 Tanousd32c4fa2021-09-14 13:16:51 -070019#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070020#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070021#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Ed Tanous57fce802019-05-21 13:00:34 -070033 json_html_util::dumpHtml(res.body(), res.jsonValue);
34
Ed Tanous93ef5802019-01-03 10:15:41 -080035 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070036}
37
Ed Tanous55c7b7a2018-05-22 15:27:24 -070038#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070039static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070040#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070041
Ed Tanous0260d9d2021-02-07 19:31:07 +000042// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060043constexpr unsigned int httpReqBodyLimit =
Ed Tanous0260d9d2021-02-07 19:31:07 +000044 1024 * 1024 * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070045
James Feist3909dc82020-04-03 10:58:55 -070046constexpr uint64_t loggedOutPostBodyLimit = 4096;
47
48constexpr uint32_t httpHeaderLimit = 8192;
49
50// drop all connections after 1 minute, this time limit was chosen
51// arbitrarily and can be adjusted later if needed
52static constexpr const size_t loggedInAttempts =
53 (60 / timerQueueTimeoutSeconds);
54
55static constexpr const size_t loggedOutAttempts =
56 (15 / timerQueueTimeoutSeconds);
57
Ed Tanous52cc1122020-07-18 13:51:21 -070058template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050059class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070060 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070061{
62 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070063 Connection(Handler* handlerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000064 std::function<std::string()>& getCachedDateStrF,
Ed Tanous271584a2019-07-09 16:24:22 -070065 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080066 adaptor(std::move(adaptorIn)),
Ed Tanous81ce6092020-12-17 16:54:55 +000067 handler(handlerIn), getCachedDateStr(getCachedDateStrF),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070068 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070069 {
70 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070071 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070072 parser->header_limit(httpHeaderLimit);
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 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070087 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070088 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 = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700266 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700267 userSession = persistent_data::SessionStore::getInstance()
268 .generateUserSession(
269 sslUser, req->ipAddress.to_string(),
270 unsupportedClientId,
271 persistent_data::PersistenceType::TIMEOUT);
272 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100273 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700274 BMCWEB_LOG_DEBUG
275 << this
276 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100277 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100278 return true;
279 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280 }
281
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700285 }
286
Ed Tanous1abe55e2018-09-05 08:30:59 -0700287 void start()
288 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700289
James Feist3909dc82020-04-03 10:58:55 -0700290 startDeadline(0);
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500291
Ed Tanousceac6f72018-12-02 11:58:47 -0800292 // TODO(ed) Abstract this to a more clever class with the idea of an
293 // asynchronous "start"
294 if constexpr (std::is_same_v<Adaptor,
295 boost::beast::ssl_stream<
296 boost::asio::ip::tcp::socket>>)
297 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000298 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
299 [this, self(shared_from_this())](
300 const boost::system::error_code& ec) {
301 if (ec)
302 {
303 return;
304 }
305 doReadHeaders();
306 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800307 }
308 else
309 {
310 doReadHeaders();
311 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700313
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 void handle()
315 {
316 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700317
Ed Tanous596b2032021-09-13 10:32:22 -0700318 crow::Request& thisReq = req.emplace(parser->release());
319 thisReq.session = userSession;
320
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000321 // Fetch the client IP address
322 readClientIp();
323
Ed Tanous1abe55e2018-09-05 08:30:59 -0700324 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700325 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 {
Ed Tanous596b2032021-09-13 10:32:22 -0700327 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700329 res.result(boost::beast::http::status::bad_request);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700330 completeRequest();
331 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 }
333 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700334
Ed Tanouse278c182019-03-13 16:23:37 -0700335 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700336 << " " << this << " HTTP/" << thisReq.version() / 10
337 << "." << thisReq.version() % 10 << ' '
338 << thisReq.methodString() << " " << thisReq.target()
339 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700340
341 boost::urls::error_code ec;
342 req->urlView = boost::urls::parse_relative_ref(
343 boost::urls::string_view(req->target().data(),
344 req->target().size()),
345 ec);
346 if (ec)
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700347 {
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700348 return;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700349 }
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700350 req->url = std::string_view(req->urlView.encoded_path().data(),
351 req->urlView.encoded_path().size());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700352
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700353 res.setCompleteRequestHandler(nullptr);
354 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700355
Ed Tanous596b2032021-09-13 10:32:22 -0700356 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700357 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200358
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700359 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700360 {
361 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700362 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700363 }
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700364 res.setCompleteRequestHandler([self(shared_from_this())] {
365 boost::asio::post(self->adaptor.get_executor(),
366 [self] { self->completeRequest(); });
367 });
368
Ed Tanous596b2032021-09-13 10:32:22 -0700369 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700370 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700371 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700372 "websocket"))
373 {
Ed Tanous596b2032021-09-13 10:32:22 -0700374 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700375 // delete lambda with self shared_ptr
376 // to enable connection destruction
377 res.setCompleteRequestHandler(nullptr);
378 return;
379 }
380 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700381 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700382 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700383
Ed Tanouse278c182019-03-13 16:23:37 -0700384 bool isAlive()
385 {
Ed Tanouse278c182019-03-13 16:23:37 -0700386 if constexpr (std::is_same_v<Adaptor,
387 boost::beast::ssl_stream<
388 boost::asio::ip::tcp::socket>>)
389 {
390 return adaptor.next_layer().is_open();
391 }
392 else
393 {
394 return adaptor.is_open();
395 }
396 }
397 void close()
398 {
Ed Tanouse278c182019-03-13 16:23:37 -0700399 if constexpr (std::is_same_v<Adaptor,
400 boost::beast::ssl_stream<
401 boost::asio::ip::tcp::socket>>)
402 {
403 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200404#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700405 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200406 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700407 BMCWEB_LOG_DEBUG
408 << this
409 << " Removing TLS session: " << userSession->uniqueId;
410 persistent_data::SessionStore::getInstance().removeSession(
411 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200412 }
413#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700414 }
415 else
416 {
417 adaptor.close();
418 }
419 }
420
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 void completeRequest()
422 {
423 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
424 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425
Ed Tanous0260d9d2021-02-07 19:31:07 +0000426 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700427
Ed Tanouscf099fa2021-08-25 12:37:31 -0700428 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700429
Ed Tanouse278c182019-03-13 16:23:37 -0700430 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 {
432 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
433 // isReading
434 // << ' ' << isWriting;
435 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000436
437 // delete lambda with self shared_ptr
438 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700439 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 return;
441 }
442 if (res.body().empty() && !res.jsonValue.empty())
443 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700444 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 {
446 prettyPrintJson(res);
447 }
448 else
449 {
450 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800451 res.body() = res.jsonValue.dump(
452 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700453 }
454 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700455
Ed Tanous1abe55e2018-09-05 08:30:59 -0700456 if (res.resultInt() >= 400 && res.body().empty())
457 {
458 res.body() = std::string(res.reason());
459 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700460
461 if (res.result() == boost::beast::http::status::no_content)
462 {
463 // Boost beast throws if content is provided on a no-content
464 // response. Ideally, this would never happen, but in the case that
465 // it does, we don't want to throw.
466 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100467 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700468 res.body().clear();
469 }
470
Ed Tanous1abe55e2018-09-05 08:30:59 -0700471 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
472
473 res.keepAlive(req->keepAlive());
474
475 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000476
477 // delete lambda with self shared_ptr
478 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700479 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 }
481
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500482 void readClientIp()
483 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700484 boost::asio::ip::address ip;
485 boost::system::error_code ec = getClientIp(ip);
486 if (ec)
487 {
488 return;
489 }
490 req->ipAddress = ip;
491 }
492
493 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
494 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500495 boost::system::error_code ec;
496 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
497 boost::asio::ip::tcp::endpoint endpoint =
498 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
499
500 if (ec)
501 {
502 // If remote endpoint fails keep going. "ClientOriginIPAddress"
503 // will be empty.
504 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
505 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700506 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500507 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700508 ip = endpoint.address();
509 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500510 }
511
Ed Tanous1abe55e2018-09-05 08:30:59 -0700512 private:
513 void doReadHeaders()
514 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
516
517 // Clean up any previous Connection.
518 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800519 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000520 [this,
521 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000522 std::size_t bytesTransferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 BMCWEB_LOG_ERROR << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000524 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 bool errorWhileReading = false;
526 if (ec)
527 {
528 errorWhileReading = true;
529 BMCWEB_LOG_ERROR
530 << this << " Error while reading: " << ec.message();
531 }
532 else
533 {
534 // if the adaptor isn't open anymore, and wasn't handed to a
535 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700536 if (!isAlive() &&
537 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700538 {
539 errorWhileReading = true;
540 }
541 }
542
James Feist3909dc82020-04-03 10:58:55 -0700543 cancelDeadlineTimer();
544
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545 if (errorWhileReading)
546 {
Ed Tanouse278c182019-03-13 16:23:37 -0700547 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700548 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700549 return;
550 }
551
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700552 boost::beast::http::verb method = parser->get().method();
553 readClientIp();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700554 boost::urls::error_code uriEc;
555 boost::urls::string_view uriStringView(
556 parser->get().target().data(),
557 parser->get().target().size());
558 BMCWEB_LOG_DEBUG << "Parsing URI: " << uriStringView;
559 req->urlView =
560 boost::urls::parse_relative_ref(uriStringView, uriEc);
561 if (uriEc)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700562 {
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700563 BMCWEB_LOG_ERROR << "Failed to parse URI "
564 << uriEc.message();
565 return;
Ed Tanousdc7a7932020-08-17 15:04:58 -0700566 }
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700567 req->url = std::string_view(req->urlView.encoded_path().data(),
568 req->urlView.encoded_path().size());
Ed Tanous92ccb882020-08-18 10:36:33 -0700569
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700570 boost::asio::ip::address ip;
571 if (getClientIp(ip))
572 {
573 BMCWEB_LOG_DEBUG << "Unable to get client IP";
574 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700575 sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700576 userSession = crow::authorization::authenticate(
577 req->url, ip, res, method, parser->get().base(),
578 userSession);
579 bool loggedIn = userSession != nullptr;
James Feist3909dc82020-04-03 10:58:55 -0700580 if (loggedIn)
581 {
582 startDeadline(loggedInAttempts);
583 BMCWEB_LOG_DEBUG << "Starting slow deadline";
584
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700585 req->urlParams = req->urlView.query_params();
James Feist5a7e8772020-07-22 09:08:38 -0700586
587#ifdef BMCWEB_ENABLE_DEBUG
588 std::string paramList = "";
589 for (const auto param : req->urlParams)
590 {
591 paramList += param->key() + " " + param->value() + " ";
592 }
593 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
594#endif
James Feist3909dc82020-04-03 10:58:55 -0700595 }
596 else
597 {
598 const boost::optional<uint64_t> contentLength =
599 parser->content_length();
600 if (contentLength &&
601 *contentLength > loggedOutPostBodyLimit)
602 {
603 BMCWEB_LOG_DEBUG << "Content length greater than limit "
604 << *contentLength;
605 close();
606 return;
607 }
608
609 startDeadline(loggedOutAttempts);
610 BMCWEB_LOG_DEBUG << "Starting quick deadline";
611 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 doRead();
613 });
614 }
615
616 void doRead()
617 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 BMCWEB_LOG_DEBUG << this << " doRead";
619
620 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800621 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000622 [this,
623 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000624 std::size_t bytesTransferred) {
625 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700626 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627
628 bool errorWhileReading = false;
629 if (ec)
630 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100631 BMCWEB_LOG_ERROR
632 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 errorWhileReading = true;
634 }
635 else
636 {
James Feist3909dc82020-04-03 10:58:55 -0700637 if (isAlive())
638 {
639 cancelDeadlineTimer();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700640 if (userSession != nullptr)
James Feist3909dc82020-04-03 10:58:55 -0700641 {
642 startDeadline(loggedInAttempts);
643 }
644 else
645 {
646 startDeadline(loggedOutAttempts);
647 }
648 }
649 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 {
651 errorWhileReading = true;
652 }
653 }
654 if (errorWhileReading)
655 {
656 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700657 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700659 return;
660 }
661 handle();
662 });
663 }
664
665 void doWrite()
666 {
James Feist3909dc82020-04-03 10:58:55 -0700667 bool loggedIn = req && req->session;
668 if (loggedIn)
669 {
670 startDeadline(loggedInAttempts);
671 }
672 else
673 {
674 startDeadline(loggedOutAttempts);
675 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100676 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 res.preparePayload();
678 serializer.emplace(*res.stringResponse);
679 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800680 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000681 [this,
682 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000683 std::size_t bytesTransferred) {
684 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 << " bytes";
686
James Feist54d8bb12020-07-20 13:28:59 -0700687 cancelDeadlineTimer();
688
Ed Tanous1abe55e2018-09-05 08:30:59 -0700689 if (ec)
690 {
691 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700692 return;
693 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800694 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700695 {
Ed Tanouse278c182019-03-13 16:23:37 -0700696 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700697 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700698 return;
699 }
700
701 serializer.reset();
702 BMCWEB_LOG_DEBUG << this << " Clearing response";
703 res.clear();
704 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500705 parser->body_limit(httpReqBodyLimit); // reset body limit for
706 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700707 buffer.consume(buffer.size());
708
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700709 // If the session was built from the transport, we don't need to
710 // clear it. All other sessions are generated per request.
711 if (!sessionIsFromTransport)
712 {
713 userSession = nullptr;
714 }
715
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700716 req.emplace(parser->release());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700717 doReadHeaders();
718 });
719 }
720
Ed Tanous1abe55e2018-09-05 08:30:59 -0700721 void cancelDeadlineTimer()
722 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000723 if (timerCancelKey)
724 {
725 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
726 << ' ' << *timerCancelKey;
727 timerQueue.cancel(*timerCancelKey);
728 timerCancelKey.reset();
729 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 }
731
James Feist3909dc82020-04-03 10:58:55 -0700732 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700733 {
734 cancelDeadlineTimer();
735
James Feist3909dc82020-04-03 10:58:55 -0700736 if (timerIterations)
737 {
738 timerIterations--;
739 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100740
James Feist3909dc82020-04-03 10:58:55 -0700741 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700742 timerQueue.add([self(shared_from_this()), timerIterations,
743 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700744 // Mark timer as not active to avoid canceling it during
745 // Connection destructor which leads to double free issue
746 self->timerCancelKey.reset();
747 if (!self->isAlive())
748 {
749 return;
750 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100751
James Feistbe5dfca2020-07-22 08:54:59 -0700752 bool loggedIn = self->req && self->req->session;
753 // allow slow uploads for logged in users
754 if (loggedIn && self->parser->get().body().size() > readCount)
755 {
756 BMCWEB_LOG_DEBUG << self.get()
757 << " restart timer - read in progress";
758 self->startDeadline(timerIterations);
759 return;
760 }
761
James Feist3909dc82020-04-03 10:58:55 -0700762 // Threshold can be used to drop slow connections
763 // to protect against slow-rate DoS attack
764 if (timerIterations)
765 {
James Feistbe5dfca2020-07-22 08:54:59 -0700766 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700767 self->startDeadline(timerIterations);
768 return;
769 }
770
771 self->close();
772 });
James Feistcb6cb492020-04-03 13:36:17 -0700773
774 if (!timerCancelKey)
775 {
776 close();
777 return;
778 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000780 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700781 }
782
783 private:
784 Adaptor adaptor;
785 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800786 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700787 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800788 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700789 boost::beast::http::request_parser<boost::beast::http::string_body>>
790 parser;
791
Ed Tanous3112a142018-11-29 15:45:10 -0800792 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700793
Ed Tanousa24526d2018-12-10 15:17:59 -0800794 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700795 boost::beast::http::string_body>>
796 serializer;
797
Ed Tanousa24526d2018-12-10 15:17:59 -0800798 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700799 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700800
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700801 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700802 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700803
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000804 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700805
Ed Tanous1abe55e2018-09-05 08:30:59 -0700806 std::function<std::string()>& getCachedDateStr;
807 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000808
809 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700810 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800811};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700812} // namespace crow