25 char *r = (
char *) malloc(l + 1);
29 for (i = 0; i < l; i++) {
37 savec[0] = str[i + 1];
38 savec[1] = str[i + 2];
41 r[j] = strtol(savec, 0, 16);
44 }
else if (str[i] ==
'+') r[j] =
' ';
62 output.reserve(input.size());
63 char prior_chr =
'\0';
64 size_t output_idx = 0;
65 for (
size_t idx = 0; idx < input.size(); idx++) {
66 char chr = input[idx];
67 if (prior_chr ==
'/' && chr ==
'/') {
71 output += input[output_idx];
82 if (input.find(
"PT") != 0)
87 std::string remaining = input;
90 remaining = remaining.substr(pos);
91 if (remaining.size() == 0)
break;
95 cur_duration = stol(remaining, &pos);
100 if (pos >= remaining.size())
104 char unit = remaining[pos];
112 cur_duration *= 3600;
118 duration += cur_duration;
131 Handler::GenerateID(
const std::string &resource,
133 const std::string &activities,
134 const std::vector<std::string> &other_caveats,
135 const std::string &before)
138 uuid_generate_random(uu);
140 uuid_unparse(uu, uuid_buf);
141 std::string result(uuid_buf);
149 std::stringstream ss;
150 ss <<
"ID=" << result <<
", ";
152 if (entity.
prot[0] !=
'\0') {ss <<
"protocol=" << entity.
prot <<
", ";}
153 if (entity.
name) {ss <<
"name=" << entity.
name <<
", ";}
154 if (entity.
host) {ss <<
"host=" << entity.
host <<
", ";}
155 if (entity.
vorg) {ss <<
"vorg=" << entity.
vorg <<
", ";}
156 if (entity.
role) {ss <<
"role=" << entity.
role <<
", ";}
157 if (entity.
grps) {ss <<
"groups=" << entity.
grps <<
", ";}
159 if (activities.size()) {ss <<
"base_activities=" << activities <<
", ";}
161 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
162 iter != other_caveats.end();
165 ss <<
"user_caveat=" << *iter <<
", ";
168 ss <<
"expires=" << before;
170 m_log->
Emsg(
"MacaroonGen", ss.str().c_str());
177 Handler::GenerateActivities(
const XrdHttpExtReq & req,
const std::string &resource)
const
179 std::string result =
"activity:READ_METADATA";
197 return !strcmp(verb,
"POST") || !strncmp(path,
"/.well-known/", 13) ||
198 !strncmp(path,
"/.oauth2/", 9);
203 if (req.
verb !=
"GET")
205 return req.
SendSimpleResp(405, NULL, NULL,
"Only GET is valid for oauth config.", 0);
208 if (header == req.
headers.end())
210 return req.
SendSimpleResp(400, NULL, NULL,
"Host header is required.", 0);
213 json_object *response_obj = json_object_new_object();
216 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create new JSON response object.", 0);
218 std::string token_endpoint =
"https://" + header->second +
"/.oauth2/token";
219 json_object *endpoint_obj =
220 json_object_new_string_len(token_endpoint.c_str(), token_endpoint.size());
223 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON macaroon string.", 0);
225 json_object_object_add(response_obj,
"token_endpoint", endpoint_obj);
227 const char *response_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
228 int retval = req.
SendSimpleResp(200, NULL, NULL, response_result, 0);
229 json_object_put(response_obj);
236 if (req.
verb !=
"POST")
238 return req.
SendSimpleResp(405, NULL, NULL,
"Only POST is valid for token request.", 0);
241 if (header == req.
headers.end())
243 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type missing; not a valid macaroon request?", 0);
245 if (header->second !=
"application/x-www-form-urlencoded")
247 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type must be set to `application/macaroon-request' to request a macaroon", 0);
249 char *request_data_raw;
253 return req.
SendSimpleResp(400, NULL, NULL,
"Missing or invalid body of request.", 0);
255 std::string request_data(request_data_raw, req.
length);
256 bool found_grant_type =
false;
257 ssize_t validity = -1;
260 std::istringstream token_stream(request_data);
263 std::string::size_type eq = token.find(
"=");
264 if (eq == std::string::npos)
266 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid format for form-encoding", 0);
268 std::string key = token.substr(0, eq);
269 std::string value = token.substr(eq + 1);
271 if (key ==
"grant_type")
273 found_grant_type =
true;
274 if (value !=
"client_credentials")
276 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid grant type specified.", 0);
279 else if (key ==
"expire_in")
283 validity = std::stoll(value);
287 return req.
SendSimpleResp(400, NULL, NULL,
"Expiration request not parseable.", 0);
291 return req.
SendSimpleResp(400, NULL, NULL,
"Expiration request has invalid value.", 0);
294 else if (key ==
"scope")
296 char *value_raw =
unquote(value.c_str());
297 if (value_raw == NULL)
299 return req.
SendSimpleResp(400, NULL, NULL,
"Unable to unquote scope.", 0);
305 if (!found_grant_type)
307 return req.
SendSimpleResp(400, NULL, NULL,
"Grant type not specified.", 0);
311 return req.
SendSimpleResp(400, NULL, NULL,
"Scope was not specified.", 0);
313 std::istringstream token_stream_scope(scope);
315 std::vector<std::string> other_caveats;
318 std::string::size_type col = token.find(
":");
319 if (col == std::string::npos)
321 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid format for requested scope", 0);
323 std::string key = token.substr(0, col);
324 std::string value = token.substr(col + 1);
330 else if (value != path)
333 std::stringstream ss;
334 ss <<
"Encountered requested scope request for authorization " << key
335 <<
" with resource path " << value <<
"; however, prior request had path "
337 m_log->
Emsg(
"MacaroonRequest", ss.str().c_str());
339 return req.
SendSimpleResp(500, NULL, NULL,
"Server only supports all scopes having the same path", 0);
341 other_caveats.push_back(key);
347 std::vector<std::string> other_caveats_final;
348 if (!other_caveats.empty()) {
349 std::stringstream ss;
351 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
352 iter != other_caveats.end();
357 const std::string &final_str = ss.str();
358 other_caveats_final.push_back(final_str.substr(0, final_str.size() - 1));
360 return GenerateMacaroonResponse(req, path, other_caveats_final, validity,
true);
367 if (req.
resource ==
"/.well-known/oauth-authorization-server") {
368 return ProcessOAuthConfig(req);
369 }
else if (req.
resource ==
"/.oauth2/token") {
370 return ProcessTokenRequest(req);
374 if (header == req.
headers.end())
376 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type missing; not a valid macaroon request?", 0);
378 if (header->second !=
"application/macaroon-request")
380 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type must be set to `application/macaroon-request' to request a macaroon", 0);
383 if (header == req.
headers.end())
385 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length missing; not a valid POST", 0);
390 blen = std::stoll(header->second);
394 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length not parseable.", 0);
398 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length has invalid value.", 0);
405 if (req.
BuffgetData(blen, &request_data,
true) != blen)
407 return req.
SendSimpleResp(400, NULL, NULL,
"Missing or invalid body of request.", 0);
409 json_tokener *tokener = json_tokener_new();
412 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error when allocating token parser.", 0);
414 json_object *macaroon_req = json_tokener_parse_ex(tokener, request_data, blen);
415 enum json_tokener_error err = json_tokener_get_error(tokener);
416 json_tokener_free(tokener);
417 if (err != json_tokener_success)
419 if (macaroon_req) json_object_put(macaroon_req);
420 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid JSON serialization of macaroon request.", 0);
422 json_object *validity_obj;
423 if (!json_object_object_get_ex(macaroon_req,
"validity", &validity_obj))
425 json_object_put(macaroon_req);
426 return req.
SendSimpleResp(400, NULL, NULL,
"JSON request does not include a `validity`", 0);
428 const char *validity_cstr = json_object_get_string(validity_obj);
431 json_object_put(macaroon_req);
432 return req.
SendSimpleResp(400, NULL, NULL,
"validity key cannot be cast to a string", 0);
434 std::string validity_str(validity_cstr);
438 json_object_put(macaroon_req);
439 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid ISO 8601 duration for validity key", 0);
441 json_object *caveats_obj;
442 std::vector<std::string> other_caveats;
443 if (json_object_object_get_ex(macaroon_req,
"caveats", &caveats_obj))
445 if (json_object_is_type(caveats_obj, json_type_array))
448 int array_length = json_object_array_length(caveats_obj);
449 other_caveats.reserve(array_length);
450 for (
int idx=0; idx<array_length; idx++)
452 json_object *caveat_item = json_object_array_get_idx(caveats_obj, idx);
455 const char *caveat_item_str = json_object_get_string(caveat_item);
456 other_caveats.emplace_back(caveat_item_str);
461 json_object_put(macaroon_req);
463 return GenerateMacaroonResponse(req, req.
resource, other_caveats, validity,
false);
468 Handler::GenerateMacaroonResponse(
XrdHttpExtReq &req,
const std::string &resource,
469 const std::vector<std::string> &other_caveats, ssize_t validity,
bool oauth_response)
473 if (m_max_duration > 0)
475 validity = (validity > m_max_duration) ? m_max_duration : validity;
479 char utc_time_buf[21];
480 if (!strftime(utc_time_buf, 21,
"%FT%TZ", gmtime(&now)))
482 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error constructing UTC time", 0);
484 std::string utc_time_str(utc_time_buf);
485 std::stringstream ss;
486 ss <<
"before:" << utc_time_str;
487 std::string utc_time_caveat = ss.str();
489 std::string activities = GenerateActivities(req, resource);
490 std::string macaroon_id = GenerateID(resource, req.
GetSecEntity(), activities, other_caveats, utc_time_str);
491 enum macaroon_returncode mac_err;
493 struct macaroon *mac = macaroon_create(
reinterpret_cast<const unsigned char*
>(m_location.c_str()),
495 reinterpret_cast<const unsigned char*
>(m_secret.c_str()),
497 reinterpret_cast<const unsigned char*
>(macaroon_id.c_str()),
498 macaroon_id.size(), &mac_err);
500 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error constructing the macaroon", 0);
504 struct macaroon *mac_with_name;
507 std::stringstream name_caveat_ss;
508 name_caveat_ss <<
"name:" << sec_name;
509 std::string name_caveat = name_caveat_ss.str();
510 mac_with_name = macaroon_add_first_party_caveat(mac,
511 reinterpret_cast<const unsigned char*
>(name_caveat.c_str()),
514 macaroon_destroy(mac);
520 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding default activities to macaroon", 0);
523 struct macaroon *mac_with_activities = macaroon_add_first_party_caveat(mac_with_name,
524 reinterpret_cast<const unsigned char*
>(activities.c_str()),
527 macaroon_destroy(mac_with_name);
528 if (!mac_with_activities)
530 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding default activities to macaroon", 0);
534 for (
const auto &caveat : other_caveats)
536 struct macaroon *mac_tmp = mac_with_activities;
537 mac_with_activities = macaroon_add_first_party_caveat(mac_tmp,
538 reinterpret_cast<const unsigned char*
>(caveat.c_str()),
541 macaroon_destroy(mac_tmp);
542 if (!mac_with_activities)
544 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding user caveat to macaroon", 0);
552 std::string path_caveat =
"path:" + resource;
553 struct macaroon *mac_with_path = macaroon_add_first_party_caveat(mac_with_activities,
554 reinterpret_cast<const unsigned char*
>(path_caveat.c_str()),
557 macaroon_destroy(mac_with_activities);
558 if (!mac_with_path) {
559 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding path to macaroon", 0);
562 struct macaroon *mac_with_date = macaroon_add_first_party_caveat(mac_with_path,
563 reinterpret_cast<const unsigned char*
>(utc_time_caveat.c_str()),
564 utc_time_caveat.size(),
566 macaroon_destroy(mac_with_path);
567 if (!mac_with_date) {
568 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding date to macaroon", 0);
571 size_t size_hint = macaroon_serialize_size_hint(mac_with_date);
573 std::vector<char> macaroon_resp; macaroon_resp.resize(size_hint);
574 if (macaroon_serialize(mac_with_date, &macaroon_resp[0], size_hint, &mac_err))
576 printf(
"Returned macaroon_serialize code: %zu\n", size_hint);
577 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error serializing macaroon", 0);
579 macaroon_destroy(mac_with_date);
581 json_object *response_obj = json_object_new_object();
584 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create new JSON response object.", 0);
586 json_object *macaroon_obj = json_object_new_string_len(&macaroon_resp[0], strlen(&macaroon_resp[0]));
589 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON macaroon string.", 0);
591 json_object_object_add(response_obj, oauth_response ?
"access_token" :
"macaroon", macaroon_obj);
593 json_object *expire_in_obj = json_object_new_int64(validity);
596 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON validity object.", 0);
598 json_object_object_add(response_obj,
"expires_in", expire_in_obj);
600 const char *macaroon_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
601 int retval = req.
SendSimpleResp(200, NULL, NULL, macaroon_result, 0);
602 json_object_put(response_obj);
@ AOP_Any
Special for getting privs.
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 &)