summaryrefslogtreecommitdiff
path: root/include/token_authorization_middleware.hpp
blob: 809902022fe5ef1969859c05d9b527f44859d759 (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
#pragma once

#include <pam_authenticate.hpp>
#include <persistent_data_middleware.hpp>
#include <webassets.hpp>
#include <random>
#include <crow/app.h>
#include <crow/http_codes.h>
#include <crow/http_request.h>
#include <crow/http_response.h>
#include <boost/bimap.hpp>
#include <boost/container/flat_set.hpp>

namespace crow {

namespace TokenAuthorization {

class Middleware {
 public:
  struct context {
    const crow::PersistentData::UserSession* session;
  };
  template <typename AllContext>
  void before_handle(crow::request& req, response& res, context& ctx,
                     AllContext& allctx) {
    auto& sessions =
        allctx.template get<crow::PersistentData::Middleware>().sessions;
    std::string auth_header = req.get_header_value("Authorization");
    if (auth_header != "") {
      // Reject any kind of auth other than basic or token
      if (boost::starts_with(auth_header, "Basic ")) {
        ctx.session = perform_basic_auth(auth_header, sessions);
      } else if (boost::starts_with(auth_header, "Token ")) {
        ctx.session = perform_token_auth(auth_header, sessions);
      }
    } else if (req.headers.count("X-Auth-Token") == 1) {
      ctx.session = perform_xtoken_auth(req, sessions);
    } else if (req.headers.count("Cookie") == 1) {
      ctx.session = perform_cookie_auth(req, sessions);
    }

    if (ctx.session == nullptr && !is_on_whitelist(req)) {
      CROW_LOG_WARNING << "[AuthMiddleware] authorization failed";
      res.code = static_cast<int>(HttpRespCode::UNAUTHORIZED);
      res.add_header("WWW-Authenticate", "Basic");
      res.end();
      return;
    }

    // TODO get user privileges here and propagate it via MW context
    // else let the request continue unharmed
  }

  template <typename AllContext>
  void after_handle(request& req, response& res, context& ctx,
                    AllContext& allctx) {
    // 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 (ctx.session != nullptr &&
        ctx.session->persistence ==
            crow::PersistentData::PersistenceType::SINGLE_REQUEST) {
      auto& session_store =
          allctx.template get<crow::PersistentData::Middleware>().sessions;

      session_store->remove_session(ctx.session);
    }
  }

 private:
  const crow::PersistentData::UserSession* perform_basic_auth(
      const std::string& auth_header,
      crow::PersistentData::SessionStore* sessions) const {
    CROW_LOG_DEBUG << "[AuthMiddleware] Basic authentication";

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

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

    CROW_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;

    if (!pam_authenticate_user(user, pass)) {
      return nullptr;
    }

    // TODO(ed) generate_user_session 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 &(sessions->generate_user_session(
        user, crow::PersistentData::PersistenceType::SINGLE_REQUEST));
  }

  const crow::PersistentData::UserSession* perform_token_auth(
      const std::string& auth_header,
      crow::PersistentData::SessionStore* sessions) const {
    CROW_LOG_DEBUG << "[AuthMiddleware] Token authentication";

    std::string token = auth_header.substr(strlen("Token "));
    auto session = sessions->login_session_by_token(token);
    return session;
  }

  const crow::PersistentData::UserSession* perform_xtoken_auth(
      const crow::request& req,
      crow::PersistentData::SessionStore* sessions) const {
    CROW_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";

    auto& token = req.get_header_value("X-Auth-Token");
    auto session = sessions->login_session_by_token(token);
    return session;
  }

  const crow::PersistentData::UserSession* perform_cookie_auth(
      const crow::request& req,
      crow::PersistentData::SessionStore* sessions) const {
    CROW_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";

    auto& cookie_value = req.get_header_value("Cookie");

    auto start_index = cookie_value.find("SESSION=");
    if (start_index == std::string::npos) {
      return nullptr;
    }
    start_index += sizeof("SESSION=") - 1;
    auto end_index = cookie_value.find(";", start_index);
    if (end_index == std::string::npos) {
      end_index = cookie_value.size();
    }
    std::string auth_key =
        cookie_value.substr(start_index, end_index - start_index);

    const crow::PersistentData::UserSession* session =
        sessions->login_session_by_token(auth_key);
    if (session == nullptr) {
      return nullptr;
    }

    // RFC7231 defines methods that need csrf protection
    if (req.method != "GET"_method) {
      const std::string& csrf = req.get_header_value("X-XSRF-TOKEN");
      // Make sure both tokens are filled
      if (csrf.empty() || session->csrf_token.empty()) {
        return nullptr;
      }
      // Reject if csrf token not available
      if (csrf != session->csrf_token) {
        return nullptr;
      }
    }
    return session;
  }

  // checks if request can be forwarded without authentication
  bool is_on_whitelist(const crow::request& req) const {
    // it's allowed to GET root node without authentication
    if ("GET"_method == req.method) {
      if (req.url == "/redfish/v1") {
        return true;
      } else if (crow::webassets::routes.find(req.url) !=
                 crow::webassets::routes.end()) {
        return true;
      }
    }

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

    return false;
  }
};

