blob: 2e9ff3894b4febf852a5b34db367fd1352aa9681 [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();
Ed Tanousf79b7a52021-09-22 19:04:29 -0700317 std::error_code reqEc;
318 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
319 if (reqEc)
320 {
321 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
322 return;
323 }
Ed Tanous596b2032021-09-13 10:32:22 -0700324 thisReq.session = userSession;
325
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000326 // Fetch the client IP address
327 readClientIp();
328
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700330 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 {
Ed Tanous596b2032021-09-13 10:32:22 -0700332 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700334 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600335 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700336 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700337 }
338 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700339
Ed Tanouse278c182019-03-13 16:23:37 -0700340 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700341 << " " << this << " HTTP/" << thisReq.version() / 10
342 << "." << thisReq.version() % 10 << ' '
343 << thisReq.methodString() << " " << thisReq.target()
344 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700345
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700346 res.setCompleteRequestHandler(nullptr);
347 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700348
Ed Tanous596b2032021-09-13 10:32:22 -0700349 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700350 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200351
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700352 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700353 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600354 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700355 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800357#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700358 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700359 thisReq.session == nullptr)
360 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600361 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700362 forward_unauthorized::sendUnauthorized(
363 req->url, req->getHeaderValue("User-Agent"),
364 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600365 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700366 return;
367 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800368#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600369 res.setCompleteRequestHandler([self(shared_from_this())] {
370 boost::asio::post(self->adaptor.get_executor(),
371 [self] { self->completeRequest(); });
372 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700373
Ed Tanous596b2032021-09-13 10:32:22 -0700374 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700375 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700376 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700377 "websocket"))
378 {
Ed Tanous596b2032021-09-13 10:32:22 -0700379 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700380 // delete lambda with self shared_ptr
381 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600382 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700383 return;
384 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600385 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700386 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700387 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700388
Ed Tanouse278c182019-03-13 16:23:37 -0700389 bool isAlive()
390 {
Ed Tanouse278c182019-03-13 16:23:37 -0700391 if constexpr (std::is_same_v<Adaptor,
392 boost::beast::ssl_stream<
393 boost::asio::ip::tcp::socket>>)
394 {
395 return adaptor.next_layer().is_open();
396 }
397 else
398 {
399 return adaptor.is_open();
400 }
401 }
402 void close()
403 {
Ed Tanouse278c182019-03-13 16:23:37 -0700404 if constexpr (std::is_same_v<Adaptor,
405 boost::beast::ssl_stream<
406 boost::asio::ip::tcp::socket>>)
407 {
408 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600409#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
410 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200411 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700412 BMCWEB_LOG_DEBUG
413 << this
414 << " Removing TLS session: " << userSession->uniqueId;
415 persistent_data::SessionStore::getInstance().removeSession(
416 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200417 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600418#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700419 }
420 else
421 {
422 adaptor.close();
423 }
424 }
425
Gunnar Mills9062d472021-11-16 11:37:47 -0600426 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700428 if (!req)
429 {
430 return;
431 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700432 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
433 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700434
Ed Tanous0260d9d2021-02-07 19:31:07 +0000435 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700436
Ed Tanouscf099fa2021-08-25 12:37:31 -0700437 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700438
Ed Tanouse278c182019-03-13 16:23:37 -0700439 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 {
441 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
442 // isReading
443 // << ' ' << isWriting;
444 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000445
446 // delete lambda with self shared_ptr
447 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700448 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700449 return;
450 }
451 if (res.body().empty() && !res.jsonValue.empty())
452 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700453 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700454 {
455 prettyPrintJson(res);
456 }
457 else
458 {
459 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800460 res.body() = res.jsonValue.dump(
461 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700462 }
463 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700464
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 if (res.resultInt() >= 400 && res.body().empty())
466 {
467 res.body() = std::string(res.reason());
468 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700469
470 if (res.result() == boost::beast::http::status::no_content)
471 {
472 // Boost beast throws if content is provided on a no-content
473 // response. Ideally, this would never happen, but in the case that
474 // it does, we don't want to throw.
475 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100476 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700477 res.body().clear();
478 }
479
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
481
482 res.keepAlive(req->keepAlive());
483
Gunnar Mills9062d472021-11-16 11:37:47 -0600484 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000485
486 // delete lambda with self shared_ptr
487 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700488 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 }
490
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500491 void readClientIp()
492 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700493 boost::asio::ip::address ip;
494 boost::system::error_code ec = getClientIp(ip);
495 if (ec)
496 {
497 return;
498 }
499 req->ipAddress = ip;
500 }
501
502 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
503 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500504 boost::system::error_code ec;
505 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
506 boost::asio::ip::tcp::endpoint endpoint =
507 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
508
509 if (ec)
510 {
511 // If remote endpoint fails keep going. "ClientOriginIPAddress"
512 // will be empty.
513 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
514 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700515 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500516 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700517 ip = endpoint.address();
518 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500519 }
520
Ed Tanous1abe55e2018-09-05 08:30:59 -0700521 private:
522 void doReadHeaders()
523 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700524 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
525
526 // Clean up any previous Connection.
527 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800528 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000529 [this,
530 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000531 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500532 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000533 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700534 bool errorWhileReading = false;
535 if (ec)
536 {
537 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500538 if (ec == boost::asio::error::eof)
539 {
540 BMCWEB_LOG_WARNING
541 << this << " Error while reading: " << ec.message();
542 }
543 else
544 {
545 BMCWEB_LOG_ERROR
546 << this << " Error while reading: " << ec.message();
547 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700548 }
549 else
550 {
551 // if the adaptor isn't open anymore, and wasn't handed to a
552 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700553 if (!isAlive() &&
554 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700555 {
556 errorWhileReading = true;
557 }
558 }
559
James Feist3909dc82020-04-03 10:58:55 -0700560 cancelDeadlineTimer();
561
Ed Tanous1abe55e2018-09-05 08:30:59 -0700562 if (errorWhileReading)
563 {
Ed Tanouse278c182019-03-13 16:23:37 -0700564 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 return;
567 }
568
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700569 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700570
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700571 boost::asio::ip::address ip;
572 if (getClientIp(ip))
573 {
574 BMCWEB_LOG_DEBUG << "Unable to get client IP";
575 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700576 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800577#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
578 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700579 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700580 ip, res, method, parser->get().base(), userSession);
Nan Zhou8682c5a2021-11-13 11:00:07 -0800581#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700582 bool loggedIn = userSession != nullptr;
James Feist3909dc82020-04-03 10:58:55 -0700583 if (loggedIn)
584 {
585 startDeadline(loggedInAttempts);
586 BMCWEB_LOG_DEBUG << "Starting slow deadline";
James Feist3909dc82020-04-03 10:58:55 -0700587 }
588 else
589 {
590 const boost::optional<uint64_t> contentLength =
591 parser->content_length();
592 if (contentLength &&
593 *contentLength > loggedOutPostBodyLimit)
594 {
595 BMCWEB_LOG_DEBUG << "Content length greater than limit "
596 << *contentLength;
597 close();
598 return;
599 }
600
601 startDeadline(loggedOutAttempts);
602 BMCWEB_LOG_DEBUG << "Starting quick deadline";
603 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 doRead();
605 });
606 }
607
608 void doRead()
609 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 BMCWEB_LOG_DEBUG << this << " doRead";
611
612 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800613 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000614 [this,
615 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000616 std::size_t bytesTransferred) {
617 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619
620 bool errorWhileReading = false;
621 if (ec)
622 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100623 BMCWEB_LOG_ERROR
624 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 errorWhileReading = true;
626 }
627 else
628 {
James Feist3909dc82020-04-03 10:58:55 -0700629 if (isAlive())
630 {
631 cancelDeadlineTimer();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700632 if (userSession != nullptr)
James Feist3909dc82020-04-03 10:58:55 -0700633 {
634 startDeadline(loggedInAttempts);
635 }
636 else
637 {
638 startDeadline(loggedOutAttempts);
639 }
640 }
641 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 {
643 errorWhileReading = true;
644 }
645 }
646 if (errorWhileReading)
647 {
648 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700649 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 return;
652 }
653 handle();
654 });
655 }
656
Gunnar Mills9062d472021-11-16 11:37:47 -0600657 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 {
James Feist3909dc82020-04-03 10:58:55 -0700659 bool loggedIn = req && req->session;
660 if (loggedIn)
661 {
662 startDeadline(loggedInAttempts);
663 }
664 else
665 {
666 startDeadline(loggedOutAttempts);
667 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100668 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600669 res.preparePayload();
670 serializer.emplace(*res.stringResponse);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800672 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000673 [this,
674 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000675 std::size_t bytesTransferred) {
676 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 << " bytes";
678
James Feist54d8bb12020-07-20 13:28:59 -0700679 cancelDeadlineTimer();
680
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 if (ec)
682 {
683 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 return;
685 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800686 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700687 {
Ed Tanouse278c182019-03-13 16:23:37 -0700688 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700689 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700690 return;
691 }
692
693 serializer.reset();
694 BMCWEB_LOG_DEBUG << this << " Clearing response";
695 res.clear();
696 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500697 parser->body_limit(httpReqBodyLimit); // reset body limit for
698 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700699 buffer.consume(buffer.size());
700
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700701 // If the session was built from the transport, we don't need to
702 // clear it. All other sessions are generated per request.
703 if (!sessionIsFromTransport)
704 {
705 userSession = nullptr;
706 }
707
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700708 // Destroy the Request via the std::optional
709 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700710 doReadHeaders();
711 });
712 }
713
Ed Tanous1abe55e2018-09-05 08:30:59 -0700714 void cancelDeadlineTimer()
715 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000716 if (timerCancelKey)
717 {
718 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
719 << ' ' << *timerCancelKey;
720 timerQueue.cancel(*timerCancelKey);
721 timerCancelKey.reset();
722 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700723 }
724
James Feist3909dc82020-04-03 10:58:55 -0700725 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700726 {
727 cancelDeadlineTimer();
728
James Feist3909dc82020-04-03 10:58:55 -0700729 if (timerIterations)
730 {
731 timerIterations--;
732 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100733
James Feist3909dc82020-04-03 10:58:55 -0700734 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700735 timerQueue.add([self(shared_from_this()), timerIterations,
736 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700737 // Mark timer as not active to avoid canceling it during
738 // Connection destructor which leads to double free issue
739 self->timerCancelKey.reset();
740 if (!self->isAlive())
741 {
742 return;
743 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100744
James Feistbe5dfca2020-07-22 08:54:59 -0700745 bool loggedIn = self->req && self->req->session;
746 // allow slow uploads for logged in users
747 if (loggedIn && self->parser->get().body().size() > readCount)
748 {
749 BMCWEB_LOG_DEBUG << self.get()
750 << " restart timer - read in progress";
751 self->startDeadline(timerIterations);
752 return;
753 }
754
James Feist3909dc82020-04-03 10:58:55 -0700755 // Threshold can be used to drop slow connections
756 // to protect against slow-rate DoS attack
757 if (timerIterations)
758 {
James Feistbe5dfca2020-07-22 08:54:59 -0700759 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700760 self->startDeadline(timerIterations);
761 return;
762 }
763
764 self->close();
765 });
James Feistcb6cb492020-04-03 13:36:17 -0700766
767 if (!timerCancelKey)
768 {
769 close();
770 return;
771 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700772 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000773 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700774 }
775
776 private:
777 Adaptor adaptor;
778 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800779 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700780 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800781 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782 boost::beast::http::request_parser<boost::beast::http::string_body>>
783 parser;
784
Ed Tanous3112a142018-11-29 15:45:10 -0800785 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700786
Ed Tanousa24526d2018-12-10 15:17:59 -0800787 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700788 boost::beast::http::string_body>>
789 serializer;
790
Ed Tanousa24526d2018-12-10 15:17:59 -0800791 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700792 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700793
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700794 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700795 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700796
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000797 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700798
Ed Tanous1abe55e2018-09-05 08:30:59 -0700799 std::function<std::string()>& getCachedDateStr;
800 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000801
802 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700803 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800804};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700805} // namespace crow