blob: ccc2f2830ccd5d89c7408756a75a0fd4663d7bae [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(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800269 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700270 persistent_data::PersistenceType::TIMEOUT);
271 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100272 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700273 BMCWEB_LOG_DEBUG
274 << this
275 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100276 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100277 return true;
278 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700279 }
280
Ed Tanousceac6f72018-12-02 11:58:47 -0800281 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800283 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700284 }
285
Ed Tanous1abe55e2018-09-05 08:30:59 -0700286 void start()
287 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700288
James Feist3909dc82020-04-03 10:58:55 -0700289 startDeadline(0);
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500290
Ed Tanousceac6f72018-12-02 11:58:47 -0800291 // TODO(ed) Abstract this to a more clever class with the idea of an
292 // asynchronous "start"
293 if constexpr (std::is_same_v<Adaptor,
294 boost::beast::ssl_stream<
295 boost::asio::ip::tcp::socket>>)
296 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000297 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
298 [this, self(shared_from_this())](
299 const boost::system::error_code& ec) {
300 if (ec)
301 {
302 return;
303 }
304 doReadHeaders();
305 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800306 }
307 else
308 {
309 doReadHeaders();
310 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700311 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312
Ed Tanous1abe55e2018-09-05 08:30:59 -0700313 void handle()
314 {
315 cancelDeadlineTimer();
Ed Tanousf79b7a52021-09-22 19:04:29 -0700316 std::error_code reqEc;
317 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
318 if (reqEc)
319 {
320 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
321 return;
322 }
Ed Tanous596b2032021-09-13 10:32:22 -0700323 thisReq.session = userSession;
324
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000325 // Fetch the client IP address
326 readClientIp();
327
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700329 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700330 {
Ed Tanous596b2032021-09-13 10:32:22 -0700331 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700333 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600334 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700335 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700336 }
337 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700338
Ed Tanouse278c182019-03-13 16:23:37 -0700339 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700340 << " " << this << " HTTP/" << thisReq.version() / 10
341 << "." << thisReq.version() % 10 << ' '
342 << thisReq.methodString() << " " << thisReq.target()
343 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700344
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700345 res.setCompleteRequestHandler(nullptr);
346 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700347
Ed Tanous596b2032021-09-13 10:32:22 -0700348 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700349 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200350
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700351 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600353 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700354 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800356#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700357 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700358 thisReq.session == nullptr)
359 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600360 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700361 forward_unauthorized::sendUnauthorized(
362 req->url, req->getHeaderValue("User-Agent"),
363 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600364 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700365 return;
366 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800367#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600368 res.setCompleteRequestHandler([self(shared_from_this())] {
369 boost::asio::post(self->adaptor.get_executor(),
370 [self] { self->completeRequest(); });
371 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700372
Ed Tanous596b2032021-09-13 10:32:22 -0700373 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700374 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700375 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700376 "websocket"))
377 {
Ed Tanous596b2032021-09-13 10:32:22 -0700378 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700379 // delete lambda with self shared_ptr
380 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600381 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700382 return;
383 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600384 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700385 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700386 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700387
Ed Tanouse278c182019-03-13 16:23:37 -0700388 bool isAlive()
389 {
Ed Tanouse278c182019-03-13 16:23:37 -0700390 if constexpr (std::is_same_v<Adaptor,
391 boost::beast::ssl_stream<
392 boost::asio::ip::tcp::socket>>)
393 {
394 return adaptor.next_layer().is_open();
395 }
396 else
397 {
398 return adaptor.is_open();
399 }
400 }
401 void close()
402 {
Ed Tanouse278c182019-03-13 16:23:37 -0700403 if constexpr (std::is_same_v<Adaptor,
404 boost::beast::ssl_stream<
405 boost::asio::ip::tcp::socket>>)
406 {
407 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600408#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
409 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200410 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700411 BMCWEB_LOG_DEBUG
412 << this
413 << " Removing TLS session: " << userSession->uniqueId;
414 persistent_data::SessionStore::getInstance().removeSession(
415 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200416 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600417#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700418 }
419 else
420 {
421 adaptor.close();
422 }
423 }
424
Gunnar Mills9062d472021-11-16 11:37:47 -0600425 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700426 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700427 if (!req)
428 {
429 return;
430 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
432 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700433
Ed Tanous0260d9d2021-02-07 19:31:07 +0000434 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700435
Ed Tanouscf099fa2021-08-25 12:37:31 -0700436 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700437
Ed Tanouse278c182019-03-13 16:23:37 -0700438 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 {
440 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
441 // isReading
442 // << ' ' << isWriting;
443 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000444
445 // delete lambda with self shared_ptr
446 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700447 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700448 return;
449 }
450 if (res.body().empty() && !res.jsonValue.empty())
451 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700452 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700453 {
454 prettyPrintJson(res);
455 }
456 else
457 {
458 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800459 res.body() = res.jsonValue.dump(
460 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 }
462 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700463
Ed Tanous1abe55e2018-09-05 08:30:59 -0700464 if (res.resultInt() >= 400 && res.body().empty())
465 {
466 res.body() = std::string(res.reason());
467 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700468
469 if (res.result() == boost::beast::http::status::no_content)
470 {
471 // Boost beast throws if content is provided on a no-content
472 // response. Ideally, this would never happen, but in the case that
473 // it does, we don't want to throw.
474 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100475 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700476 res.body().clear();
477 }
478
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
480
481 res.keepAlive(req->keepAlive());
482
Gunnar Mills9062d472021-11-16 11:37:47 -0600483 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000484
485 // delete lambda with self shared_ptr
486 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700487 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700488 }
489
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500490 void readClientIp()
491 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700492 boost::asio::ip::address ip;
493 boost::system::error_code ec = getClientIp(ip);
494 if (ec)
495 {
496 return;
497 }
498 req->ipAddress = ip;
499 }
500
501 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
502 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500503 boost::system::error_code ec;
504 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
505 boost::asio::ip::tcp::endpoint endpoint =
506 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
507
508 if (ec)
509 {
510 // If remote endpoint fails keep going. "ClientOriginIPAddress"
511 // will be empty.
512 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
513 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700514 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500515 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700516 ip = endpoint.address();
517 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500518 }
519
Ed Tanous1abe55e2018-09-05 08:30:59 -0700520 private:
521 void doReadHeaders()
522 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
524
525 // Clean up any previous Connection.
526 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800527 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000528 [this,
529 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000530 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500531 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000532 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700533 bool errorWhileReading = false;
534 if (ec)
535 {
536 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500537 if (ec == boost::asio::error::eof)
538 {
539 BMCWEB_LOG_WARNING
540 << this << " Error while reading: " << ec.message();
541 }
542 else
543 {
544 BMCWEB_LOG_ERROR
545 << this << " Error while reading: " << ec.message();
546 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700547 }
548 else
549 {
550 // if the adaptor isn't open anymore, and wasn't handed to a
551 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700552 if (!isAlive() &&
553 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700554 {
555 errorWhileReading = true;
556 }
557 }
558
James Feist3909dc82020-04-03 10:58:55 -0700559 cancelDeadlineTimer();
560
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 if (errorWhileReading)
562 {
Ed Tanouse278c182019-03-13 16:23:37 -0700563 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 return;
566 }
567
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700568 readClientIp();
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;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800576#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
577 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700578 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700579 ip, res, method, parser->get().base(), userSession);
Nan Zhou8682c5a2021-11-13 11:00:07 -0800580#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700581 bool loggedIn = userSession != nullptr;
James Feist3909dc82020-04-03 10:58:55 -0700582 if (loggedIn)
583 {
584 startDeadline(loggedInAttempts);
585 BMCWEB_LOG_DEBUG << "Starting slow deadline";
James Feist3909dc82020-04-03 10:58:55 -0700586 }
587 else
588 {
589 const boost::optional<uint64_t> contentLength =
590 parser->content_length();
591 if (contentLength &&
592 *contentLength > loggedOutPostBodyLimit)
593 {
594 BMCWEB_LOG_DEBUG << "Content length greater than limit "
595 << *contentLength;
596 close();
597 return;
598 }
599
600 startDeadline(loggedOutAttempts);
601 BMCWEB_LOG_DEBUG << "Starting quick deadline";
602 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700603 doRead();
604 });
605 }
606
607 void doRead()
608 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 BMCWEB_LOG_DEBUG << this << " doRead";
610
611 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800612 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000613 [this,
614 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000615 std::size_t bytesTransferred) {
616 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618
619 bool errorWhileReading = false;
620 if (ec)
621 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100622 BMCWEB_LOG_ERROR
623 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700624 errorWhileReading = true;
625 }
626 else
627 {
James Feist3909dc82020-04-03 10:58:55 -0700628 if (isAlive())
629 {
630 cancelDeadlineTimer();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700631 if (userSession != nullptr)
James Feist3909dc82020-04-03 10:58:55 -0700632 {
633 startDeadline(loggedInAttempts);
634 }
635 else
636 {
637 startDeadline(loggedOutAttempts);
638 }
639 }
640 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 {
642 errorWhileReading = true;
643 }
644 }
645 if (errorWhileReading)
646 {
647 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700648 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 return;
651 }
652 handle();
653 });
654 }
655
Gunnar Mills9062d472021-11-16 11:37:47 -0600656 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 {
James Feist3909dc82020-04-03 10:58:55 -0700658 bool loggedIn = req && req->session;
659 if (loggedIn)
660 {
661 startDeadline(loggedInAttempts);
662 }
663 else
664 {
665 startDeadline(loggedOutAttempts);
666 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100667 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600668 res.preparePayload();
669 serializer.emplace(*res.stringResponse);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700670 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800671 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000672 [this,
673 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000674 std::size_t bytesTransferred) {
675 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 << " bytes";
677
James Feist54d8bb12020-07-20 13:28:59 -0700678 cancelDeadlineTimer();
679
Ed Tanous1abe55e2018-09-05 08:30:59 -0700680 if (ec)
681 {
682 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700683 return;
684 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800685 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700686 {
Ed Tanouse278c182019-03-13 16:23:37 -0700687 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700688 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700689 return;
690 }
691
692 serializer.reset();
693 BMCWEB_LOG_DEBUG << this << " Clearing response";
694 res.clear();
695 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500696 parser->body_limit(httpReqBodyLimit); // reset body limit for
697 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700698 buffer.consume(buffer.size());
699
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700700 // If the session was built from the transport, we don't need to
701 // clear it. All other sessions are generated per request.
702 if (!sessionIsFromTransport)
703 {
704 userSession = nullptr;
705 }
706
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700707 // Destroy the Request via the std::optional
708 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700709 doReadHeaders();
710 });
711 }
712
Ed Tanous1abe55e2018-09-05 08:30:59 -0700713 void cancelDeadlineTimer()
714 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000715 if (timerCancelKey)
716 {
717 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
718 << ' ' << *timerCancelKey;
719 timerQueue.cancel(*timerCancelKey);
720 timerCancelKey.reset();
721 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700722 }
723
James Feist3909dc82020-04-03 10:58:55 -0700724 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725 {
726 cancelDeadlineTimer();
727
James Feist3909dc82020-04-03 10:58:55 -0700728 if (timerIterations)
729 {
730 timerIterations--;
731 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100732
James Feist3909dc82020-04-03 10:58:55 -0700733 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700734 timerQueue.add([self(shared_from_this()), timerIterations,
735 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700736 // Mark timer as not active to avoid canceling it during
737 // Connection destructor which leads to double free issue
738 self->timerCancelKey.reset();
739 if (!self->isAlive())
740 {
741 return;
742 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100743
James Feistbe5dfca2020-07-22 08:54:59 -0700744 bool loggedIn = self->req && self->req->session;
745 // allow slow uploads for logged in users
746 if (loggedIn && self->parser->get().body().size() > readCount)
747 {
748 BMCWEB_LOG_DEBUG << self.get()
749 << " restart timer - read in progress";
750 self->startDeadline(timerIterations);
751 return;
752 }
753
James Feist3909dc82020-04-03 10:58:55 -0700754 // Threshold can be used to drop slow connections
755 // to protect against slow-rate DoS attack
756 if (timerIterations)
757 {
James Feistbe5dfca2020-07-22 08:54:59 -0700758 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700759 self->startDeadline(timerIterations);
760 return;
761 }
762
763 self->close();
764 });
James Feistcb6cb492020-04-03 13:36:17 -0700765
766 if (!timerCancelKey)
767 {
768 close();
769 return;
770 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700771 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000772 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700773 }
774
775 private:
776 Adaptor adaptor;
777 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800778 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800780 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700781 boost::beast::http::request_parser<boost::beast::http::string_body>>
782 parser;
783
Ed Tanous3112a142018-11-29 15:45:10 -0800784 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785
Ed Tanousa24526d2018-12-10 15:17:59 -0800786 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700787 boost::beast::http::string_body>>
788 serializer;
789
Ed Tanousa24526d2018-12-10 15:17:59 -0800790 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700791 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700792
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700793 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700794 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700795
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000796 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700797
Ed Tanous1abe55e2018-09-05 08:30:59 -0700798 std::function<std::string()>& getCachedDateStr;
799 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000800
801 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700802 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800803};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700804} // namespace crow