summaryrefslogtreecommitdiff
path: root/include/authorization.hpp
blob: c0a84b661a341816b850a4ddb9a8d0e208336d24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#pragma once

#include "webroutes.hpp"

#include <app.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/container/flat_set.hpp>
#include <common.hpp>
#include <http_request.hpp>
#include <http_response.hpp>
#include <http_utility.hpp>
#include <pam_authenticate.hpp>

#include <random>
#include <utility>

namespace crow
{

namespace authorization
{

static void cleanupTempSession(Request& req)
{
    // TODO(ed) THis should really be handled by the persistent data
    // middleware, but because it is upstream, it doesn't have access to the
    // session information.  Should the data middleware persist the current
    // user session?
    if (req.session != nullptr &&
        req.session->persistence ==
            persistent_data::PersistenceType::SINGLE_REQUEST)
    {
        persistent_data::SessionStore::getInstance().removeSession(req.session);
    }
}

#ifdef BMCWEB_ENABLE_BASIC_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performBasicAuth(const boost::asio::ip::address& clientIp,
                     std::string_view auth_header)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";

    std::string authData;
    std::string_view param = auth_header.substr(strlen("Basic "));
    if (!crow::utility::base64Decode(param, authData))
    {
        return nullptr;
    }
    std::size_t separator = authData.find(':');
    if (separator == std::string::npos)
    {
        return nullptr;
    }

    std::string user = authData.substr(0, separator);
    separator += 1;
    if (separator > authData.size())
    {
        return nullptr;
    }
    std::string pass = authData.substr(separator);

    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] User IPAddress: "
                     << clientIp.to_string();

    int pamrc = pamAuthenticateUser(user, pass);
    bool isConfigureSelfOnly = pamrc == PAM_NEW_AUTHTOK_REQD;
    if ((pamrc != PAM_SUCCESS) && !isConfigureSelfOnly)
    {
        return nullptr;
    }

    // TODO(ed) generateUserSession is a little expensive for basic
    // auth, as it generates some random identifiers that will never be
    // used.  This should have a "fast" path for when user tokens aren't
    // needed.
    // This whole flow needs to be revisited anyway, as we can't be
    // calling directly into pam for every request
    return persistent_data::SessionStore::getInstance().generateUserSession(
        user, persistent_data::PersistenceType::SINGLE_REQUEST,
        isConfigureSelfOnly, clientIp.to_string());
}
#endif

#ifdef BMCWEB_ENABLE_SESSION_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performTokenAuth(std::string_view auth_header)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";

    std::string_view token = auth_header.substr(strlen("Token "));
    auto session =
        persistent_data::SessionStore::getInstance().loginSessionByToken(token);
    return session;
}
#endif

#ifdef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performXtokenAuth(const crow::Request& req)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";

    std::string_view token = req.getHeaderValue("X-Auth-Token");
    if (token.empty())
    {
        return nullptr;
    }
    auto session =
        persistent_data::SessionStore::getInstance().loginSessionByToken(token);
    return session;
}
#endif

#ifdef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performCookieAuth(const crow::Request& req)
{
    BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";

    std::string_view cookieValue = req.getHeaderValue("Cookie");
    if (cookieValue.empty())
    {
        return nullptr;
    }

    auto startIndex = cookieValue.find("SESSION=");
    if (startIndex == std::string::npos)
    {
        return nullptr;
    }
    startIndex += sizeof("SESSION=") - 1;
    auto endIndex = cookieValue.find(";", startIndex);
    if (endIndex == std::string::npos)
    {
        endIndex = cookieValue.size();
    }
    std::string_view authKey =
        cookieValue.substr(startIndex, endIndex - startIndex);

    std::shared_ptr<persistent_data::UserSession> session =
        persistent_data::SessionStore::getInstance().loginSessionByToken(
            authKey);
    if (session == nullptr)
    {
        return nullptr;
    }
#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
    // RFC7231 defines methods that need csrf protection
    if (req.method() != boost::beast::http::verb::get)
    {
        std::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN");
        // Make sure both tokens are filled
        if (csrf.empty() || session->csrfToken.empty())
        {
            return nullptr;
        }

        if (csrf.size() != persistent_data::sessionTokenSize)
        {
            return nullptr;
        }
        // Reject if csrf token not available
        if (!crow::utility::constantTimeStringCompare(csrf, session->csrfToken))
        {
            return nullptr;
        }
    }
#endif
    return session;
}
#endif

