blob: d0619737283ea6a24f38385018d12c2e225fc755 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08002#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06003
Nan Zhoud055a342022-05-25 01:15:34 +00004#include "authentication.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07005#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07006#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "logging.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanous257f5792018-03-17 14:40:09 -070010#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080011#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080012#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070013#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080014#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080015#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070016#include <boost/beast/http/parser.hpp>
17#include <boost/beast/http/read.hpp>
18#include <boost/beast/http/serializer.hpp>
19#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053020#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070022#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070023#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070024#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <ssl_key_handler.hpp>
26
Manojkiran Eda44250442020-06-16 12:51:38 +053027#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028#include <chrono>
29#include <vector>
30
Ed Tanous1abe55e2018-09-05 08:30:59 -070031namespace crow
32{
Ed Tanous257f5792018-03-17 14:40:09 -070033
Ed Tanous1abe55e2018-09-05 08:30:59 -070034inline void prettyPrintJson(crow::Response& res)
35{
Ed Tanous57fce802019-05-21 13:00:34 -070036 json_html_util::dumpHtml(res.body(), res.jsonValue);
37
Ed Tanous93ef5802019-01-03 10:15:41 -080038 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070039}
40
Ed Tanous6fbdbca2021-12-06 14:36:06 -080041static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070042
Ed Tanous0260d9d2021-02-07 19:31:07 +000043// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080044constexpr uint64_t httpReqBodyLimit =
45 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070046
James Feist3909dc82020-04-03 10:58:55 -070047constexpr uint64_t loggedOutPostBodyLimit = 4096;
48
49constexpr uint32_t httpHeaderLimit = 8192;
50
Ed Tanous52cc1122020-07-18 13:51:21 -070051template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050052class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070053 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070054{
55 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080056 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000057 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080058 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080059 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080060 handler(handlerIn), timer(std::move(timerIn)),
61 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 {
63 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070064 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070065 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020066
67#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070068 prepareMutualTls();
69#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
70
Ed Tanous40aa0582021-07-14 13:24:40 -070071 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080072
Ed Tanous40aa0582021-07-14 13:24:40 -070073 BMCWEB_LOG_DEBUG << this << " Connection open, total "
74 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070075 }
76
77 ~Connection()
78 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070079 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070080 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080081
Ed Tanous40aa0582021-07-14 13:24:40 -070082 connectionCount--;
83 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
84 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070085 }
86
Ed Tanousecd6a3a2022-01-07 09:18:40 -080087 Connection(const Connection&) = delete;
88 Connection(Connection&&) = delete;
89 Connection& operator=(const Connection&) = delete;
90 Connection& operator=(Connection&&) = delete;
91
Ed Tanous40aa0582021-07-14 13:24:40 -070092 void prepareMutualTls()
93 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -080094 std::error_code error;
95 std::filesystem::path caPath(ensuressl::trustStorePath);
96 auto caAvailable = !std::filesystem::is_empty(caPath, error);
97 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -070098 if (caAvailable && persistent_data::SessionStore::getInstance()
99 .getAuthMethodsConfig()
100 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100101 {
102 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700103 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800104
Ed Tanous9eb808c2022-01-25 10:19:23 -0800105 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800106 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800107 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700108 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800109 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700110 static_cast<unsigned int>(id.length()));
111 if (ret == 0)
112 {
113 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
114 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100115 }
116
Ed Tanous002d39b2022-05-31 08:59:27 -0700117 adaptor.set_verify_callback(
118 [this](bool preverified, boost::asio::ssl::verify_context& ctx) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100119 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700120 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100121 .getAuthMethodsConfig()
122 .tls)
123 {
124 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200125 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100126 }
127
128 // We always return true to allow full auth flow
129 if (!preverified)
130 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100131 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100132 return true;
133 }
134
135 X509_STORE_CTX* cts = ctx.native_handle();
136 if (cts == nullptr)
137 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100138 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100139 return true;
140 }
141
142 // Get certificate
143 X509* peerCert =
144 X509_STORE_CTX_get_current_cert(ctx.native_handle());
145 if (peerCert == nullptr)
146 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100147 BMCWEB_LOG_DEBUG << this
148 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100149 return true;
150 }
151
152 // Check if certificate is OK
Ed Tanous8a592812022-06-04 09:06:59 -0700153 int ctxError = X509_STORE_CTX_get_error(cts);
154 if (ctxError != X509_V_OK)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100155 {
Ed Tanous8a592812022-06-04 09:06:59 -0700156 BMCWEB_LOG_INFO << this << " Last TLS error is: " << ctxError;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100157 return true;
158 }
159 // Check that we have reached final certificate in chain
160 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
161 if (depth != 0)
162
163 {
164 BMCWEB_LOG_DEBUG
165 << this << " Certificate verification in progress (depth "
166 << depth << "), waiting to reach final depth";
167 return true;
168 }
169
170 BMCWEB_LOG_DEBUG << this
171 << " Certificate verification of final depth";
172
173 // Verify KeyUsage
174 bool isKeyUsageDigitalSignature = false;
175 bool isKeyUsageKeyAgreement = false;
176
177 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000178 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100179
180 if (usage == nullptr)
181 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100182 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100183 return true;
184 }
185
186 for (int i = 0; i < usage->length; i++)
187 {
Ed Tanousca45aa32022-01-07 09:28:45 -0800188 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
189 unsigned char usageChar = usage->data[i];
190 if (KU_DIGITAL_SIGNATURE & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100191 {
192 isKeyUsageDigitalSignature = true;
193 }
Ed Tanousca45aa32022-01-07 09:28:45 -0800194 if (KU_KEY_AGREEMENT & usageChar)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100195 {
196 isKeyUsageKeyAgreement = true;
197 }
198 }
Vernon Maueryb9378302021-06-16 14:06:57 -0700199 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100200
201 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
202 {
203 BMCWEB_LOG_DEBUG << this
204 << " Certificate ExtendedKeyUsage does "
205 "not allow provided certificate to "
206 "be used for user authentication";
207 return true;
208 }
209
210 // Determine that ExtendedKeyUsage includes Client Auth
211
Ed Tanous23a21a12020-07-25 04:45:05 +0000212 stack_st_ASN1_OBJECT* extUsage =
213 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
214 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100215
216 if (extUsage == nullptr)
217 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100218 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100219 return true;
220 }
221
222 bool isExKeyUsageClientAuth = false;
223 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
224 {
Ed Tanous4bac4a82022-01-07 09:37:55 -0800225 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
226 int nid = OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i));
227 if (NID_client_auth == nid)
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100228 {
229 isExKeyUsageClientAuth = true;
230 break;
231 }
232 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200233 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100234
235 // Certificate has to have proper key usages set
236 if (!isExKeyUsageClientAuth)
237 {
238 BMCWEB_LOG_DEBUG << this
239 << " Certificate ExtendedKeyUsage does "
240 "not allow provided certificate to "
241 "be used for user authentication";
242 return true;
243 }
244 std::string sslUser;
245 // Extract username contained in CommonName
246 sslUser.resize(256, '\0');
247
248 int status = X509_NAME_get_text_by_NID(
249 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
250 static_cast<int>(sslUser.size()));
251
252 if (status == -1)
253 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100254 BMCWEB_LOG_DEBUG
255 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100256 return true;
257 }
258
259 size_t lastChar = sslUser.find('\0');
260 if (lastChar == std::string::npos || lastChar == 0)
261 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100262 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100263 return true;
264 }
265 sslUser.resize(lastChar);
Ed Tanouse05aec52022-01-25 10:28:56 -0800266 std::string unsupportedClientId;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700267 sessionIsFromTransport = true;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700268 userSession = persistent_data::SessionStore::getInstance()
269 .generateUserSession(
Jiaqing Zhao41d61c82021-12-07 13:21:47 +0800270 sslUser, req->ipAddress, unsupportedClientId,
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700271 persistent_data::PersistenceType::TIMEOUT);
272 if (userSession != nullptr)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100273 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700274 BMCWEB_LOG_DEBUG
275 << this
276 << " Generating TLS session: " << userSession->uniqueId;
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100277 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100278 return true;
279 });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280 }
281
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700285 }
286
Ed Tanous1abe55e2018-09-05 08:30:59 -0700287 void start()
288 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800289 if (connectionCount >= 100)
290 {
291 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
292 return;
293 }
294
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800295 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500296
Ed Tanousceac6f72018-12-02 11:58:47 -0800297 // TODO(ed) Abstract this to a more clever class with the idea of an
298 // asynchronous "start"
299 if constexpr (std::is_same_v<Adaptor,
300 boost::beast::ssl_stream<
301 boost::asio::ip::tcp::socket>>)
302 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000303 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
304 [this, self(shared_from_this())](
305 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700306 if (ec)
307 {
308 return;
309 }
310 doReadHeaders();
311 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800312 }
313 else
314 {
315 doReadHeaders();
316 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700317 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700318
Ed Tanous1abe55e2018-09-05 08:30:59 -0700319 void handle()
320 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700321 std::error_code reqEc;
322 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
323 if (reqEc)
324 {
325 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
326 return;
327 }
Ed Tanous596b2032021-09-13 10:32:22 -0700328 thisReq.session = userSession;
329
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000330 // Fetch the client IP address
331 readClientIp();
332
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700334 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 {
Ed Tanous596b2032021-09-13 10:32:22 -0700336 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700337 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700338 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800339 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700340 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 }
342 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700343
Ed Tanouse278c182019-03-13 16:23:37 -0700344 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700345 << " " << this << " HTTP/" << thisReq.version() / 10
346 << "." << thisReq.version() % 10 << ' '
347 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800348 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700349
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700350 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700351
Ed Tanous596b2032021-09-13 10:32:22 -0700352 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700353 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200354
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700355 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800357 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700358 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000360#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhoud055a342022-05-25 01:15:34 +0000361 if (!crow::authentication::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700362 thisReq.session == nullptr)
363 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800364 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700365 forward_unauthorized::sendUnauthorized(
Ed Tanousc127a0f2022-05-11 15:23:59 -0700366 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700367 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800368 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700369 return;
370 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000371#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800372 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
373 BMCWEB_LOG_DEBUG << "Setting completion handler";
374 asyncResp->res.setCompleteRequestHandler(
375 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700376 self->completeRequest(thisRes);
377 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700378
Ed Tanous596b2032021-09-13 10:32:22 -0700379 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700380 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700381 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700382 "websocket"))
383 {
Ed Tanous596b2032021-09-13 10:32:22 -0700384 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700385 // delete lambda with self shared_ptr
386 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800387 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700388 return;
389 }
Ed Tanous596b2032021-09-13 10:32:22 -0700390 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700391 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700392
Ed Tanouse278c182019-03-13 16:23:37 -0700393 bool isAlive()
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 return adaptor.next_layer().is_open();
400 }
401 else
402 {
403 return adaptor.is_open();
404 }
405 }
406 void close()
407 {
Ed Tanouse278c182019-03-13 16:23:37 -0700408 if constexpr (std::is_same_v<Adaptor,
409 boost::beast::ssl_stream<
410 boost::asio::ip::tcp::socket>>)
411 {
412 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800413 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200414 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700415 BMCWEB_LOG_DEBUG
416 << this
417 << " Removing TLS session: " << userSession->uniqueId;
418 persistent_data::SessionStore::getInstance().removeSession(
419 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200420 }
Ed Tanouse278c182019-03-13 16:23:37 -0700421 }
422 else
423 {
424 adaptor.close();
425 }
426 }
427
Nan Zhou72374eb2022-01-27 17:06:51 -0800428 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700430 if (!req)
431 {
432 return;
433 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800434 res = std::move(thisRes);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700435 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
436 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700437
Ed Tanous0260d9d2021-02-07 19:31:07 +0000438 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700439
Nan Zhoud055a342022-05-25 01:15:34 +0000440 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700441
Ed Tanouse278c182019-03-13 16:23:37 -0700442 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700443 {
444 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
445 // isReading
446 // << ' ' << isWriting;
447 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000448
449 // delete lambda with self shared_ptr
450 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700451 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700452 return;
453 }
454 if (res.body().empty() && !res.jsonValue.empty())
455 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700456 if (http_helpers::requestPrefersHtml(req->getHeaderValue("Accept")))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700457 {
458 prettyPrintJson(res);
459 }
460 else
461 {
Ed Tanousf610caa2022-03-17 08:53:00 -0700462 res.addHeader(boost::beast::http::field::content_type,
463 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800464 res.body() = res.jsonValue.dump(
465 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700466 }
467 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700468
Ed Tanous1abe55e2018-09-05 08:30:59 -0700469 if (res.resultInt() >= 400 && res.body().empty())
470 {
471 res.body() = std::string(res.reason());
472 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700473
474 if (res.result() == boost::beast::http::status::no_content)
475 {
476 // Boost beast throws if content is provided on a no-content
477 // response. Ideally, this would never happen, but in the case that
478 // it does, we don't want to throw.
479 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100480 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700481 res.body().clear();
482 }
483
Ed Tanous1abe55e2018-09-05 08:30:59 -0700484 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
485
486 res.keepAlive(req->keepAlive());
487
Nan Zhou72374eb2022-01-27 17:06:51 -0800488 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000489
490 // delete lambda with self shared_ptr
491 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700492 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700493 }
494
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500495 void readClientIp()
496 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700497 boost::asio::ip::address ip;
498 boost::system::error_code ec = getClientIp(ip);
499 if (ec)
500 {
501 return;
502 }
503 req->ipAddress = ip;
504 }
505
506 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
507 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500508 boost::system::error_code ec;
509 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
510 boost::asio::ip::tcp::endpoint endpoint =
511 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
512
513 if (ec)
514 {
515 // If remote endpoint fails keep going. "ClientOriginIPAddress"
516 // will be empty.
517 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
518 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700519 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500520 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700521 ip = endpoint.address();
522 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500523 }
524
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 private:
526 void doReadHeaders()
527 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
529
530 // Clean up any previous Connection.
531 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800532 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000533 [this,
534 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000535 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700536 BMCWEB_LOG_DEBUG << this << " async_read_header "
537 << bytesTransferred << " Bytes";
538 bool errorWhileReading = false;
539 if (ec)
540 {
541 errorWhileReading = true;
542 if (ec == boost::asio::error::eof)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700543 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700544 BMCWEB_LOG_WARNING
545 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 }
547 else
548 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700549 BMCWEB_LOG_ERROR
550 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700551 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700552 }
553 else
554 {
555 // if the adaptor isn't open anymore, and wasn't handed to a
556 // websocket, treat as an error
557 if (!isAlive() &&
558 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700559 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700560 errorWhileReading = true;
561 }
562 }
563
564 cancelDeadlineTimer();
565
566 if (errorWhileReading)
567 {
568 close();
569 BMCWEB_LOG_DEBUG << this << " from read(1)";
570 return;
571 }
572
573 readClientIp();
574
575 boost::asio::ip::address ip;
576 if (getClientIp(ip))
577 {
578 BMCWEB_LOG_DEBUG << "Unable to get client IP";
579 }
580 sessionIsFromTransport = false;
581#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
582 boost::beast::http::verb method = parser->get().method();
583 userSession = crow::authentication::authenticate(
584 ip, res, method, parser->get().base(), userSession);
585
586 bool loggedIn = userSession != nullptr;
587 if (!loggedIn)
588 {
589 const boost::optional<uint64_t> contentLength =
590 parser->content_length();
591 if (contentLength && *contentLength > loggedOutPostBodyLimit)
592 {
593 BMCWEB_LOG_DEBUG << "Content length greater than limit "
594 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700595 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 return;
597 }
598
Ed Tanous002d39b2022-05-31 08:59:27 -0700599 BMCWEB_LOG_DEBUG << "Starting quick deadline";
600 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000601#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800602
Ed Tanous002d39b2022-05-31 08:59:27 -0700603 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 });
605 }
606
607 void doRead()
608 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800610 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700611 boost::beast::http::async_read(adaptor, buffer, *parser,
612 [this, self(shared_from_this())](
613 const boost::system::error_code& ec,
614 std::size_t bytesTransferred) {
615 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
616 << " Bytes";
617 cancelDeadlineTimer();
618 if (ec)
619 {
620 BMCWEB_LOG_ERROR << this
621 << " Error while reading: " << ec.message();
622 close();
623 BMCWEB_LOG_DEBUG << this << " from read(1)";
624 return;
625 }
626 handle();
627 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 }
629
Nan Zhou72374eb2022-01-27 17:06:51 -0800630 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100632 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800633 thisRes.preparePayload();
634 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800635 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700636 boost::beast::http::async_write(adaptor, *serializer,
637 [this, self(shared_from_this())](
638 const boost::system::error_code& ec,
639 std::size_t bytesTransferred) {
640 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
641 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642
Ed Tanous002d39b2022-05-31 08:59:27 -0700643 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700644
Ed Tanous002d39b2022-05-31 08:59:27 -0700645 if (ec)
646 {
647 BMCWEB_LOG_DEBUG << this << " from write(2)";
648 return;
649 }
650 if (!res.keepAlive())
651 {
652 close();
653 BMCWEB_LOG_DEBUG << this << " from write(1)";
654 return;
655 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656
Ed Tanous002d39b2022-05-31 08:59:27 -0700657 serializer.reset();
658 BMCWEB_LOG_DEBUG << this << " Clearing response";
659 res.clear();
660 parser.emplace(std::piecewise_construct, std::make_tuple());
661 parser->body_limit(httpReqBodyLimit); // reset body limit for
662 // newly created parser
663 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664
Ed Tanous002d39b2022-05-31 08:59:27 -0700665 // If the session was built from the transport, we don't need to
666 // clear it. All other sessions are generated per request.
667 if (!sessionIsFromTransport)
668 {
669 userSession = nullptr;
670 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700671
Ed Tanous002d39b2022-05-31 08:59:27 -0700672 // Destroy the Request via the std::optional
673 req.reset();
674 doReadHeaders();
675 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 }
677
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 void cancelDeadlineTimer()
679 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800680 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 }
682
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800683 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 {
685 cancelDeadlineTimer();
686
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 std::chrono::seconds timeout(15);
688 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800689 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800690 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700691 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800692 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700693 return;
694 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800695
696 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
697 timer.expires_after(timeout);
698 timer.async_wait([weakSelf](const boost::system::error_code ec) {
699 // Note, we are ignoring other types of errors here; If the timer
700 // failed for any reason, we should still close the connection
701
702 std::shared_ptr<Connection<Adaptor, Handler>> self =
703 weakSelf.lock();
704 if (!self)
705 {
706 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
707 return;
708 }
709 if (ec == boost::asio::error::operation_aborted)
710 {
711 // Canceled wait means the path succeeeded.
712 return;
713 }
714 if (ec)
715 {
716 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
717 }
718
719 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
720
721 self->close();
722 });
723
724 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725 }
726
Ed Tanous1abe55e2018-09-05 08:30:59 -0700727 Adaptor adaptor;
728 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800729 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800731 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700732 boost::beast::http::request_parser<boost::beast::http::string_body>>
733 parser;
734
Ed Tanous3112a142018-11-29 15:45:10 -0800735 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736
Ed Tanousa24526d2018-12-10 15:17:59 -0800737 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 boost::beast::http::string_body>>
739 serializer;
740
Ed Tanousa24526d2018-12-10 15:17:59 -0800741 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700743
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700744 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700745 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800747 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000750
751 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700752 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800753
754 using std::enable_shared_from_this<
755 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800756};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757} // namespace crow