blob: 6de2bf7a0af029c012768e331ac1119b78f4697a [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08002#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06003
James Feist3909dc82020-04-03 10:58:55 -07004#include "authorization.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07005#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07006#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "logging.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanouse0d918b2018-03-27 17:41:04 -070010#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070011#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080012#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080013#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070014#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080015#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/beast/core/flat_static_buffer.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053017#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070019#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070020#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070021#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Ed Tanous57fce802019-05-21 13:00:34 -070033 json_html_util::dumpHtml(res.body(), res.jsonValue);
34
Ed Tanous93ef5802019-01-03 10:15:41 -080035 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070036}
37
Ed Tanous6fbdbca2021-12-06 14:36:06 -080038static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070039
Ed Tanous0260d9d2021-02-07 19:31:07 +000040// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080041constexpr uint64_t httpReqBodyLimit =
42 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
James Feist3909dc82020-04-03 10:58:55 -070044constexpr uint64_t loggedOutPostBodyLimit = 4096;
45
46constexpr uint32_t httpHeaderLimit = 8192;
47
Ed Tanous52cc1122020-07-18 13:51:21 -070048template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050049class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070050 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070051{
52 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080053 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000054 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 handler(handlerIn), timer(std::move(timerIn)),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
60 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070062 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020063
64#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070065 prepareMutualTls();
66#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
67
Ed Tanous40aa0582021-07-14 13:24:40 -070068 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080069
Ed Tanous40aa0582021-07-14 13:24:40 -070070 BMCWEB_LOG_DEBUG << this << " Connection open, total "
71 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070072 }
73
74 ~Connection()
75 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070076 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount--;
80 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
84 void prepareMutualTls()
85 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080086 std::error_code error;
87 std::filesystem::path caPath(ensuressl::trustStorePath);
88 auto caAvailable = !std::filesystem::is_empty(caPath, error);
89 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070090 if (caAvailable && persistent_data::SessionStore::getInstance()
91 .getAuthMethodsConfig()
92 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010093 {
94 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070095 std::string id = "bmcweb";
96 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010097 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070098 reinterpret_cast<const unsigned char*>(id.c_str()),
99 static_cast<unsigned int>(id.length()));
100 if (ret == 0)
101 {
102 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
103 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100104 }
105
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100106 adaptor.set_verify_callback([this](
107 bool preverified,
108 boost::asio::ssl::verify_context& ctx) {
109 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700110 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100111 .getAuthMethodsConfig()
112 .tls)
113 {
114 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200115 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100116 }
117
118 // We always return true to allow full auth flow
119 if (!preverified)
120 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100121 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100122 return true;
123 }
124
125 X509_STORE_CTX* cts = ctx.native_handle();
126 if (cts == nullptr)
127 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100128 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100129 return true;
130 }
131
132 // Get certificate
133 X509* peerCert =
134 X509_STORE_CTX_get_current_cert(ctx.native_handle());
135 if (peerCert == nullptr)
136 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100137 BMCWEB_LOG_DEBUG << this
138 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100139 return true;
140 }
141
142 // Check if certificate is OK
143 int error = X509_STORE_CTX_get_error(cts);
144 if (error != X509_V_OK)
145 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100146 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100147 return true;
148 }
149 // Check that we have reached final certificate in chain
150 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
151 if (depth != 0)
152
153 {
154 BMCWEB_LOG_DEBUG
155 << this << " Certificate verification in progress (depth "
156 << depth << "), waiting to reach final depth";
157 return true;
158 }
159
160 BMCWEB_LOG_DEBUG << this
161 << " Certificate verification of final depth";
162
163 // Verify KeyUsage
164 bool isKeyUsageDigitalSignature = false;
165 bool isKeyUsageKeyAgreement = false;
166
167 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000168 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100169
170 if (usage == nullptr)
171 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100172 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100173 return true;
174 }
175
176 for (int i = 0; i < usage->length; i++)
177 {
178 if (KU_DIGITAL_SIGNATURE & usage->data[i])
179 {
180 isKeyUsageDigitalSignature = true;
181 }
182 if (KU_KEY_AGREEMENT & usage->data[i])
183 {
184 isKeyUsageKeyAgreement = true;
185 }
186 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700187 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100188
189 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
190 {
191 BMCWEB_LOG_DEBUG << this
192 << " Certificate ExtendedKeyUsage does "
193 "not allow provided certificate to "
194 "be used for user authentication";
195 return true;
196 }
197
198 // Determine that ExtendedKeyUsage includes Client Auth
199
Ed Tanous23a21a12020-07-25 04:45:05 +0000200 stack_st_ASN1_OBJECT* extUsage =
201 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
202 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100203
204 if (extUsage == nullptr)
205 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100206 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100207 return true;
208 }
209
210 bool isExKeyUsageClientAuth = false;
211 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
212 {
213 if (NID_client_auth ==
214 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
215 {
216 isExKeyUsageClientAuth = true;
217 break;
218 }
219 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200220 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100221
222 // Certificate has to have proper key usages set
223 if (!isExKeyUsageClientAuth)
224 {
225 BMCWEB_LOG_DEBUG << this
226 << " Certificate ExtendedKeyUsage does "
227 "not allow provided certificate to "
228 "be used for user authentication";
229 return true;
230 }
231 std::string sslUser;
232 // Extract username contained in CommonName
233 sslUser.resize(256, '\0');
234
235 int status = X509_NAME_get_text_by_NID(
236 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
237 static_cast<int>(sslUser.size()));
238
239 if (status == -1)
240 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100241 BMCWEB_LOG_DEBUG
242 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100243 return true;
244 }
245
246 size_t lastChar = sslUser.find('\0');
247 if (lastChar == std::string::npos || lastChar == 0)
248 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100249 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100250 return true;
251 }
252 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530253 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700254 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700255 userSession = persistent_data::SessionStore::getInstance()
256 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800257 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700258 persistent_data::PersistenceType::TIMEOUT);
259 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100260 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700261 BMCWEB_LOG_DEBUG
262 << this
263 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100264 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100265 return true;
266 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700267 }
268
Ed Tanousceac6f72018-12-02 11:58:47 -0800269 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700270 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800271 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700272 }
273
Ed Tanous1abe55e2018-09-05 08:30:59 -0700274 void start()
275 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800276 if (connectionCount >= 100)
277 {
278 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
279 return;
280 }
281
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800282 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500283
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 // TODO(ed) Abstract this to a more clever class with the idea of an
285 // asynchronous "start"
286 if constexpr (std::is_same_v<Adaptor,
287 boost::beast::ssl_stream<
288 boost::asio::ip::tcp::socket>>)
289 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000290 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
291 [this, self(shared_from_this())](
292 const boost::system::error_code& ec) {
293 if (ec)
294 {
295 return;
296 }
297 doReadHeaders();
298 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800299 }
300 else
301 {
302 doReadHeaders();
303 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700304 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700305
Ed Tanous1abe55e2018-09-05 08:30:59 -0700306 void handle()
307 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700308 std::error_code reqEc;
309 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
310 if (reqEc)
311 {
312 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
313 return;
314 }
Ed Tanous596b2032021-09-13 10:32:22 -0700315 thisReq.session = userSession;
316
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000317 // Fetch the client IP address
318 readClientIp();
319
Ed Tanous1abe55e2018-09-05 08:30:59 -0700320 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700321 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700322 {
Ed Tanous596b2032021-09-13 10:32:22 -0700323 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700324 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700325 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600326 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700327 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 }
329 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanouse278c182019-03-13 16:23:37 -0700331 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700332 << " " << this << " HTTP/" << thisReq.version() / 10
333 << "." << thisReq.version() % 10 << ' '
334 << thisReq.methodString() << " " << thisReq.target()
335 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700336
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700337 res.setCompleteRequestHandler(nullptr);
338 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700339
Ed Tanous596b2032021-09-13 10:32:22 -0700340 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700341 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200342
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700343 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700344 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600345 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700346 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700347 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800348#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700349 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700350 thisReq.session == nullptr)
351 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600352 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700353 forward_unauthorized::sendUnauthorized(
354 req->url, req->getHeaderValue("User-Agent"),
355 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600356 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700357 return;
358 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800359#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600360 res.setCompleteRequestHandler([self(shared_from_this())] {
361 boost::asio::post(self->adaptor.get_executor(),
362 [self] { self->completeRequest(); });
363 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700364
Ed Tanous596b2032021-09-13 10:32:22 -0700365 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700366 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700367 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700368 "websocket"))
369 {
Ed Tanous596b2032021-09-13 10:32:22 -0700370 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700371 // delete lambda with self shared_ptr
372 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600373 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700374 return;
375 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600376 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700377 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700378 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700379
Ed Tanouse278c182019-03-13 16:23:37 -0700380 bool isAlive()
381 {
Ed Tanouse278c182019-03-13 16:23:37 -0700382 if constexpr (std::is_same_v<Adaptor,
383 boost::beast::ssl_stream<
384 boost::asio::ip::tcp::socket>>)
385 {
386 return adaptor.next_layer().is_open();
387 }
388 else
389 {
390 return adaptor.is_open();
391 }
392 }
393 void close()
394 {
Ed Tanouse278c182019-03-13 16:23:37 -0700395 if constexpr (std::is_same_v<Adaptor,
396 boost::beast::ssl_stream<
397 boost::asio::ip::tcp::socket>>)
398 {
399 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600400#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
401 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200402 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700403 BMCWEB_LOG_DEBUG
404 << this
405 << " Removing TLS session: " << userSession->uniqueId;
406 persistent_data::SessionStore::getInstance().removeSession(
407 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200408 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600409#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700410 }
411 else
412 {
413 adaptor.close();
414 }
415 }
416
Gunnar Mills9062d472021-11-16 11:37:47 -0600417 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700419 if (!req)
420 {
421 return;
422 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
424 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425
Ed Tanous0260d9d2021-02-07 19:31:07 +0000426 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700427
Ed Tanouscf099fa2021-08-25 12:37:31 -0700428 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700429
Ed Tanouse278c182019-03-13 16:23:37 -0700430 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 {
432 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
433 // isReading
434 // << ' ' << isWriting;
435 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000436
437 // delete lambda with self shared_ptr
438 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700439 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 return;
441 }
442 if (res.body().empty() && !res.jsonValue.empty())
443 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700444 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 {
446 prettyPrintJson(res);
447 }
448 else
449 {
450 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800451 res.body() = res.jsonValue.dump(
452 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700453 }
454 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700455
Ed Tanous1abe55e2018-09-05 08:30:59 -0700456 if (res.resultInt() >= 400 && res.body().empty())
457 {
458 res.body() = std::string(res.reason());
459 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700460
461 if (res.result() == boost::beast::http::status::no_content)
462 {
463 // Boost beast throws if content is provided on a no-content
464 // response. Ideally, this would never happen, but in the case that
465 // it does, we don't want to throw.
466 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100467 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700468 res.body().clear();
469 }
470
Ed Tanous1abe55e2018-09-05 08:30:59 -0700471 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
472
473 res.keepAlive(req->keepAlive());
474
Gunnar Mills9062d472021-11-16 11:37:47 -0600475 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000476
477 // delete lambda with self shared_ptr
478 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700479 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 }
481
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500482 void readClientIp()
483 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700484 boost::asio::ip::address ip;
485 boost::system::error_code ec = getClientIp(ip);
486 if (ec)
487 {
488 return;
489 }
490 req->ipAddress = ip;
491 }
492
493 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
494 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500495 boost::system::error_code ec;
496 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
497 boost::asio::ip::tcp::endpoint endpoint =
498 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
499
500 if (ec)
501 {
502 // If remote endpoint fails keep going. "ClientOriginIPAddress"
503 // will be empty.
504 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
505 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700506 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500507 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700508 ip = endpoint.address();
509 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500510 }
511
Ed Tanous1abe55e2018-09-05 08:30:59 -0700512 private:
513 void doReadHeaders()
514 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
516
517 // Clean up any previous Connection.
518 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800519 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000520 [this,
521 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000522 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500523 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000524 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 bool errorWhileReading = false;
526 if (ec)
527 {
528 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500529 if (ec == boost::asio::error::eof)
530 {
531 BMCWEB_LOG_WARNING
532 << this << " Error while reading: " << ec.message();
533 }
534 else
535 {
536 BMCWEB_LOG_ERROR
537 << this << " Error while reading: " << ec.message();
538 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700539 }
540 else
541 {
542 // if the adaptor isn't open anymore, and wasn't handed to a
543 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700544 if (!isAlive() &&
545 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 {
547 errorWhileReading = true;
548 }
549 }
550
James Feist3909dc82020-04-03 10:58:55 -0700551 cancelDeadlineTimer();
552
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553 if (errorWhileReading)
554 {
Ed Tanouse278c182019-03-13 16:23:37 -0700555 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 return;
558 }
559
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700560 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700561
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700562 boost::asio::ip::address ip;
563 if (getClientIp(ip))
564 {
565 BMCWEB_LOG_DEBUG << "Unable to get client IP";
566 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700567 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800568#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
569 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700570 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700571 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800572
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700573 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700575 {
576 const boost::optional<uint64_t> contentLength =
577 parser->content_length();
578 if (contentLength &&
579 *contentLength > loggedOutPostBodyLimit)
580 {
581 BMCWEB_LOG_DEBUG << "Content length greater than limit "
582 << *contentLength;
583 close();
584 return;
585 }
586
James Feist3909dc82020-04-03 10:58:55 -0700587 BMCWEB_LOG_DEBUG << "Starting quick deadline";
588 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800589#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800590
Ed Tanous1abe55e2018-09-05 08:30:59 -0700591 doRead();
592 });
593 }
594
595 void doRead()
596 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800598 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700599 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800600 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000601 [this,
602 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000603 std::size_t bytesTransferred) {
604 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800606 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700607 if (ec)
608 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100609 BMCWEB_LOG_ERROR
610 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700611 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 return;
614 }
615 handle();
616 });
617 }
618
Gunnar Mills9062d472021-11-16 11:37:47 -0600619 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100621 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600622 res.preparePayload();
623 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800624 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800626 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000627 [this,
628 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000629 std::size_t bytesTransferred) {
630 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 << " bytes";
632
James Feist54d8bb12020-07-20 13:28:59 -0700633 cancelDeadlineTimer();
634
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 if (ec)
636 {
637 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 return;
639 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800640 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 {
Ed Tanouse278c182019-03-13 16:23:37 -0700642 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 return;
645 }
646
647 serializer.reset();
648 BMCWEB_LOG_DEBUG << this << " Clearing response";
649 res.clear();
650 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500651 parser->body_limit(httpReqBodyLimit); // reset body limit for
652 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 buffer.consume(buffer.size());
654
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700655 // If the session was built from the transport, we don't need to
656 // clear it. All other sessions are generated per request.
657 if (!sessionIsFromTransport)
658 {
659 userSession = nullptr;
660 }
661
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700662 // Destroy the Request via the std::optional
663 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 doReadHeaders();
665 });
666 }
667
Ed Tanous1abe55e2018-09-05 08:30:59 -0700668 void cancelDeadlineTimer()
669 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800670 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 }
672
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800673 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700674 {
675 cancelDeadlineTimer();
676
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800677 std::chrono::seconds timeout(15);
678 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800679 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700681 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800682 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700683 return;
684 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800685
686 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
687 timer.expires_after(timeout);
688 timer.async_wait([weakSelf](const boost::system::error_code ec) {
689 // Note, we are ignoring other types of errors here; If the timer
690 // failed for any reason, we should still close the connection
691
692 std::shared_ptr<Connection<Adaptor, Handler>> self =
693 weakSelf.lock();
694 if (!self)
695 {
696 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
697 return;
698 }
699 if (ec == boost::asio::error::operation_aborted)
700 {
701 // Canceled wait means the path succeeeded.
702 return;
703 }
704 if (ec)
705 {
706 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
707 }
708
709 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
710
711 self->close();
712 });
713
714 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700715 }
716
717 private:
718 Adaptor adaptor;
719 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800720 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700721 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800722 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700723 boost::beast::http::request_parser<boost::beast::http::string_body>>
724 parser;
725
Ed Tanous3112a142018-11-29 15:45:10 -0800726 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700727
Ed Tanousa24526d2018-12-10 15:17:59 -0800728 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700729 boost::beast::http::string_body>>
730 serializer;
731
Ed Tanousa24526d2018-12-10 15:17:59 -0800732 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700733 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700734
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700735 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700736 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700737
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800738 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739
Ed Tanous1abe55e2018-09-05 08:30:59 -0700740 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000741
742 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700743 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800744
745 using std::enable_shared_from_this<
746 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800747};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748} // namespace crow