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];
80 return cv.compare(0, 5,
"name:") == 0 ||
81 cv.compare(0, 5,
"path:") == 0 ||
82 cv.compare(0, 9,
"activity:") == 0 ||
83 cv.compare(0, 7,
"before:") == 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;
139 Handler::GenerateID(
const std::string &resource,
141 const std::string &activities,
142 const std::vector<std::string> &other_caveats,
143 const std::string &before)
146 uuid_generate_random(uu);
148 uuid_unparse(uu, uuid_buf);
149 std::string result(uuid_buf);
157 std::stringstream ss;
158 ss <<
"ID=" << result <<
", ";
160 if (entity.
prot[0] !=
'\0') {ss <<
"protocol=" << entity.
prot <<
", ";}
161 if (entity.
name) {ss <<
"name=" << entity.
name <<
", ";}
162 if (entity.
host) {ss <<
"host=" << entity.
host <<
", ";}
163 if (entity.
vorg) {ss <<
"vorg=" << entity.
vorg <<
", ";}
164 if (entity.
role) {ss <<
"role=" << entity.
role <<
", ";}
165 if (entity.
grps) {ss <<
"groups=" << entity.
grps <<
", ";}
167 if (activities.size()) {ss <<
"base_activities=" << activities <<
", ";}
169 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
170 iter != other_caveats.end();
173 ss <<
"user_caveat=" << *iter <<
", ";
176 ss <<
"expires=" << before;
178 m_log->
Emsg(
"MacaroonGen", ss.str().c_str());
185 Handler::GenerateActivities(
const XrdHttpExtReq & req,
const std::string &resource)
const
187 std::string result =
"activity:READ_METADATA";
205 return !strcmp(verb,
"POST") || !strncmp(path,
"/.well-known/", 13) ||
206 !strncmp(path,
"/.oauth2/", 9);
211 if (req.
verb !=
"GET")
213 return req.
SendSimpleResp(405, NULL, NULL,
"Only GET is valid for oauth config.", 0);
216 if (header == req.
headers.end())
218 return req.
SendSimpleResp(400, NULL, NULL,
"Host header is required.", 0);
221 json_object *response_obj = json_object_new_object();
224 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create new JSON response object.", 0);
226 std::string token_endpoint =
"https://" + header->second +
"/.oauth2/token";
227 json_object *endpoint_obj =
228 json_object_new_string_len(token_endpoint.c_str(), token_endpoint.size());
231 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON macaroon string.", 0);
233 json_object_object_add(response_obj,
"token_endpoint", endpoint_obj);
235 const char *response_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
236 int retval = req.
SendSimpleResp(200, NULL, NULL, response_result, 0);
237 json_object_put(response_obj);
244 if (req.
verb !=
"POST")
246 return req.
SendSimpleResp(405, NULL, NULL,
"Only POST is valid for token request.", 0);
249 if (header == req.
headers.end())
251 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type missing; not a valid macaroon request?", 0);
253 if (header->second !=
"application/x-www-form-urlencoded")
255 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type must be set to `application/macaroon-request' to request a macaroon", 0);
257 char *request_data_raw;
261 return req.
SendSimpleResp(400, NULL, NULL,
"Missing or invalid body of request.", 0);
263 std::string request_data(request_data_raw, req.
length);
264 bool found_grant_type =
false;
265 ssize_t validity = -1;
268 std::istringstream token_stream(request_data);
271 std::string::size_type eq = token.find(
"=");
272 if (eq == std::string::npos)
274 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid format for form-encoding", 0);
276 std::string key = token.substr(0, eq);
277 std::string value = token.substr(eq + 1);
279 if (key ==
"grant_type")
281 found_grant_type =
true;
282 if (value !=
"client_credentials")
284 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid grant type specified.", 0);
287 else if (key ==
"expire_in")
291 validity = std::stoll(value);
295 return req.
SendSimpleResp(400, NULL, NULL,
"Expiration request not parseable.", 0);
299 return req.
SendSimpleResp(400, NULL, NULL,
"Expiration request has invalid value.", 0);
302 else if (key ==
"scope")
304 char *value_raw =
unquote(value.c_str());
305 if (value_raw == NULL)
307 return req.
SendSimpleResp(400, NULL, NULL,
"Unable to unquote scope.", 0);
313 if (!found_grant_type)
315 return req.
SendSimpleResp(400, NULL, NULL,
"Grant type not specified.", 0);
319 return req.
SendSimpleResp(400, NULL, NULL,
"Scope was not specified.", 0);
321 std::istringstream token_stream_scope(scope);
323 std::vector<std::string> other_caveats;
326 std::string::size_type col = token.find(
":");
327 if (col == std::string::npos)
329 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid format for requested scope", 0);
331 std::string key = token.substr(0, col);
332 std::string value = token.substr(col + 1);
338 else if (value != path)
341 std::stringstream ss;
342 ss <<
"Encountered requested scope request for authorization " << key
343 <<
" with resource path " << value <<
"; however, prior request had path "
345 m_log->
Emsg(
"MacaroonRequest", ss.str().c_str());
347 return req.
SendSimpleResp(500, NULL, NULL,
"Server only supports all scopes having the same path", 0);
349 other_caveats.push_back(key);
355 std::vector<std::string> other_caveats_final;
356 if (!other_caveats.empty()) {
357 std::stringstream ss;
359 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
360 iter != other_caveats.end();
365 const std::string &final_str = ss.str();
366 other_caveats_final.push_back(final_str.substr(0, final_str.size() - 1));
368 return GenerateMacaroonResponse(req, path, other_caveats_final, validity,
true);
375 if (req.
resource ==
"/.well-known/oauth-authorization-server") {
376 return ProcessOAuthConfig(req);
377 }
else if (req.
resource ==
"/.oauth2/token") {
378 return ProcessTokenRequest(req);
382 if (header == req.
headers.end())
384 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type missing; not a valid macaroon request?", 0);
386 if (header->second !=
"application/macaroon-request")
388 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Type must be set to `application/macaroon-request' to request a macaroon", 0);
391 if (header == req.
headers.end())
393 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length missing; not a valid POST", 0);
398 blen = std::stoll(header->second);
402 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length not parseable.", 0);
406 return req.
SendSimpleResp(400, NULL, NULL,
"Content-Length has invalid value.", 0);
413 if (req.
BuffgetData(blen, &request_data,
true) != blen)
415 return req.
SendSimpleResp(400, NULL, NULL,
"Missing or invalid body of request.", 0);
417 json_tokener *tokener = json_tokener_new();
420 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error when allocating token parser.", 0);
422 json_object *macaroon_req = json_tokener_parse_ex(tokener, request_data, blen);
423 enum json_tokener_error err = json_tokener_get_error(tokener);
424 json_tokener_free(tokener);
425 if (err != json_tokener_success)
427 if (macaroon_req) json_object_put(macaroon_req);
428 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid JSON serialization of macaroon request.", 0);
430 json_object *validity_obj;
431 if (!json_object_object_get_ex(macaroon_req,
"validity", &validity_obj))
433 json_object_put(macaroon_req);
434 return req.
SendSimpleResp(400, NULL, NULL,
"JSON request does not include a `validity`", 0);
436 const char *validity_cstr = json_object_get_string(validity_obj);
439 json_object_put(macaroon_req);
440 return req.
SendSimpleResp(400, NULL, NULL,
"validity key cannot be cast to a string", 0);
442 std::string validity_str(validity_cstr);
446 json_object_put(macaroon_req);
447 return req.
SendSimpleResp(400, NULL, NULL,
"Invalid ISO 8601 duration for validity key", 0);
449 json_object *caveats_obj;
450 std::vector<std::string> other_caveats;
451 if (json_object_object_get_ex(macaroon_req,
"caveats", &caveats_obj))
453 if (json_object_is_type(caveats_obj, json_type_array))
456 int array_length = json_object_array_length(caveats_obj);
457 other_caveats.reserve(array_length);
458 for (
int idx=0; idx<array_length; idx++)
460 json_object *caveat_item = json_object_array_get_idx(caveats_obj, idx);
463 const char *caveat_item_str = json_object_get_string(caveat_item);
465 json_object_put(macaroon_req);
467 "Caveat uses a reserved predicate key (name:/path:/activity:/before:)", 0);
469 other_caveats.emplace_back(caveat_item_str);
474 json_object_put(macaroon_req);
476 return GenerateMacaroonResponse(req, req.
resource, other_caveats, validity,
false);
481 Handler::GenerateMacaroonResponse(
XrdHttpExtReq &req,
const std::string &resource,
482 const std::vector<std::string> &other_caveats, ssize_t validity,
bool oauth_response)
486 if (m_max_duration > 0)
488 validity = (validity > m_max_duration) ? m_max_duration : validity;
492 char utc_time_buf[21];
493 if (!strftime(utc_time_buf, 21,
"%FT%TZ", gmtime(&now)))
495 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error constructing UTC time", 0);
497 std::string utc_time_str(utc_time_buf);
498 std::stringstream ss;
499 ss <<
"before:" << utc_time_str;
500 std::string utc_time_caveat = ss.str();
502 std::string activities = GenerateActivities(req, resource);
503 std::string macaroon_id = GenerateID(resource, req.
GetSecEntity(), activities, other_caveats, utc_time_str);
504 enum macaroon_returncode mac_err;
506 struct macaroon *mac = macaroon_create(
reinterpret_cast<const unsigned char*
>(m_location.c_str()),
508 reinterpret_cast<const unsigned char*
>(m_secret.c_str()),
510 reinterpret_cast<const unsigned char*
>(macaroon_id.c_str()),
511 macaroon_id.size(), &mac_err);
513 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error constructing the macaroon", 0);
517 struct macaroon *mac_with_name;
520 std::stringstream name_caveat_ss;
521 name_caveat_ss <<
"name:" << sec_name;
522 std::string name_caveat = name_caveat_ss.str();
523 mac_with_name = macaroon_add_first_party_caveat(mac,
524 reinterpret_cast<const unsigned char*
>(name_caveat.c_str()),
527 macaroon_destroy(mac);
533 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding default activities to macaroon", 0);
536 struct macaroon *mac_with_activities = macaroon_add_first_party_caveat(mac_with_name,
537 reinterpret_cast<const unsigned char*
>(activities.c_str()),
540 macaroon_destroy(mac_with_name);
541 if (!mac_with_activities)
543 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding default activities to macaroon", 0);
547 for (
const auto &caveat : other_caveats)
549 struct macaroon *mac_tmp = mac_with_activities;
550 mac_with_activities = macaroon_add_first_party_caveat(mac_tmp,
551 reinterpret_cast<const unsigned char*
>(caveat.c_str()),
554 macaroon_destroy(mac_tmp);
555 if (!mac_with_activities)
557 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding user caveat to macaroon", 0);
565 std::string path_caveat =
"path:" + resource;
566 struct macaroon *mac_with_path = macaroon_add_first_party_caveat(mac_with_activities,
567 reinterpret_cast<const unsigned char*
>(path_caveat.c_str()),
570 macaroon_destroy(mac_with_activities);
571 if (!mac_with_path) {
572 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding path to macaroon", 0);
575 struct macaroon *mac_with_date = macaroon_add_first_party_caveat(mac_with_path,
576 reinterpret_cast<const unsigned char*
>(utc_time_caveat.c_str()),
577 utc_time_caveat.size(),
579 macaroon_destroy(mac_with_path);
580 if (!mac_with_date) {
581 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error adding date to macaroon", 0);
584 size_t size_hint = macaroon_serialize_size_hint(mac_with_date);
586 std::vector<char> macaroon_resp; macaroon_resp.resize(size_hint);
587 if (macaroon_serialize(mac_with_date, &macaroon_resp[0], size_hint, &mac_err))
589 printf(
"Returned macaroon_serialize code: %zu\n", size_hint);
590 return req.
SendSimpleResp(500, NULL, NULL,
"Internal error serializing macaroon", 0);
592 macaroon_destroy(mac_with_date);
594 json_object *response_obj = json_object_new_object();
597 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create new JSON response object.", 0);
599 json_object *macaroon_obj = json_object_new_string_len(&macaroon_resp[0], strlen(&macaroon_resp[0]));
602 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON macaroon string.", 0);
604 json_object_object_add(response_obj, oauth_response ?
"access_token" :
"macaroon", macaroon_obj);
606 json_object *expire_in_obj = json_object_new_int64(validity);
609 return req.
SendSimpleResp(500, NULL, NULL,
"Unable to create a new JSON validity object.", 0);
611 json_object_object_add(response_obj,
"expires_in", expire_in_obj);
613 const char *macaroon_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
614 int retval = req.
SendSimpleResp(200, NULL, NULL, macaroon_result, 0);
615 json_object_put(response_obj);
@ AOP_Any
Special for getting privs.
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 &)