blob: bfd641154e6dd211d38b04e60f12606ea3aa03c0 [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 Tanous55c7b7a2018-05-22 15:27:24 -070038#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070039static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070040#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070041
Ed Tanous0260d9d2021-02-07 19:31:07 +000042// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060043constexpr unsigned int httpReqBodyLimit =
Ed Tanous0260d9d2021-02-07 19:31:07 +000044 1024 * 1024 * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070045
James Feist3909dc82020-04-03 10:58:55 -070046constexpr uint64_t loggedOutPostBodyLimit = 4096;
47
48constexpr uint32_t httpHeaderLimit = 8192;
49
Ed Tanous52cc1122020-07-18 13:51:21 -070050template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050051class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070052 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070053{
54 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000056 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080058 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080059 handler(handlerIn), timer(std::move(timerIn)),
60 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 {
62 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070063 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070064 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020065
66#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070067 prepareMutualTls();
68#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
69
70#ifdef BMCWEB_ENABLE_DEBUG
71 connectionCount++;
72 BMCWEB_LOG_DEBUG << this << " Connection open, total "
73 << connectionCount;
74#endif
75 }
76
77 ~Connection()
78 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070079 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070080 cancelDeadlineTimer();
81#ifdef BMCWEB_ENABLE_DEBUG
82 connectionCount--;
83 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
84 << connectionCount;
85#endif
86 }
87
88 void prepareMutualTls()
89 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080090 std::error_code error;
91 std::filesystem::path caPath(ensuressl::trustStorePath);
92 auto caAvailable = !std::filesystem::is_empty(caPath, error);
93 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070094 if (caAvailable && persistent_data::SessionStore::getInstance()
95 .getAuthMethodsConfig()
96 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010097 {
98 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070099 std::string id = "bmcweb";
100 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100101 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700102 reinterpret_cast<const unsigned char*>(id.c_str()),
103 static_cast<unsigned int>(id.length()));
104 if (ret == 0)
105 {
106 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
107 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100108 }
109
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100110 adaptor.set_verify_callback([this](
111 bool preverified,
112 boost::asio::ssl::verify_context& ctx) {
113 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700114 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100115 .getAuthMethodsConfig()
116 .tls)
117 {
118 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200119 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100120 }
121
122 // We always return true to allow full auth flow
123 if (!preverified)
124 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100126 return true;
127 }
128
129 X509_STORE_CTX* cts = ctx.native_handle();
130 if (cts == nullptr)
131 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100132 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100133 return true;
134 }
135
136 // Get certificate
137 X509* peerCert =
138 X509_STORE_CTX_get_current_cert(ctx.native_handle());
139 if (peerCert == nullptr)
140 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100141 BMCWEB_LOG_DEBUG << this
142 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100143 return true;
144 }
145
146 // Check if certificate is OK
147 int error = X509_STORE_CTX_get_error(cts);
148 if (error != X509_V_OK)
149 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100150 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100151 return true;
152 }
153 // Check that we have reached final certificate in chain
154 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
155 if (depth != 0)
156
157 {
158 BMCWEB_LOG_DEBUG
159 << this << " Certificate verification in progress (depth "
160 << depth << "), waiting to reach final depth";
161 return true;
162 }
163
164 BMCWEB_LOG_DEBUG << this
165 << " Certificate verification of final depth";
166
167 // Verify KeyUsage
168 bool isKeyUsageDigitalSignature = false;
169 bool isKeyUsageKeyAgreement = false;
170
171 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000172 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100173
174 if (usage == nullptr)
175 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100176 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100177 return true;
178 }
179
180 for (int i = 0; i < usage->length; i++)
181 {
182 if (KU_DIGITAL_SIGNATURE & usage->data[i])
183 {
184 isKeyUsageDigitalSignature = true;
185 }
186 if (KU_KEY_AGREEMENT & usage->data[i])
187 {
188 isKeyUsageKeyAgreement = true;
189 }
190 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700191 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192
193 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
194 {
195 BMCWEB_LOG_DEBUG << this
196 << " Certificate ExtendedKeyUsage does "
197 "not allow provided certificate to "
198 "be used for user authentication";
199 return true;
200 }
201
202 // Determine that ExtendedKeyUsage includes Client Auth
203
Ed Tanous23a21a12020-07-25 04:45:05 +0000204 stack_st_ASN1_OBJECT* extUsage =
205 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
206 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100207
208 if (extUsage == nullptr)
209 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100210 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100211 return true;
212 }
213
214 bool isExKeyUsageClientAuth = false;
215 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
216 {
217 if (NID_client_auth ==
218 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
219 {
220 isExKeyUsageClientAuth = true;
221 break;
222 }
223 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200224 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100225
226 // Certificate has to have proper key usages set
227 if (!isExKeyUsageClientAuth)
228 {
229 BMCWEB_LOG_DEBUG << this
230 << " Certificate ExtendedKeyUsage does "
231 "not allow provided certificate to "
232 "be used for user authentication";
233 return true;
234 }
235 std::string sslUser;
236 // Extract username contained in CommonName
237 sslUser.resize(256, '\0');
238
239 int status = X509_NAME_get_text_by_NID(
240 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
241 static_cast<int>(sslUser.size()));
242
243 if (status == -1)
244 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100245 BMCWEB_LOG_DEBUG
246 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100247 return true;
248 }
249
250 size_t lastChar = sslUser.find('\0');
251 if (lastChar == std::string::npos || lastChar == 0)
252 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100253 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100254 return true;
255 }
256 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530257 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700258 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700259 userSession = persistent_data::SessionStore::getInstance()
260 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800261 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700262 persistent_data::PersistenceType::TIMEOUT);
263 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100264 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700265 BMCWEB_LOG_DEBUG
266 << this
267 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100268 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100269 return true;
270 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700271 }
272
Ed Tanousceac6f72018-12-02 11:58:47 -0800273 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700274 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800275 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700276 }
277
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 void start()
279 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800280 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500281
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 // TODO(ed) Abstract this to a more clever class with the idea of an
283 // asynchronous "start"
284 if constexpr (std::is_same_v<Adaptor,
285 boost::beast::ssl_stream<
286 boost::asio::ip::tcp::socket>>)
287 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000288 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
289 [this, self(shared_from_this())](
290 const boost::system::error_code& ec) {
291 if (ec)
292 {
293 return;
294 }
295 doReadHeaders();
296 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800297 }
298 else
299 {
300 doReadHeaders();
301 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700302 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700303
Ed Tanous1abe55e2018-09-05 08:30:59 -0700304 void handle()
305 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700306 std::error_code reqEc;
307 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
308 if (reqEc)
309 {
310 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
311 return;
312 }
Ed Tanous596b2032021-09-13 10:32:22 -0700313 thisReq.session = userSession;
314
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000315 // Fetch the client IP address
316 readClientIp();
317
Ed Tanous1abe55e2018-09-05 08:30:59 -0700318 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700319 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700320 {
Ed Tanous596b2032021-09-13 10:32:22 -0700321 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700322 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700323 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600324 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700325 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 }
327 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700328
Ed Tanouse278c182019-03-13 16:23:37 -0700329 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700330 << " " << this << " HTTP/" << thisReq.version() / 10
331 << "." << thisReq.version() % 10 << ' '
332 << thisReq.methodString() << " " << thisReq.target()
333 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700334
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700335 res.setCompleteRequestHandler(nullptr);
336 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanous596b2032021-09-13 10:32:22 -0700338 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700339 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200340
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700341 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700342 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600343 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700344 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700345 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800346#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700347 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700348 thisReq.session == nullptr)
349 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600350 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700351 forward_unauthorized::sendUnauthorized(
352 req->url, req->getHeaderValue("User-Agent"),
353 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600354 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700355 return;
356 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800357#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600358 res.setCompleteRequestHandler([self(shared_from_this())] {
359 boost::asio::post(self->adaptor.get_executor(),
360 [self] { self->completeRequest(); });
361 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700362
Ed Tanous596b2032021-09-13 10:32:22 -0700363 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700364 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700365 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700366 "websocket"))
367 {
Ed Tanous596b2032021-09-13 10:32:22 -0700368 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700369 // delete lambda with self shared_ptr
370 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600371 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700372 return;
373 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600374 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700375 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700376 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700377
Ed Tanouse278c182019-03-13 16:23:37 -0700378 bool isAlive()
379 {
Ed Tanouse278c182019-03-13 16:23:37 -0700380 if constexpr (std::is_same_v<Adaptor,
381 boost::beast::ssl_stream<
382 boost::asio::ip::tcp::socket>>)
383 {
384 return adaptor.next_layer().is_open();
385 }
386 else
387 {
388 return adaptor.is_open();
389 }
390 }
391 void close()
392 {
Ed Tanouse278c182019-03-13 16:23:37 -0700393 if constexpr (std::is_same_v<Adaptor,
394 boost::beast::ssl_stream<
395 boost::asio::ip::tcp::socket>>)
396 {
397 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600398#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
399 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200400 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700401 BMCWEB_LOG_DEBUG
402 << this
403 << " Removing TLS session: " << userSession->uniqueId;
404 persistent_data::SessionStore::getInstance().removeSession(
405 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200406 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600407#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700408 }
409 else
410 {
411 adaptor.close();
412 }
413 }
414
Gunnar Mills9062d472021-11-16 11:37:47 -0600415 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700417 if (!req)
418 {
419 return;
420 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
422 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700423
Ed Tanous0260d9d2021-02-07 19:31:07 +0000424 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700425
Ed Tanouscf099fa2021-08-25 12:37:31 -0700426 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700427
Ed Tanouse278c182019-03-13 16:23:37 -0700428 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 {
430 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
431 // isReading
432 // << ' ' << isWriting;
433 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000434
435 // delete lambda with self shared_ptr
436 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700437 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438 return;
439 }
440 if (res.body().empty() && !res.jsonValue.empty())
441 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700442 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700443 {
444 prettyPrintJson(res);
445 }
446 else
447 {
448 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800449 res.body() = res.jsonValue.dump(
450 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700451 }
452 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700453
Ed Tanous1abe55e2018-09-05 08:30:59 -0700454 if (res.resultInt() >= 400 && res.body().empty())
455 {
456 res.body() = std::string(res.reason());
457 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700458
459 if (res.result() == boost::beast::http::status::no_content)
460 {
461 // Boost beast throws if content is provided on a no-content
462 // response. Ideally, this would never happen, but in the case that
463 // it does, we don't want to throw.
464 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100465 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700466 res.body().clear();
467 }
468
Ed Tanous1abe55e2018-09-05 08:30:59 -0700469 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
470
471 res.keepAlive(req->keepAlive());
472
Gunnar Mills9062d472021-11-16 11:37:47 -0600473 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000474
475 // delete lambda with self shared_ptr
476 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700477 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700478 }
479
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500480 void readClientIp()
481 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700482 boost::asio::ip::address ip;
483 boost::system::error_code ec = getClientIp(ip);
484 if (ec)
485 {
486 return;
487 }
488 req->ipAddress = ip;
489 }
490
491 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
492 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500493 boost::system::error_code ec;
494 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
495 boost::asio::ip::tcp::endpoint endpoint =
496 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
497
498 if (ec)
499 {
500 // If remote endpoint fails keep going. "ClientOriginIPAddress"
501 // will be empty.
502 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
503 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700504 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500505 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700506 ip = endpoint.address();
507 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500508 }
509
Ed Tanous1abe55e2018-09-05 08:30:59 -0700510 private:
511 void doReadHeaders()
512 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700513 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
514
515 // Clean up any previous Connection.
516 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800517 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000518 [this,
519 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000520 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500521 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000522 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 bool errorWhileReading = false;
524 if (ec)
525 {
526 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500527 if (ec == boost::asio::error::eof)
528 {
529 BMCWEB_LOG_WARNING
530 << this << " Error while reading: " << ec.message();
531 }
532 else
533 {
534 BMCWEB_LOG_ERROR
535 << this << " Error while reading: " << ec.message();
536 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700537 }
538 else
539 {
540 // if the adaptor isn't open anymore, and wasn't handed to a
541 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700542 if (!isAlive() &&
543 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700544 {
545 errorWhileReading = true;
546 }
547 }
548
James Feist3909dc82020-04-03 10:58:55 -0700549 cancelDeadlineTimer();
550
Ed Tanous1abe55e2018-09-05 08:30:59 -0700551 if (errorWhileReading)
552 {
Ed Tanouse278c182019-03-13 16:23:37 -0700553 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700554 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700555 return;
556 }
557
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700558 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700559
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700560 boost::asio::ip::address ip;
561 if (getClientIp(ip))
562 {
563 BMCWEB_LOG_DEBUG << "Unable to get client IP";
564 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700565 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800566#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
567 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700568 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700569 ip, res, method, parser->get().base(), userSession);
Nan Zhou8682c5a2021-11-13 11:00:07 -0800570#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800571
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700572 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800573 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700574 {
575 const boost::optional<uint64_t> contentLength =
576 parser->content_length();
577 if (contentLength &&
578 *contentLength > loggedOutPostBodyLimit)
579 {
580 BMCWEB_LOG_DEBUG << "Content length greater than limit "
581 << *contentLength;
582 close();
583 return;
584 }
585
James Feist3909dc82020-04-03 10:58:55 -0700586 BMCWEB_LOG_DEBUG << "Starting quick deadline";
587 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800588
Ed Tanous1abe55e2018-09-05 08:30:59 -0700589 doRead();
590 });
591 }
592
593 void doRead()
594 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700595 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800596 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800598 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000599 [this,
600 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000601 std::size_t bytesTransferred) {
602 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700603 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800604 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605 if (ec)
606 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100607 BMCWEB_LOG_ERROR
608 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700609 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 return;
612 }
613 handle();
614 });
615 }
616
Gunnar Mills9062d472021-11-16 11:37:47 -0600617 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100619 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600620 res.preparePayload();
621 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800622 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800624 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000625 [this,
626 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000627 std::size_t bytesTransferred) {
628 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 << " bytes";
630
James Feist54d8bb12020-07-20 13:28:59 -0700631 cancelDeadlineTimer();
632
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 if (ec)
634 {
635 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 return;
637 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800638 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 {
Ed Tanouse278c182019-03-13 16:23:37 -0700640 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 return;
643 }
644
645 serializer.reset();
646 BMCWEB_LOG_DEBUG << this << " Clearing response";
647 res.clear();
648 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500649 parser->body_limit(httpReqBodyLimit); // reset body limit for
650 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 buffer.consume(buffer.size());
652
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700653 // If the session was built from the transport, we don't need to
654 // clear it. All other sessions are generated per request.
655 if (!sessionIsFromTransport)
656 {
657 userSession = nullptr;
658 }
659
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700660 // Destroy the Request via the std::optional
661 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 doReadHeaders();
663 });
664 }
665
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666 void cancelDeadlineTimer()
667 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800668 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700669 }
670
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800671 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700672 {
673 cancelDeadlineTimer();
674
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800675 std::chrono::seconds timeout(15);
676 // allow slow uploads for logged in users
677 bool loggedIn = req && req->session;
678 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700679 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700681 return;
682 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800683
684 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
685 timer.expires_after(timeout);
686 timer.async_wait([weakSelf](const boost::system::error_code ec) {
687 // Note, we are ignoring other types of errors here; If the timer
688 // failed for any reason, we should still close the connection
689
690 std::shared_ptr<Connection<Adaptor, Handler>> self =
691 weakSelf.lock();
692 if (!self)
693 {
694 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
695 return;
696 }
697 if (ec == boost::asio::error::operation_aborted)
698 {
699 // Canceled wait means the path succeeeded.
700 return;
701 }
702 if (ec)
703 {
704 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
705 }
706
707 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
708
709 self->close();
710 });
711
712 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700713 }
714
715 private:
716 Adaptor adaptor;
717 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800718 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700719 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800720 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700721 boost::beast::http::request_parser<boost::beast::http::string_body>>
722 parser;
723
Ed Tanous3112a142018-11-29 15:45:10 -0800724 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725
Ed Tanousa24526d2018-12-10 15:17:59 -0800726 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700727 boost::beast::http::string_body>>
728 serializer;
729
Ed Tanousa24526d2018-12-10 15:17:59 -0800730 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700732
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700733 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700734 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700735
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800736 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700737
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000739
740 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700741 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800742
743 using std::enable_shared_from_this<
744 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800745};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746} // namespace crow