blob: 2ea3f18b276c88bc4ba4b44fa03a8912fb470f1b [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 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>
Ed Tanous918ef252022-05-25 10:40:41 -070017#include <boost/beast/http/parser.hpp>
18#include <boost/beast/http/read.hpp>
19#include <boost/beast/http/serializer.hpp>
20#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053021#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070023#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070024#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070025#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050026#include <ssl_key_handler.hpp>
27
Manojkiran Eda44250442020-06-16 12:51:38 +053028#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050029#include <chrono>
30#include <vector>
31
Ed Tanous1abe55e2018-09-05 08:30:59 -070032namespace crow
33{
Ed Tanous257f5792018-03-17 14:40:09 -070034
Ed Tanous1abe55e2018-09-05 08:30:59 -070035inline void prettyPrintJson(crow::Response& res)
36{
Ed Tanous57fce802019-05-21 13:00:34 -070037 json_html_util::dumpHtml(res.body(), res.jsonValue);
38
Ed Tanous93ef5802019-01-03 10:15:41 -080039 res.addHeader("Content-Type", "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
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 adaptor.set_verify_callback([this](
119 bool preverified,
120 boost::asio::ssl::verify_context& ctx) {
121 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700122 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100123 .getAuthMethodsConfig()
124 .tls)
125 {
126 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200127 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100128 }
129
130 // We always return true to allow full auth flow
131 if (!preverified)
132 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100133 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100134 return true;
135 }
136
137 X509_STORE_CTX* cts = ctx.native_handle();
138 if (cts == nullptr)
139 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100140 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100141 return true;
142 }
143
144 // Get certificate
145 X509* peerCert =
146 X509_STORE_CTX_get_current_cert(ctx.native_handle());
147 if (peerCert == nullptr)
148 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100149 BMCWEB_LOG_DEBUG << this
150 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100151 return true;
152 }
153
154 // Check if certificate is OK
155 int error = X509_STORE_CTX_get_error(cts);
156 if (error != X509_V_OK)
157 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100158 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100159 return true;
160 }
161 // Check that we have reached final certificate in chain
162 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
163 if (depth != 0)
164
165 {
166 BMCWEB_LOG_DEBUG
167 << this << " Certificate verification in progress (depth "
168 << depth << "), waiting to reach final depth";
169 return true;
170 }
171
172 BMCWEB_LOG_DEBUG << this
173 << " Certificate verification of final depth";
174
175 // Verify KeyUsage
176 bool isKeyUsageDigitalSignature = false;
177 bool isKeyUsageKeyAgreement = false;
178
179 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000180 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100181
182 if (usage == nullptr)
183 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100184 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100185 return true;
186 }
187
188 for (int i = 0; i < usage->length; i++)
189 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800190 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
191 unsigned char usageChar = usage->data[i];
192 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100193 {
194 isKeyUsageDigitalSignature = true;
195 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800196 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100197 {
198 isKeyUsageKeyAgreement = true;
199 }
200 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700201 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100202
203 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
204 {
205 BMCWEB_LOG_DEBUG << this
206 << " Certificate ExtendedKeyUsage does "
207 "not allow provided certificate to "
208 "be used for user authentication";
209 return true;
210 }
211
212 // Determine that ExtendedKeyUsage includes Client Auth
213
Ed Tanous23a21a12020-07-25 04:45:05 +0000214 stack_st_ASN1_OBJECT* extUsage =
215 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
216 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100217
218 if (extUsage == nullptr)
219 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100220 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100221 return true;
222 }
223
224 bool isExKeyUsageClientAuth = false;
225 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
226 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800227 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
228 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
229 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100230 {
231 isExKeyUsageClientAuth = true;
232 break;
233 }
234 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200235 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100236
237 // Certificate has to have proper key usages set
238 if (!isExKeyUsageClientAuth)
239 {
240 BMCWEB_LOG_DEBUG << this
241 << " Certificate ExtendedKeyUsage does "
242 "not allow provided certificate to "
243 "be used for user authentication";
244 return true;
245 }
246 std::string sslUser;
247 // Extract username contained in CommonName
248 sslUser.resize(256, '\0');
249
250 int status = X509_NAME_get_text_by_NID(
251 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
252 static_cast<int>(sslUser.size()));
253
254 if (status == -1)
255 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100256 BMCWEB_LOG_DEBUG
257 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100258 return true;
259 }
260
261 size_t lastChar = sslUser.find('\0');
262 if (lastChar == std::string::npos || lastChar == 0)
263 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100264 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100265 return true;
266 }
267 sslUser.resize(lastChar);
Ed Tanouse05aec52022-01-25 10:28:56 -0800268 std::string unsupportedClientId;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700269 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700270 userSession = persistent_data::SessionStore::getInstance()
271 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800272 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700273 persistent_data::PersistenceType::TIMEOUT);
274 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100275 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700276 BMCWEB_LOG_DEBUG
277 << this
278 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100279 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100280 return true;
281 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700282 }
283
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800286 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700287 }
288
Ed Tanous1abe55e2018-09-05 08:30:59 -0700289 void start()
290 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800291 if (connectionCount >= 100)
292 {
293 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
294 return;
295 }
296
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800297 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500298
Ed Tanousceac6f72018-12-02 11:58:47 -0800299 // TODO(ed) Abstract this to a more clever class with the idea of an
300 // asynchronous "start"
301 if constexpr (std::is_same_v<Adaptor,
302 boost::beast::ssl_stream<
303 boost::asio::ip::tcp::socket>>)
304 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000305 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
306 [this, self(shared_from_this())](
307 const boost::system::error_code& ec) {
308 if (ec)
309 {
310 return;
311 }
312 doReadHeaders();
313 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800314 }
315 else
316 {
317 doReadHeaders();
318 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700319 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700320
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 void handle()
322 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700323 std::error_code reqEc;
324 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
325 if (reqEc)
326 {
327 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
328 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(
368 req->url, req->getHeaderValue("User-Agent"),
369 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) {
378 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 Tanous596b2032021-09-13 10:32:22 -0700392 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700393 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700394
Ed Tanouse278c182019-03-13 16:23:37 -0700395 bool isAlive()
396 {
Ed Tanouse278c182019-03-13 16:23:37 -0700397 if constexpr (std::is_same_v<Adaptor,
398 boost::beast::ssl_stream<
399 boost::asio::ip::tcp::socket>>)
400 {
401 return adaptor.next_layer().is_open();
402 }
403 else
404 {
405 return adaptor.is_open();
406 }
407 }
408 void close()
409 {
Ed Tanouse278c182019-03-13 16:23:37 -0700410 if constexpr (std::is_same_v<Adaptor,
411 boost::beast::ssl_stream<
412 boost::asio::ip::tcp::socket>>)
413 {
414 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800415 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200416 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700417 BMCWEB_LOG_DEBUG
418 << this
419 << " Removing TLS session: " << userSession->uniqueId;
420 persistent_data::SessionStore::getInstance().removeSession(
421 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200422 }
Ed Tanouse278c182019-03-13 16:23:37 -0700423 }
424 else
425 {
426 adaptor.close();
427 }
428 }
429
Nan Zhou72374eb2022-01-27 17:06:51 -0800430 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700432 if (!req)
433 {
434 return;
435 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800436 res = std::move(thisRes);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
438 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700439
Ed Tanous0260d9d2021-02-07 19:31:07 +0000440 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700441
Nan Zhoud055a342022-05-25 01:15:34 +0000442 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700443
Ed Tanouse278c182019-03-13 16:23:37 -0700444 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 {
446 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
447 // isReading
448 // << ' ' << isWriting;
449 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000450
451 // delete lambda with self shared_ptr
452 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700453 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700454 return;
455 }
456 if (res.body().empty() && !res.jsonValue.empty())
457 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700458 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700459 {
460 prettyPrintJson(res);
461 }
462 else
463 {
464 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800465 res.body() = res.jsonValue.dump(
466 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 }
468 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700469
Ed Tanous1abe55e2018-09-05 08:30:59 -0700470 if (res.resultInt() >= 400 && res.body().empty())
471 {
472 res.body() = std::string(res.reason());
473 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700474
475 if (res.result() == boost::beast::http::status::no_content)
476 {
477 // Boost beast throws if content is provided on a no-content
478 // response. Ideally, this would never happen, but in the case that
479 // it does, we don't want to throw.
480 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100481 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700482 res.body().clear();
483 }
484
Ed Tanous1abe55e2018-09-05 08:30:59 -0700485 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
486
487 res.keepAlive(req->keepAlive());
488
Nan Zhou72374eb2022-01-27 17:06:51 -0800489 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000490
491 // delete lambda with self shared_ptr
492 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700493 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700494 }
495
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500496 void readClientIp()
497 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700498 boost::asio::ip::address ip;
499 boost::system::error_code ec = getClientIp(ip);
500 if (ec)
501 {
502 return;
503 }
504 req->ipAddress = ip;
505 }
506
507 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
508 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500509 boost::system::error_code ec;
510 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
511 boost::asio::ip::tcp::endpoint endpoint =
512 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
513
514 if (ec)
515 {
516 // If remote endpoint fails keep going. "ClientOriginIPAddress"
517 // will be empty.
518 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
519 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700520 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500521 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700522 ip = endpoint.address();
523 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500524 }
525
Ed Tanous1abe55e2018-09-05 08:30:59 -0700526 private:
527 void doReadHeaders()
528 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700529 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
530
531 // Clean up any previous Connection.
532 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800533 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000534 [this,
535 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000536 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500537 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000538 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700539 bool errorWhileReading = false;
540 if (ec)
541 {
542 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500543 if (ec == boost::asio::error::eof)
544 {
545 BMCWEB_LOG_WARNING
546 << this << " Error while reading: " << ec.message();
547 }
548 else
549 {
550 BMCWEB_LOG_ERROR
551 << this << " Error while reading: " << ec.message();
552 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553 }
554 else
555 {
556 // if the adaptor isn't open anymore, and wasn't handed to a
557 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700558 if (!isAlive() &&
559 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700560 {
561 errorWhileReading = true;
562 }
563 }
564
James Feist3909dc82020-04-03 10:58:55 -0700565 cancelDeadlineTimer();
566
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 if (errorWhileReading)
568 {
Ed Tanouse278c182019-03-13 16:23:37 -0700569 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700570 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571 return;
572 }
573
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700574 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700575
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700576 boost::asio::ip::address ip;
577 if (getClientIp(ip))
578 {
579 BMCWEB_LOG_DEBUG << "Unable to get client IP";
580 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700581 sessionIsFromTransport = false;
Nan Zhoua43ea822022-05-27 00:42:44 +0000582#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou8682c5a2021-11-13 11:00:07 -0800583 boost::beast::http::verb method = parser->get().method();
Nan Zhoud055a342022-05-25 01:15:34 +0000584 userSession = crow::authentication::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700585 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800586
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700587 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800588 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700589 {
590 const boost::optional<uint64_t> contentLength =
591 parser->content_length();
592 if (contentLength &&
593 *contentLength > loggedOutPostBodyLimit)
594 {
595 BMCWEB_LOG_DEBUG << "Content length greater than limit "
596 << *contentLength;
597 close();
598 return;
599 }
600
James Feist3909dc82020-04-03 10:58:55 -0700601 BMCWEB_LOG_DEBUG << "Starting quick deadline";
602 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000603#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800604
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605 doRead();
606 });
607 }
608
609 void doRead()
610 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800612 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800614 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000615 [this,
616 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000617 std::size_t bytesTransferred) {
618 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800620 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700621 if (ec)
622 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100623 BMCWEB_LOG_ERROR
624 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700625 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700626 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627 return;
628 }
629 handle();
630 });
631 }
632
Nan Zhou72374eb2022-01-27 17:06:51 -0800633 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100635 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800636 thisRes.preparePayload();
637 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800638 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800640 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000641 [this,
642 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000643 std::size_t bytesTransferred) {
644 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 << " bytes";
646
James Feist54d8bb12020-07-20 13:28:59 -0700647 cancelDeadlineTimer();
648
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 if (ec)
650 {
651 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700652 return;
653 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800654 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700655 {
Ed Tanouse278c182019-03-13 16:23:37 -0700656 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 return;
659 }
660
661 serializer.reset();
662 BMCWEB_LOG_DEBUG << this << " Clearing response";
663 res.clear();
664 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500665 parser->body_limit(httpReqBodyLimit); // reset body limit for
666 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700667 buffer.consume(buffer.size());
668
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700669 // If the session was built from the transport, we don't need to
670 // clear it. All other sessions are generated per request.
671 if (!sessionIsFromTransport)
672 {
673 userSession = nullptr;
674 }
675
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700676 // Destroy the Request via the std::optional
677 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 doReadHeaders();
679 });
680 }
681
Ed Tanous1abe55e2018-09-05 08:30:59 -0700682 void cancelDeadlineTimer()
683 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800684 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 }
686
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700688 {
689 cancelDeadlineTimer();
690
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800691 std::chrono::seconds timeout(15);
692 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800693 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800694 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700695 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800696 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700697 return;
698 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800699
700 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
701 timer.expires_after(timeout);
702 timer.async_wait([weakSelf](const boost::system::error_code ec) {
703 // Note, we are ignoring other types of errors here; If the timer
704 // failed for any reason, we should still close the connection
705
706 std::shared_ptr<Connection<Adaptor, Handler>> self =
707 weakSelf.lock();
708 if (!self)
709 {
710 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
711 return;
712 }
713 if (ec == boost::asio::error::operation_aborted)
714 {
715 // Canceled wait means the path succeeeded.
716 return;
717 }
718 if (ec)
719 {
720 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
721 }
722
723 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
724
725 self->close();
726 });
727
728 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700729 }
730
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731 Adaptor adaptor;
732 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800733 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700734 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800735 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736 boost::beast::http::request_parser<boost::beast::http::string_body>>
737 parser;
738
Ed Tanous3112a142018-11-29 15:45:10 -0800739 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700740
Ed Tanousa24526d2018-12-10 15:17:59 -0800741 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 boost::beast::http::string_body>>
743 serializer;
744
Ed Tanousa24526d2018-12-10 15:17:59 -0800745 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700747
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700748 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700749 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800751 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000754
755 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700756 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800757
758 using std::enable_shared_from_this<
759 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800760};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700761} // namespace crow