blob: 115b7ff92999ed16584bfa26de19e4bf848bc25d [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
Nan Zhoud055a342022-05-25 01:15:34 +00004#include "authentication.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 Tanous257f5792018-03-17 14:40:09 -070010#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080011#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080012#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070013#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080014#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080015#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070016#include <boost/beast/http/parser.hpp>
17#include <boost/beast/http/read.hpp>
18#include <boost/beast/http/serializer.hpp>
19#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053020#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070022#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070023#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070024#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <ssl_key_handler.hpp>
26
Manojkiran Eda44250442020-06-16 12:51:38 +053027#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028#include <chrono>
29#include <vector>
30
Ed Tanous1abe55e2018-09-05 08:30:59 -070031namespace crow
32{
Ed Tanous257f5792018-03-17 14:40:09 -070033
Ed Tanous1abe55e2018-09-05 08:30:59 -070034inline void prettyPrintJson(crow::Response& res)
35{
Ed Tanous57fce802019-05-21 13:00:34 -070036 json_html_util::dumpHtml(res.body(), res.jsonValue);
37
Ed Tanousd9f6c622022-03-17 09:12:17 -070038 res.addHeader(boost::beast::http::field::content_type,
39 "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070040}
41
Ed Tanous6fbdbca2021-12-06 14:36:06 -080042static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
Ed Tanous0260d9d2021-02-07 19:31:07 +000044// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080045constexpr uint64_t httpReqBodyLimit =
46 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070047
James Feist3909dc82020-04-03 10:58:55 -070048constexpr uint64_t loggedOutPostBodyLimit = 4096;
49
50constexpr uint32_t httpHeaderLimit = 8192;
51
Ed Tanous52cc1122020-07-18 13:51:21 -070052template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050053class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070054 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070055{
56 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000058 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080059 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080060 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080061 handler(handlerIn), timer(std::move(timerIn)),
62 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070063 {
64 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070065 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070066 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020067
68#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070069 prepareMutualTls();
70#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
71
Ed Tanous40aa0582021-07-14 13:24:40 -070072 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080073
Ed Tanous40aa0582021-07-14 13:24:40 -070074 BMCWEB_LOG_DEBUG << this << " Connection open, total "
75 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070076 }
77
78 ~Connection()
79 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070080 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070081 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080082
Ed Tanous40aa0582021-07-14 13:24:40 -070083 connectionCount--;
84 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
85 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070086 }
87
Ed Tanousecd6a3a2022-01-07 09:18:40 -080088 Connection(const Connection&) = delete;
89 Connection(Connection&&) = delete;
90 Connection& operator=(const Connection&) = delete;
91 Connection& operator=(Connection&&) = delete;
92
Ed Tanous40aa0582021-07-14 13:24:40 -070093 void prepareMutualTls()
94 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080095 std::error_code error;
96 std::filesystem::path caPath(ensuressl::trustStorePath);
97 auto caAvailable = !std::filesystem::is_empty(caPath, error);
98 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070099 if (caAvailable && persistent_data::SessionStore::getInstance()
100 .getAuthMethodsConfig()
101 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100102 {
103 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700104 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800105
Ed Tanous9eb808c2022-01-25 10:19:23 -0800106 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800107 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800108 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700109 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800110 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700111 static_cast<unsigned int>(id.length()));
112 if (ret == 0)
113 {
114 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
115 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100116 }
117
Ed Tanous002d39b2022-05-31 08:59:27 -0700118 adaptor.set_verify_callback(
119 [this](bool preverified, boost::asio::ssl::verify_context& ctx) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100120 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700121 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100122 .getAuthMethodsConfig()
123 .tls)
124 {
125 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200126 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100127 }
128
129 // We always return true to allow full auth flow
130 if (!preverified)
131 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100132 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100133 return true;
134 }
135
136 X509_STORE_CTX* cts = ctx.native_handle();
137 if (cts == nullptr)
138 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100139 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100140 return true;
141 }
142
143 // Get certificate
144 X509* peerCert =
145 X509_STORE_CTX_get_current_cert(ctx.native_handle());
146 if (peerCert == nullptr)
147 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100148 BMCWEB_LOG_DEBUG << this
149 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100150 return true;
151 }
152
153 // Check if certificate is OK
Ed Tanous8a592812022-06-04 09:06:59 -0700154 int ctxError = X509_STORE_CTX_get_error(cts);
155 if (ctxError != X509_V_OK)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100156 {
Ed Tanous8a592812022-06-04 09:06:59 -0700157 BMCWEB_LOG_INFO << this << " Last TLS error is: " << ctxError;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158 return true;
159 }
160 // Check that we have reached final certificate in chain
161 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
162 if (depth != 0)
163
164 {
165 BMCWEB_LOG_DEBUG
166 << this << " Certificate verification in progress (depth "
167 << depth << "), waiting to reach final depth";
168 return true;
169 }
170
171 BMCWEB_LOG_DEBUG << this
172 << " Certificate verification of final depth";
173
174 // Verify KeyUsage
175 bool isKeyUsageDigitalSignature = false;
176 bool isKeyUsageKeyAgreement = false;
177
178 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000179 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100180
181 if (usage == nullptr)
182 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100183 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100184 return true;
185 }
186
187 for (int i = 0; i < usage->length; i++)
188 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800189 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
190 unsigned char usageChar = usage->data[i];
191 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192 {
193 isKeyUsageDigitalSignature = true;
194 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800195 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100196 {
197 isKeyUsageKeyAgreement = true;
198 }
199 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700200 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100201
202 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
203 {
204 BMCWEB_LOG_DEBUG << this
205 << " Certificate ExtendedKeyUsage does "
206 "not allow provided certificate to "
207 "be used for user authentication";
208 return true;
209 }
210
211 // Determine that ExtendedKeyUsage includes Client Auth
212
Ed Tanous23a21a12020-07-25 04:45:05 +0000213 stack_st_ASN1_OBJECT* extUsage =
214 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
215 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100216
217 if (extUsage == nullptr)
218 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100219 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100220 return true;
221 }
222
223 bool isExKeyUsageClientAuth = false;
224 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
225 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800226 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
227 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
228 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100229 {
230 isExKeyUsageClientAuth = true;
231 break;
232 }
233 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200234 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100235
236 // Certificate has to have proper key usages set
237 if (!isExKeyUsageClientAuth)
238 {
239 BMCWEB_LOG_DEBUG << this
240 << " Certificate ExtendedKeyUsage does "
241 "not allow provided certificate to "
242 "be used for user authentication";
243 return true;
244 }
245 std::string sslUser;
246 // Extract username contained in CommonName
247 sslUser.resize(256, '\0');
248
249 int status = X509_NAME_get_text_by_NID(
250 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
251 static_cast<int>(sslUser.size()));
252
253 if (status == -1)
254 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100255 BMCWEB_LOG_DEBUG
256 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100257 return true;
258 }
259
260 size_t lastChar = sslUser.find('\0');
261 if (lastChar == std::string::npos || lastChar == 0)
262 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100263 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100264 return true;
265 }
266 sslUser.resize(lastChar);
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700267 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700268 userSession = persistent_data::SessionStore::getInstance()
269 .generateUserSession(
Ed Tanousbb759e32022-08-02 17:07:54 -0700270 sslUser, req->ipAddress, std::nullopt,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700271 persistent_data::PersistenceType::TIMEOUT);
272 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100273 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700274 BMCWEB_LOG_DEBUG
275 << this
276 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100277 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100278 return true;
279 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280 }
281
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700285 }
286
Ed Tanous1abe55e2018-09-05 08:30:59 -0700287 void start()
288 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800289 if (connectionCount >= 100)
290 {
291 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
292 return;
293 }
294
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800295 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500296
Ed Tanousceac6f72018-12-02 11:58:47 -0800297 // TODO(ed) Abstract this to a more clever class with the idea of an
298 // asynchronous "start"
299 if constexpr (std::is_same_v<Adaptor,
300 boost::beast::ssl_stream<
301 boost::asio::ip::tcp::socket>>)
302 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000303 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
304 [this, self(shared_from_this())](
305 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700306 if (ec)
307 {
308 return;
309 }
310 doReadHeaders();
311 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800312 }
313 else
314 {
315 doReadHeaders();
316 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700317 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700318
Ed Tanous1abe55e2018-09-05 08:30:59 -0700319 void handle()
320 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700321 std::error_code reqEc;
322 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
323 if (reqEc)
324 {
325 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600326 res.result(boost::beast::http::status::bad_request);
327 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700328 return;
329 }
Ed Tanous596b2032021-09-13 10:32:22 -0700330 thisReq.session = userSession;
331
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000332 // Fetch the client IP address
333 readClientIp();
334
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700336 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700337 {
Ed Tanous596b2032021-09-13 10:32:22 -0700338 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700339 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700340 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800341 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700342 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 }
344 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700345
Ed Tanouse278c182019-03-13 16:23:37 -0700346 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700347 << " " << this << " HTTP/" << thisReq.version() / 10
348 << "." << thisReq.version() % 10 << ' '
349 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800350 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700351
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700352 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700353
Ed Tanous596b2032021-09-13 10:32:22 -0700354 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700355 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200356
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700357 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800359 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700360 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000362#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhoud055a342022-05-25 01:15:34 +0000363 if (!crow::authentication::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700364 thisReq.session == nullptr)
365 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800366 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700367 forward_unauthorized::sendUnauthorized(
Ed Tanousc127a0f2022-05-11 15:23:59 -0700368 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700369 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800370 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700371 return;
372 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000373#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800374 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
375 BMCWEB_LOG_DEBUG << "Setting completion handler";
376 asyncResp->res.setCompleteRequestHandler(
377 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700378 self->completeRequest(thisRes);
379 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700380
Ed Tanous596b2032021-09-13 10:32:22 -0700381 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700382 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700383 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700384 "websocket"))
385 {
Ed Tanous596b2032021-09-13 10:32:22 -0700386 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700387 // delete lambda with self shared_ptr
388 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800389 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700390 return;
391 }
Ed Tanous291d7092022-04-13 12:34:57 -0700392 std::string_view expected =
393 req->getHeaderValue(boost::beast::http::field::if_none_match);
394 if (!expected.empty())
395 {
396 res.setExpectedHash(expected);
397 }
Ed Tanous596b2032021-09-13 10:32:22 -0700398 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700399 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700400
Ed Tanouse278c182019-03-13 16:23:37 -0700401 bool isAlive()
402 {
Ed Tanouse278c182019-03-13 16:23:37 -0700403 if constexpr (std::is_same_v<Adaptor,
404 boost::beast::ssl_stream<
405 boost::asio::ip::tcp::socket>>)
406 {
407 return adaptor.next_layer().is_open();
408 }
409 else
410 {
411 return adaptor.is_open();
412 }
413 }
414 void close()
415 {
Ed Tanouse278c182019-03-13 16:23:37 -0700416 if constexpr (std::is_same_v<Adaptor,
417 boost::beast::ssl_stream<
418 boost::asio::ip::tcp::socket>>)
419 {
420 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800421 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200422 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700423 BMCWEB_LOG_DEBUG
424 << this
425 << " Removing TLS session: " << userSession->uniqueId;
426 persistent_data::SessionStore::getInstance().removeSession(
427 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200428 }
Ed Tanouse278c182019-03-13 16:23:37 -0700429 }
430 else
431 {
432 adaptor.close();
433 }
434 }
435
Nan Zhou72374eb2022-01-27 17:06:51 -0800436 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700438 if (!req)
439 {
440 return;
441 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800442 res = std::move(thisRes);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700443 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
444 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700445
Ed Tanous0260d9d2021-02-07 19:31:07 +0000446 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700447
Nan Zhoud055a342022-05-25 01:15:34 +0000448 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700449
Ed Tanouse278c182019-03-13 16:23:37 -0700450 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700451 {
452 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
453 // isReading
454 // << ' ' << isWriting;
455 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000456
457 // delete lambda with self shared_ptr
458 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700459 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700460 return;
461 }
Ed Tanous291d7092022-04-13 12:34:57 -0700462
463 res.setHashAndHandleNotModified();
464
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 if (res.body().empty() && !res.jsonValue.empty())
466 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700467 using http_helpers::ContentType;
Ed Tanous06fe2752022-09-13 12:11:19 -0700468 std::array<ContentType, 2> allowed{ContentType::JSON,
469 ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700470 ContentType prefered =
471 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
472
473 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700474 {
475 prettyPrintJson(res);
476 }
477 else
478 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700479 // Technically prefered could also be NoMatch here, but we'd
480 // like to default to something rather than return 400 for
481 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700482 res.addHeader(boost::beast::http::field::content_type,
483 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800484 res.body() = res.jsonValue.dump(
485 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700486 }
487 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700488
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 if (res.resultInt() >= 400 && res.body().empty())
490 {
491 res.body() = std::string(res.reason());
492 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700493
494 if (res.result() == boost::beast::http::status::no_content)
495 {
496 // Boost beast throws if content is provided on a no-content
497 // response. Ideally, this would never happen, but in the case that
498 // it does, we don't want to throw.
499 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100500 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700501 res.body().clear();
502 }
503
Ed Tanous1abe55e2018-09-05 08:30:59 -0700504 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
505
506 res.keepAlive(req->keepAlive());
507
Nan Zhou72374eb2022-01-27 17:06:51 -0800508 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000509
510 // delete lambda with self shared_ptr
511 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700512 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700513 }
514
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500515 void readClientIp()
516 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700517 boost::asio::ip::address ip;
518 boost::system::error_code ec = getClientIp(ip);
519 if (ec)
520 {
521 return;
522 }
523 req->ipAddress = ip;
524 }
525
526 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
527 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500528 boost::system::error_code ec;
529 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
530 boost::asio::ip::tcp::endpoint endpoint =
531 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
532
533 if (ec)
534 {
535 // If remote endpoint fails keep going. "ClientOriginIPAddress"
536 // will be empty.
537 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
538 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700539 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500540 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700541 ip = endpoint.address();
542 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500543 }
544
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545 private:
546 void doReadHeaders()
547 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700548 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
549
550 // Clean up any previous Connection.
551 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800552 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000553 [this,
554 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000555 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700556 BMCWEB_LOG_DEBUG << this << " async_read_header "
557 << bytesTransferred << " Bytes";
558 bool errorWhileReading = false;
559 if (ec)
560 {
561 errorWhileReading = true;
562 if (ec == boost::asio::error::eof)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700564 BMCWEB_LOG_WARNING
565 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 }
567 else
568 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700569 BMCWEB_LOG_ERROR
570 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700572 }
573 else
574 {
575 // if the adaptor isn't open anymore, and wasn't handed to a
576 // websocket, treat as an error
577 if (!isAlive() &&
578 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700579 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700580 errorWhileReading = true;
581 }
582 }
583
584 cancelDeadlineTimer();
585
586 if (errorWhileReading)
587 {
588 close();
589 BMCWEB_LOG_DEBUG << this << " from read(1)";
590 return;
591 }
592
593 readClientIp();
594
595 boost::asio::ip::address ip;
596 if (getClientIp(ip))
597 {
598 BMCWEB_LOG_DEBUG << "Unable to get client IP";
599 }
600 sessionIsFromTransport = false;
601#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
602 boost::beast::http::verb method = parser->get().method();
603 userSession = crow::authentication::authenticate(
604 ip, res, method, parser->get().base(), userSession);
605
606 bool loggedIn = userSession != nullptr;
607 if (!loggedIn)
608 {
609 const boost::optional<uint64_t> contentLength =
610 parser->content_length();
611 if (contentLength && *contentLength > loggedOutPostBodyLimit)
612 {
613 BMCWEB_LOG_DEBUG << "Content length greater than limit "
614 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700615 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 return;
617 }
618
Ed Tanous002d39b2022-05-31 08:59:27 -0700619 BMCWEB_LOG_DEBUG << "Starting quick deadline";
620 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000621#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800622
Ed Tanous002d39b2022-05-31 08:59:27 -0700623 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700624 });
625 }
626
627 void doRead()
628 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800630 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700631 boost::beast::http::async_read(adaptor, buffer, *parser,
632 [this, self(shared_from_this())](
633 const boost::system::error_code& ec,
634 std::size_t bytesTransferred) {
635 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
636 << " Bytes";
637 cancelDeadlineTimer();
638 if (ec)
639 {
640 BMCWEB_LOG_ERROR << this
641 << " Error while reading: " << ec.message();
642 close();
643 BMCWEB_LOG_DEBUG << this << " from read(1)";
644 return;
645 }
646 handle();
647 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 }
649
Nan Zhou72374eb2022-01-27 17:06:51 -0800650 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100652 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800653 thisRes.preparePayload();
654 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800655 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700656 boost::beast::http::async_write(adaptor, *serializer,
657 [this, self(shared_from_this())](
658 const boost::system::error_code& ec,
659 std::size_t bytesTransferred) {
660 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
661 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662
Ed Tanous002d39b2022-05-31 08:59:27 -0700663 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700664
Ed Tanous002d39b2022-05-31 08:59:27 -0700665 if (ec)
666 {
667 BMCWEB_LOG_DEBUG << this << " from write(2)";
668 return;
669 }
670 if (!res.keepAlive())
671 {
672 close();
673 BMCWEB_LOG_DEBUG << this << " from write(1)";
674 return;
675 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676
Ed Tanous002d39b2022-05-31 08:59:27 -0700677 serializer.reset();
678 BMCWEB_LOG_DEBUG << this << " Clearing response";
679 res.clear();
680 parser.emplace(std::piecewise_construct, std::make_tuple());
681 parser->body_limit(httpReqBodyLimit); // reset body limit for
682 // newly created parser
683 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684
Ed Tanous002d39b2022-05-31 08:59:27 -0700685 // If the session was built from the transport, we don't need to
686 // clear it. All other sessions are generated per request.
687 if (!sessionIsFromTransport)
688 {
689 userSession = nullptr;
690 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700691
Ed Tanous002d39b2022-05-31 08:59:27 -0700692 // Destroy the Request via the std::optional
693 req.reset();
694 doReadHeaders();
695 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700696 }
697
Ed Tanous1abe55e2018-09-05 08:30:59 -0700698 void cancelDeadlineTimer()
699 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800700 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700701 }
702
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800703 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700704 {
705 cancelDeadlineTimer();
706
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800707 std::chrono::seconds timeout(15);
708 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800709 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800710 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700711 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800712 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700713 return;
714 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800715
716 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
717 timer.expires_after(timeout);
718 timer.async_wait([weakSelf](const boost::system::error_code ec) {
719 // Note, we are ignoring other types of errors here; If the timer
720 // failed for any reason, we should still close the connection
721
722 std::shared_ptr<Connection<Adaptor, Handler>> self =
723 weakSelf.lock();
724 if (!self)
725 {
726 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
727 return;
728 }
729 if (ec == boost::asio::error::operation_aborted)
730 {
731 // Canceled wait means the path succeeeded.
732 return;
733 }
734 if (ec)
735 {
736 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
737 }
738
739 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
740
741 self->close();
742 });
743
744 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700745 }
746
Ed Tanous1abe55e2018-09-05 08:30:59 -0700747 Adaptor adaptor;
748 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800749 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800751 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752 boost::beast::http::request_parser<boost::beast::http::string_body>>
753 parser;
754
Ed Tanous3112a142018-11-29 15:45:10 -0800755 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700756
Ed Tanousa24526d2018-12-10 15:17:59 -0800757 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758 boost::beast::http::string_body>>
759 serializer;
760
Ed Tanousa24526d2018-12-10 15:17:59 -0800761 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700763
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700764 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700765 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700766
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800767 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000770
771 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700772 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800773
774 using std::enable_shared_from_this<
775 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800776};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700777} // namespace crow