// TODO(ed) see if there is a better way to allow middlewares to request
// routes.
// Possibly an init function on first construction?
template <typename... Middlewares>
void request_routes(Crow<Middlewares...>& app) {
  static_assert(
      black_magic::contains<PersistentData::Middleware, Middlewares...>::value,
      "TokenAuthorization middleware must be enabled in app to use "
      "auth routes");
  CROW_ROUTE(app, "/login")
      .methods(
          "POST"_method)([&](const crow::request& req, crow::response& res) {
        std::string content_type;
        auto content_type_it = req.headers.find("content-type");
        if (content_type_it != req.headers.end()) {
          content_type = content_type_it->second;
          boost::algorithm::to_lower(content_type);
        }
        std::string username;
        std::string password;
        bool looks_like_ibm = false;
        // Check if auth was provided by a payload
        if (content_type == "application/json") {
          auto login_credentials =
              nlohmann::json::parse(req.body, nullptr, false);
          if (login_credentials.is_discarded()) {
            res.code = 400;
            res.end();
            return;
          }
          // check for username/password in the root object
          // THis method is how intel APIs authenticate
          auto user_it = login_credentials.find("username");
          auto pass_it = login_credentials.find("password");
          if (user_it != login_credentials.end() &&
              pass_it != login_credentials.end()) {
            username = user_it->get<const std::string>();
            password = pass_it->get<const std::string>();
          } else {
            // Openbmc appears to push a data object that contains the same
            // keys (username and password), attempt to use that
            auto data_it = login_credentials.find("data");
            if (data_it != login_credentials.end()) {
              // Some apis produce an array of value ["username",
              // "password"]
              if (data_it->is_array()) {
                if (data_it->size() == 2) {
                  username = (*data_it)[0].get<const std::string>();
                  password = (*data_it)[1].get<const std::string>();
                  looks_like_ibm = true;
                }
              } else if (data_it->is_object()) {
                auto user_it = data_it->find("username");
                auto pass_it = data_it->find("password");
                if (user_it != data_it->end() && pass_it != data_it->end()) {
                  username = user_it->get<const std::string>();
                  password = pass_it->get<const std::string>();
                }
              }
            }
          }
        } else {
          // check if auth was provided as a query string
          auto user_it = req.headers.find("username");
          auto pass_it = req.headers.find("password");
          if (user_it != req.headers.end() && pass_it != req.headers.end()) {
            username = user_it->second;
            password = pass_it->second;
          }
        }

        if (!username.empty() && !password.empty()) {
          if (!pam_authenticate_user(username, password)) {
            res.code = res.code = static_cast<int>(HttpRespCode::UNAUTHORIZED);
          } else {
            auto& context =
                app.template get_context<PersistentData::Middleware>(req);
            auto& session_store = context.sessions;
            auto& session = session_store->generate_user_session(username);

            if (looks_like_ibm) {
              // IBM requires a very specific login structure, and doesn't
              // actually look at the status code.  TODO(ed).... Fix that
              // upstream
              nlohmann::json ret{{"data", "User '" + username + "' logged in"},
                                 {"message", "200 OK"},
                                 {"status", "ok"}};
              res.add_header("Set-Cookie", "XSRF-TOKEN=" + session.csrf_token);
              res.add_header(
                  "Set-Cookie",
                  "SESSION=" + session.session_token + "; Secure; HttpOnly");

              res.write(ret.dump());
            } else {
              // if content type is json, assume json token
              nlohmann::json ret{{"token", session.session_token}};

              res.write(ret.dump());
              res.add_header("Content-Type", "application/json");
            }
          }

        } else {
          res.code = static_cast<int>(HttpRespCode::BAD_REQUEST);
        }
        res.end();
      });

  CROW_ROUTE(app, "/logout")
      .methods(
          "POST"_method)([&](const crow::request& req, crow::response& res) {
        auto& session_store =
            app.template get_context<PersistentData::Middleware>(req).sessions;
        auto& session =
            app.template get_context<TokenAuthorization::Middleware>(req)
                .session;
        if (session != nullptr) {
          session_store->remove_session(session);
        }
        res.code = static_cast<int>(HttpRespCode::OK);
        res.end();
        return;

      });
}
}  // namespaec TokenAuthorization
}  // namespace crow