blob: ad6855f434814efc303c3cc6d59a2d7bb6970666 [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 {
222 if (NID_client_auth ==
223 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
224 {
225 isExKeyUsageClientAuth = true;
226 break;
227 }
228 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200229 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100230
231 // Certificate has to have proper key usages set
232 if (!isExKeyUsageClientAuth)
233 {
234 BMCWEB_LOG_DEBUG << this
235 << " Certificate ExtendedKeyUsage does "
236 "not allow provided certificate to "
237 "be used for user authentication";
238 return true;
239 }
240 std::string sslUser;
241 // Extract username contained in CommonName
242 sslUser.resize(256, '\0');
243
244 int status = X509_NAME_get_text_by_NID(
245 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
246 static_cast<int>(sslUser.size()));
247
248 if (status == -1)
249 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100250 BMCWEB_LOG_DEBUG
251 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100252 return true;
253 }
254
255 size_t lastChar = sslUser.find('\0');
256 if (lastChar == std::string::npos || lastChar == 0)
257 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100258 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100259 return true;
260 }
261 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530262 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700263 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700264 userSession = persistent_data::SessionStore::getInstance()
265 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800266 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700267 persistent_data::PersistenceType::TIMEOUT);
268 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100269 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700270 BMCWEB_LOG_DEBUG
271 << this
272 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100273 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100274 return true;
275 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700276 }
277
Ed Tanousceac6f72018-12-02 11:58:47 -0800278 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800280 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700281 }
282
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 void start()
284 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800285 if (connectionCount >= 100)
286 {
287 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
288 return;
289 }
290
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800291 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500292
Ed Tanousceac6f72018-12-02 11:58:47 -0800293 // TODO(ed) Abstract this to a more clever class with the idea of an
294 // asynchronous "start"
295 if constexpr (std::is_same_v<Adaptor,
296 boost::beast::ssl_stream<
297 boost::asio::ip::tcp::socket>>)
298 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000299 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
300 [this, self(shared_from_this())](
301 const boost::system::error_code& ec) {
302 if (ec)
303 {
304 return;
305 }
306 doReadHeaders();
307 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800308 }
309 else
310 {
311 doReadHeaders();
312 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700313 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700314
Ed Tanous1abe55e2018-09-05 08:30:59 -0700315 void handle()
316 {
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);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800581
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700582 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800583 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700584 {
585 const boost::optional<uint64_t> contentLength =
586 parser->content_length();
587 if (contentLength &&
588 *contentLength > loggedOutPostBodyLimit)
589 {
590 BMCWEB_LOG_DEBUG << "Content length greater than limit "
591 << *contentLength;
592 close();
593 return;
594 }
595
James Feist3909dc82020-04-03 10:58:55 -0700596 BMCWEB_LOG_DEBUG << "Starting quick deadline";
597 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800598#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800599
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600 doRead();
601 });
602 }
603
604 void doRead()
605 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700606 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800607 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800609 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000610 [this,
611 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000612 std::size_t bytesTransferred) {
613 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800615 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 if (ec)
617 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100618 BMCWEB_LOG_ERROR
619 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700620 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700621 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 return;
623 }
624 handle();
625 });
626 }
627
Gunnar Mills9062d472021-11-16 11:37:47 -0600628 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100630 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600631 res.preparePayload();
632 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800633 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800635 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000636 [this,
637 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000638 std::size_t bytesTransferred) {
639 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 << " bytes";
641
James Feist54d8bb12020-07-20 13:28:59 -0700642 cancelDeadlineTimer();
643
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 if (ec)
645 {
646 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 return;
648 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800649 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 {
Ed Tanouse278c182019-03-13 16:23:37 -0700651 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700652 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 return;
654 }
655
656 serializer.reset();
657 BMCWEB_LOG_DEBUG << this << " Clearing response";
658 res.clear();
659 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500660 parser->body_limit(httpReqBodyLimit); // reset body limit for
661 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 buffer.consume(buffer.size());
663
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700664 // If the session was built from the transport, we don't need to
665 // clear it. All other sessions are generated per request.
666 if (!sessionIsFromTransport)
667 {
668 userSession = nullptr;
669 }
670
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700671 // Destroy the Request via the std::optional
672 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700673 doReadHeaders();
674 });
675 }
676
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 void cancelDeadlineTimer()
678 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800679 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700680 }
681
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800682 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700683 {
684 cancelDeadlineTimer();
685
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800686 std::chrono::seconds timeout(15);
687 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800688 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800689 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700690 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800691 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700692 return;
693 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800694
695 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
696 timer.expires_after(timeout);
697 timer.async_wait([weakSelf](const boost::system::error_code ec) {
698 // Note, we are ignoring other types of errors here; If the timer
699 // failed for any reason, we should still close the connection
700
701 std::shared_ptr<Connection<Adaptor, Handler>> self =
702 weakSelf.lock();
703 if (!self)
704 {
705 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
706 return;
707 }
708 if (ec == boost::asio::error::operation_aborted)
709 {
710 // Canceled wait means the path succeeeded.
711 return;
712 }
713 if (ec)
714 {
715 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
716 }
717
718 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
719
720 self->close();
721 });
722
723 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700724 }
725
726 private:
727 Adaptor adaptor;
728 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800729 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800731 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700732 boost::beast::http::request_parser<boost::beast::http::string_body>>
733 parser;
734
Ed Tanous3112a142018-11-29 15:45:10 -0800735 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736
Ed Tanousa24526d2018-12-10 15:17:59 -0800737 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 boost::beast::http::string_body>>
739 serializer;
740
Ed Tanousa24526d2018-12-10 15:17:59 -0800741 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700743
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700744 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700745 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800747 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000750
751 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700752 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800753
754 using std::enable_shared_from_this<
755 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800756};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757} // namespace crow