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] =
' ';
58 return cv.compare(0, 5,
"name:") == 0 ||
59 cv.compare(0, 5,
"path:") == 0 ||
60 cv.compare(0, 7,
"before:") == 0;
65 return cv.compare(0, 9,
"activity:") == 0;
75Handler::GenerateID(
const std::string &resource,
77 const std::string &activities,
78 const std::vector<std::string> &other_caveats,
79 const std::string &before)
82 uuid_generate_random(uu);
84 uuid_unparse(uu, uuid_buf);
85 std::string result(uuid_buf);
94 ss <<
"ID=" << result <<
", ";
96 if (entity.
prot[0] !=
'\0') {ss <<
"protocol=" << entity.
prot <<
", ";}
97 if (entity.
name) {ss <<
"name=" << entity.
name <<
", ";}
98 if (entity.
host) {ss <<
"host=" << entity.
host <<
", ";}
99 if (entity.
vorg) {ss <<
"vorg=" << entity.
vorg <<
", ";}
100 if (entity.
role) {ss <<
"role=" << entity.
role <<
", ";}
101 if (entity.
grps) {ss <<
"groups=" << entity.
grps <<
", ";}
103 if (activities.size()) {ss <<
"base_activities=" << activities <<
", ";}
105 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
106 iter != other_caveats.end();
109 ss <<
"user_caveat=" << *iter <<
", ";
112 ss <<
"expires=" << before;
114 m_log->Emsg(
"MacaroonGen", ss.str().c_str());
120Handler::GenerateActivities(
const XrdHttpExtReq & req,
const std::string &resource)
const
122 std::string result =
"activity:READ_METADATA";
139 return !strcmp(verb,
"POST") || !strncmp(path,
"/.well-known/", 13) ||
140 !strncmp(path,
"/.oauth2/", 9);
144 if (req.
verb !=
"GET")
146 return req.
SendSimpleResp(405,
nullptr,
nullptr,
"Only GET is valid for oauth config.", 0);
149 if (header == req.
headers.end())
151 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Host header is required.", 0);
154 json_object *response_obj = json_object_new_object();
157 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
159 std::string token_endpoint =
"https://" + header->second +
"/.oauth2/token";
160 json_object *endpoint_obj =
161 json_object_new_string_len(token_endpoint.c_str(), token_endpoint.size());
164 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
166 json_object_object_add(response_obj,
"token_endpoint", endpoint_obj);
168 const char *response_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
169 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, response_result, 0);
170 json_object_put(response_obj);
174int Handler::ProcessTokenRequest(XrdHttpExtReq &req)
176 if (req.
verb !=
"POST")
178 "Only POST method is allowed to request a macaroon",
false);
181 if (header == req.
headers.end() || header->second !=
"application/x-www-form-urlencoded")
182 return req.
SendSimpleResp(415,
nullptr,
"accept: application/x-www-form-urlencoded",
183 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
186 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
189 char *request_data_raw =
nullptr;
192 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
194 std::string request_data(request_data_raw, req.
length);
195 bool found_grant_type =
false;
196 ssize_t validity = -1;
199 std::istringstream token_stream(request_data);
200 while (std::getline(token_stream, token,
'&'))
202 std::string::size_type eq = token.find(
"=");
203 if (eq == std::string::npos)
205 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for form-encoding", 0);
207 std::string key = token.substr(0, eq);
208 std::string value = token.substr(eq + 1);
210 if (key ==
"grant_type")
212 found_grant_type =
true;
213 if (value !=
"client_credentials")
215 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid grant type specified.", 0);
218 else if (key ==
"expire_in")
220 if ((validity = std::strtoll(value.c_str(),
nullptr, 10)) <= 0)
221 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Expiration request has invalid value.", 0);
223 else if (key ==
"scope")
225 char *value_raw =
unquote(value.c_str());
226 if (value_raw ==
nullptr)
228 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Unable to unquote scope.", 0);
234 if (!found_grant_type)
236 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Grant type not specified.", 0);
240 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Scope was not specified.", 0);
242 std::istringstream token_stream_scope(scope);
244 std::vector<std::string> other_caveats;
245 while (std::getline(token_stream_scope, token,
' '))
247 std::string::size_type col = token.find(
":");
248 if (col == std::string::npos)
250 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for requested scope", 0);
252 std::string key = token.substr(0, col);
253 std::string value = token.substr(col + 1);
259 else if (value != path)
262 std::stringstream ss;
263 ss <<
"Encountered requested scope request for authorization " << key
264 <<
" with resource path " << value <<
"; however, prior request had path "
266 m_log->Emsg(
"MacaroonRequest", ss.str().c_str());
268 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Server only supports all scopes having the same path", 0);
270 other_caveats.push_back(key);
276 std::vector<std::string> other_caveats_final;
277 if (!other_caveats.empty()) {
278 std::stringstream ss;
280 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
281 iter != other_caveats.end();
286 const std::string &final_str = ss.str();
287 other_caveats_final.push_back(final_str.substr(0, final_str.size() - 1));
289 return GenerateMacaroonResponse(req, path, other_caveats_final, validity,
true);
295 if (req.
resource ==
"/.well-known/oauth-authorization-server") {
296 return ProcessOAuthConfig(req);
297 }
else if (req.
resource ==
"/.oauth2/token") {
298 return ProcessTokenRequest(req);
302 if (header == req.
headers.end() || header->second !=
"application/macaroon-request")
303 return req.
SendSimpleResp(415,
nullptr,
"accept: application/macaroon-request",
304 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
307 if (header == req.
headers.end())
308 return req.
SendSimpleResp(411,
nullptr,
nullptr,
"Content-Length missing; not a valid POST",
false);
310 ssize_t blen = std::strtoll(header->second.c_str(),
nullptr, 10);
313 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Content-Length has invalid value.",
false);
316 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
321 if (req.
BuffgetData(blen, &request_data,
true) != blen)
323 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
325 json_tokener *tokener = json_tokener_new();
328 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error when allocating token parser.", 0);
330 json_object *macaroon_req = json_tokener_parse_ex(tokener, request_data, blen);
331 enum json_tokener_error err = json_tokener_get_error(tokener);
332 json_tokener_free(tokener);
333 if (err != json_tokener_success)
335 if (macaroon_req) json_object_put(macaroon_req);
336 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid JSON serialization of macaroon request.", 0);
338 json_object *validity_obj;
339 if (!json_object_object_get_ex(macaroon_req,
"validity", &validity_obj))
341 json_object_put(macaroon_req);
342 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"JSON request does not include a `validity`", 0);
344 const char *validity_cstr = json_object_get_string(validity_obj);
347 json_object_put(macaroon_req);
348 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"validity key cannot be cast to a string", 0);
350 std::string validity_str(validity_cstr);
354 json_object_put(macaroon_req);
355 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid ISO 8601 duration for validity key", 0);
357 json_object *caveats_obj;
358 std::vector<std::string> other_caveats;
359 if (json_object_object_get_ex(macaroon_req,
"caveats", &caveats_obj))
361 if (json_object_is_type(caveats_obj, json_type_array))
364 int array_length = json_object_array_length(caveats_obj);
365 other_caveats.reserve(array_length);
366 for (
int idx=0; idx<array_length; idx++)
368 json_object *caveat_item = json_object_array_get_idx(caveats_obj, idx);
371 const char *caveat_item_str = json_object_get_string(caveat_item);
373 if (!caveat_item_str) {
374 json_object_put(macaroon_req);
375 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Malformed or invalid caveat", 0);
379 json_object_put(macaroon_req);
381 "Cannot accept caveat with reserved key (name, path, before)\n", 0);
385 json_object_put(macaroon_req);
387 "Cannot accept caveat of unsupported type (supported types: activity)\n", 0);
390 other_caveats.emplace_back(caveat_item_str);
395 json_object_put(macaroon_req);
397 return GenerateMacaroonResponse(req, req.
resource, other_caveats, validity,
false);
402Handler::GenerateMacaroonResponse(
XrdHttpExtReq &req,
const std::string &resource,
403 const std::vector<std::string> &other_caveats, ssize_t validity,
bool oauth_response)
407 if (m_max_duration > 0)
409 validity = (validity > m_max_duration) ? m_max_duration : validity;
413 char utc_time_buf[21];
414 if (!strftime(utc_time_buf, 21,
"%FT%TZ", gmtime(&now)))
416 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing UTC time", 0);
418 std::string utc_time_str(utc_time_buf);
419 std::stringstream ss;
420 ss <<
"before:" << utc_time_str;
421 std::string utc_time_caveat = ss.str();
423 std::string activities = GenerateActivities(req, resource);
427 for (
const auto &caveat : other_caveats) {
428 if (caveat.compare(0, 9,
"activity:") == 0) {
429 std::set<std::string> allowed;
430 { std::stringstream ss(activities.substr(9));
431 for (std::string a; std::getline(ss, a,
','); )
433 std::string result =
"activity:";
435 std::stringstream ss(caveat.substr(9));
436 for (std::string a; std::getline(ss, a,
','); ) {
437 if (allowed.count(a)) {
438 if (!first) result +=
',';
443 if (result.size() > 9)
448 std::string macaroon_id = GenerateID(resource, req.
GetSecEntity(), activities, other_caveats, utc_time_str);
449 enum macaroon_returncode mac_err;
451 struct macaroon *mac = macaroon_create(
reinterpret_cast<const unsigned char*
>(m_location.c_str()),
453 reinterpret_cast<const unsigned char*
>(m_secret.c_str()),
455 reinterpret_cast<const unsigned char*
>(macaroon_id.c_str()),
456 macaroon_id.size(), &mac_err);
458 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing the macaroon", 0);
462 struct macaroon *mac_with_name;
465 std::stringstream name_caveat_ss;
466 name_caveat_ss <<
"name:" << sec_name;
467 std::string name_caveat = name_caveat_ss.str();
468 mac_with_name = macaroon_add_first_party_caveat(mac,
469 reinterpret_cast<const unsigned char*
>(name_caveat.c_str()),
472 macaroon_destroy(mac);
478 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'name' caveat to macaroon", 0);
481 struct macaroon *mac_with_activities = macaroon_add_first_party_caveat(mac_with_name,
482 reinterpret_cast<const unsigned char*
>(activities.c_str()),
485 macaroon_destroy(mac_with_name);
486 if (!mac_with_activities)
488 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'activity' caveat to macaroon", 0);
495 std::string path_caveat =
"path:" + resource;
496 struct macaroon *mac_with_path = macaroon_add_first_party_caveat(mac_with_activities,
497 reinterpret_cast<const unsigned char*
>(path_caveat.c_str()),
500 macaroon_destroy(mac_with_activities);
501 if (!mac_with_path) {
502 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'path' caveat to macaroon", 0);
505 struct macaroon *mac_with_date = macaroon_add_first_party_caveat(mac_with_path,
506 reinterpret_cast<const unsigned char*
>(utc_time_caveat.c_str()),
507 utc_time_caveat.size(),
509 macaroon_destroy(mac_with_path);
510 if (!mac_with_date) {
511 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding date to macaroon", 0);
514 size_t size_hint = macaroon_serialize_size_hint(mac_with_date);
516 std::vector<char> macaroon_resp; macaroon_resp.resize(size_hint);
517 if (macaroon_serialize(mac_with_date, &macaroon_resp[0], size_hint, &mac_err))
519 printf(
"Returned macaroon_serialize code: %zu\n", size_hint);
520 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error serializing macaroon", 0);
522 macaroon_destroy(mac_with_date);
524 json_object *response_obj = json_object_new_object();
527 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
529 json_object *macaroon_obj = json_object_new_string_len(&macaroon_resp[0], strlen(&macaroon_resp[0]));
532 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
534 json_object_object_add(response_obj, oauth_response ?
"access_token" :
"macaroon", macaroon_obj);
536 json_object *expire_in_obj = json_object_new_int64(validity);
539 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON validity object.", 0);
541 json_object_object_add(response_obj,
"expires_in", expire_in_obj);
543 const char *macaroon_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
544 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, macaroon_result, 0);
545 json_object_put(response_obj);
@ AOP_Any
Special for getting privs.
char * unquote(char *str)
static bool is_supported_caveat(const std::string &cv)
static bool is_reserved_caveat(const std::string &cv)
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
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)
static std::string NormalizePath(const std::string &path)
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.
ssize_t determine_validity(const std::string &input)