blob: aaa1325b7a9eb95df43b1faf67b636659706764f [file] [log] [blame]
Ed Tanousf9273472017-02-28 16:05:13 -08001#pragma once
2
Ed Tanousc94ad492019-10-10 15:39:33 -07003#include <app.h>
4#include <common.h>
5#include <http_request.h>
6#include <http_response.h>
Ed Tanous1abe55e2018-09-05 08:30:59 -07007
Ed Tanous4758d5b2017-06-06 15:28:13 -07008#include <boost/container/flat_set.hpp>
Ed Tanous1abe55e2018-09-05 08:30:59 -07009#include <pam_authenticate.hpp>
10#include <persistent_data_middleware.hpp>
11#include <random>
12#include <webassets.hpp>
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010013
Ed Tanous1abe55e2018-09-05 08:30:59 -070014namespace crow
15{
Ed Tanousb4d29f42017-03-24 16:39:25 -070016
Ed Tanous1abe55e2018-09-05 08:30:59 -070017namespace token_authorization
18{
Ed Tanousb4d29f42017-03-24 16:39:25 -070019
Ed Tanous1abe55e2018-09-05 08:30:59 -070020class Middleware
21{
22 public:
23 struct Context
24 {
Ed Tanous1abe55e2018-09-05 08:30:59 -070025 };
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +010026
Ed Tanous1abe55e2018-09-05 08:30:59 -070027 void beforeHandle(crow::Request& req, Response& res, Context& ctx)
28 {
29 if (isOnWhitelist(req))
30 {
31 return;
Ed Tanouse0d918b2018-03-27 17:41:04 -070032 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010033
Zbigniew Kurzynski78158632019-11-05 12:57:37 +010034 const crow::persistent_data::AuthConfigMethods& authMethodsConfig =
35 crow::persistent_data::SessionStore::getInstance()
36 .getAuthMethodsConfig();
37
38 if (req.session == nullptr && authMethodsConfig.xtoken)
39 {
40 req.session = performXtokenAuth(req);
41 }
42 if (req.session == nullptr && authMethodsConfig.cookie)
Ed Tanous1abe55e2018-09-05 08:30:59 -070043 {
Ratan Gupta6f359562019-04-03 10:39:08 +053044 req.session = performCookieAuth(req);
Ed Tanous9bd21fc2018-04-26 16:08:56 -070045 }
Ratan Gupta6f359562019-04-03 10:39:08 +053046 if (req.session == nullptr)
Ed Tanous1abe55e2018-09-05 08:30:59 -070047 {
Ed Tanous39e77502019-03-04 17:35:53 -080048 std::string_view authHeader = req.getHeaderValue("Authorization");
Ed Tanous1abe55e2018-09-05 08:30:59 -070049 if (!authHeader.empty())
50 {
51 // Reject any kind of auth other than basic or token
Zbigniew Kurzynski78158632019-11-05 12:57:37 +010052 if (boost::starts_with(authHeader, "Token ") &&
53 authMethodsConfig.sessionToken)
Ed Tanous1abe55e2018-09-05 08:30:59 -070054 {
Ratan Gupta6f359562019-04-03 10:39:08 +053055 req.session = performTokenAuth(authHeader);
Ed Tanous1abe55e2018-09-05 08:30:59 -070056 }
Zbigniew Kurzynski78158632019-11-05 12:57:37 +010057 else if (boost::starts_with(authHeader, "Basic ") &&
58 authMethodsConfig.basic)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
Ratan Gupta6f359562019-04-03 10:39:08 +053060 req.session = performBasicAuth(authHeader);
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 }
62 }
63 }
Ed Tanouse0d918b2018-03-27 17:41:04 -070064
Ratan Gupta6f359562019-04-03 10:39:08 +053065 if (req.session == nullptr)
Ed Tanous1abe55e2018-09-05 08:30:59 -070066 {
67 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
68
69 // If it's a browser connecting, don't send the HTTP authenticate
70 // header, to avoid possible CSRF attacks with basic auth
71 if (http_helpers::requestPrefersHtml(req))
72 {
73 res.result(boost::beast::http::status::temporary_redirect);
Ed Tanous6b5e77d2018-11-16 14:52:56 -080074 res.addHeader("Location", "/#/login?next=" +
75 http_helpers::urlEncode(req.url));
Ed Tanous1abe55e2018-09-05 08:30:59 -070076 }
77 else
78 {
79 res.result(boost::beast::http::status::unauthorized);
80 // only send the WWW-authenticate header if this isn't a xhr
81 // from the browser. most scripts,
82 if (req.getHeaderValue("User-Agent").empty())
83 {
84 res.addHeader("WWW-Authenticate", "Basic");
85 }
86 }
87
88 res.end();
89 return;
90 }
91
92 // TODO get user privileges here and propagate it via MW Context
93 // else let the request continue unharmed
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010094 }
Ed Tanousf9273472017-02-28 16:05:13 -080095
Ed Tanous1abe55e2018-09-05 08:30:59 -070096 template <typename AllContext>
97 void afterHandle(Request& req, Response& res, Context& ctx,
98 AllContext& allctx)
99 {
100 // TODO(ed) THis should really be handled by the persistent data
101 // middleware, but because it is upstream, it doesn't have access to the
102 // session information. Should the data middleware persist the current
103 // user session?
Ratan Gupta6f359562019-04-03 10:39:08 +0530104 if (req.session != nullptr &&
105 req.session->persistence ==
Ed Tanous1abe55e2018-09-05 08:30:59 -0700106 crow::persistent_data::PersistenceType::SINGLE_REQUEST)
107 {
108 persistent_data::SessionStore::getInstance().removeSession(
Ratan Gupta6f359562019-04-03 10:39:08 +0530109 req.session);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700110 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100111 }
112
Ed Tanous1abe55e2018-09-05 08:30:59 -0700113 private:
114 const std::shared_ptr<crow::persistent_data::UserSession>
Ed Tanous39e77502019-03-04 17:35:53 -0800115 performBasicAuth(std::string_view auth_header) const
Ed Tanous1abe55e2018-09-05 08:30:59 -0700116 {
117 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100118
Ed Tanous1abe55e2018-09-05 08:30:59 -0700119 std::string authData;
Ed Tanous39e77502019-03-04 17:35:53 -0800120 std::string_view param = auth_header.substr(strlen("Basic "));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700121 if (!crow::utility::base64Decode(param, authData))
122 {
123 return nullptr;
124 }
125 std::size_t separator = authData.find(':');
126 if (separator == std::string::npos)
127 {
128 return nullptr;
129 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100130
Ed Tanous1abe55e2018-09-05 08:30:59 -0700131 std::string user = authData.substr(0, separator);
132 separator += 1;
133 if (separator > authData.size())
134 {
135 return nullptr;
136 }
137 std::string pass = authData.substr(separator);
138
139 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
140
Joseph Reynoldsd887fff2020-01-14 16:34:09 -0600141 if (pamAuthenticateUser(user, pass) != PAM_SUCCESS)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 {
143 return nullptr;
144 }
145
146 // TODO(ed) generateUserSession is a little expensive for basic
147 // auth, as it generates some random identifiers that will never be
148 // used. This should have a "fast" path for when user tokens aren't
149 // needed.
150 // This whole flow needs to be revisited anyway, as we can't be
151 // calling directly into pam for every request
152 return persistent_data::SessionStore::getInstance().generateUserSession(
153 user, crow::persistent_data::PersistenceType::SINGLE_REQUEST);
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100154 }
155
Ed Tanous1abe55e2018-09-05 08:30:59 -0700156 const std::shared_ptr<crow::persistent_data::UserSession>
Ed Tanous39e77502019-03-04 17:35:53 -0800157 performTokenAuth(std::string_view auth_header) const
Ed Tanous1abe55e2018-09-05 08:30:59 -0700158 {
159 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";
Ed Tanous8041f312017-04-03 09:47:01 -0700160
Ed Tanous39e77502019-03-04 17:35:53 -0800161 std::string_view token = auth_header.substr(strlen("Token "));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700162 auto session =
163 persistent_data::SessionStore::getInstance().loginSessionByToken(
164 token);
165 return session;
Ed Tanous1ea9f062018-03-27 17:45:20 -0700166 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100167
Ed Tanous1abe55e2018-09-05 08:30:59 -0700168 const std::shared_ptr<crow::persistent_data::UserSession>
169 performXtokenAuth(const crow::Request& req) const
170 {
171 BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100172
Ed Tanous39e77502019-03-04 17:35:53 -0800173 std::string_view token = req.getHeaderValue("X-Auth-Token");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700174 if (token.empty())
175 {
176 return nullptr;
177 }
178 auto session =
179 persistent_data::SessionStore::getInstance().loginSessionByToken(
180 token);
181 return session;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100182 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700183
184 const std::shared_ptr<crow::persistent_data::UserSession>
185 performCookieAuth(const crow::Request& req) const
186 {
187 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";
188
Ed Tanous39e77502019-03-04 17:35:53 -0800189 std::string_view cookieValue = req.getHeaderValue("Cookie");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700190 if (cookieValue.empty())
191 {
192 return nullptr;
193 }
194
195 auto startIndex = cookieValue.find("SESSION=");
196 if (startIndex == std::string::npos)
197 {
198 return nullptr;
199 }
200 startIndex += sizeof("SESSION=") - 1;
201 auto endIndex = cookieValue.find(";", startIndex);
202 if (endIndex == std::string::npos)
203 {
204 endIndex = cookieValue.size();
205 }
Ed Tanous39e77502019-03-04 17:35:53 -0800206 std::string_view authKey =
Ed Tanous1abe55e2018-09-05 08:30:59 -0700207 cookieValue.substr(startIndex, endIndex - startIndex);
208
209 const std::shared_ptr<crow::persistent_data::UserSession> session =
210 persistent_data::SessionStore::getInstance().loginSessionByToken(
211 authKey);
212 if (session == nullptr)
213 {
214 return nullptr;
215 }
Ed Tanous1e439872018-05-18 11:48:52 -0700216#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
Ed Tanous1abe55e2018-09-05 08:30:59 -0700217 // RFC7231 defines methods that need csrf protection
218 if (req.method() != "GET"_method)
219 {
Ed Tanous39e77502019-03-04 17:35:53 -0800220 std::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700221 // Make sure both tokens are filled
222 if (csrf.empty() || session->csrfToken.empty())
223 {
224 return nullptr;
225 }
Ed Tanous51dae672018-09-05 16:07:32 -0700226
227 if (csrf.size() != crow::persistent_data::sessionTokenSize)
228 {
229 return nullptr;
230 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700231 // Reject if csrf token not available
Ed Tanous51dae672018-09-05 16:07:32 -0700232 if (!crow::utility::constantTimeStringCompare(csrf,
233 session->csrfToken))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700234 {
235 return nullptr;
236 }
237 }
Ed Tanous1e439872018-05-18 11:48:52 -0700238#endif
James Feistf8aa3d22020-04-08 18:32:33 -0700239 session->cookieAuth = true;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240 return session;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100241 }
242
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 // checks if request can be forwarded without authentication
244 bool isOnWhitelist(const crow::Request& req) const
245 {
246 // it's allowed to GET root node without authentica tion
247 if ("GET"_method == req.method())
248 {
249 if (req.url == "/redfish/v1" || req.url == "/redfish/v1/" ||
250 req.url == "/redfish" || req.url == "/redfish/" ||
251 req.url == "/redfish/v1/odata" ||
252 req.url == "/redfish/v1/odata/")
253 {
254 return true;
255 }
256 else if (crow::webassets::routes.find(std::string(req.url)) !=
257 crow::webassets::routes.end())
258 {
259 return true;
260 }
261 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100262
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 // it's allowed to POST on session collection & login without
264 // authentication
265 if ("POST"_method == req.method())
266 {
267 if ((req.url == "/redfish/v1/SessionService/Sessions") ||
268 (req.url == "/redfish/v1/SessionService/Sessions/") ||
269 (req.url == "/login"))
270 {
271 return true;
272 }
273 }
274
275 return false;
276 }
Ed Tanous99923322017-03-03 14:21:24 -0800277};
Ed Tanousf3d847c2017-06-12 16:01:42 -0700278
Ed Tanousba9f9a62017-10-11 16:40:35 -0700279// TODO(ed) see if there is a better way to allow middlewares to request
280// routes.
Ed Tanous911ac312017-08-15 09:37:42 -0700281// Possibly an init function on first construction?
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282template <typename... Middlewares> void requestRoutes(Crow<Middlewares...>& app)
283{
284 static_assert(
285 black_magic::Contains<persistent_data::Middleware,
286 Middlewares...>::value,
287 "token_authorization middleware must be enabled in app to use "
288 "auth routes");
Ed Tanousc7a29d32019-10-23 13:30:04 -0700289
Ed Tanous1abe55e2018-09-05 08:30:59 -0700290 BMCWEB_ROUTE(app, "/login")
291 .methods(
Ed Tanousfd4859a2019-10-23 13:31:38 -0700292 "POST"_method)([](const crow::Request& req, crow::Response& res) {
Ed Tanous39e77502019-03-04 17:35:53 -0800293 std::string_view contentType = req.getHeaderValue("content-type");
294 std::string_view username;
295 std::string_view password;
Ed Tanouse0d918b2018-03-27 17:41:04 -0700296
Ed Tanousc7a29d32019-10-23 13:30:04 -0700297 bool looksLikePhosphorRest = false;
Ed Tanousdb024a52018-03-06 12:50:34 -0800298
Ed Tanous1abe55e2018-09-05 08:30:59 -0700299 // This object needs to be declared at this scope so the strings
300 // within it are not destroyed before we can use them
301 nlohmann::json loginCredentials;
302 // Check if auth was provided by a payload
Ed Tanousfdf43a32019-07-31 16:52:24 -0700303 if (boost::starts_with(contentType, "application/json"))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700304 {
305 loginCredentials =
306 nlohmann::json::parse(req.body, nullptr, false);
307 if (loginCredentials.is_discarded())
308 {
Ed Tanousfdf43a32019-07-31 16:52:24 -0700309 BMCWEB_LOG_DEBUG << "Bad json in request";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700310 res.result(boost::beast::http::status::bad_request);
311 res.end();
312 return;
313 }
314
315 // check for username/password in the root object
316 // THis method is how intel APIs authenticate
317 nlohmann::json::iterator userIt =
318 loginCredentials.find("username");
319 nlohmann::json::iterator passIt =
320 loginCredentials.find("password");
321 if (userIt != loginCredentials.end() &&
322 passIt != loginCredentials.end())
323 {
324 const std::string* userStr =
325 userIt->get_ptr<const std::string*>();
326 const std::string* passStr =
327 passIt->get_ptr<const std::string*>();
328 if (userStr != nullptr && passStr != nullptr)
329 {
330 username = *userStr;
331 password = *passStr;
332 }
333 }
334 else
335 {
336 // Openbmc appears to push a data object that contains the
337 // same keys (username and password), attempt to use that
338 auto dataIt = loginCredentials.find("data");
339 if (dataIt != loginCredentials.end())
340 {
341 // Some apis produce an array of value ["username",
342 // "password"]
343 if (dataIt->is_array())
344 {
345 if (dataIt->size() == 2)
346 {
347 nlohmann::json::iterator userIt2 =
348 dataIt->begin();
349 nlohmann::json::iterator passIt2 =
350 dataIt->begin() + 1;
Ed Tanousc7a29d32019-10-23 13:30:04 -0700351 looksLikePhosphorRest = true;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 if (userIt2 != dataIt->end() &&
353 passIt2 != dataIt->end())
354 {
355 const std::string* userStr =
356 userIt2->get_ptr<const std::string*>();
357 const std::string* passStr =
358 passIt2->get_ptr<const std::string*>();
359 if (userStr != nullptr &&
360 passStr != nullptr)
361 {
362 username = *userStr;
363 password = *passStr;
364 }
365 }
366 }
367 }
368 else if (dataIt->is_object())
369 {
370 nlohmann::json::iterator userIt2 =
371 dataIt->find("username");
372 nlohmann::json::iterator passIt2 =
373 dataIt->find("password");
374 if (userIt2 != dataIt->end() &&
375 passIt2 != dataIt->end())
376 {
377 const std::string* userStr =
378 userIt2->get_ptr<const std::string*>();
379 const std::string* passStr =
380 passIt2->get_ptr<const std::string*>();
381 if (userStr != nullptr && passStr != nullptr)
382 {
383 username = *userStr;
384 password = *passStr;
385 }
386 }
387 }
388 }
389 }
390 }
391 else
392 {
393 // check if auth was provided as a headers
394 username = req.getHeaderValue("username");
395 password = req.getHeaderValue("password");
396 }
397
398 if (!username.empty() && !password.empty())
399 {
Joseph Reynoldsd887fff2020-01-14 16:34:09 -0600400 if (pamAuthenticateUser(username, password) != PAM_SUCCESS)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700401 {
402 res.result(boost::beast::http::status::unauthorized);
403 }
404 else
405 {
406 auto session = persistent_data::SessionStore::getInstance()
407 .generateUserSession(username);
408
Ed Tanousc7a29d32019-10-23 13:30:04 -0700409 if (looksLikePhosphorRest)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700410 {
Ed Tanousc7a29d32019-10-23 13:30:04 -0700411 // Phosphor-Rest requires a very specific login
412 // structure, and doesn't actually look at the status
413 // code.
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 // TODO(ed).... Fix that upstream
415 res.jsonValue = {
416 {"data",
417 "User '" + std::string(username) + "' logged in"},
418 {"message", "200 OK"},
419 {"status", "ok"}};
420
421 // Hack alert. Boost beast by default doesn't let you
422 // declare multiple headers of the same name, and in
423 // most cases this is fine. Unfortunately here we need
424 // to set the Session cookie, which requires the
425 // httpOnly attribute, as well as the XSRF cookie, which
426 // requires it to not have an httpOnly attribute. To get
427 // the behavior we want, we simply inject the second
428 // "set-cookie" string into the value header, and get
429 // the result we want, even though we are technicaly
430 // declaring two headers here.
431 res.addHeader("Set-Cookie",
432 "XSRF-TOKEN=" + session->csrfToken +
433 "; Secure\r\nSet-Cookie: SESSION=" +
434 session->sessionToken +
435 "; Secure; HttpOnly");
436 }
437 else
438 {
439 // if content type is json, assume json token
440 res.jsonValue = {{"token", session->sessionToken}};
441 }
442 }
443 }
444 else
445 {
Ed Tanousfdf43a32019-07-31 16:52:24 -0700446 BMCWEB_LOG_DEBUG << "Couldn't interpret password";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 res.result(boost::beast::http::status::bad_request);
448 }
449 res.end();
450 });
451
452 BMCWEB_ROUTE(app, "/logout")
Ratan Gupta6f359562019-04-03 10:39:08 +0530453 .methods("POST"_method)(
Ed Tanousfd4859a2019-10-23 13:31:38 -0700454 [](const crow::Request& req, crow::Response& res) {
Ratan Gupta6f359562019-04-03 10:39:08 +0530455 auto& session = req.session;
456 if (session != nullptr)
457 {
458 res.jsonValue = {
459 {"data", "User '" + session->username + "' logged out"},
460 {"message", "200 OK"},
461 {"status", "ok"}};
Anthony Wilsonaf713a62019-03-15 15:40:58 -0500462
Ratan Gupta6f359562019-04-03 10:39:08 +0530463 persistent_data::SessionStore::getInstance().removeSession(
464 session);
465 }
466 res.end();
467 return;
468 });
Ed Tanous911ac312017-08-15 09:37:42 -0700469}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700470} // namespace token_authorization
471} // namespace crow