#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
static std::shared_ptr<persistent_data::UserSession>
    performTLSAuth(const crow::Request& req, Response& res,
                   const std::weak_ptr<persistent_data::UserSession>& session)
{
    if (auto sp = session.lock())
    {
        // set cookie only if this is req from the browser.
        if (req.getHeaderValue("User-Agent").empty())
        {
            BMCWEB_LOG_DEBUG << " TLS session: " << sp->uniqueId
                             << " will be used for this request.";
            return sp;
        }
        std::string_view cookieValue = req.getHeaderValue("Cookie");
        if (cookieValue.empty() ||
            cookieValue.find("SESSION=") == std::string::npos)
        {
            // TODO: change this to not switch to cookie auth
            res.addHeader("Set-Cookie", "XSRF-TOKEN=" + sp->csrfToken +
                                            "; Secure\r\nSet-Cookie: SESSION=" +
                                            sp->sessionToken +
                                            "; Secure; HttpOnly\r\nSet-Cookie: "
                                            "IsAuthenticated=true; Secure");
            BMCWEB_LOG_DEBUG << " TLS session: " << sp->uniqueId
                             << " with cookie will be used for this request.";
            return sp;
        }
    }
    return nullptr;
}
#endif

// checks if request can be forwarded without authentication
static bool isOnWhitelist(const crow::Request& req)
{
    // it's allowed to GET root node without authentication
    if (boost::beast::http::verb::get == req.method())
    {
        if (req.url == "/redfish/v1" || req.url == "/redfish/v1/" ||
            req.url == "/redfish" || req.url == "/redfish/" ||
            req.url == "/redfish/v1/odata" || req.url == "/redfish/v1/odata/")
        {
            return true;
        }
        if (crow::webroutes::routes.find(std::string(req.url)) !=
            crow::webroutes::routes.end())
        {
            return true;
        }
    }

    // it's allowed to POST on session collection & login without
    // authentication
    if (boost::beast::http::verb::post == req.method())
    {
        if ((req.url == "/redfish/v1/SessionService/Sessions") ||
            (req.url == "/redfish/v1/SessionService/Sessions/") ||
            (req.url == "/login"))
        {
            return true;
        }
    }

    return false;
}

static void authenticate(
    crow::Request& req, Response& res,
    [[maybe_unused]] const std::weak_ptr<persistent_data::UserSession>& session)
{
    if (isOnWhitelist(req))
    {
        return;
    }

    const persistent_data::AuthConfigMethods& authMethodsConfig =
        persistent_data::SessionStore::getInstance().getAuthMethodsConfig();

#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
    if (req.session == nullptr && authMethodsConfig.tls)
    {
        req.session = performTLSAuth(req, res, session);
    }
#endif
#ifdef BMCWEB_ENABLE_XTOKEN_AUTHENTICATION
    if (req.session == nullptr && authMethodsConfig.xtoken)
    {
        req.session = performXtokenAuth(req);
    }
#endif
#ifdef BMCWEB_ENABLE_COOKIE_AUTHENTICATION
    if (req.session == nullptr && authMethodsConfig.cookie)
    {
        req.session = performCookieAuth(req);
    }
#endif
    if (req.session == nullptr)
    {
        std::string_view authHeader = req.getHeaderValue("Authorization");
        if (!authHeader.empty())
        {
            // Reject any kind of auth other than basic or token
            if (boost::starts_with(authHeader, "Token ") &&
                authMethodsConfig.sessionToken)
            {
#ifdef BMCWEB_ENABLE_SESSION_AUTHENTICATION
                req.session = performTokenAuth(authHeader);
#endif
            }
            else if (boost::starts_with(authHeader, "Basic ") &&
                     authMethodsConfig.basic)
            {
#ifdef BMCWEB_ENABLE_BASIC_AUTHENTICATION
                req.session = performBasicAuth(req.ipAddress, authHeader);
#endif
            }
        }
    }

    if (req.session == nullptr)
    {
        BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";

        // If it's a browser connecting, don't send the HTTP authenticate
        // header, to avoid possible CSRF attacks with basic auth
        if (http_helpers::requestPrefersHtml(req))
        {
            res.result(boost::beast::http::status::temporary_redirect);
            res.addHeader("Location",
                          "/#/login?next=" + http_helpers::urlEncode(req.url));
        }
        else
        {
            res.result(boost::beast::http::status::unauthorized);
            // only send the WWW-authenticate header if this isn't a xhr
            // from the browser.  most scripts,
            if (req.getHeaderValue("User-Agent").empty())
            {
                res.addHeader("WWW-Authenticate", "Basic");
            }
        }

        res.end();
        return;
    }
}

} // namespace authorization
} // namespace crow