blob: 77886c5da1ca4f456462d6cad98fd18441389130 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08002#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06003
James Feist3909dc82020-04-03 10:58:55 -07004#include "authorization.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07005#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07006#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "logging.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanouse0d918b2018-03-27 17:41:04 -070010#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070011#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080012#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080013#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070014#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080015#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/beast/core/flat_static_buffer.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053017#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070019#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070020#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070021#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Ed Tanous57fce802019-05-21 13:00:34 -070033 json_html_util::dumpHtml(res.body(), res.jsonValue);
34
Ed Tanous93ef5802019-01-03 10:15:41 -080035 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070036}
37
Ed Tanous6fbdbca2021-12-06 14:36:06 -080038static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070039
Ed Tanous0260d9d2021-02-07 19:31:07 +000040// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080041constexpr uint64_t httpReqBodyLimit =
42 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
James Feist3909dc82020-04-03 10:58:55 -070044constexpr uint64_t loggedOutPostBodyLimit = 4096;
45
46constexpr uint32_t httpHeaderLimit = 8192;
47
Ed Tanous52cc1122020-07-18 13:51:21 -070048template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050049class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070050 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070051{
52 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080053 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000054 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 handler(handlerIn), timer(std::move(timerIn)),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
60 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070062 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020063
64#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070065 prepareMutualTls();
66#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
67
Ed Tanous40aa0582021-07-14 13:24:40 -070068 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080069
Ed Tanous40aa0582021-07-14 13:24:40 -070070 BMCWEB_LOG_DEBUG << this << " Connection open, total "
71 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070072 }
73
74 ~Connection()
75 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070076 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount--;
80 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
Ed Tanousecd6a3a2022-01-07 09:18:40 -080084 Connection(const Connection&) = delete;
85 Connection(Connection&&) = delete;
86 Connection& operator=(const Connection&) = delete;
87 Connection& operator=(Connection&&) = delete;
88
Ed Tanous40aa0582021-07-14 13:24:40 -070089 void prepareMutualTls()
90 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080091 std::error_code error;
92 std::filesystem::path caPath(ensuressl::trustStorePath);
93 auto caAvailable = !std::filesystem::is_empty(caPath, error);
94 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070095 if (caAvailable && persistent_data::SessionStore::getInstance()
96 .getAuthMethodsConfig()
97 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010098 {
99 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700100 std::string id = "bmcweb";
101 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100102 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700103 reinterpret_cast<const unsigned char*>(id.c_str()),
104 static_cast<unsigned int>(id.length()));
105 if (ret == 0)
106 {
107 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
108 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100109 }
110
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100111 adaptor.set_verify_callback([this](
112 bool preverified,
113 boost::asio::ssl::verify_context& ctx) {
114 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700115 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100116 .getAuthMethodsConfig()
117 .tls)
118 {
119 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200120 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100121 }
122
123 // We always return true to allow full auth flow
124 if (!preverified)
125 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100126 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100127 return true;
128 }
129
130 X509_STORE_CTX* cts = ctx.native_handle();
131 if (cts == nullptr)
132 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100133 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100134 return true;
135 }
136
137 // Get certificate
138 X509* peerCert =
139 X509_STORE_CTX_get_current_cert(ctx.native_handle());
140 if (peerCert == nullptr)
141 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100142 BMCWEB_LOG_DEBUG << this
143 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100144 return true;
145 }
146
147 // Check if certificate is OK
148 int error = X509_STORE_CTX_get_error(cts);
149 if (error != X509_V_OK)
150 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100151 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100152 return true;
153 }
154 // Check that we have reached final certificate in chain
155 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
156 if (depth != 0)
157
158 {
159 BMCWEB_LOG_DEBUG
160 << this << " Certificate verification in progress (depth "
161 << depth << "), waiting to reach final depth";
162 return true;
163 }
164
165 BMCWEB_LOG_DEBUG << this
166 << " Certificate verification of final depth";
167
168 // Verify KeyUsage
169 bool isKeyUsageDigitalSignature = false;
170 bool isKeyUsageKeyAgreement = false;
171
172 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000173 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100174
175 if (usage == nullptr)
176 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100177 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100178 return true;
179 }
180
181 for (int i = 0; i < usage->length; i++)
182 {
183 if (KU_DIGITAL_SIGNATURE & usage->data[i])
184 {
185 isKeyUsageDigitalSignature = true;
186 }
187 if (KU_KEY_AGREEMENT & usage->data[i])
188 {
189 isKeyUsageKeyAgreement = true;
190 }
191 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700192 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100193
194 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
195 {
196 BMCWEB_LOG_DEBUG << this
197 << " Certificate ExtendedKeyUsage does "
198 "not allow provided certificate to "
199 "be used for user authentication";
200 return true;
201 }
202
203 // Determine that ExtendedKeyUsage includes Client Auth
204
Ed Tanous23a21a12020-07-25 04:45:05 +0000205 stack_st_ASN1_OBJECT* extUsage =
206 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
207 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100208
209 if (extUsage == nullptr)
210 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100211 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100212 return true;
213 }
214
215 bool isExKeyUsageClientAuth = false;
216 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
217 {
218 if (NID_client_auth ==
219 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
220 {
221 isExKeyUsageClientAuth = true;
222 break;
223 }
224 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200225 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100226
227 // Certificate has to have proper key usages set
228 if (!isExKeyUsageClientAuth)
229 {
230 BMCWEB_LOG_DEBUG << this
231 << " Certificate ExtendedKeyUsage does "
232 "not allow provided certificate to "
233 "be used for user authentication";
234 return true;
235 }
236 std::string sslUser;
237 // Extract username contained in CommonName
238 sslUser.resize(256, '\0');
239
240 int status = X509_NAME_get_text_by_NID(
241 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
242 static_cast<int>(sslUser.size()));
243
244 if (status == -1)
245 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100246 BMCWEB_LOG_DEBUG
247 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100248 return true;
249 }
250
251 size_t lastChar = sslUser.find('\0');
252 if (lastChar == std::string::npos || lastChar == 0)
253 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100254 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100255 return true;
256 }
257 sslUser.resize(lastChar);
Sunitha Harishd3239222021-02-24 15:33:29 +0530258 std::string unsupportedClientId = "";
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700259 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700260 userSession = persistent_data::SessionStore::getInstance()
261 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800262 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700263 persistent_data::PersistenceType::TIMEOUT);
264 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100265 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700266 BMCWEB_LOG_DEBUG
267 << this
268 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100269 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100270 return true;
271 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700272 }
273
Ed Tanousceac6f72018-12-02 11:58:47 -0800274 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800276 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700277 }
278
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 void start()
280 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800281 if (connectionCount >= 100)
282 {
283 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
284 return;
285 }
286
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800287 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500288
Ed Tanousceac6f72018-12-02 11:58:47 -0800289 // TODO(ed) Abstract this to a more clever class with the idea of an
290 // asynchronous "start"
291 if constexpr (std::is_same_v<Adaptor,
292 boost::beast::ssl_stream<
293 boost::asio::ip::tcp::socket>>)
294 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000295 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
296 [this, self(shared_from_this())](
297 const boost::system::error_code& ec) {
298 if (ec)
299 {
300 return;
301 }
302 doReadHeaders();
303 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800304 }
305 else
306 {
307 doReadHeaders();
308 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700309 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700310
Ed Tanous1abe55e2018-09-05 08:30:59 -0700311 void handle()
312 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700313 std::error_code reqEc;
314 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
315 if (reqEc)
316 {
317 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
318 return;
319 }
Ed Tanous596b2032021-09-13 10:32:22 -0700320 thisReq.session = userSession;
321
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000322 // Fetch the client IP address
323 readClientIp();
324
Ed Tanous1abe55e2018-09-05 08:30:59 -0700325 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700326 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 {
Ed Tanous596b2032021-09-13 10:32:22 -0700328 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700330 res.result(boost::beast::http::status::bad_request);
Gunnar Mills9062d472021-11-16 11:37:47 -0600331 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700332 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 }
334 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700335
Ed Tanouse278c182019-03-13 16:23:37 -0700336 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700337 << " " << this << " HTTP/" << thisReq.version() / 10
338 << "." << thisReq.version() % 10 << ' '
339 << thisReq.methodString() << " " << thisReq.target()
340 << " " << thisReq.ipAddress;
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700341
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700342 res.setCompleteRequestHandler(nullptr);
343 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700344
Ed Tanous596b2032021-09-13 10:32:22 -0700345 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700346 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200347
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700348 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600350 completeRequest();
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700351 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800353#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanousefee36b2021-09-22 19:09:11 -0700354 if (!crow::authorization::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700355 thisReq.session == nullptr)
356 {
Gunnar Mills9062d472021-11-16 11:37:47 -0600357 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700358 forward_unauthorized::sendUnauthorized(
359 req->url, req->getHeaderValue("User-Agent"),
360 req->getHeaderValue("Accept"), res);
Gunnar Mills9062d472021-11-16 11:37:47 -0600361 completeRequest();
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700362 return;
363 }
Nan Zhou8682c5a2021-11-13 11:00:07 -0800364#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Gunnar Mills9062d472021-11-16 11:37:47 -0600365 res.setCompleteRequestHandler([self(shared_from_this())] {
366 boost::asio::post(self->adaptor.get_executor(),
367 [self] { self->completeRequest(); });
368 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700369
Ed Tanous596b2032021-09-13 10:32:22 -0700370 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700371 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700372 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700373 "websocket"))
374 {
Ed Tanous596b2032021-09-13 10:32:22 -0700375 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700376 // delete lambda with self shared_ptr
377 // to enable connection destruction
Gunnar Mills9062d472021-11-16 11:37:47 -0600378 res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700379 return;
380 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600381 auto asyncResp = std::make_shared<bmcweb::AsyncResp>(res);
Ed Tanous596b2032021-09-13 10:32:22 -0700382 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700383 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700384
Ed Tanouse278c182019-03-13 16:23:37 -0700385 bool isAlive()
386 {
Ed Tanouse278c182019-03-13 16:23:37 -0700387 if constexpr (std::is_same_v<Adaptor,
388 boost::beast::ssl_stream<
389 boost::asio::ip::tcp::socket>>)
390 {
391 return adaptor.next_layer().is_open();
392 }
393 else
394 {
395 return adaptor.is_open();
396 }
397 }
398 void close()
399 {
Ed Tanouse278c182019-03-13 16:23:37 -0700400 if constexpr (std::is_same_v<Adaptor,
401 boost::beast::ssl_stream<
402 boost::asio::ip::tcp::socket>>)
403 {
404 adaptor.next_layer().close();
Gunnar Mills9062d472021-11-16 11:37:47 -0600405#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
406 if (userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200407 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700408 BMCWEB_LOG_DEBUG
409 << this
410 << " Removing TLS session: " << userSession->uniqueId;
411 persistent_data::SessionStore::getInstance().removeSession(
412 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200413 }
Gunnar Mills9062d472021-11-16 11:37:47 -0600414#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700415 }
416 else
417 {
418 adaptor.close();
419 }
420 }
421
Gunnar Mills9062d472021-11-16 11:37:47 -0600422 void completeRequest()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700424 if (!req)
425 {
426 return;
427 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700428 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
429 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700430
Ed Tanous0260d9d2021-02-07 19:31:07 +0000431 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700432
Ed Tanouscf099fa2021-08-25 12:37:31 -0700433 crow::authorization::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700434
Ed Tanouse278c182019-03-13 16:23:37 -0700435 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 {
437 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
438 // isReading
439 // << ' ' << isWriting;
440 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000441
442 // delete lambda with self shared_ptr
443 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700444 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 return;
446 }
447 if (res.body().empty() && !res.jsonValue.empty())
448 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700449 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 {
451 prettyPrintJson(res);
452 }
453 else
454 {
455 res.jsonMode();
Ed Tanous71f52d92021-02-19 08:51:17 -0800456 res.body() = res.jsonValue.dump(
457 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700458 }
459 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700460
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 if (res.resultInt() >= 400 && res.body().empty())
462 {
463 res.body() = std::string(res.reason());
464 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700465
466 if (res.result() == boost::beast::http::status::no_content)
467 {
468 // Boost beast throws if content is provided on a no-content
469 // response. Ideally, this would never happen, but in the case that
470 // it does, we don't want to throw.
471 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100472 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700473 res.body().clear();
474 }
475
Ed Tanous1abe55e2018-09-05 08:30:59 -0700476 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
477
478 res.keepAlive(req->keepAlive());
479
Gunnar Mills9062d472021-11-16 11:37:47 -0600480 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000481
482 // delete lambda with self shared_ptr
483 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700484 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700485 }
486
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500487 void readClientIp()
488 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700489 boost::asio::ip::address ip;
490 boost::system::error_code ec = getClientIp(ip);
491 if (ec)
492 {
493 return;
494 }
495 req->ipAddress = ip;
496 }
497
498 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
499 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500500 boost::system::error_code ec;
501 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
502 boost::asio::ip::tcp::endpoint endpoint =
503 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
504
505 if (ec)
506 {
507 // If remote endpoint fails keep going. "ClientOriginIPAddress"
508 // will be empty.
509 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
510 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700511 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500512 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700513 ip = endpoint.address();
514 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500515 }
516
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 private:
518 void doReadHeaders()
519 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700520 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
521
522 // Clean up any previous Connection.
523 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800524 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000525 [this,
526 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000527 std::size_t bytesTransferred) {
Andrew Geissler1c801e12021-10-08 14:36:01 -0500528 BMCWEB_LOG_DEBUG << this << " async_read_header "
Ed Tanous81ce6092020-12-17 16:54:55 +0000529 << bytesTransferred << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700530 bool errorWhileReading = false;
531 if (ec)
532 {
533 errorWhileReading = true;
Andrew Geissler1c801e12021-10-08 14:36:01 -0500534 if (ec == boost::asio::error::eof)
535 {
536 BMCWEB_LOG_WARNING
537 << this << " Error while reading: " << ec.message();
538 }
539 else
540 {
541 BMCWEB_LOG_ERROR
542 << this << " Error while reading: " << ec.message();
543 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700544 }
545 else
546 {
547 // if the adaptor isn't open anymore, and wasn't handed to a
548 // websocket, treat as an error
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700549 if (!isAlive() &&
550 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700551 {
552 errorWhileReading = true;
553 }
554 }
555
James Feist3909dc82020-04-03 10:58:55 -0700556 cancelDeadlineTimer();
557
Ed Tanous1abe55e2018-09-05 08:30:59 -0700558 if (errorWhileReading)
559 {
Ed Tanouse278c182019-03-13 16:23:37 -0700560 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700562 return;
563 }
564
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700565 readClientIp();
Ed Tanous92ccb882020-08-18 10:36:33 -0700566
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700567 boost::asio::ip::address ip;
568 if (getClientIp(ip))
569 {
570 BMCWEB_LOG_DEBUG << "Unable to get client IP";
571 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700572 sessionIsFromTransport = false;
Nan Zhou8682c5a2021-11-13 11:00:07 -0800573#ifndef BMCWEB_INSECURE_DISABLE_AUTHENTICATION
574 boost::beast::http::verb method = parser->get().method();
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700575 userSession = crow::authorization::authenticate(
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700576 ip, res, method, parser->get().base(), userSession);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800577
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700578 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800579 if (!loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700580 {
581 const boost::optional<uint64_t> contentLength =
582 parser->content_length();
583 if (contentLength &&
584 *contentLength > loggedOutPostBodyLimit)
585 {
586 BMCWEB_LOG_DEBUG << "Content length greater than limit "
587 << *contentLength;
588 close();
589 return;
590 }
591
James Feist3909dc82020-04-03 10:58:55 -0700592 BMCWEB_LOG_DEBUG << "Starting quick deadline";
593 }
JunLin Chen895e46d2021-12-16 13:58:45 +0800594#endif // BMCWEB_INSECURE_DISABLE_AUTHENTICATION
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800595
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 doRead();
597 });
598 }
599
600 void doRead()
601 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700602 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800603 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800605 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000606 [this,
607 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000608 std::size_t bytesTransferred) {
609 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 << " Bytes";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800611 cancelDeadlineTimer();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 if (ec)
613 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100614 BMCWEB_LOG_ERROR
615 << this << " Error while reading: " << ec.message();
Ed Tanouse278c182019-03-13 16:23:37 -0700616 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 return;
619 }
620 handle();
621 });
622 }
623
Gunnar Mills9062d472021-11-16 11:37:47 -0600624 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100626 BMCWEB_LOG_DEBUG << this << " doWrite";
Gunnar Mills9062d472021-11-16 11:37:47 -0600627 res.preparePayload();
628 serializer.emplace(*res.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800629 startDeadline();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800631 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000632 [this,
633 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000634 std::size_t bytesTransferred) {
635 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 << " bytes";
637
James Feist54d8bb12020-07-20 13:28:59 -0700638 cancelDeadlineTimer();
639
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 if (ec)
641 {
642 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643 return;
644 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800645 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700646 {
Ed Tanouse278c182019-03-13 16:23:37 -0700647 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 return;
650 }
651
652 serializer.reset();
653 BMCWEB_LOG_DEBUG << this << " Clearing response";
654 res.clear();
655 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500656 parser->body_limit(httpReqBodyLimit); // reset body limit for
657 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 buffer.consume(buffer.size());
659
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700660 // If the session was built from the transport, we don't need to
661 // clear it. All other sessions are generated per request.
662 if (!sessionIsFromTransport)
663 {
664 userSession = nullptr;
665 }
666
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700667 // Destroy the Request via the std::optional
668 req.reset();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700669 doReadHeaders();
670 });
671 }
672
Ed Tanous1abe55e2018-09-05 08:30:59 -0700673 void cancelDeadlineTimer()
674 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800675 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 }
677
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800678 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 {
680 cancelDeadlineTimer();
681
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800682 std::chrono::seconds timeout(15);
683 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800684 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800685 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700686 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700688 return;
689 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800690
691 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
692 timer.expires_after(timeout);
693 timer.async_wait([weakSelf](const boost::system::error_code ec) {
694 // Note, we are ignoring other types of errors here; If the timer
695 // failed for any reason, we should still close the connection
696
697 std::shared_ptr<Connection<Adaptor, Handler>> self =
698 weakSelf.lock();
699 if (!self)
700 {
701 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
702 return;
703 }
704 if (ec == boost::asio::error::operation_aborted)
705 {
706 // Canceled wait means the path succeeeded.
707 return;
708 }
709 if (ec)
710 {
711 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
712 }
713
714 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
715
716 self->close();
717 });
718
719 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700720 }
721
722 private:
723 Adaptor adaptor;
724 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800725 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700726 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800727 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700728 boost::beast::http::request_parser<boost::beast::http::string_body>>
729 parser;
730
Ed Tanous3112a142018-11-29 15:45:10 -0800731 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700732
Ed Tanousa24526d2018-12-10 15:17:59 -0800733 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700734 boost::beast::http::string_body>>
735 serializer;
736
Ed Tanousa24526d2018-12-10 15:17:59 -0800737 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700739
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700740 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700741 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800743 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744
Ed Tanous1abe55e2018-09-05 08:30:59 -0700745 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000746
747 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700748 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800749
750 using std::enable_shared_from_this<
751 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800752};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753} // namespace crow