blob: 840f2b6ceb4f84867ab2071fdfbd3cdc208bf306 [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 {
185 if (KU_DIGITAL_SIGNATURE & usage->data[i])
186 {
187 isKeyUsageDigitalSignature = true;
188 }
189 if (KU_KEY_AGREEMENT & usage->data[i])
190 {
191 isKeyUsageKeyAgreement = true;
192 }
193 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700194 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100195
196 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
197 {
198 BMCWEB_LOG_DEBUG << this
199 << " Certificate ExtendedKeyUsage does "
200 "not allow provided certificate to "
201 "be used for user authentication";
202 return true;
203 }
204
205 // Determine that ExtendedKeyUsage includes Client Auth
206
Ed Tanous23a21a12020-07-25 04:45:05 +0000207 stack_st_ASN1_OBJECT* extUsage =
208 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
209 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100210
211 if (extUsage == nullptr)
212 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100213 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100214 return true;
215 }
216
217 bool isExKeyUsageClientAuth = false;
218 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
219 {
220 if (NID_client_auth ==
221 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
222 {
223 isExKeyUsageClientAuth = true;
224 break;
225 }
226 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200227 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100228
229 // Certificate has to have proper key usages set
230 if (!isExKeyUsageClientAuth)
231 {
232 BMCWEB_LOG_DEBUG << this
233 << " Certificate ExtendedKeyUsage does "
234 "not allow provided certificate to "
235 "be used for user authentication";
236 return true;
237 }
238 std::string sslUser;
239 // Extract username contained in CommonName
240 sslUser.resize(256, '\0');
241
242 int status = X509_NAME_get_text_by_NID(
243 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
244 static_cast<int>(sslUser.size()));
245
246 if (status == -1)
247 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100248 BMCWEB_LOG_DEBUG
249 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100250 return true;
251 }
252
253 size_t lastChar = sslUser.find('\0');
254 if (lastChar == std::string::npos || lastChar == 0)
255 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100256 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100257 return true;
258 }
259 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530260 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700261 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700262 userSession = persistent_data::SessionStore::getInstance()
263 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800264 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700265 persistent_data::PersistenceType::TIMEOUT);
266 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100267 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700268 BMCWEB_LOG_DEBUG
269 << this
270 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100271 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100272 return true;
273 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700274 }
275
Ed Tanousceac6f72018-12-02 11:58:47 -0800276 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700277 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800278 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700279 }
280
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 void start()
282 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800283 if (connectionCount >= 100)
284 {
285 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
286 return;
287 }
288
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800289 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500290
Ed Tanousceac6f72018-12-02 11:58:47 -0800291 // TODO(ed) Abstract this to a more clever class with the idea of an
292 // asynchronous "start"
293 if constexpr (std::is_same_v<Adaptor,
294 boost::beast::ssl_stream<
295 boost::asio::ip::tcp::socket>>)
296 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000297 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
298 [this, self(shared_from_this())](
299 const boost::system::error_code& ec) {
300 if (ec)
301 {
302 return;
303 }
304 doReadHeaders();
305 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800306 }
307 else
308 {
309 doReadHeaders();
310 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700311 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312
Ed Tanous1abe55e2018-09-05 08:30:59 -0700313 void handle()
314 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700315 std::error_code reqEc;
316 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
317 if (reqEc)
318 {
319 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
320 return;
321 }
Ed Tanous596b2032021-09-13 10:32:22 -0700322 thisReq.session = userSession;
323
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000324 // Fetch the client IP address
325 readClientIp();
326
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700328 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 {
Ed Tanous596b2032021-09-13 10:32:22 -0700330 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700332 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600333 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700334 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 }
336 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanouse278c182019-03-13 16:23:37 -0700338 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700339 << " " << this << " HTTP/" << thisReq.version() / 10
340 << "." << thisReq.version() % 10 << ' '
341 << thisReq.methodString() << " " << thisReq.target()
342 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700343
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700344 res.setCompleteRequestHandler(nullptr);
345 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700346
Ed Tanous596b2032021-09-13 10:32:22 -0700347 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700348 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200349
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700350 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700351 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600352 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700353 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800355#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700356 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700357 thisReq.session == nullptr)
358 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600359 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700360 forward_unauthorized::sendUnauthorized(
361 req->url, req->getHeaderValue("User-Agent"),
362 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600363 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700364 return;
365 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800366#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600367 res.setCompleteRequestHandler([self(shared_from_this())] {
368 boost::asio::post(self->adaptor.get_executor(),
369 [self] { self->completeRequest(); });
370 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700371
Ed Tanous596b2032021-09-13 10:32:22 -0700372 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700373 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700374 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700375 "websocket"))
376 {
Ed Tanous596b2032021-09-13 10:32:22 -0700377 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700378 // delete lambda with self shared_ptr
379 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600380 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700381 return;
382 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600383 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700384 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700385 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700386
Ed Tanouse278c182019-03-13 16:23:37 -0700387 bool isAlive()
388 {
Ed Tanouse278c182019-03-13 16:23:37 -0700389 if constexpr (std::is_same_v<Adaptor,
390 boost::beast::ssl_stream<
391 boost::asio::ip::tcp::socket>>)
392 {
393 return adaptor.next_layer().is_open();
394 }
395 else
396 {
397 return adaptor.is_open();
398 }
399 }
400 void close()
401 {
Ed Tanouse278c182019-03-13 16:23:37 -0700402 if constexpr (std::is_same_v<Adaptor,
403 boost::beast::ssl_stream<
404 boost::asio::ip::tcp::socket>>)
405 {
406 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600407#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
408 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200409 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700410 BMCWEB_LOG_DEBUG
411 << this
412 << " Removing TLS session: " << userSession->uniqueId;
413 persistent_data::SessionStore::getInstance().removeSession(
414 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200415 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600416#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700417 }
418 else
419 {
420 adaptor.close();
421 }
422 }
423
Gunnar Mills9062d472021-11-16 11:37:47 -0600424 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700425 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700426 if (!req)
427 {
428 return;
429 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700430 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
431 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700432
Ed Tanous0260d9d2021-02-07 19:31:07 +0000433 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700434
Ed Tanouscf099fa2021-08-25 12:37:31 -0700435 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700436
Ed Tanouse278c182019-03-13 16:23:37 -0700437 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438 {
439 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
440 // isReading
441 // << ' ' << isWriting;
442 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000443
444 // delete lambda with self shared_ptr
445 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700446 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 return;
448 }
449 if (res.body().empty() && !res.jsonValue.empty())
450 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700451 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700452 {
453 prettyPrintJson(res);
454 }
455 else
456 {
457 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800458 res.body() = res.jsonValue.dump(
459 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700460 }
461 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700462
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 if (res.resultInt() >= 400 && res.body().empty())
464 {
465 res.body() = std::string(res.reason());
466 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700467
468 if (res.result() == boost::beast::http::status::no_content)
469 {
470 // Boost beast throws if content is provided on a no-content
471 // response. Ideally, this would never happen, but in the case that
472 // it does, we don't want to throw.
473 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100474 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700475 res.body().clear();
476 }
477
Ed Tanous1abe55e2018-09-05 08:30:59 -0700478 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
479
480 res.keepAlive(req->keepAlive());
481
Gunnar Mills9062d472021-11-16 11:37:47 -0600482 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000483
484 // delete lambda with self shared_ptr
485 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700486 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700487 }
488
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500489 void readClientIp()
490 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700491 boost::asio::ip::address ip;
492 boost::system::error_code ec = getClientIp(ip);
493 if (ec)
494 {
495 return;
496 }
497 req->ipAddress = ip;
498 }
499
500 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
501 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500502 boost::system::error_code ec;
503 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
504 boost::asio::ip::tcp::endpoint endpoint =
505 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
506
507 if (ec)
508 {
509 // If remote endpoint fails keep going. "ClientOriginIPAddress"
510 // will be empty.
511 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
512 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700513 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500514 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700515 ip = endpoint.address();
516 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500517 }
518
Ed Tanous1abe55e2018-09-05 08:30:59 -0700519 private:
520 void doReadHeaders()
521 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
523
524 // Clean up any previous Connection.
525 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800526 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000527 [this,
528 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000529 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500530 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000531 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700532 bool errorWhileReading = false;
533 if (ec)
534 {
535 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500536 if (ec == boost::asio::error::eof)
537 {
538 BMCWEB_LOG_WARNING
539 << this << " Error while reading: " << ec.message();
540 }
541 else
542 {
543 BMCWEB_LOG_ERROR
544 << this << " Error while reading: " << ec.message();
545 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 }
547 else
548 {
549 // if the adaptor isn't open anymore, and wasn't handed to a
550 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700551 if (!isAlive() &&
552 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553 {
554 errorWhileReading = true;
555 }
556 }
557
James Feist3909dc82020-04-03 10:58:55 -0700558 cancelDeadlineTimer();
559
Ed Tanous1abe55e2018-09-05 08:30:59 -0700560 if (errorWhileReading)
561 {
Ed Tanouse278c182019-03-13 16:23:37 -0700562 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 return;
565 }
566
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700567 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700568
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700569 boost::asio::ip::address ip;
570 if (getClientIp(ip))
571 {
572 BMCWEB_LOG_DEBUG << "Unable to get client IP";
573 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700574 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800575#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
576 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700577 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700578 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800579
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700580 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800581 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700582 {
583 const boost::optional<uint64_t> contentLength =
584 parser->content_length();
585 if (contentLength &&
586 *contentLength > loggedOutPostBodyLimit)
587 {
588 BMCWEB_LOG_DEBUG << "Content length greater than limit "
589 << *contentLength;
590 close();
591 return;
592 }
593
James Feist3909dc82020-04-03 10:58:55 -0700594 BMCWEB_LOG_DEBUG << "Starting quick deadline";
595 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800596#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800597
Ed Tanous1abe55e2018-09-05 08:30:59 -0700598 doRead();
599 });
600 }
601
602 void doRead()
603 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800605 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700606 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800607 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000608 [this,
609 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000610 std::size_t bytesTransferred) {
611 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800613 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 if (ec)
615 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100616 BMCWEB_LOG_ERROR
617 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700618 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620 return;
621 }
622 handle();
623 });
624 }
625
Gunnar Mills9062d472021-11-16 11:37:47 -0600626 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100628 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600629 res.preparePayload();
630 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800631 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800633 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000634 [this,
635 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000636 std::size_t bytesTransferred) {
637 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 << " bytes";
639
James Feist54d8bb12020-07-20 13:28:59 -0700640 cancelDeadlineTimer();
641
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 if (ec)
643 {
644 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 return;
646 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800647 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 {
Ed Tanouse278c182019-03-13 16:23:37 -0700649 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 return;
652 }
653
654 serializer.reset();
655 BMCWEB_LOG_DEBUG << this << " Clearing response";
656 res.clear();
657 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500658 parser->body_limit(httpReqBodyLimit); // reset body limit for
659 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700660 buffer.consume(buffer.size());
661
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700662 // If the session was built from the transport, we don't need to
663 // clear it. All other sessions are generated per request.
664 if (!sessionIsFromTransport)
665 {
666 userSession = nullptr;
667 }
668
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700669 // Destroy the Request via the std::optional
670 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 doReadHeaders();
672 });
673 }
674
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 void cancelDeadlineTimer()
676 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800677 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 }
679
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 {
682 cancelDeadlineTimer();
683
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800684 std::chrono::seconds timeout(15);
685 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800686 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700688 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800689 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700690 return;
691 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800692
693 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
694 timer.expires_after(timeout);
695 timer.async_wait([weakSelf](const boost::system::error_code ec) {
696 // Note, we are ignoring other types of errors here; If the timer
697 // failed for any reason, we should still close the connection
698
699 std::shared_ptr<Connection<Adaptor, Handler>> self =
700 weakSelf.lock();
701 if (!self)
702 {
703 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
704 return;
705 }
706 if (ec == boost::asio::error::operation_aborted)
707 {
708 // Canceled wait means the path succeeeded.
709 return;
710 }
711 if (ec)
712 {
713 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
714 }
715
716 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
717
718 self->close();
719 });
720
721 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700722 }
723
724 private:
725 Adaptor adaptor;
726 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800727 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700728 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800729 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 boost::beast::http::request_parser<boost::beast::http::string_body>>
731 parser;
732
Ed Tanous3112a142018-11-29 15:45:10 -0800733 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700734
Ed Tanousa24526d2018-12-10 15:17:59 -0800735 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736 boost::beast::http::string_body>>
737 serializer;
738
Ed Tanousa24526d2018-12-10 15:17:59 -0800739 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700740 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700741
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700742 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700743 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800745 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746
Ed Tanous1abe55e2018-09-05 08:30:59 -0700747 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000748
749 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700750 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800751
752 using std::enable_shared_from_this<
753 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800754};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700755} // namespace crow