blob: c00090b4dd4fe392492f175e2993e564b93e92b2 [file] [log] [blame]
James Feist3909dc82020-04-03 10:58:55 -07001#pragma once
2
3#include "webroutes.hpp"
4
5#include <app.h>
6#include <common.h>
7#include <http_request.h>
8#include <http_response.h>
9
10#include <boost/algorithm/string/predicate.hpp>
11#include <boost/container/flat_set.hpp>
12#include <http_utility.hpp>
13#include <pam_authenticate.hpp>
14#include <persistent_data_middleware.hpp>
15
16#include <random>
17
18namespace crow
19{
20
21namespace authorization
22{
23
24static void cleanupTempSession(Request& req)
25{
26 // TODO(ed) THis should really be handled by the persistent data
27 // middleware, but because it is upstream, it doesn't have access to the
28 // session information. Should the data middleware persist the current
29 // user session?
30 if (req.session != nullptr &&
31 req.session->persistence ==
32 crow::persistent_data::PersistenceType::SINGLE_REQUEST)
33 {
34 persistent_data::SessionStore::getInstance().removeSession(req.session);
35 }
36}
37
38static const std::shared_ptr<crow::persistent_data::UserSession>
39 performBasicAuth(std::string_view auth_header)
40{
41 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";
42
43 std::string authData;
44 std::string_view param = auth_header.substr(strlen("Basic "));
45 if (!crow::utility::base64Decode(param, authData))
46 {
47 return nullptr;
48 }
49 std::size_t separator = authData.find(':');
50 if (separator == std::string::npos)
51 {
52 return nullptr;
53 }
54
55 std::string user = authData.substr(0, separator);
56 separator += 1;
57 if (separator > authData.size())
58 {
59 return nullptr;
60 }
61 std::string pass = authData.substr(separator);
62
63 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
64
65 int pamrc = pamAuthenticateUser(user, pass);
66 bool isConfigureSelfOnly = pamrc == PAM_NEW_AUTHTOK_REQD;
67 if ((pamrc != PAM_SUCCESS) && !isConfigureSelfOnly)
68 {
69 return nullptr;
70 }
71
72 // TODO(ed) generateUserSession is a little expensive for basic
73 // auth, as it generates some random identifiers that will never be
74 // used. This should have a "fast" path for when user tokens aren't
75 // needed.
76 // This whole flow needs to be revisited anyway, as we can't be
77 // calling directly into pam for every request
78 return persistent_data::SessionStore::getInstance().generateUserSession(
79 user, crow::persistent_data::PersistenceType::SINGLE_REQUEST,
80 isConfigureSelfOnly);
81}
82
83static const std::shared_ptr<crow::persistent_data::UserSession>
84 performTokenAuth(std::string_view auth_header)
85{
86 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";
87
88 std::string_view token = auth_header.substr(strlen("Token "));
89 auto session =
90 persistent_data::SessionStore::getInstance().loginSessionByToken(token);
91 return session;
92}
93
94static const std::shared_ptr<crow::persistent_data::UserSession>
95 performXtokenAuth(const crow::Request& req)
96{
97 BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";
98
99 std::string_view token = req.getHeaderValue("X-Auth-Token");
100 if (token.empty())
101 {
102 return nullptr;
103 }
104 auto session =
105 persistent_data::SessionStore::getInstance().loginSessionByToken(token);
106 return session;
107}
108
109static const std::shared_ptr<crow::persistent_data::UserSession>
110 performCookieAuth(const crow::Request& req)
111{
112 BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";
113
114 std::string_view cookieValue = req.getHeaderValue("Cookie");
115 if (cookieValue.empty())
116 {
117 return nullptr;
118 }
119
120 auto startIndex = cookieValue.find("SESSION=");
121 if (startIndex == std::string::npos)
122 {
123 return nullptr;
124 }
125 startIndex += sizeof("SESSION=") - 1;
126 auto endIndex = cookieValue.find(";", startIndex);
127 if (endIndex == std::string::npos)
128 {
129 endIndex = cookieValue.size();
130 }
131 std::string_view authKey =
132 cookieValue.substr(startIndex, endIndex - startIndex);
133
134 const std::shared_ptr<crow::persistent_data::UserSession> session =
135 persistent_data::SessionStore::getInstance().loginSessionByToken(
136 authKey);
137 if (session == nullptr)
138 {
139 return nullptr;
140 }
141#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
142 // RFC7231 defines methods that need csrf protection
Ed Tanousb41187f2019-10-24 16:30:02 -0700143 if (req.method() != boost::beast::http::verb::get)
James Feist3909dc82020-04-03 10:58:55 -0700144 {
145 std::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN");
146 // Make sure both tokens are filled
147 if (csrf.empty() || session->csrfToken.empty())
148 {
149 return nullptr;
150 }
151
152 if (csrf.size() != crow::persistent_data::sessionTokenSize)
153 {
154 return nullptr;
155 }
156 // Reject if csrf token not available
157 if (!crow::utility::constantTimeStringCompare(csrf, session->csrfToken))
158 {
159 return nullptr;
160 }
161 }
162#endif
163 return session;
164}
165
James Feist6964c982020-07-28 16:10:23 -0700166static const std::shared_ptr<crow::persistent_data::UserSession>
167 performTLSAuth(const crow::Request& req, Response& res,
168 std::weak_ptr<crow::persistent_data::UserSession> session)
169{
170#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
171 if (auto sp = session.lock())
172 {
173 // set cookie only if this is req from the browser.
174 if (req.getHeaderValue("User-Agent").empty())
175 {
176 BMCWEB_LOG_DEBUG << " TLS session: " << sp->uniqueId
177 << " will be used for this request.";
178 return sp;
179 }
180 else
181 {
182 std::string_view cookieValue = req.getHeaderValue("Cookie");
183 if (cookieValue.empty() ||
184 cookieValue.find("SESSION=") == std::string::npos)
185 {
186 // TODO: change this to not switch to cookie auth
187 res.addHeader(
188 "Set-Cookie",
189 "XSRF-TOKEN=" + sp->csrfToken +
190 "; Secure\r\nSet-Cookie: SESSION=" + sp->sessionToken +
191 "; Secure; HttpOnly\r\nSet-Cookie: "
192 "IsAuthenticated=true; Secure");
193 BMCWEB_LOG_DEBUG
194 << " TLS session: " << sp->uniqueId
195 << " with cookie will be used for this request.";
196 return sp;
197 }
198 }
199 }
200#endif
201 return nullptr;
202}
203
James Feist3909dc82020-04-03 10:58:55 -0700204// checks if request can be forwarded without authentication
205static bool isOnWhitelist(const crow::Request& req)
206{
207 // it's allowed to GET root node without authentication
Ed Tanousb41187f2019-10-24 16:30:02 -0700208 if (boost::beast::http::verb::get == req.method())
James Feist3909dc82020-04-03 10:58:55 -0700209 {
210 if (req.url == "/redfish/v1" || req.url == "/redfish/v1/" ||
211 req.url == "/redfish" || req.url == "/redfish/" ||
212 req.url == "/redfish/v1/odata" || req.url == "/redfish/v1/odata/")
213 {
214 return true;
215 }
216 else if (crow::webroutes::routes.find(std::string(req.url)) !=
217 crow::webroutes::routes.end())
218 {
219 return true;
220 }
221 }
222
223 // it's allowed to POST on session collection & login without
224 // authentication
Ed Tanousb41187f2019-10-24 16:30:02 -0700225 if (boost::beast::http::verb::post == req.method())
James Feist3909dc82020-04-03 10:58:55 -0700226 {
227 if ((req.url == "/redfish/v1/SessionService/Sessions") ||
228 (req.url == "/redfish/v1/SessionService/Sessions/") ||
229 (req.url == "/login"))
230 {
231 return true;
232 }
233 }
234
235 return false;
236}
237
James Feist6964c982020-07-28 16:10:23 -0700238static void
239 authenticate(crow::Request& req, Response& res,
240 std::weak_ptr<crow::persistent_data::UserSession> session)
James Feist3909dc82020-04-03 10:58:55 -0700241{
242 if (isOnWhitelist(req))
243 {
244 return;
245 }
246
247 const crow::persistent_data::AuthConfigMethods& authMethodsConfig =
248 crow::persistent_data::SessionStore::getInstance()
249 .getAuthMethodsConfig();
250
James Feist6964c982020-07-28 16:10:23 -0700251 if (req.session == nullptr && authMethodsConfig.tls)
252 {
253 req.session = performTLSAuth(req, res, session);
254 }
James Feist3909dc82020-04-03 10:58:55 -0700255 if (req.session == nullptr && authMethodsConfig.xtoken)
256 {
257 req.session = performXtokenAuth(req);
258 }
259 if (req.session == nullptr && authMethodsConfig.cookie)
260 {
261 req.session = performCookieAuth(req);
262 }
263 if (req.session == nullptr)
264 {
265 std::string_view authHeader = req.getHeaderValue("Authorization");
266 if (!authHeader.empty())
267 {
268 // Reject any kind of auth other than basic or token
269 if (boost::starts_with(authHeader, "Token ") &&
270 authMethodsConfig.sessionToken)
271 {
272 req.session = performTokenAuth(authHeader);
273 }
274 else if (boost::starts_with(authHeader, "Basic ") &&
275 authMethodsConfig.basic)
276 {
277 req.session = performBasicAuth(authHeader);
278 }
279 }
280 }
281
282 if (req.session == nullptr)
283 {
284 BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
285
286 // If it's a browser connecting, don't send the HTTP authenticate
287 // header, to avoid possible CSRF attacks with basic auth
288 if (http_helpers::requestPrefersHtml(req))
289 {
290 res.result(boost::beast::http::status::temporary_redirect);
291 res.addHeader("Location",
292 "/#/login?next=" + http_helpers::urlEncode(req.url));
293 }
294 else
295 {
296 res.result(boost::beast::http::status::unauthorized);
297 // only send the WWW-authenticate header if this isn't a xhr
298 // from the browser. most scripts,
299 if (req.getHeaderValue("User-Agent").empty())
300 {
301 res.addHeader("WWW-Authenticate", "Basic");
302 }
303 }
304
305 res.end();
306 return;
307 }
308}
309
310} // namespace authorization
311} // namespace crow