blob: 7e23de4786dc8c7171bd88f1b7d82a2e8bc10552 [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
Manojkiran Eda44250442020-06-16 12:51:38 +05304#include "http_response.h"
5#include "logging.h"
Manojkiran Eda44250442020-06-16 12:51:38 +05306#include "timer_queue.h"
7#include "utility.h"
8
James Feist3909dc82020-04-03 10:58:55 -07009#include "authorization.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010#include "http_utility.hpp"
11
Ed Tanouse0d918b2018-03-27 17:41:04 -070012#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070013#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080014#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080015#include <boost/asio/ip/tcp.hpp>
Ed Tanous2f1ebcd2019-02-13 19:39:07 -080016#include <boost/asio/ssl.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/beast/core/flat_static_buffer.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/http.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053019#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050020#include <boost/beast/websocket.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{
Jason M. Bills193ad2f2018-09-26 15:08:52 -070033 std::string value = res.jsonValue.dump(4, ' ', true);
Ed Tanousa29c9972018-11-29 15:54:32 -080034 utility::escapeHtml(value);
35 utility::convertToLinks(value);
Ed Tanous1abe55e2018-09-05 08:30:59 -070036 res.body() = "<html>\n"
37 "<head>\n"
38 "<title>Redfish API</title>\n"
39 "<link rel=\"stylesheet\" type=\"text/css\" "
40 "href=\"/styles/default.css\">\n"
41 "<script src=\"/highlight.pack.js\"></script>"
42 "<script>hljs.initHighlightingOnLoad();</script>"
43 "</head>\n"
44 "<body>\n"
45 "<div style=\"max-width: 576px;margin:0 auto;\">\n"
46 "<img src=\"/DMTF_Redfish_logo_2017.svg\" alt=\"redfish\" "
47 "height=\"406px\" "
48 "width=\"576px\">\n"
49 "<br>\n"
50 "<pre>\n"
51 "<code class=\"json\">" +
52 value +
53 "</code>\n"
54 "</pre>\n"
55 "</div>\n"
56 "</body>\n"
57 "</html>\n";
Ed Tanous93ef5802019-01-03 10:15:41 -080058 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070059}
60
Ed Tanous55c7b7a2018-05-22 15:27:24 -070061#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070062static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070063#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070064
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060065// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
66constexpr unsigned int httpReqBodyLimit =
67 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070068
James Feist3909dc82020-04-03 10:58:55 -070069constexpr uint64_t loggedOutPostBodyLimit = 4096;
70
71constexpr uint32_t httpHeaderLimit = 8192;
72
73// drop all connections after 1 minute, this time limit was chosen
74// arbitrarily and can be adjusted later if needed
75static constexpr const size_t loggedInAttempts =
76 (60 / timerQueueTimeoutSeconds);
77
78static constexpr const size_t loggedOutAttempts =
79 (15 / timerQueueTimeoutSeconds);
80
Ed Tanous52cc1122020-07-18 13:51:21 -070081template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050082class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070083 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070084{
85 public:
Ed Tanouscb13a392020-07-25 19:02:03 +000086 Connection(Handler* handlerIn, const std::string& ServerNameIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070087 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070088 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080089 adaptor(std::move(adaptorIn)),
Ed Tanous271584a2019-07-09 16:24:22 -070090 handler(handlerIn), serverName(ServerNameIn),
Ed Tanous52cc1122020-07-18 13:51:21 -070091 getCachedDateStr(get_cached_date_str_f), timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070092 {
93 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070094 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070095 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -070096 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020097
98#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010099 auto ca_available = !std::filesystem::is_empty(
100 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous52cc1122020-07-18 13:51:21 -0700101 if (ca_available && persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100102 .getAuthMethodsConfig()
103 .tls)
104 {
105 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
106 SSL_set_session_id_context(
107 adaptor.native_handle(),
108 reinterpret_cast<const unsigned char*>(serverName.c_str()),
Zbigniew Kurzynskicac94c52019-11-07 12:55:04 +0100109 static_cast<unsigned int>(serverName.length()));
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100110 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
111 }
112
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100113 adaptor.set_verify_callback([this](
114 bool preverified,
115 boost::asio::ssl::verify_context& ctx) {
116 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700117 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 .getAuthMethodsConfig()
119 .tls)
120 {
121 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200122 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100123 }
124
125 // We always return true to allow full auth flow
126 if (!preverified)
127 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100128 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100129 return true;
130 }
131
132 X509_STORE_CTX* cts = ctx.native_handle();
133 if (cts == nullptr)
134 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100135 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100136 return true;
137 }
138
139 // Get certificate
140 X509* peerCert =
141 X509_STORE_CTX_get_current_cert(ctx.native_handle());
142 if (peerCert == nullptr)
143 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100144 BMCWEB_LOG_DEBUG << this
145 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100146 return true;
147 }
148
149 // Check if certificate is OK
150 int error = X509_STORE_CTX_get_error(cts);
151 if (error != X509_V_OK)
152 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100153 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100154 return true;
155 }
156 // Check that we have reached final certificate in chain
157 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
158 if (depth != 0)
159
160 {
161 BMCWEB_LOG_DEBUG
162 << this << " Certificate verification in progress (depth "
163 << depth << "), waiting to reach final depth";
164 return true;
165 }
166
167 BMCWEB_LOG_DEBUG << this
168 << " Certificate verification of final depth";
169
170 // Verify KeyUsage
171 bool isKeyUsageDigitalSignature = false;
172 bool isKeyUsageKeyAgreement = false;
173
174 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000175 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100176
177 if (usage == nullptr)
178 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100179 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100180 return true;
181 }
182
183 for (int i = 0; i < usage->length; i++)
184 {
185 if (KU_DIGITAL_SIGNATURE & usage->data[i])
186 {
187 isKeyUsageDigitalSignature = true;
188 }
189 if (KU_KEY_AGREEMENT & usage->data[i])
190 {
191 isKeyUsageKeyAgreement = true;
192 }
193 }
194
195 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
196 {
197 BMCWEB_LOG_DEBUG << this
198 << " Certificate ExtendedKeyUsage does "
199 "not allow provided certificate to "
200 "be used for user authentication";
201 return true;
202 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200203 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100204
205 // Determine that ExtendedKeyUsage includes Client Auth
206
Ed Tanous23a21a12020-07-25 04:45:05 +0000207 stack_st_ASN1_OBJECT* extUsage =
208 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
209 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100210
211 if (extUsage == nullptr)
212 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100213 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100214 return true;
215 }
216
217 bool isExKeyUsageClientAuth = false;
218 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
219 {
220 if (NID_client_auth ==
221 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
222 {
223 isExKeyUsageClientAuth = true;
224 break;
225 }
226 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200227 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100228
229 // Certificate has to have proper key usages set
230 if (!isExKeyUsageClientAuth)
231 {
232 BMCWEB_LOG_DEBUG << this
233 << " Certificate ExtendedKeyUsage does "
234 "not allow provided certificate to "
235 "be used for user authentication";
236 return true;
237 }
238 std::string sslUser;
239 // Extract username contained in CommonName
240 sslUser.resize(256, '\0');
241
242 int status = X509_NAME_get_text_by_NID(
243 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
244 static_cast<int>(sslUser.size()));
245
246 if (status == -1)
247 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100248 BMCWEB_LOG_DEBUG
249 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100250 return true;
251 }
252
253 size_t lastChar = sslUser.find('\0');
254 if (lastChar == std::string::npos || lastChar == 0)
255 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100256 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100257 return true;
258 }
259 sslUser.resize(lastChar);
260
Ed Tanous52cc1122020-07-18 13:51:21 -0700261 session =
262 persistent_data::SessionStore::getInstance()
263 .generateUserSession(
264 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100265 if (auto sp = session.lock())
266 {
267 BMCWEB_LOG_DEBUG << this
268 << " Generating TLS session: " << sp->uniqueId;
269 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100270 return true;
271 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200272#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
273
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700274#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 connectionCount++;
276 BMCWEB_LOG_DEBUG << this << " Connection open, total "
277 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700278#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 ~Connection()
282 {
283 res.completeRequestHandler = nullptr;
284 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700285#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700286 connectionCount--;
287 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
288 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700289#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700290 }
291
Ed Tanousceac6f72018-12-02 11:58:47 -0800292 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700293 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800294 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700295 }
296
Ed Tanous1abe55e2018-09-05 08:30:59 -0700297 void start()
298 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700299
James Feist3909dc82020-04-03 10:58:55 -0700300 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800301 // TODO(ed) Abstract this to a more clever class with the idea of an
302 // asynchronous "start"
303 if constexpr (std::is_same_v<Adaptor,
304 boost::beast::ssl_stream<
305 boost::asio::ip::tcp::socket>>)
306 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000307 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
308 [this, self(shared_from_this())](
309 const boost::system::error_code& ec) {
310 if (ec)
311 {
312 return;
313 }
314 doReadHeaders();
315 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800316 }
317 else
318 {
319 doReadHeaders();
320 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700321 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700322
Ed Tanous1abe55e2018-09-05 08:30:59 -0700323 void handle()
324 {
325 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700326
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700328
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 // Check for HTTP version 1.1.
330 if (req->version() == 11)
331 {
332 if (req->getHeaderValue(boost::beast::http::field::host).empty())
333 {
334 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700335 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700336 }
337 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700338
Ed Tanouse278c182019-03-13 16:23:37 -0700339 BMCWEB_LOG_INFO << "Request: "
340 << " " << this << " HTTP/" << req->version() / 10 << "."
341 << req->version() % 10 << ' ' << req->methodString()
342 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700343
Ed Tanous1abe55e2018-09-05 08:30:59 -0700344 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700345
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 if (!isInvalidRequest)
347 {
348 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700349 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700350
Ed Tanouse278c182019-03-13 16:23:37 -0700351 req->ioService = static_cast<decltype(req->ioService)>(
352 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200353
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 if (!res.completed)
355 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000356 needToCallAfterHandlers = true;
357 res.completeRequestHandler = [self(shared_from_this())] {
358 self->completeRequest();
359 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700360 if (req->isUpgrade() &&
361 boost::iequals(
362 req->getHeaderValue(boost::beast::http::field::upgrade),
363 "websocket"))
364 {
365 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000366 // delete lambda with self shared_ptr
367 // to enable connection destruction
368 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700369 return;
370 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700371 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700372 }
373 else
374 {
375 completeRequest();
376 }
377 }
378 else
379 {
380 completeRequest();
381 }
382 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700383
Ed Tanouse278c182019-03-13 16:23:37 -0700384 bool isAlive()
385 {
386
387 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();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200405#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
406 if (auto sp = session.lock())
407 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100408 BMCWEB_LOG_DEBUG << this
409 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200410 persistent_data::SessionStore::getInstance().removeSession(sp);
411 }
412#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700413 }
414 else
415 {
416 adaptor.close();
417 }
418 }
419
Ed Tanous1abe55e2018-09-05 08:30:59 -0700420 void completeRequest()
421 {
422 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
423 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700424
Ed Tanous52cc1122020-07-18 13:51:21 -0700425 addSecurityHeaders(res);
426
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 if (needToCallAfterHandlers)
428 {
James Feist3909dc82020-04-03 10:58:55 -0700429 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700430 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700431
Ed Tanouse278c182019-03-13 16:23:37 -0700432 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 {
434 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
435 // isReading
436 // << ' ' << isWriting;
437 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000438
439 // delete lambda with self shared_ptr
440 // to enable connection destruction
441 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700442 return;
443 }
444 if (res.body().empty() && !res.jsonValue.empty())
445 {
446 if (http_helpers::requestPrefersHtml(*req))
447 {
448 prettyPrintJson(res);
449 }
450 else
451 {
452 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700453 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700454 }
455 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700456
Ed Tanous1abe55e2018-09-05 08:30:59 -0700457 if (res.resultInt() >= 400 && res.body().empty())
458 {
459 res.body() = std::string(res.reason());
460 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700461
462 if (res.result() == boost::beast::http::status::no_content)
463 {
464 // Boost beast throws if content is provided on a no-content
465 // response. Ideally, this would never happen, but in the case that
466 // it does, we don't want to throw.
467 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100468 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700469 res.body().clear();
470 }
471
Ed Tanous1abe55e2018-09-05 08:30:59 -0700472 res.addHeader(boost::beast::http::field::server, serverName);
473 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
474
475 res.keepAlive(req->keepAlive());
476
477 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000478
479 // delete lambda with self shared_ptr
480 // to enable connection destruction
481 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700482 }
483
484 private:
485 void doReadHeaders()
486 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700487 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
488
489 // Clean up any previous Connection.
490 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800491 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000492 [this,
493 self(shared_from_this())](const boost::system::error_code& ec,
494 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700495 BMCWEB_LOG_ERROR << this << " async_read_header "
496 << bytes_transferred << " Bytes";
497 bool errorWhileReading = false;
498 if (ec)
499 {
500 errorWhileReading = true;
501 BMCWEB_LOG_ERROR
502 << this << " Error while reading: " << ec.message();
503 }
504 else
505 {
506 // if the adaptor isn't open anymore, and wasn't handed to a
507 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700508 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700509 {
510 errorWhileReading = true;
511 }
512 }
513
James Feist3909dc82020-04-03 10:58:55 -0700514 cancelDeadlineTimer();
515
Ed Tanous1abe55e2018-09-05 08:30:59 -0700516 if (errorWhileReading)
517 {
Ed Tanouse278c182019-03-13 16:23:37 -0700518 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700519 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700520 return;
521 }
522
James Feist3909dc82020-04-03 10:58:55 -0700523 if (!req)
524 {
525 close();
526 return;
527 }
528
Ed Tanousdc7a7932020-08-17 15:04:58 -0700529 // Note, despite the bmcweb coding policy on use of exceptions
530 // for error handling, this one particular use of exceptions is
531 // deemed acceptible, as it solved a significant error handling
532 // problem that resulted in seg faults, the exact thing that the
533 // exceptions rule is trying to avoid. If at some point,
534 // boost::urls makes the parser object public (or we port it
535 // into bmcweb locally) this will be replaced with
536 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700537
Ed Tanousdc7a7932020-08-17 15:04:58 -0700538 try
539 {
540 req->urlView = boost::urls::url_view(req->target());
541 req->url = req->urlView.encoded_path();
542 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700543 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700544 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700545 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700546 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700547
James Feist6964c982020-07-28 16:10:23 -0700548 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700549
550 bool loggedIn = req && req->session;
551 if (loggedIn)
552 {
553 startDeadline(loggedInAttempts);
554 BMCWEB_LOG_DEBUG << "Starting slow deadline";
555
James Feist5a7e8772020-07-22 09:08:38 -0700556 req->urlParams = req->urlView.params();
557
558#ifdef BMCWEB_ENABLE_DEBUG
559 std::string paramList = "";
560 for (const auto param : req->urlParams)
561 {
562 paramList += param->key() + " " + param->value() + " ";
563 }
564 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
565#endif
James Feist3909dc82020-04-03 10:58:55 -0700566 }
567 else
568 {
569 const boost::optional<uint64_t> contentLength =
570 parser->content_length();
571 if (contentLength &&
572 *contentLength > loggedOutPostBodyLimit)
573 {
574 BMCWEB_LOG_DEBUG << "Content length greater than limit "
575 << *contentLength;
576 close();
577 return;
578 }
579
580 startDeadline(loggedOutAttempts);
581 BMCWEB_LOG_DEBUG << "Starting quick deadline";
582 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700583 doRead();
584 });
585 }
586
587 void doRead()
588 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700589 BMCWEB_LOG_DEBUG << this << " doRead";
590
591 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800592 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000593 [this,
594 self(shared_from_this())](const boost::system::error_code& ec,
595 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100596 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700598
599 bool errorWhileReading = false;
600 if (ec)
601 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100602 BMCWEB_LOG_ERROR
603 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 errorWhileReading = true;
605 }
606 else
607 {
James Feist3909dc82020-04-03 10:58:55 -0700608 if (isAlive())
609 {
610 cancelDeadlineTimer();
611 bool loggedIn = req && req->session;
612 if (loggedIn)
613 {
614 startDeadline(loggedInAttempts);
615 }
616 else
617 {
618 startDeadline(loggedOutAttempts);
619 }
620 }
621 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 {
623 errorWhileReading = true;
624 }
625 }
626 if (errorWhileReading)
627 {
628 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700629 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 return;
632 }
633 handle();
634 });
635 }
636
637 void doWrite()
638 {
James Feist3909dc82020-04-03 10:58:55 -0700639 bool loggedIn = req && req->session;
640 if (loggedIn)
641 {
642 startDeadline(loggedInAttempts);
643 }
644 else
645 {
646 startDeadline(loggedOutAttempts);
647 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100648 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 res.preparePayload();
650 serializer.emplace(*res.stringResponse);
651 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800652 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000653 [this,
654 self(shared_from_this())](const boost::system::error_code& ec,
655 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100656 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 << " bytes";
658
James Feist54d8bb12020-07-20 13:28:59 -0700659 cancelDeadlineTimer();
660
Ed Tanous1abe55e2018-09-05 08:30:59 -0700661 if (ec)
662 {
663 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 return;
665 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800666 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700667 {
Ed Tanouse278c182019-03-13 16:23:37 -0700668 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700669 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700670 return;
671 }
672
673 serializer.reset();
674 BMCWEB_LOG_DEBUG << this << " Clearing response";
675 res.clear();
676 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500677 parser->body_limit(httpReqBodyLimit); // reset body limit for
678 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 buffer.consume(buffer.size());
680
681 req.emplace(parser->get());
682 doReadHeaders();
683 });
684 }
685
Ed Tanous1abe55e2018-09-05 08:30:59 -0700686 void cancelDeadlineTimer()
687 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000688 if (timerCancelKey)
689 {
690 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
691 << ' ' << *timerCancelKey;
692 timerQueue.cancel(*timerCancelKey);
693 timerCancelKey.reset();
694 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700695 }
696
James Feist3909dc82020-04-03 10:58:55 -0700697 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700698 {
699 cancelDeadlineTimer();
700
James Feist3909dc82020-04-03 10:58:55 -0700701 if (timerIterations)
702 {
703 timerIterations--;
704 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100705
James Feist3909dc82020-04-03 10:58:55 -0700706 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700707 timerQueue.add([self(shared_from_this()), timerIterations,
708 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700709 // Mark timer as not active to avoid canceling it during
710 // Connection destructor which leads to double free issue
711 self->timerCancelKey.reset();
712 if (!self->isAlive())
713 {
714 return;
715 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100716
James Feistbe5dfca2020-07-22 08:54:59 -0700717 bool loggedIn = self->req && self->req->session;
718 // allow slow uploads for logged in users
719 if (loggedIn && self->parser->get().body().size() > readCount)
720 {
721 BMCWEB_LOG_DEBUG << self.get()
722 << " restart timer - read in progress";
723 self->startDeadline(timerIterations);
724 return;
725 }
726
James Feist3909dc82020-04-03 10:58:55 -0700727 // Threshold can be used to drop slow connections
728 // to protect against slow-rate DoS attack
729 if (timerIterations)
730 {
James Feistbe5dfca2020-07-22 08:54:59 -0700731 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700732 self->startDeadline(timerIterations);
733 return;
734 }
735
736 self->close();
737 });
James Feistcb6cb492020-04-03 13:36:17 -0700738
739 if (!timerCancelKey)
740 {
741 close();
742 return;
743 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000745 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746 }
747
748 private:
749 Adaptor adaptor;
750 Handler* handler;
751
Ed Tanousa24526d2018-12-10 15:17:59 -0800752 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800754 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700755 boost::beast::http::request_parser<boost::beast::http::string_body>>
756 parser;
757
Ed Tanous3112a142018-11-29 15:45:10 -0800758 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700759
Ed Tanousa24526d2018-12-10 15:17:59 -0800760 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700761 boost::beast::http::string_body>>
762 serializer;
763
Ed Tanousa24526d2018-12-10 15:17:59 -0800764 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700765 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700766
767 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768
769 const std::string& serverName;
770
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000771 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700772
Ed Tanous1abe55e2018-09-05 08:30:59 -0700773 bool needToCallAfterHandlers{};
774 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700775
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776 std::function<std::string()>& getCachedDateStr;
777 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000778
779 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700780 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800781};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782} // namespace crow