15 #include <macaroons.h>
16 #include <uuid/uuid.h>
22 char *r = (
char *) malloc(l + 1);
26 for (i = 0; i < l; i++) {
34 savec[0] = str[i + 1];
35 savec[1] = str[i + 2];
38 r[j] = strtol(savec, 0, 16);
41 }
else if (str[i] ==
'+') r[j] =
' ';
58 output.reserve(input.size());
59 char prior_chr =
'\0';
60 size_t output_idx = 0;
61 for (
size_t idx = 0; idx < input.size(); idx++) {
62 char chr = input[idx];
63 if (prior_chr ==
'/' && chr ==
'/') {
67 output += input[output_idx];
76 return cv.compare(0, 5,
"name:") == 0 ||
77 cv.compare(0, 5,
"path:") == 0 ||
78 cv.compare(0, 7,
"before:") == 0;
83 return cv.compare(0, 9,
"activity:") == 0;
90 if (input.find(
"PT") != 0)
95 std::string remaining = input;
98 remaining = remaining.substr(pos);
99 if (remaining.size() == 0)
break;
103 cur_duration = stol(remaining, &pos);
108 if (pos >= remaining.size())
112 char unit = remaining[pos];
120 cur_duration *= 3600;
126 duration += cur_duration;
138 Handler::GenerateID(
const std::string &resource,
140 const std::string &activities,
141 const std::vector<std::string> &other_caveats,
142 const std::string &before)
145 uuid_generate_random(uu);
147 uuid_unparse(uu, uuid_buf);
148 std::string result(uuid_buf);
156 std::stringstream ss;
157 ss <<
"ID=" << result <<
", ";
159 if (entity.
prot[0] !=
'\0') {ss <<
"protocol=" << entity.
prot <<
", ";}
160 if (entity.
name) {ss <<
"name=" << entity.
name <<
", ";}
161 if (entity.
host) {ss <<
"host=" << entity.
host <<
", ";}
162 if (entity.
vorg) {ss <<
"vorg=" << entity.
vorg <<
", ";}
163 if (entity.
role) {ss <<
"role=" << entity.
role <<
", ";}
164 if (entity.
grps) {ss <<
"groups=" << entity.
grps <<
", ";}
166 if (activities.size()) {ss <<
"base_activities=" << activities <<
", ";}
168 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
169 iter != other_caveats.end();
172 ss <<
"user_caveat=" << *iter <<
", ";
175 ss <<
"expires=" << before;
177 m_log->
Emsg(
"MacaroonGen", ss.str().c_str());
183 Handler::GenerateActivities(
const XrdHttpExtReq & req,
const std::string &resource)
const
185 std::string result =
"activity:READ_METADATA";
202 return !strcmp(verb,
"POST") || !strncmp(path,
"/.well-known/", 13) ||
203 !strncmp(path,
"/.oauth2/", 9);
207 if (req.
verb !=
"GET")
209 return req.
SendSimpleResp(405,
nullptr,
nullptr,
"Only GET is valid for oauth config.", 0);
212 if (header == req.
headers.end())
214 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Host header is required.", 0);
217 json_object *response_obj = json_object_new_object();
220 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
222 std::string token_endpoint =
"https://" + header->second +
"/.oauth2/token";
223 json_object *endpoint_obj =
224 json_object_new_string_len(token_endpoint.c_str(), token_endpoint.size());
227 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
229 json_object_object_add(response_obj,
"token_endpoint", endpoint_obj);
231 const char *response_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
232 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, response_result, 0);
233 json_object_put(response_obj);
239 if (req.
verb !=
"POST")
241 "Only POST method is allowed to request a macaroon",
false);
244 if (header == req.
headers.end() || header->second !=
"application/x-www-form-urlencoded")
245 return req.
SendSimpleResp(415,
nullptr,
"accept: application/x-www-form-urlencoded",
246 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
249 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
252 char *request_data_raw =
nullptr;
255 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
257 std::string request_data(request_data_raw, req.
length);
258 bool found_grant_type =
false;
259 ssize_t validity = -1;
262 std::istringstream token_stream(request_data);
265 std::string::size_type eq = token.find(
"=");
266 if (eq == std::string::npos)
268 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for form-encoding", 0);
270 std::string key = token.substr(0, eq);
271 std::string value = token.substr(eq + 1);
273 if (key ==
"grant_type")
275 found_grant_type =
true;
276 if (value !=
"client_credentials")
278 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid grant type specified.", 0);
281 else if (key ==
"expire_in")
283 if ((validity = std::strtoll(value.c_str(),
nullptr, 10)) <= 0)
284 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Expiration request has invalid value.", 0);
286 else if (key ==
"scope")
288 char *value_raw =
unquote(value.c_str());
289 if (value_raw ==
nullptr)
291 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Unable to unquote scope.", 0);
297 if (!found_grant_type)
299 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Grant type not specified.", 0);
303 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Scope was not specified.", 0);
305 std::istringstream token_stream_scope(scope);
307 std::vector<std::string> other_caveats;
310 std::string::size_type col = token.find(
":");
311 if (col == std::string::npos)
313 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for requested scope", 0);
315 std::string key = token.substr(0, col);
316 std::string value = token.substr(col + 1);
322 else if (value != path)
325 std::stringstream ss;
326 ss <<
"Encountered requested scope request for authorization " << key
327 <<
" with resource path " << value <<
"; however, prior request had path "
329 m_log->
Emsg(
"MacaroonRequest", ss.str().c_str());
331 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Server only supports all scopes having the same path", 0);
333 other_caveats.push_back(key);
339 std::vector<std::string> other_caveats_final;
340 if (!other_caveats.empty()) {
341 std::stringstream ss;
343 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
344 iter != other_caveats.end();
349 const std::string &final_str = ss.str();
350 other_caveats_final.push_back(final_str.substr(0, final_str.size() - 1));
352 return GenerateMacaroonResponse(req, path, other_caveats_final, validity,
true);
358 if (req.
resource ==
"/.well-known/oauth-authorization-server") {
359 return ProcessOAuthConfig(req);
360 }
else if (req.
resource ==
"/.oauth2/token") {
361 return ProcessTokenRequest(req);
365 if (header == req.
headers.end() || header->second !=
"application/macaroon-request")
366 return req.
SendSimpleResp(415,
nullptr,
"accept: application/macaroon-request",
367 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
370 if (header == req.
headers.end())
371 return req.
SendSimpleResp(411,
nullptr,
nullptr,
"Content-Length missing; not a valid POST",
false);
373 ssize_t blen = std::strtoll(header->second.c_str(),
nullptr, 10);
376 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Content-Length has invalid value.",
false);
379 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
384 if (req.
BuffgetData(blen, &request_data,
true) != blen)
386 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
388 json_tokener *tokener = json_tokener_new();
391 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error when allocating token parser.", 0);
393 json_object *macaroon_req = json_tokener_parse_ex(tokener, request_data, blen);
394 enum json_tokener_error err = json_tokener_get_error(tokener);
395 json_tokener_free(tokener);
396 if (err != json_tokener_success)
398 if (macaroon_req) json_object_put(macaroon_req);
399 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid JSON serialization of macaroon request.", 0);
401 json_object *validity_obj;
402 if (!json_object_object_get_ex(macaroon_req,
"validity", &validity_obj))
404 json_object_put(macaroon_req);
405 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"JSON request does not include a `validity`", 0);
407 const char *validity_cstr = json_object_get_string(validity_obj);
410 json_object_put(macaroon_req);
411 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"validity key cannot be cast to a string", 0);
413 std::string validity_str(validity_cstr);
417 json_object_put(macaroon_req);
418 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid ISO 8601 duration for validity key", 0);
420 json_object *caveats_obj;
421 std::vector<std::string> other_caveats;
422 if (json_object_object_get_ex(macaroon_req,
"caveats", &caveats_obj))
424 if (json_object_is_type(caveats_obj, json_type_array))
427 int array_length = json_object_array_length(caveats_obj);
428 other_caveats.reserve(array_length);
429 for (
int idx=0; idx<array_length; idx++)
431 json_object *caveat_item = json_object_array_get_idx(caveats_obj, idx);
434 const char *caveat_item_str = json_object_get_string(caveat_item);
436 if (!caveat_item_str) {
437 json_object_put(macaroon_req);
438 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Malformed or invalid caveat", 0);
442 json_object_put(macaroon_req);
444 "Cannot accept caveat with reserved key (name, path, before)\n", 0);
448 json_object_put(macaroon_req);
450 "Cannot accept caveat of unsupported type (supported types: activity)\n", 0);
453 other_caveats.emplace_back(caveat_item_str);
458 json_object_put(macaroon_req);
460 return GenerateMacaroonResponse(req, req.
resource, other_caveats, validity,
false);
465 Handler::GenerateMacaroonResponse(
XrdHttpExtReq &req,
const std::string &resource,
466 const std::vector<std::string> &other_caveats, ssize_t validity,
bool oauth_response)
470 if (m_max_duration > 0)
472 validity = (validity > m_max_duration) ? m_max_duration : validity;
476 char utc_time_buf[21];
477 if (!strftime(utc_time_buf, 21,
"%FT%TZ", gmtime(&now)))
479 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing UTC time", 0);
481 std::string utc_time_str(utc_time_buf);
482 std::stringstream ss;
483 ss <<
"before:" << utc_time_str;
484 std::string utc_time_caveat = ss.str();
486 std::string activities = GenerateActivities(req, resource);
489 for (
const auto &caveat : other_caveats) {
490 if (caveat.compare(0, 9,
"activity:") == 0)
494 std::string macaroon_id = GenerateID(resource, req.
GetSecEntity(), activities, other_caveats, utc_time_str);
495 enum macaroon_returncode mac_err;
497 struct macaroon *mac = macaroon_create(
reinterpret_cast<const unsigned char*
>(m_location.c_str()),
499 reinterpret_cast<const unsigned char*
>(m_secret.c_str()),
501 reinterpret_cast<const unsigned char*
>(macaroon_id.c_str()),
502 macaroon_id.size(), &mac_err);
504 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing the macaroon", 0);
508 struct macaroon *mac_with_name;
511 std::stringstream name_caveat_ss;
512 name_caveat_ss <<
"name:" << sec_name;
513 std::string name_caveat = name_caveat_ss.str();
514 mac_with_name = macaroon_add_first_party_caveat(mac,
515 reinterpret_cast<const unsigned char*
>(name_caveat.c_str()),
518 macaroon_destroy(mac);
524 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'name' caveat to macaroon", 0);
527 struct macaroon *mac_with_activities = macaroon_add_first_party_caveat(mac_with_name,
528 reinterpret_cast<const unsigned char*
>(activities.c_str()),
531 macaroon_destroy(mac_with_name);
532 if (!mac_with_activities)
534 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'activity' caveat to macaroon", 0);
541 std::string path_caveat =
"path:" + resource;
542 struct macaroon *mac_with_path = macaroon_add_first_party_caveat(mac_with_activities,
543 reinterpret_cast<const unsigned char*
>(path_caveat.c_str()),
546 macaroon_destroy(mac_with_activities);
547 if (!mac_with_path) {
548 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'path' caveat to macaroon", 0);
551 struct macaroon *mac_with_date = macaroon_add_first_party_caveat(mac_with_path,
552 reinterpret_cast<const unsigned char*
>(utc_time_caveat.c_str()),
553 utc_time_caveat.size(),
555 macaroon_destroy(mac_with_path);
556 if (!mac_with_date) {
557 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding date to macaroon", 0);
560 size_t size_hint = macaroon_serialize_size_hint(mac_with_date);
562 std::vector<char> macaroon_resp; macaroon_resp.resize(size_hint);
563 if (macaroon_serialize(mac_with_date, &macaroon_resp[0], size_hint, &mac_err))
565 printf(
"Returned macaroon_serialize code: %zu\n", size_hint);
566 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error serializing macaroon", 0);
568 macaroon_destroy(mac_with_date);
570 json_object *response_obj = json_object_new_object();
573 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
575 json_object *macaroon_obj = json_object_new_string_len(&macaroon_resp[0], strlen(&macaroon_resp[0]));
578 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
580 json_object_object_add(response_obj, oauth_response ?
"access_token" :
"macaroon", macaroon_obj);
582 json_object *expire_in_obj = json_object_new_int64(validity);
585 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON validity object.", 0);
587 json_object_object_add(response_obj,
"expires_in", expire_in_obj);
589 const char *macaroon_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
590 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, macaroon_result, 0);
591 json_object_put(response_obj);
@ AOP_Any
Special for getting privs.
static bool is_supported_caveat(const std::string &cv)
static bool is_reserved_caveat(const std::string &cv)
char * unquote(const char *str)
static ssize_t determine_validity(const std::string &input)
void getline(uchar *buff, int blen)
virtual bool MatchesPath(const char *verb, const char *path) override
Tells if the incoming path is recognized as one of the paths that have to be processed.
virtual int ProcessReq(XrdHttpExtReq &req) override
virtual XrdAccPrivs Access(const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *Env=0)=0
std::map< std::string, std::string > & headers
int BuffgetData(int blen, char **data, bool wait)
Get a pointer to data read from the client, valid for up to blen bytes from the buffer....
const XrdSecEntity & GetSecEntity() const
int SendSimpleResp(int code, const char *desc, const char *header_to_add, const char *body, long long bodylen)
Sends a basic response. If the length is < 0 then it is calculated internally.
static std::map< std::string, T >::const_iterator caseInsensitiveFind(const std::map< std::string, T > &m, const std::string &lowerCaseSearchKey)
char * vorg
Entity's virtual organization(s)
char prot[XrdSecPROTOIDSIZE]
Auth protocol used (e.g. krb5)
char * grps
Entity's group name(s)
char * name
Entity's name.
char * role
Entity's role(s)
char * endorsements
Protocol specific endorsements.
char * host
Entity's host name dnr dependent.
int Emsg(const char *esfx, int ecode, const char *text1, const char *text2=0)
std::string NormalizeSlashes(const std::string &)