blob: 6610beec9f32223ace957079d219bba9718c05c1 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06002#include "config.h"
3
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"
8#include "timer_queue.hpp"
9#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010
Ed Tanouse0d918b2018-03-27 17:41:04 -070011#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070012#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080013#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080014#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070015#include <boost/asio/ssl/stream.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 Tanous57fce802019-05-21 13:00:34 -070019#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070020#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <ssl_key_handler.hpp>
22
Manojkiran Eda44250442020-06-16 12:51:38 +053023#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050024#include <chrono>
25#include <vector>
26
Ed Tanous1abe55e2018-09-05 08:30:59 -070027namespace crow
28{
Ed Tanous257f5792018-03-17 14:40:09 -070029
Ed Tanous1abe55e2018-09-05 08:30:59 -070030inline void prettyPrintJson(crow::Response& res)
31{
Ed Tanous57fce802019-05-21 13:00:34 -070032 json_html_util::dumpHtml(res.body(), res.jsonValue);
33
Ed Tanous93ef5802019-01-03 10:15:41 -080034 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070035}
36
Ed Tanous55c7b7a2018-05-22 15:27:24 -070037#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070038static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070039#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070040
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060041// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
42constexpr unsigned int httpReqBodyLimit =
43 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070044
James Feist3909dc82020-04-03 10:58:55 -070045constexpr uint64_t loggedOutPostBodyLimit = 4096;
46
47constexpr uint32_t httpHeaderLimit = 8192;
48
49// drop all connections after 1 minute, this time limit was chosen
50// arbitrarily and can be adjusted later if needed
51static constexpr const size_t loggedInAttempts =
52 (60 / timerQueueTimeoutSeconds);
53
54static constexpr const size_t loggedOutAttempts =
55 (15 / timerQueueTimeoutSeconds);
56
Ed Tanous52cc1122020-07-18 13:51:21 -070057template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050058class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070059 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070060{
61 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070062 Connection(Handler* handlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070063 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070064 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070066 handler(handlerIn), getCachedDateStr(get_cached_date_str_f),
67 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070068 {
69 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070071 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020073
74#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous2c70f802020-09-28 14:29:23 -070075 auto caAvailable = !std::filesystem::is_empty(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010076 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous2c70f802020-09-28 14:29:23 -070077 if (caAvailable && persistent_data::SessionStore::getInstance()
78 .getAuthMethodsConfig()
79 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010080 {
81 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070082 std::string id = "bmcweb";
83 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010084 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070085 reinterpret_cast<const unsigned char*>(id.c_str()),
86 static_cast<unsigned int>(id.length()));
87 if (ret == 0)
88 {
89 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
90 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010091 }
92
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010093 adaptor.set_verify_callback([this](
94 bool preverified,
95 boost::asio::ssl::verify_context& ctx) {
96 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070097 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010098 .getAuthMethodsConfig()
99 .tls)
100 {
101 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200102 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100103 }
104
105 // We always return true to allow full auth flow
106 if (!preverified)
107 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100108 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100109 return true;
110 }
111
112 X509_STORE_CTX* cts = ctx.native_handle();
113 if (cts == nullptr)
114 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100115 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100116 return true;
117 }
118
119 // Get certificate
120 X509* peerCert =
121 X509_STORE_CTX_get_current_cert(ctx.native_handle());
122 if (peerCert == nullptr)
123 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100124 BMCWEB_LOG_DEBUG << this
125 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100126 return true;
127 }
128
129 // Check if certificate is OK
130 int error = X509_STORE_CTX_get_error(cts);
131 if (error != X509_V_OK)
132 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100133 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100134 return true;
135 }
136 // Check that we have reached final certificate in chain
137 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
138 if (depth != 0)
139
140 {
141 BMCWEB_LOG_DEBUG
142 << this << " Certificate verification in progress (depth "
143 << depth << "), waiting to reach final depth";
144 return true;
145 }
146
147 BMCWEB_LOG_DEBUG << this
148 << " Certificate verification of final depth";
149
150 // Verify KeyUsage
151 bool isKeyUsageDigitalSignature = false;
152 bool isKeyUsageKeyAgreement = false;
153
154 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000155 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100156
157 if (usage == nullptr)
158 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100159 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100160 return true;
161 }
162
163 for (int i = 0; i < usage->length; i++)
164 {
165 if (KU_DIGITAL_SIGNATURE & usage->data[i])
166 {
167 isKeyUsageDigitalSignature = true;
168 }
169 if (KU_KEY_AGREEMENT & usage->data[i])
170 {
171 isKeyUsageKeyAgreement = true;
172 }
173 }
174
175 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
176 {
177 BMCWEB_LOG_DEBUG << this
178 << " Certificate ExtendedKeyUsage does "
179 "not allow provided certificate to "
180 "be used for user authentication";
181 return true;
182 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200183 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100184
185 // Determine that ExtendedKeyUsage includes Client Auth
186
Ed Tanous23a21a12020-07-25 04:45:05 +0000187 stack_st_ASN1_OBJECT* extUsage =
188 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
189 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100190
191 if (extUsage == nullptr)
192 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100193 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100194 return true;
195 }
196
197 bool isExKeyUsageClientAuth = false;
198 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
199 {
200 if (NID_client_auth ==
201 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
202 {
203 isExKeyUsageClientAuth = true;
204 break;
205 }
206 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200207 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100208
209 // Certificate has to have proper key usages set
210 if (!isExKeyUsageClientAuth)
211 {
212 BMCWEB_LOG_DEBUG << this
213 << " Certificate ExtendedKeyUsage does "
214 "not allow provided certificate to "
215 "be used for user authentication";
216 return true;
217 }
218 std::string sslUser;
219 // Extract username contained in CommonName
220 sslUser.resize(256, '\0');
221
222 int status = X509_NAME_get_text_by_NID(
223 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
224 static_cast<int>(sslUser.size()));
225
226 if (status == -1)
227 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100228 BMCWEB_LOG_DEBUG
229 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100230 return true;
231 }
232
233 size_t lastChar = sslUser.find('\0');
234 if (lastChar == std::string::npos || lastChar == 0)
235 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100236 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100237 return true;
238 }
239 sslUser.resize(lastChar);
240
Ed Tanous52cc1122020-07-18 13:51:21 -0700241 session =
242 persistent_data::SessionStore::getInstance()
243 .generateUserSession(
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500244 sslUser, persistent_data::PersistenceType::TIMEOUT,
245 false, req->ipAddress.to_string());
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100246 if (auto sp = session.lock())
247 {
248 BMCWEB_LOG_DEBUG << this
249 << " Generating TLS session: " << sp->uniqueId;
250 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100251 return true;
252 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200253#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
254
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700255#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700256 connectionCount++;
257 BMCWEB_LOG_DEBUG << this << " Connection open, total "
258 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700259#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700261
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 ~Connection()
263 {
264 res.completeRequestHandler = nullptr;
265 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700266#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700267 connectionCount--;
268 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
269 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700270#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700271 }
272
Ed Tanousceac6f72018-12-02 11:58:47 -0800273 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700274 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800275 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700276 }
277
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 void start()
279 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280
James Feist3909dc82020-04-03 10:58:55 -0700281 startDeadline(0);
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500282
283 // Fetch the client IP address
284 readClientIp();
285
Ed Tanousceac6f72018-12-02 11:58:47 -0800286 // TODO(ed) Abstract this to a more clever class with the idea of an
287 // asynchronous "start"
288 if constexpr (std::is_same_v<Adaptor,
289 boost::beast::ssl_stream<
290 boost::asio::ip::tcp::socket>>)
291 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000292 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
293 [this, self(shared_from_this())](
294 const boost::system::error_code& ec) {
295 if (ec)
296 {
297 return;
298 }
299 doReadHeaders();
300 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800301 }
302 else
303 {
304 doReadHeaders();
305 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700306 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700307
Ed Tanous1abe55e2018-09-05 08:30:59 -0700308 void handle()
309 {
310 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700311
Ed Tanous1abe55e2018-09-05 08:30:59 -0700312 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700313
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 // Check for HTTP version 1.1.
315 if (req->version() == 11)
316 {
317 if (req->getHeaderValue(boost::beast::http::field::host).empty())
318 {
319 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700320 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 }
322 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700323
Ed Tanouse278c182019-03-13 16:23:37 -0700324 BMCWEB_LOG_INFO << "Request: "
325 << " " << this << " HTTP/" << req->version() / 10 << "."
326 << req->version() % 10 << ' ' << req->methodString()
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500327 << " " << req->target() << " " << req->ipAddress;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700328
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 if (!isInvalidRequest)
332 {
333 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700334 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700335
Ed Tanouse278c182019-03-13 16:23:37 -0700336 req->ioService = static_cast<decltype(req->ioService)>(
337 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200338
Ed Tanous1abe55e2018-09-05 08:30:59 -0700339 if (!res.completed)
340 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000341 needToCallAfterHandlers = true;
342 res.completeRequestHandler = [self(shared_from_this())] {
Wludzik, Jozefc7d34222020-10-19 12:59:41 +0200343 boost::asio::post(self->adaptor.get_executor(),
344 [self] { self->completeRequest(); });
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000345 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 if (req->isUpgrade() &&
347 boost::iequals(
348 req->getHeaderValue(boost::beast::http::field::upgrade),
349 "websocket"))
350 {
351 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000352 // delete lambda with self shared_ptr
353 // to enable connection destruction
354 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 return;
356 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700357 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 }
359 else
360 {
361 completeRequest();
362 }
363 }
364 else
365 {
366 completeRequest();
367 }
368 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700369
Ed Tanouse278c182019-03-13 16:23:37 -0700370 bool isAlive()
371 {
372
373 if constexpr (std::is_same_v<Adaptor,
374 boost::beast::ssl_stream<
375 boost::asio::ip::tcp::socket>>)
376 {
377 return adaptor.next_layer().is_open();
378 }
379 else
380 {
381 return adaptor.is_open();
382 }
383 }
384 void close()
385 {
Ed Tanouse278c182019-03-13 16:23:37 -0700386 if constexpr (std::is_same_v<Adaptor,
387 boost::beast::ssl_stream<
388 boost::asio::ip::tcp::socket>>)
389 {
390 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200391#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
392 if (auto sp = session.lock())
393 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100394 BMCWEB_LOG_DEBUG << this
395 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200396 persistent_data::SessionStore::getInstance().removeSession(sp);
397 }
398#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700399 }
400 else
401 {
402 adaptor.close();
403 }
404 }
405
Ed Tanous1abe55e2018-09-05 08:30:59 -0700406 void completeRequest()
407 {
408 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
409 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700410
Ed Tanous52cc1122020-07-18 13:51:21 -0700411 addSecurityHeaders(res);
412
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 if (needToCallAfterHandlers)
414 {
James Feist3909dc82020-04-03 10:58:55 -0700415 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700417
Ed Tanouse278c182019-03-13 16:23:37 -0700418 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700419 {
420 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
421 // isReading
422 // << ' ' << isWriting;
423 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000424
425 // delete lambda with self shared_ptr
426 // to enable connection destruction
427 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700428 return;
429 }
430 if (res.body().empty() && !res.jsonValue.empty())
431 {
432 if (http_helpers::requestPrefersHtml(*req))
433 {
434 prettyPrintJson(res);
435 }
436 else
437 {
438 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700439 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 }
441 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700442
Ed Tanous1abe55e2018-09-05 08:30:59 -0700443 if (res.resultInt() >= 400 && res.body().empty())
444 {
445 res.body() = std::string(res.reason());
446 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700447
448 if (res.result() == boost::beast::http::status::no_content)
449 {
450 // Boost beast throws if content is provided on a no-content
451 // response. Ideally, this would never happen, but in the case that
452 // it does, we don't want to throw.
453 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100454 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700455 res.body().clear();
456 }
457
Ed Tanous1abe55e2018-09-05 08:30:59 -0700458 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
459
460 res.keepAlive(req->keepAlive());
461
462 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000463
464 // delete lambda with self shared_ptr
465 // to enable connection destruction
466 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 }
468
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500469 void readClientIp()
470 {
471 boost::system::error_code ec;
472 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
473 boost::asio::ip::tcp::endpoint endpoint =
474 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
475
476 if (ec)
477 {
478 // If remote endpoint fails keep going. "ClientOriginIPAddress"
479 // will be empty.
480 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
481 << ec;
482 }
483 else
484 {
485 req->ipAddress = endpoint.address();
486 }
487 }
488
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 private:
490 void doReadHeaders()
491 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700492 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
493
494 // Clean up any previous Connection.
495 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800496 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000497 [this,
498 self(shared_from_this())](const boost::system::error_code& ec,
499 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700500 BMCWEB_LOG_ERROR << this << " async_read_header "
501 << bytes_transferred << " Bytes";
502 bool errorWhileReading = false;
503 if (ec)
504 {
505 errorWhileReading = true;
506 BMCWEB_LOG_ERROR
507 << this << " Error while reading: " << ec.message();
508 }
509 else
510 {
511 // if the adaptor isn't open anymore, and wasn't handed to a
512 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700513 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700514 {
515 errorWhileReading = true;
516 }
517 }
518
James Feist3909dc82020-04-03 10:58:55 -0700519 cancelDeadlineTimer();
520
Ed Tanous1abe55e2018-09-05 08:30:59 -0700521 if (errorWhileReading)
522 {
Ed Tanouse278c182019-03-13 16:23:37 -0700523 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700524 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700525 return;
526 }
527
James Feist3909dc82020-04-03 10:58:55 -0700528 if (!req)
529 {
530 close();
531 return;
532 }
533
Ed Tanousdc7a7932020-08-17 15:04:58 -0700534 // Note, despite the bmcweb coding policy on use of exceptions
535 // for error handling, this one particular use of exceptions is
536 // deemed acceptible, as it solved a significant error handling
537 // problem that resulted in seg faults, the exact thing that the
538 // exceptions rule is trying to avoid. If at some point,
539 // boost::urls makes the parser object public (or we port it
540 // into bmcweb locally) this will be replaced with
541 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700542
Ed Tanousdc7a7932020-08-17 15:04:58 -0700543 try
544 {
545 req->urlView = boost::urls::url_view(req->target());
546 req->url = req->urlView.encoded_path();
547 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700548 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700549 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700550 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700551 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700552
James Feist6964c982020-07-28 16:10:23 -0700553 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700554
555 bool loggedIn = req && req->session;
556 if (loggedIn)
557 {
558 startDeadline(loggedInAttempts);
559 BMCWEB_LOG_DEBUG << "Starting slow deadline";
560
James Feist5a7e8772020-07-22 09:08:38 -0700561 req->urlParams = req->urlView.params();
562
563#ifdef BMCWEB_ENABLE_DEBUG
564 std::string paramList = "";
565 for (const auto param : req->urlParams)
566 {
567 paramList += param->key() + " " + param->value() + " ";
568 }
569 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
570#endif
James Feist3909dc82020-04-03 10:58:55 -0700571 }
572 else
573 {
574 const boost::optional<uint64_t> contentLength =
575 parser->content_length();
576 if (contentLength &&
577 *contentLength > loggedOutPostBodyLimit)
578 {
579 BMCWEB_LOG_DEBUG << "Content length greater than limit "
580 << *contentLength;
581 close();
582 return;
583 }
584
585 startDeadline(loggedOutAttempts);
586 BMCWEB_LOG_DEBUG << "Starting quick deadline";
587 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 doRead();
589 });
590 }
591
592 void doRead()
593 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700594 BMCWEB_LOG_DEBUG << this << " doRead";
595
596 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800597 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000598 [this,
599 self(shared_from_this())](const boost::system::error_code& ec,
600 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100601 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700602 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700603
604 bool errorWhileReading = false;
605 if (ec)
606 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100607 BMCWEB_LOG_ERROR
608 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 errorWhileReading = true;
610 }
611 else
612 {
James Feist3909dc82020-04-03 10:58:55 -0700613 if (isAlive())
614 {
615 cancelDeadlineTimer();
616 bool loggedIn = req && req->session;
617 if (loggedIn)
618 {
619 startDeadline(loggedInAttempts);
620 }
621 else
622 {
623 startDeadline(loggedOutAttempts);
624 }
625 }
626 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627 {
628 errorWhileReading = true;
629 }
630 }
631 if (errorWhileReading)
632 {
633 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700634 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 return;
637 }
638 handle();
639 });
640 }
641
642 void doWrite()
643 {
James Feist3909dc82020-04-03 10:58:55 -0700644 bool loggedIn = req && req->session;
645 if (loggedIn)
646 {
647 startDeadline(loggedInAttempts);
648 }
649 else
650 {
651 startDeadline(loggedOutAttempts);
652 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100653 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 res.preparePayload();
655 serializer.emplace(*res.stringResponse);
656 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800657 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000658 [this,
659 self(shared_from_this())](const boost::system::error_code& ec,
660 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100661 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 << " bytes";
663
James Feist54d8bb12020-07-20 13:28:59 -0700664 cancelDeadlineTimer();
665
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666 if (ec)
667 {
668 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700669 return;
670 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800671 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700672 {
Ed Tanouse278c182019-03-13 16:23:37 -0700673 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700674 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 return;
676 }
677
678 serializer.reset();
679 BMCWEB_LOG_DEBUG << this << " Clearing response";
680 res.clear();
681 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500682 parser->body_limit(httpReqBodyLimit); // reset body limit for
683 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700684 buffer.consume(buffer.size());
685
686 req.emplace(parser->get());
687 doReadHeaders();
688 });
689 }
690
Ed Tanous1abe55e2018-09-05 08:30:59 -0700691 void cancelDeadlineTimer()
692 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000693 if (timerCancelKey)
694 {
695 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
696 << ' ' << *timerCancelKey;
697 timerQueue.cancel(*timerCancelKey);
698 timerCancelKey.reset();
699 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700700 }
701
James Feist3909dc82020-04-03 10:58:55 -0700702 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700703 {
704 cancelDeadlineTimer();
705
James Feist3909dc82020-04-03 10:58:55 -0700706 if (timerIterations)
707 {
708 timerIterations--;
709 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100710
James Feist3909dc82020-04-03 10:58:55 -0700711 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700712 timerQueue.add([self(shared_from_this()), timerIterations,
713 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700714 // Mark timer as not active to avoid canceling it during
715 // Connection destructor which leads to double free issue
716 self->timerCancelKey.reset();
717 if (!self->isAlive())
718 {
719 return;
720 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100721
James Feistbe5dfca2020-07-22 08:54:59 -0700722 bool loggedIn = self->req && self->req->session;
723 // allow slow uploads for logged in users
724 if (loggedIn && self->parser->get().body().size() > readCount)
725 {
726 BMCWEB_LOG_DEBUG << self.get()
727 << " restart timer - read in progress";
728 self->startDeadline(timerIterations);
729 return;
730 }
731
James Feist3909dc82020-04-03 10:58:55 -0700732 // Threshold can be used to drop slow connections
733 // to protect against slow-rate DoS attack
734 if (timerIterations)
735 {
James Feistbe5dfca2020-07-22 08:54:59 -0700736 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700737 self->startDeadline(timerIterations);
738 return;
739 }
740
741 self->close();
742 });
James Feistcb6cb492020-04-03 13:36:17 -0700743
744 if (!timerCancelKey)
745 {
746 close();
747 return;
748 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000750 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751 }
752
753 private:
754 Adaptor adaptor;
755 Handler* handler;
756
Ed Tanousa24526d2018-12-10 15:17:59 -0800757 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800759 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760 boost::beast::http::request_parser<boost::beast::http::string_body>>
761 parser;
762
Ed Tanous3112a142018-11-29 15:45:10 -0800763 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700764
Ed Tanousa24526d2018-12-10 15:17:59 -0800765 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700766 boost::beast::http::string_body>>
767 serializer;
768
Ed Tanousa24526d2018-12-10 15:17:59 -0800769 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700770 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700771
772 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700773
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000774 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700775
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776 bool needToCallAfterHandlers{};
777 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700778
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779 std::function<std::string()>& getCachedDateStr;
780 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000781
782 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700783 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800784};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785} // namespace crow