blob: 84f5c18ece22768978224c87e4ae7f3b5ccb550e [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
102 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
103 auto* idC = reinterpret_cast<const unsigned char*>(id.c_str());
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700104 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800105 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700106 static_cast<unsigned int>(id.length()));
107 if (ret == 0)
108 {
109 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
110 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100111 }
112
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100113 adaptor.set_verify_callback([this](
114 bool preverified,
115 boost::asio::ssl::verify_context& ctx) {
116 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700117 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 .getAuthMethodsConfig()
119 .tls)
120 {
121 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200122 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100123 }
124
125 // We always return true to allow full auth flow
126 if (!preverified)
127 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100128 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100129 return true;
130 }
131
132 X509_STORE_CTX* cts = ctx.native_handle();
133 if (cts == nullptr)
134 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100135 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100136 return true;
137 }
138
139 // Get certificate
140 X509* peerCert =
141 X509_STORE_CTX_get_current_cert(ctx.native_handle());
142 if (peerCert == nullptr)
143 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100144 BMCWEB_LOG_DEBUG << this
145 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100146 return true;
147 }
148
149 // Check if certificate is OK
150 int error = X509_STORE_CTX_get_error(cts);
151 if (error != X509_V_OK)
152 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100153 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100154 return true;
155 }
156 // Check that we have reached final certificate in chain
157 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
158 if (depth != 0)
159
160 {
161 BMCWEB_LOG_DEBUG
162 << this << " Certificate verification in progress (depth "
163 << depth << "), waiting to reach final depth";
164 return true;
165 }
166
167 BMCWEB_LOG_DEBUG << this
168 << " Certificate verification of final depth";
169
170 // Verify KeyUsage
171 bool isKeyUsageDigitalSignature = false;
172 bool isKeyUsageKeyAgreement = false;
173
174 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000175 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100176
177 if (usage == nullptr)
178 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100179 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100180 return true;
181 }
182
183 for (int i = 0; i < usage->length; i++)
184 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800185 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
186 unsigned char usageChar = usage->data[i];
187 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100188 {
189 isKeyUsageDigitalSignature = true;
190 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800191 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192 {
193 isKeyUsageKeyAgreement = true;
194 }
195 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700196 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100197
198 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
199 {
200 BMCWEB_LOG_DEBUG << this
201 << " Certificate ExtendedKeyUsage does "
202 "not allow provided certificate to "
203 "be used for user authentication";
204 return true;
205 }
206
207 // Determine that ExtendedKeyUsage includes Client Auth
208
Ed Tanous23a21a12020-07-25 04:45:05 +0000209 stack_st_ASN1_OBJECT* extUsage =
210 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
211 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100212
213 if (extUsage == nullptr)
214 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100215 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100216 return true;
217 }
218
219 bool isExKeyUsageClientAuth = false;
220 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
221 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800222 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
223 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
224 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100225 {
226 isExKeyUsageClientAuth = true;
227 break;
228 }
229 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200230 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100231
232 // Certificate has to have proper key usages set
233 if (!isExKeyUsageClientAuth)
234 {
235 BMCWEB_LOG_DEBUG << this
236 << " Certificate ExtendedKeyUsage does "
237 "not allow provided certificate to "
238 "be used for user authentication";
239 return true;
240 }
241 std::string sslUser;
242 // Extract username contained in CommonName
243 sslUser.resize(256, '\0');
244
245 int status = X509_NAME_get_text_by_NID(
246 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
247 static_cast<int>(sslUser.size()));
248
249 if (status == -1)
250 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100251 BMCWEB_LOG_DEBUG
252 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100253 return true;
254 }
255
256 size_t lastChar = sslUser.find('\0');
257 if (lastChar == std::string::npos || lastChar == 0)
258 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100259 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100260 return true;
261 }
262 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530263 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700264 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700265 userSession = persistent_data::SessionStore::getInstance()
266 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800267 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700268 persistent_data::PersistenceType::TIMEOUT);
269 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100270 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700271 BMCWEB_LOG_DEBUG
272 << this
273 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100274 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100275 return true;
276 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700277 }
278
Ed Tanousceac6f72018-12-02 11:58:47 -0800279 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700280 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800281 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700282 }
283
Ed Tanous1abe55e2018-09-05 08:30:59 -0700284 void start()
285 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800286 if (connectionCount >= 100)
287 {
288 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
289 return;
290 }
291
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800292 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500293
Ed Tanousceac6f72018-12-02 11:58:47 -0800294 // TODO(ed) Abstract this to a more clever class with the idea of an
295 // asynchronous "start"
296 if constexpr (std::is_same_v<Adaptor,
297 boost::beast::ssl_stream<
298 boost::asio::ip::tcp::socket>>)
299 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000300 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
301 [this, self(shared_from_this())](
302 const boost::system::error_code& ec) {
303 if (ec)
304 {
305 return;
306 }
307 doReadHeaders();
308 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800309 }
310 else
311 {
312 doReadHeaders();
313 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700314 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315
Ed Tanous1abe55e2018-09-05 08:30:59 -0700316 void handle()
317 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700318 std::error_code reqEc;
319 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
320 if (reqEc)
321 {
322 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
323 return;
324 }
Ed Tanous596b2032021-09-13 10:32:22 -0700325 thisReq.session = userSession;
326
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000327 // Fetch the client IP address
328 readClientIp();
329
Ed Tanous1abe55e2018-09-05 08:30:59 -0700330 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700331 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 {
Ed Tanous596b2032021-09-13 10:32:22 -0700333 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700334 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700335 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600336 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700337 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 }
339 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700340
Ed Tanouse278c182019-03-13 16:23:37 -0700341 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700342 << " " << this << " HTTP/" << thisReq.version() / 10
343 << "." << thisReq.version() % 10 << ' '
344 << thisReq.methodString() << " " << thisReq.target()
345 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700346
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700347 res.setCompleteRequestHandler(nullptr);
348 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700349
Ed Tanous596b2032021-09-13 10:32:22 -0700350 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700351 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200352
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700353 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600355 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700356 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700357 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800358#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700359 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700360 thisReq.session == nullptr)
361 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600362 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700363 forward_unauthorized::sendUnauthorized(
364 req->url, req->getHeaderValue("User-Agent"),
365 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600366 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700367 return;
368 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800369#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600370 res.setCompleteRequestHandler([self(shared_from_this())] {
371 boost::asio::post(self->adaptor.get_executor(),
372 [self] { self->completeRequest(); });
373 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700374
Ed Tanous596b2032021-09-13 10:32:22 -0700375 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700376 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700377 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700378 "websocket"))
379 {
Ed Tanous596b2032021-09-13 10:32:22 -0700380 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700381 // delete lambda with self shared_ptr
382 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600383 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700384 return;
385 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600386 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700387 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700388 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700389
Ed Tanouse278c182019-03-13 16:23:37 -0700390 bool isAlive()
391 {
Ed Tanouse278c182019-03-13 16:23:37 -0700392 if constexpr (std::is_same_v<Adaptor,
393 boost::beast::ssl_stream<
394 boost::asio::ip::tcp::socket>>)
395 {
396 return adaptor.next_layer().is_open();
397 }
398 else
399 {
400 return adaptor.is_open();
401 }
402 }
403 void close()
404 {
Ed Tanouse278c182019-03-13 16:23:37 -0700405 if constexpr (std::is_same_v<Adaptor,
406 boost::beast::ssl_stream<
407 boost::asio::ip::tcp::socket>>)
408 {
409 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600410#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
411 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200412 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700413 BMCWEB_LOG_DEBUG
414 << this
415 << " Removing TLS session: " << userSession->uniqueId;
416 persistent_data::SessionStore::getInstance().removeSession(
417 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200418 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600419#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700420 }
421 else
422 {
423 adaptor.close();
424 }
425 }
426
Gunnar Mills9062d472021-11-16 11:37:47 -0600427 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700428 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700429 if (!req)
430 {
431 return;
432 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
434 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700435
Ed Tanous0260d9d2021-02-07 19:31:07 +0000436 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700437
Ed Tanouscf099fa2021-08-25 12:37:31 -0700438 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700439
Ed Tanouse278c182019-03-13 16:23:37 -0700440 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 {
442 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
443 // isReading
444 // << ' ' << isWriting;
445 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000446
447 // delete lambda with self shared_ptr
448 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700449 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 return;
451 }
452 if (res.body().empty() && !res.jsonValue.empty())
453 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700454 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700455 {
456 prettyPrintJson(res);
457 }
458 else
459 {
460 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800461 res.body() = res.jsonValue.dump(
462 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 }
464 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700465
Ed Tanous1abe55e2018-09-05 08:30:59 -0700466 if (res.resultInt() >= 400 && res.body().empty())
467 {
468 res.body() = std::string(res.reason());
469 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700470
471 if (res.result() == boost::beast::http::status::no_content)
472 {
473 // Boost beast throws if content is provided on a no-content
474 // response. Ideally, this would never happen, but in the case that
475 // it does, we don't want to throw.
476 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100477 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700478 res.body().clear();
479 }
480
Ed Tanous1abe55e2018-09-05 08:30:59 -0700481 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
482
483 res.keepAlive(req->keepAlive());
484
Gunnar Mills9062d472021-11-16 11:37:47 -0600485 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000486
487 // delete lambda with self shared_ptr
488 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700489 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 }
491
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500492 void readClientIp()
493 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700494 boost::asio::ip::address ip;
495 boost::system::error_code ec = getClientIp(ip);
496 if (ec)
497 {
498 return;
499 }
500 req->ipAddress = ip;
501 }
502
503 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
504 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500505 boost::system::error_code ec;
506 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
507 boost::asio::ip::tcp::endpoint endpoint =
508 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
509
510 if (ec)
511 {
512 // If remote endpoint fails keep going. "ClientOriginIPAddress"
513 // will be empty.
514 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
515 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700516 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500517 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700518 ip = endpoint.address();
519 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500520 }
521
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 private:
523 void doReadHeaders()
524 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
526
527 // Clean up any previous Connection.
528 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800529 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000530 [this,
531 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000532 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500533 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000534 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700535 bool errorWhileReading = false;
536 if (ec)
537 {
538 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500539 if (ec == boost::asio::error::eof)
540 {
541 BMCWEB_LOG_WARNING
542 << this << " Error while reading: " << ec.message();
543 }
544 else
545 {
546 BMCWEB_LOG_ERROR
547 << this << " Error while reading: " << ec.message();
548 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700549 }
550 else
551 {
552 // if the adaptor isn't open anymore, and wasn't handed to a
553 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700554 if (!isAlive() &&
555 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556 {
557 errorWhileReading = true;
558 }
559 }
560
James Feist3909dc82020-04-03 10:58:55 -0700561 cancelDeadlineTimer();
562
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 if (errorWhileReading)
564 {
Ed Tanouse278c182019-03-13 16:23:37 -0700565 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 return;
568 }
569
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700570 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700571
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700572 boost::asio::ip::address ip;
573 if (getClientIp(ip))
574 {
575 BMCWEB_LOG_DEBUG << "Unable to get client IP";
576 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700577 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800578#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
579 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700580 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700581 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800582
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700583 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800584 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700585 {
586 const boost::optional<uint64_t> contentLength =
587 parser->content_length();
588 if (contentLength &&
589 *contentLength > loggedOutPostBodyLimit)
590 {
591 BMCWEB_LOG_DEBUG << "Content length greater than limit "
592 << *contentLength;
593 close();
594 return;
595 }
596
James Feist3909dc82020-04-03 10:58:55 -0700597 BMCWEB_LOG_DEBUG << "Starting quick deadline";
598 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800599#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800600
Ed Tanous1abe55e2018-09-05 08:30:59 -0700601 doRead();
602 });
603 }
604
605 void doRead()
606 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700607 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800608 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800610 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000611 [this,
612 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000613 std::size_t bytesTransferred) {
614 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700615 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800616 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617 if (ec)
618 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100619 BMCWEB_LOG_ERROR
620 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700621 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 return;
624 }
625 handle();
626 });
627 }
628
Gunnar Mills9062d472021-11-16 11:37:47 -0600629 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100631 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600632 res.preparePayload();
633 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800634 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800636 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000637 [this,
638 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000639 std::size_t bytesTransferred) {
640 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 << " bytes";
642
James Feist54d8bb12020-07-20 13:28:59 -0700643 cancelDeadlineTimer();
644
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 if (ec)
646 {
647 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 return;
649 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800650 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 {
Ed Tanouse278c182019-03-13 16:23:37 -0700652 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 return;
655 }
656
657 serializer.reset();
658 BMCWEB_LOG_DEBUG << this << " Clearing response";
659 res.clear();
660 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500661 parser->body_limit(httpReqBodyLimit); // reset body limit for
662 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700663 buffer.consume(buffer.size());
664
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700665 // If the session was built from the transport, we don't need to
666 // clear it. All other sessions are generated per request.
667 if (!sessionIsFromTransport)
668 {
669 userSession = nullptr;
670 }
671
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700672 // Destroy the Request via the std::optional
673 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700674 doReadHeaders();
675 });
676 }
677
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 void cancelDeadlineTimer()
679 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 }
682
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800683 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 {
685 cancelDeadlineTimer();
686
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 std::chrono::seconds timeout(15);
688 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800689 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800690 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700691 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800692 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700693 return;
694 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800695
696 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
697 timer.expires_after(timeout);
698 timer.async_wait([weakSelf](const boost::system::error_code ec) {
699 // Note, we are ignoring other types of errors here; If the timer
700 // failed for any reason, we should still close the connection
701
702 std::shared_ptr<Connection<Adaptor, Handler>> self =
703 weakSelf.lock();
704 if (!self)
705 {
706 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
707 return;
708 }
709 if (ec == boost::asio::error::operation_aborted)
710 {
711 // Canceled wait means the path succeeeded.
712 return;
713 }
714 if (ec)
715 {
716 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
717 }
718
719 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
720
721 self->close();
722 });
723
724 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725 }
726
727 private:
728 Adaptor adaptor;
729 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800730 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800732 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700733 boost::beast::http::request_parser<boost::beast::http::string_body>>
734 parser;
735
Ed Tanous3112a142018-11-29 15:45:10 -0800736 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700737
Ed Tanousa24526d2018-12-10 15:17:59 -0800738 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739 boost::beast::http::string_body>>
740 serializer;
741
Ed Tanousa24526d2018-12-10 15:17:59 -0800742 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700743 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700744
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700745 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700746 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700747
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800748 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000751
752 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700753 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800754
755 using std::enable_shared_from_this<
756 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800757};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758} // namespace crow