blob: c419c97fa7e784b4c4ef2abc24be5438e1f97781 [file] [log] [blame]
Ed Tanousf9273472017-02-28 16:05:13 -08001#pragma once
2
Ed Tanous911ac312017-08-15 09:37:42 -07003#include <crow/app.h>
Ed Tanouse0d918b2018-03-27 17:41:04 -07004#include <crow/common.h>
Ed Tanousf9273472017-02-28 16:05:13 -08005#include <crow/http_request.h>
6#include <crow/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 {
25 std::shared_ptr<crow::persistent_data::UserSession> session;
26 };
Kowalski, Kamil2b7981f2018-01-31 13:24:59 +010027
Ed Tanous1abe55e2018-09-05 08:30:59 -070028 void beforeHandle(crow::Request& req, Response& res, Context& ctx)
29 {
30 if (isOnWhitelist(req))
31 {
32 return;
Ed Tanouse0d918b2018-03-27 17:41:04 -070033 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010034
Ed Tanous1abe55e2018-09-05 08:30:59 -070035 ctx.session = performXtokenAuth(req);
36 if (ctx.session == nullptr)
37 {
38 ctx.session = performCookieAuth(req);
Ed Tanous9bd21fc2018-04-26 16:08:56 -070039 }
Ed Tanous1abe55e2018-09-05 08:30:59 -070040 if (ctx.session == nullptr)
41 {
42 boost::string_view authHeader = req.getHeaderValue("Authorization");
43 if (!authHeader.empty())
44 {
45 // Reject any kind of auth other than basic or token
46 if (boost::starts_with(authHeader, "Token "))
47 {
48 ctx.session = performTokenAuth(authHeader);
49 }
50 else if (boost::starts_with(authHeader, "Basic "))
51 {
52 ctx.session = performBasicAuth(authHeader);
53 }
54 }
55 }
Ed Tanouse0d918b2018-03-27 17:41:04 -070056
Ed Tanous1abe55e2018-09-05 08:30:59 -070057 if (ctx.session == nullptr)
58 {
59 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
60
61 // If it's a browser connecting, don't send the HTTP authenticate
62 // header, to avoid possible CSRF attacks with basic auth
63 if (http_helpers::requestPrefersHtml(req))
64 {
65 res.result(boost::beast::http::status::temporary_redirect);
66 res.addHeader("Location", "/#/login");
67 }
68 else
69 {
70 res.result(boost::beast::http::status::unauthorized);
71 // only send the WWW-authenticate header if this isn't a xhr
72 // from the browser. most scripts,
73 if (req.getHeaderValue("User-Agent").empty())
74 {
75 res.addHeader("WWW-Authenticate", "Basic");
76 }
77 }
78
79 res.end();
80 return;
81 }
82
83 // TODO get user privileges here and propagate it via MW Context
84 // else let the request continue unharmed
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +010085 }
Ed Tanousf9273472017-02-28 16:05:13 -080086
Ed Tanous1abe55e2018-09-05 08:30:59 -070087 template <typename AllContext>
88 void afterHandle(Request& req, Response& res, Context& ctx,
89 AllContext& allctx)
90 {
91 // TODO(ed) THis should really be handled by the persistent data
92 // middleware, but because it is upstream, it doesn't have access to the
93 // session information. Should the data middleware persist the current
94 // user session?
95 if (ctx.session != nullptr &&
96 ctx.session->persistence ==
97 crow::persistent_data::PersistenceType::SINGLE_REQUEST)
98 {
99 persistent_data::SessionStore::getInstance().removeSession(
100 ctx.session);
101 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100102 }
103
Ed Tanous1abe55e2018-09-05 08:30:59 -0700104 private:
105 const std::shared_ptr<crow::persistent_data::UserSession>
106 performBasicAuth(boost::string_view auth_header) const
107 {
108 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100109
Ed Tanous1abe55e2018-09-05 08:30:59 -0700110 std::string authData;
111 boost::string_view param = auth_header.substr(strlen("Basic "));
112 if (!crow::utility::base64Decode(param, authData))
113 {
114 return nullptr;
115 }
116 std::size_t separator = authData.find(':');
117 if (separator == std::string::npos)
118 {
119 return nullptr;
120 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100121
Ed Tanous1abe55e2018-09-05 08:30:59 -0700122 std::string user = authData.substr(0, separator);
123 separator += 1;
124 if (separator > authData.size())
125 {
126 return nullptr;
127 }
128 std::string pass = authData.substr(separator);
129
130 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
131
132 if (!pamAuthenticateUser(user, pass))
133 {
134 return nullptr;
135 }
136
137 // TODO(ed) generateUserSession is a little expensive for basic
138 // auth, as it generates some random identifiers that will never be
139 // used. This should have a "fast" path for when user tokens aren't
140 // needed.
141 // This whole flow needs to be revisited anyway, as we can't be
142 // calling directly into pam for every request
143 return persistent_data::SessionStore::getInstance().generateUserSession(
144 user, crow::persistent_data::PersistenceType::SINGLE_REQUEST);
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100145 }
146
Ed Tanous1abe55e2018-09-05 08:30:59 -0700147 const std::shared_ptr<crow::persistent_data::UserSession>
148 performTokenAuth(boost::string_view auth_header) const
149 {
150 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";
Ed Tanous8041f312017-04-03 09:47:01 -0700151
Ed Tanous1abe55e2018-09-05 08:30:59 -0700152 boost::string_view token = auth_header.substr(strlen("Token "));
153 auto session =
154 persistent_data::SessionStore::getInstance().loginSessionByToken(
155 token);
156 return session;
Ed Tanous1ea9f062018-03-27 17:45:20 -0700157 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100158
Ed Tanous1abe55e2018-09-05 08:30:59 -0700159 const std::shared_ptr<crow::persistent_data::UserSession>
160 performXtokenAuth(const crow::Request& req) const
161 {
162 BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100163
Ed Tanous1abe55e2018-09-05 08:30:59 -0700164 boost::string_view token = req.getHeaderValue("X-Auth-Token");
165 if (token.empty())
166 {
167 return nullptr;
168 }
169 auto session =
170 persistent_data::SessionStore::getInstance().loginSessionByToken(
171 token);
172 return session;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100173 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700174
175 const std::shared_ptr<crow::persistent_data::UserSession>
176 performCookieAuth(const crow::Request& req) const
177 {
178 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";
179
180 boost::string_view cookieValue = req.getHeaderValue("Cookie");
181 if (cookieValue.empty())
182 {
183 return nullptr;
184 }
185
186 auto startIndex = cookieValue.find("SESSION=");
187 if (startIndex == std::string::npos)
188 {
189 return nullptr;
190 }
191 startIndex += sizeof("SESSION=") - 1;
192 auto endIndex = cookieValue.find(";", startIndex);
193 if (endIndex == std::string::npos)
194 {
195 endIndex = cookieValue.size();
196 }
197 boost::string_view authKey =
198 cookieValue.substr(startIndex, endIndex - startIndex);
199
200 const std::shared_ptr<crow::persistent_data::UserSession> session =
201 persistent_data::SessionStore::getInstance().loginSessionByToken(
202 authKey);
203 if (session == nullptr)
204 {
205 return nullptr;
206 }
Ed Tanous1e439872018-05-18 11:48:52 -0700207#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
Ed Tanous1abe55e2018-09-05 08:30:59 -0700208 // RFC7231 defines methods that need csrf protection
209 if (req.method() != "GET"_method)
210 {
211 boost::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN");
212 // Make sure both tokens are filled
213 if (csrf.empty() || session->csrfToken.empty())
214 {
215 return nullptr;
216 }
217 // Reject if csrf token not available
218 if (csrf != session->csrfToken)
219 {
220 return nullptr;
221 }
222 }
Ed Tanous1e439872018-05-18 11:48:52 -0700223#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700224 return session;
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100225 }
226
Ed Tanous1abe55e2018-09-05 08:30:59 -0700227 // checks if request can be forwarded without authentication
228 bool isOnWhitelist(const crow::Request& req) const
229 {
230 // it's allowed to GET root node without authentica tion
231 if ("GET"_method == req.method())
232 {
233 if (req.url == "/redfish/v1" || req.url == "/redfish/v1/" ||
234 req.url == "/redfish" || req.url == "/redfish/" ||
235 req.url == "/redfish/v1/odata" ||
236 req.url == "/redfish/v1/odata/")
237 {
238 return true;
239 }
240 else if (crow::webassets::routes.find(std::string(req.url)) !=
241 crow::webassets::routes.end())
242 {
243 return true;
244 }
245 }
Borawski.Lukasz9d8fd302018-01-05 14:56:09 +0100246
Ed Tanous1abe55e2018-09-05 08:30:59 -0700247 // it's allowed to POST on session collection & login without
248 // authentication
249 if ("POST"_method == req.method())
250 {
251 if ((req.url == "/redfish/v1/SessionService/Sessions") ||
252 (req.url == "/redfish/v1/SessionService/Sessions/") ||
253 (req.url == "/login"))
254 {
255 return true;
256 }
257 }
258
259 return false;
260 }
Ed Tanous99923322017-03-03 14:21:24 -0800261};
Ed Tanousf3d847c2017-06-12 16:01:42 -0700262
Ed Tanousba9f9a62017-10-11 16:40:35 -0700263// TODO(ed) see if there is a better way to allow middlewares to request
264// routes.
Ed Tanous911ac312017-08-15 09:37:42 -0700265// Possibly an init function on first construction?
Ed Tanous1abe55e2018-09-05 08:30:59 -0700266template <typename... Middlewares> void requestRoutes(Crow<Middlewares...>& app)
267{
268 static_assert(
269 black_magic::Contains<persistent_data::Middleware,
270 Middlewares...>::value,
271 "token_authorization middleware must be enabled in app to use "
272 "auth routes");
273 BMCWEB_ROUTE(app, "/login")
274 .methods(
275 "POST"_method)([&](const crow::Request& req, crow::Response& res) {
276 boost::string_view contentType = req.getHeaderValue("content-type");
277 boost::string_view username;
278 boost::string_view password;
Ed Tanouse0d918b2018-03-27 17:41:04 -0700279
Ed Tanous1abe55e2018-09-05 08:30:59 -0700280 bool looksLikeIbm = false;
Ed Tanousdb024a52018-03-06 12:50:34 -0800281
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282 // This object needs to be declared at this scope so the strings
283 // within it are not destroyed before we can use them
284 nlohmann::json loginCredentials;
285 // Check if auth was provided by a payload
286 if (contentType == "application/json")
287 {
288 loginCredentials =
289 nlohmann::json::parse(req.body, nullptr, false);
290 if (loginCredentials.is_discarded())
291 {
292 res.result(boost::beast::http::status::bad_request);
293 res.end();
294 return;
295 }
296
297 // check for username/password in the root object
298 // THis method is how intel APIs authenticate
299 nlohmann::json::iterator userIt =
300 loginCredentials.find("username");
301 nlohmann::json::iterator passIt =
302 loginCredentials.find("password");
303 if (userIt != loginCredentials.end() &&
304 passIt != loginCredentials.end())
305 {
306 const std::string* userStr =
307 userIt->get_ptr<const std::string*>();
308 const std::string* passStr =
309 passIt->get_ptr<const std::string*>();
310 if (userStr != nullptr && passStr != nullptr)
311 {
312 username = *userStr;
313 password = *passStr;
314 }
315 }
316 else
317 {
318 // Openbmc appears to push a data object that contains the
319 // same keys (username and password), attempt to use that
320 auto dataIt = loginCredentials.find("data");
321 if (dataIt != loginCredentials.end())
322 {
323 // Some apis produce an array of value ["username",
324 // "password"]
325 if (dataIt->is_array())
326 {
327 if (dataIt->size() == 2)
328 {
329 nlohmann::json::iterator userIt2 =
330 dataIt->begin();
331 nlohmann::json::iterator passIt2 =
332 dataIt->begin() + 1;
333 looksLikeIbm = true;
334 if (userIt2 != dataIt->end() &&
335 passIt2 != dataIt->end())
336 {
337 const std::string* userStr =
338 userIt2->get_ptr<const std::string*>();
339 const std::string* passStr =
340 passIt2->get_ptr<const std::string*>();
341 if (userStr != nullptr &&
342 passStr != nullptr)
343 {
344 username = *userStr;
345 password = *passStr;
346 }
347 }
348 }
349 }
350 else if (dataIt->is_object())
351 {
352 nlohmann::json::iterator userIt2 =
353 dataIt->find("username");
354 nlohmann::json::iterator passIt2 =
355 dataIt->find("password");
356 if (userIt2 != dataIt->end() &&
357 passIt2 != dataIt->end())
358 {
359 const std::string* userStr =
360 userIt2->get_ptr<const std::string*>();
361 const std::string* passStr =
362 passIt2->get_ptr<const std::string*>();
363 if (userStr != nullptr && passStr != nullptr)
364 {
365 username = *userStr;
366 password = *passStr;
367 }
368 }
369 }
370 }
371 }
372 }
373 else
374 {
375 // check if auth was provided as a headers
376 username = req.getHeaderValue("username");
377 password = req.getHeaderValue("password");
378 }
379
380 if (!username.empty() && !password.empty())
381 {
382 if (!pamAuthenticateUser(username, password))
383 {
384 res.result(boost::beast::http::status::unauthorized);
385 }
386 else
387 {
388 auto session = persistent_data::SessionStore::getInstance()
389 .generateUserSession(username);
390
391 if (looksLikeIbm)
392 {
393 // IBM requires a very specific login structure, and
394 // doesn't actually look at the status code.
395 // TODO(ed).... Fix that upstream
396 res.jsonValue = {
397 {"data",
398 "User '" + std::string(username) + "' logged in"},
399 {"message", "200 OK"},
400 {"status", "ok"}};
401
402 // Hack alert. Boost beast by default doesn't let you
403 // declare multiple headers of the same name, and in
404 // most cases this is fine. Unfortunately here we need
405 // to set the Session cookie, which requires the
406 // httpOnly attribute, as well as the XSRF cookie, which
407 // requires it to not have an httpOnly attribute. To get
408 // the behavior we want, we simply inject the second
409 // "set-cookie" string into the value header, and get
410 // the result we want, even though we are technicaly
411 // declaring two headers here.
412 res.addHeader("Set-Cookie",
413 "XSRF-TOKEN=" + session->csrfToken +
414 "; Secure\r\nSet-Cookie: SESSION=" +
415 session->sessionToken +
416 "; Secure; HttpOnly");
417 }
418 else
419 {
420 // if content type is json, assume json token
421 res.jsonValue = {{"token", session->sessionToken}};
422 }
423 }
424 }
425 else
426 {
427 res.result(boost::beast::http::status::bad_request);
428 }
429 res.end();
430 });
431
432 BMCWEB_ROUTE(app, "/logout")
433 .methods(
434 "POST"_method)([&](const crow::Request& req, crow::Response& res) {
435 auto& session =
436 app.template getContext<token_authorization::Middleware>(req)
437 .session;
438 if (session != nullptr)
439 {
440 persistent_data::SessionStore::getInstance().removeSession(
441 session);
442 }
Ed Tanous911ac312017-08-15 09:37:42 -0700443 res.end();
444 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 });
Ed Tanous911ac312017-08-15 09:37:42 -0700446}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447} // namespace token_authorization
448} // namespace crow