blob: 0b58e9b6f5038d85e9033f15d4a487b5cc4a2275 [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"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanouse0d918b2018-03-27 17:41:04 -070010#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070011#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080012#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080013#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070014#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080015#include <boost/asio/steady_timer.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 Tanous6fbdbca2021-12-06 14:36:06 -080038static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070039
Ed Tanous0260d9d2021-02-07 19:31:07 +000040// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080041constexpr uint64_t httpReqBodyLimit =
42 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
James Feist3909dc82020-04-03 10:58:55 -070044constexpr uint64_t loggedOutPostBodyLimit = 4096;
45
46constexpr uint32_t httpHeaderLimit = 8192;
47
Ed Tanous52cc1122020-07-18 13:51:21 -070048template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050049class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070050 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070051{
52 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080053 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000054 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 handler(handlerIn), timer(std::move(timerIn)),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
60 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070062 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020063
64#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070065 prepareMutualTls();
66#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
67
Ed Tanous40aa0582021-07-14 13:24:40 -070068 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080069
Ed Tanous40aa0582021-07-14 13:24:40 -070070 BMCWEB_LOG_DEBUG << this << " Connection open, total "
71 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070072 }
73
74 ~Connection()
75 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070076 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount--;
80 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
Ed Tanousecd6a3a2022-01-07 09:18:40 -080084 Connection(const Connection&) = delete;
85 Connection(Connection&&) = delete;
86 Connection& operator=(const Connection&) = delete;
87 Connection& operator=(Connection&&) = delete;
88
Ed Tanous40aa0582021-07-14 13:24:40 -070089 void prepareMutualTls()
90 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080091 std::error_code error;
92 std::filesystem::path caPath(ensuressl::trustStorePath);
93 auto caAvailable = !std::filesystem::is_empty(caPath, error);
94 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070095 if (caAvailable && persistent_data::SessionStore::getInstance()
96 .getAuthMethodsConfig()
97 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010098 {
99 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700100 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800101
Ed Tanous9eb808c2022-01-25 10:19:23 -0800102 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800103 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800104 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700105 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800106 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700107 static_cast<unsigned int>(id.length()));
108 if (ret == 0)
109 {
110 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
111 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100112 }
113
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100114 adaptor.set_verify_callback([this](
115 bool preverified,
116 boost::asio::ssl::verify_context& ctx) {
117 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700118 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100119 .getAuthMethodsConfig()
120 .tls)
121 {
122 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200123 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100124 }
125
126 // We always return true to allow full auth flow
127 if (!preverified)
128 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100129 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100130 return true;
131 }
132
133 X509_STORE_CTX* cts = ctx.native_handle();
134 if (cts == nullptr)
135 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100136 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100137 return true;
138 }
139
140 // Get certificate
141 X509* peerCert =
142 X509_STORE_CTX_get_current_cert(ctx.native_handle());
143 if (peerCert == nullptr)
144 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100145 BMCWEB_LOG_DEBUG << this
146 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100147 return true;
148 }
149
150 // Check if certificate is OK
151 int error = X509_STORE_CTX_get_error(cts);
152 if (error != X509_V_OK)
153 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100154 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100155 return true;
156 }
157 // Check that we have reached final certificate in chain
158 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
159 if (depth != 0)
160
161 {
162 BMCWEB_LOG_DEBUG
163 << this << " Certificate verification in progress (depth "
164 << depth << "), waiting to reach final depth";
165 return true;
166 }
167
168 BMCWEB_LOG_DEBUG << this
169 << " Certificate verification of final depth";
170
171 // Verify KeyUsage
172 bool isKeyUsageDigitalSignature = false;
173 bool isKeyUsageKeyAgreement = false;
174
175 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000176 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100177
178 if (usage == nullptr)
179 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100180 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100181 return true;
182 }
183
184 for (int i = 0; i < usage->length; i++)
185 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800186 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
187 unsigned char usageChar = usage->data[i];
188 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100189 {
190 isKeyUsageDigitalSignature = true;
191 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800192 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100193 {
194 isKeyUsageKeyAgreement = true;
195 }
196 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700197 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100198
199 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
200 {
201 BMCWEB_LOG_DEBUG << this
202 << " Certificate ExtendedKeyUsage does "
203 "not allow provided certificate to "
204 "be used for user authentication";
205 return true;
206 }
207
208 // Determine that ExtendedKeyUsage includes Client Auth
209
Ed Tanous23a21a12020-07-25 04:45:05 +0000210 stack_st_ASN1_OBJECT* extUsage =
211 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
212 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100213
214 if (extUsage == nullptr)
215 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100216 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100217 return true;
218 }
219
220 bool isExKeyUsageClientAuth = false;
221 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
222 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800223 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
224 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
225 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100226 {
227 isExKeyUsageClientAuth = true;
228 break;
229 }
230 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200231 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100232
233 // Certificate has to have proper key usages set
234 if (!isExKeyUsageClientAuth)
235 {
236 BMCWEB_LOG_DEBUG << this
237 << " Certificate ExtendedKeyUsage does "
238 "not allow provided certificate to "
239 "be used for user authentication";
240 return true;
241 }
242 std::string sslUser;
243 // Extract username contained in CommonName
244 sslUser.resize(256, '\0');
245
246 int status = X509_NAME_get_text_by_NID(
247 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
248 static_cast<int>(sslUser.size()));
249
250 if (status == -1)
251 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100252 BMCWEB_LOG_DEBUG
253 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100254 return true;
255 }
256
257 size_t lastChar = sslUser.find('\0');
258 if (lastChar == std::string::npos || lastChar == 0)
259 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100260 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100261 return true;
262 }
263 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530264 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700265 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700266 userSession = persistent_data::SessionStore::getInstance()
267 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800268 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700269 persistent_data::PersistenceType::TIMEOUT);
270 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100271 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700272 BMCWEB_LOG_DEBUG
273 << this
274 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100275 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100276 return true;
277 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700278 }
279
Ed Tanousceac6f72018-12-02 11:58:47 -0800280 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700283 }
284
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 void start()
286 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800287 if (connectionCount >= 100)
288 {
289 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
290 return;
291 }
292
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800293 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500294
Ed Tanousceac6f72018-12-02 11:58:47 -0800295 // TODO(ed) Abstract this to a more clever class with the idea of an
296 // asynchronous "start"
297 if constexpr (std::is_same_v<Adaptor,
298 boost::beast::ssl_stream<
299 boost::asio::ip::tcp::socket>>)
300 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000301 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
302 [this, self(shared_from_this())](
303 const boost::system::error_code& ec) {
304 if (ec)
305 {
306 return;
307 }
308 doReadHeaders();
309 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800310 }
311 else
312 {
313 doReadHeaders();
314 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700316
Ed Tanous1abe55e2018-09-05 08:30:59 -0700317 void handle()
318 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700319 std::error_code reqEc;
320 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
321 if (reqEc)
322 {
323 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
324 return;
325 }
Ed Tanous596b2032021-09-13 10:32:22 -0700326 thisReq.session = userSession;
327
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000328 // Fetch the client IP address
329 readClientIp();
330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700332 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 {
Ed Tanous596b2032021-09-13 10:32:22 -0700334 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700336 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600337 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700338 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700339 }
340 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700341
Ed Tanouse278c182019-03-13 16:23:37 -0700342 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700343 << " " << this << " HTTP/" << thisReq.version() / 10
344 << "." << thisReq.version() % 10 << ' '
345 << thisReq.methodString() << " " << thisReq.target()
346 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700347
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700348 res.setCompleteRequestHandler(nullptr);
349 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700350
Ed Tanous596b2032021-09-13 10:32:22 -0700351 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700352 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200353
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700354 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600356 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700357 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800359#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700360 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700361 thisReq.session == nullptr)
362 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600363 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700364 forward_unauthorized::sendUnauthorized(
365 req->url, req->getHeaderValue("User-Agent"),
366 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600367 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700368 return;
369 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800370#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600371 res.setCompleteRequestHandler([self(shared_from_this())] {
372 boost::asio::post(self->adaptor.get_executor(),
373 [self] { self->completeRequest(); });
374 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700375
Ed Tanous596b2032021-09-13 10:32:22 -0700376 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700377 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700378 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700379 "websocket"))
380 {
Ed Tanous596b2032021-09-13 10:32:22 -0700381 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700382 // delete lambda with self shared_ptr
383 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600384 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700385 return;
386 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600387 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700388 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700389 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700390
Ed Tanouse278c182019-03-13 16:23:37 -0700391 bool isAlive()
392 {
Ed Tanouse278c182019-03-13 16:23:37 -0700393 if constexpr (std::is_same_v<Adaptor,
394 boost::beast::ssl_stream<
395 boost::asio::ip::tcp::socket>>)
396 {
397 return adaptor.next_layer().is_open();
398 }
399 else
400 {
401 return adaptor.is_open();
402 }
403 }
404 void close()
405 {
Ed Tanouse278c182019-03-13 16:23:37 -0700406 if constexpr (std::is_same_v<Adaptor,
407 boost::beast::ssl_stream<
408 boost::asio::ip::tcp::socket>>)
409 {
410 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600411#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
412 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200413 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700414 BMCWEB_LOG_DEBUG
415 << this
416 << " Removing TLS session: " << userSession->uniqueId;
417 persistent_data::SessionStore::getInstance().removeSession(
418 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200419 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600420#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700421 }
422 else
423 {
424 adaptor.close();
425 }
426 }
427
Gunnar Mills9062d472021-11-16 11:37:47 -0600428 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700430 if (!req)
431 {
432 return;
433 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700434 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
435 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700436
Ed Tanous0260d9d2021-02-07 19:31:07 +0000437 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700438
Ed Tanouscf099fa2021-08-25 12:37:31 -0700439 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700440
Ed Tanouse278c182019-03-13 16:23:37 -0700441 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700442 {
443 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
444 // isReading
445 // << ' ' << isWriting;
446 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000447
448 // delete lambda with self shared_ptr
449 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700450 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700451 return;
452 }
453 if (res.body().empty() && !res.jsonValue.empty())
454 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700455 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700456 {
457 prettyPrintJson(res);
458 }
459 else
460 {
461 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800462 res.body() = res.jsonValue.dump(
463 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700464 }
465 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700466
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 if (res.resultInt() >= 400 && res.body().empty())
468 {
469 res.body() = std::string(res.reason());
470 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700471
472 if (res.result() == boost::beast::http::status::no_content)
473 {
474 // Boost beast throws if content is provided on a no-content
475 // response. Ideally, this would never happen, but in the case that
476 // it does, we don't want to throw.
477 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100478 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700479 res.body().clear();
480 }
481
Ed Tanous1abe55e2018-09-05 08:30:59 -0700482 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
483
484 res.keepAlive(req->keepAlive());
485
Gunnar Mills9062d472021-11-16 11:37:47 -0600486 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000487
488 // delete lambda with self shared_ptr
489 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700490 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700491 }
492
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500493 void readClientIp()
494 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700495 boost::asio::ip::address ip;
496 boost::system::error_code ec = getClientIp(ip);
497 if (ec)
498 {
499 return;
500 }
501 req->ipAddress = ip;
502 }
503
504 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
505 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500506 boost::system::error_code ec;
507 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
508 boost::asio::ip::tcp::endpoint endpoint =
509 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
510
511 if (ec)
512 {
513 // If remote endpoint fails keep going. "ClientOriginIPAddress"
514 // will be empty.
515 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
516 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700517 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500518 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700519 ip = endpoint.address();
520 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500521 }
522
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 private:
524 void doReadHeaders()
525 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700526 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
527
528 // Clean up any previous Connection.
529 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800530 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000531 [this,
532 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000533 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500534 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000535 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700536 bool errorWhileReading = false;
537 if (ec)
538 {
539 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500540 if (ec == boost::asio::error::eof)
541 {
542 BMCWEB_LOG_WARNING
543 << this << " Error while reading: " << ec.message();
544 }
545 else
546 {
547 BMCWEB_LOG_ERROR
548 << this << " Error while reading: " << ec.message();
549 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700550 }
551 else
552 {
553 // if the adaptor isn't open anymore, and wasn't handed to a
554 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700555 if (!isAlive() &&
556 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 {
558 errorWhileReading = true;
559 }
560 }
561
James Feist3909dc82020-04-03 10:58:55 -0700562 cancelDeadlineTimer();
563
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 if (errorWhileReading)
565 {
Ed Tanouse278c182019-03-13 16:23:37 -0700566 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700568 return;
569 }
570
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700571 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700572
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700573 boost::asio::ip::address ip;
574 if (getClientIp(ip))
575 {
576 BMCWEB_LOG_DEBUG << "Unable to get client IP";
577 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700578 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800579#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
580 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700581 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700582 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800583
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700584 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800585 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700586 {
587 const boost::optional<uint64_t> contentLength =
588 parser->content_length();
589 if (contentLength &&
590 *contentLength > loggedOutPostBodyLimit)
591 {
592 BMCWEB_LOG_DEBUG << "Content length greater than limit "
593 << *contentLength;
594 close();
595 return;
596 }
597
James Feist3909dc82020-04-03 10:58:55 -0700598 BMCWEB_LOG_DEBUG << "Starting quick deadline";
599 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800600#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601
Ed Tanous1abe55e2018-09-05 08:30:59 -0700602 doRead();
603 });
604 }
605
606 void doRead()
607 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800609 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800611 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000612 [this,
613 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000614 std::size_t bytesTransferred) {
615 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800617 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 if (ec)
619 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100620 BMCWEB_LOG_ERROR
621 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700622 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700624 return;
625 }
626 handle();
627 });
628 }
629
Gunnar Mills9062d472021-11-16 11:37:47 -0600630 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100632 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600633 res.preparePayload();
634 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800635 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800637 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000638 [this,
639 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000640 std::size_t bytesTransferred) {
641 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 << " bytes";
643
James Feist54d8bb12020-07-20 13:28:59 -0700644 cancelDeadlineTimer();
645
Ed Tanous1abe55e2018-09-05 08:30:59 -0700646 if (ec)
647 {
648 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 return;
650 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800651 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700652 {
Ed Tanouse278c182019-03-13 16:23:37 -0700653 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700655 return;
656 }
657
658 serializer.reset();
659 BMCWEB_LOG_DEBUG << this << " Clearing response";
660 res.clear();
661 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500662 parser->body_limit(httpReqBodyLimit); // reset body limit for
663 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 buffer.consume(buffer.size());
665
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700666 // If the session was built from the transport, we don't need to
667 // clear it. All other sessions are generated per request.
668 if (!sessionIsFromTransport)
669 {
670 userSession = nullptr;
671 }
672
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700673 // Destroy the Request via the std::optional
674 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 doReadHeaders();
676 });
677 }
678
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 void cancelDeadlineTimer()
680 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800681 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700682 }
683
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800684 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 {
686 cancelDeadlineTimer();
687
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800688 std::chrono::seconds timeout(15);
689 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800690 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800691 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700692 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800693 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700694 return;
695 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800696
697 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
698 timer.expires_after(timeout);
699 timer.async_wait([weakSelf](const boost::system::error_code ec) {
700 // Note, we are ignoring other types of errors here; If the timer
701 // failed for any reason, we should still close the connection
702
703 std::shared_ptr<Connection<Adaptor, Handler>> self =
704 weakSelf.lock();
705 if (!self)
706 {
707 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
708 return;
709 }
710 if (ec == boost::asio::error::operation_aborted)
711 {
712 // Canceled wait means the path succeeeded.
713 return;
714 }
715 if (ec)
716 {
717 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
718 }
719
720 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
721
722 self->close();
723 });
724
725 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700726 }
727
728 private:
729 Adaptor adaptor;
730 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800731 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700732 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800733 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700734 boost::beast::http::request_parser<boost::beast::http::string_body>>
735 parser;
736
Ed Tanous3112a142018-11-29 15:45:10 -0800737 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738
Ed Tanousa24526d2018-12-10 15:17:59 -0800739 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700740 boost::beast::http::string_body>>
741 serializer;
742
Ed Tanousa24526d2018-12-10 15:17:59 -0800743 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700745
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700746 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700747 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800749 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000752
753 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700754 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800755
756 using std::enable_shared_from_this<
757 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800758};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700759} // namespace crow