23 char *r = (
char *) malloc(l + 1);
27 for (i = 0; i < l; i++) {
35 savec[0] = str[i + 1];
36 savec[1] = str[i + 2];
39 r[j] = strtol(savec, 0, 16);
42 }
else if (str[i] ==
'+') r[j] =
' ';
56 return cv.compare(0, 5,
"name:") == 0 ||
57 cv.compare(0, 5,
"path:") == 0 ||
58 cv.compare(0, 7,
"before:") == 0;
63 return cv.compare(0, 9,
"activity:") == 0;
73Handler::GenerateID(
const std::string &resource,
75 const std::string &activities,
76 const std::vector<std::string> &other_caveats,
77 const std::string &before)
80 uuid_generate_random(uu);
82 uuid_unparse(uu, uuid_buf);
83 std::string result(uuid_buf);
92 ss <<
"ID=" << result <<
", ";
94 if (entity.
prot[0] !=
'\0') {ss <<
"protocol=" << entity.
prot <<
", ";}
95 if (entity.
name) {ss <<
"name=" << entity.
name <<
", ";}
96 if (entity.
host) {ss <<
"host=" << entity.
host <<
", ";}
97 if (entity.
vorg) {ss <<
"vorg=" << entity.
vorg <<
", ";}
98 if (entity.
role) {ss <<
"role=" << entity.
role <<
", ";}
99 if (entity.
grps) {ss <<
"groups=" << entity.
grps <<
", ";}
101 if (activities.size()) {ss <<
"base_activities=" << activities <<
", ";}
103 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
104 iter != other_caveats.end();
107 ss <<
"user_caveat=" << *iter <<
", ";
110 ss <<
"expires=" << before;
112 m_log->Emsg(
"MacaroonGen", ss.str().c_str());
118Handler::GenerateActivities(
const XrdHttpExtReq & req,
const std::string &resource)
const
120 std::string result =
"activity:READ_METADATA";
137 return !strcmp(verb,
"POST") || !strncmp(path,
"/.well-known/", 13) ||
138 !strncmp(path,
"/.oauth2/", 9);
142 if (req.
verb !=
"GET")
144 return req.
SendSimpleResp(405,
nullptr,
nullptr,
"Only GET is valid for oauth config.", 0);
147 if (header == req.
headers.end())
149 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Host header is required.", 0);
152 json_object *response_obj = json_object_new_object();
155 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
157 std::string token_endpoint =
"https://" + header->second +
"/.oauth2/token";
158 json_object *endpoint_obj =
159 json_object_new_string_len(token_endpoint.c_str(), token_endpoint.size());
162 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
164 json_object_object_add(response_obj,
"token_endpoint", endpoint_obj);
166 const char *response_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
167 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, response_result, 0);
168 json_object_put(response_obj);
172int Handler::ProcessTokenRequest(XrdHttpExtReq &req)
174 if (req.
verb !=
"POST")
176 "Only POST method is allowed to request a macaroon",
false);
179 if (header == req.
headers.end() || header->second !=
"application/x-www-form-urlencoded")
180 return req.
SendSimpleResp(415,
nullptr,
"accept: application/x-www-form-urlencoded",
181 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
184 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
187 char *request_data_raw =
nullptr;
190 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
192 std::string request_data(request_data_raw, req.
length);
193 bool found_grant_type =
false;
194 ssize_t validity = -1;
197 std::istringstream token_stream(request_data);
198 while (std::getline(token_stream, token,
'&'))
200 std::string::size_type eq = token.find(
"=");
201 if (eq == std::string::npos)
203 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for form-encoding", 0);
205 std::string key = token.substr(0, eq);
206 std::string value = token.substr(eq + 1);
208 if (key ==
"grant_type")
210 found_grant_type =
true;
211 if (value !=
"client_credentials")
213 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid grant type specified.", 0);
216 else if (key ==
"expire_in")
218 if ((validity = std::strtoll(value.c_str(),
nullptr, 10)) <= 0)
219 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Expiration request has invalid value.", 0);
221 else if (key ==
"scope")
223 char *value_raw =
unquote(value.c_str());
224 if (value_raw ==
nullptr)
226 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Unable to unquote scope.", 0);
232 if (!found_grant_type)
234 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Grant type not specified.", 0);
238 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Scope was not specified.", 0);
240 std::istringstream token_stream_scope(scope);
242 std::vector<std::string> other_caveats;
243 while (std::getline(token_stream_scope, token,
' '))
245 std::string::size_type col = token.find(
":");
246 if (col == std::string::npos)
248 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid format for requested scope", 0);
250 std::string key = token.substr(0, col);
251 std::string value = token.substr(col + 1);
257 else if (value != path)
260 std::stringstream ss;
261 ss <<
"Encountered requested scope request for authorization " << key
262 <<
" with resource path " << value <<
"; however, prior request had path "
264 m_log->Emsg(
"MacaroonRequest", ss.str().c_str());
266 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Server only supports all scopes having the same path", 0);
268 other_caveats.push_back(key);
274 std::vector<std::string> other_caveats_final;
275 if (!other_caveats.empty()) {
276 std::stringstream ss;
278 for (std::vector<std::string>::const_iterator iter = other_caveats.begin();
279 iter != other_caveats.end();
284 const std::string &final_str = ss.str();
285 other_caveats_final.push_back(final_str.substr(0, final_str.size() - 1));
287 return GenerateMacaroonResponse(req, path, other_caveats_final, validity,
true);
293 if (req.
resource ==
"/.well-known/oauth-authorization-server") {
294 return ProcessOAuthConfig(req);
295 }
else if (req.
resource ==
"/.oauth2/token") {
296 return ProcessTokenRequest(req);
300 if (header == req.
headers.end() || header->second !=
"application/macaroon-request")
301 return req.
SendSimpleResp(415,
nullptr,
"accept: application/macaroon-request",
302 "Content-Type must be 'application/macaroon-request' to request a macaroon",
false);
305 if (header == req.
headers.end())
306 return req.
SendSimpleResp(411,
nullptr,
nullptr,
"Content-Length missing; not a valid POST",
false);
308 ssize_t blen = std::strtoll(header->second.c_str(),
nullptr, 10);
311 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Content-Length has invalid value.",
false);
314 return req.
SendSimpleResp(413,
nullptr,
nullptr,
"Macaroon request too large (must be less than 4KB)",
false);
319 if (req.
BuffgetData(blen, &request_data,
true) != blen)
321 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Missing or invalid body of request.", 0);
323 json_tokener *tokener = json_tokener_new();
326 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error when allocating token parser.", 0);
328 json_object *macaroon_req = json_tokener_parse_ex(tokener, request_data, blen);
329 enum json_tokener_error err = json_tokener_get_error(tokener);
330 json_tokener_free(tokener);
331 if (err != json_tokener_success)
333 if (macaroon_req) json_object_put(macaroon_req);
334 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid JSON serialization of macaroon request.", 0);
336 json_object *validity_obj;
337 if (!json_object_object_get_ex(macaroon_req,
"validity", &validity_obj))
339 json_object_put(macaroon_req);
340 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"JSON request does not include a `validity`", 0);
342 const char *validity_cstr = json_object_get_string(validity_obj);
345 json_object_put(macaroon_req);
346 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"validity key cannot be cast to a string", 0);
348 std::string validity_str(validity_cstr);
352 json_object_put(macaroon_req);
353 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Invalid ISO 8601 duration for validity key", 0);
355 json_object *caveats_obj;
356 std::vector<std::string> other_caveats;
357 if (json_object_object_get_ex(macaroon_req,
"caveats", &caveats_obj))
359 if (json_object_is_type(caveats_obj, json_type_array))
362 int array_length = json_object_array_length(caveats_obj);
363 other_caveats.reserve(array_length);
364 for (
int idx=0; idx<array_length; idx++)
366 json_object *caveat_item = json_object_array_get_idx(caveats_obj, idx);
369 const char *caveat_item_str = json_object_get_string(caveat_item);
371 if (!caveat_item_str) {
372 json_object_put(macaroon_req);
373 return req.
SendSimpleResp(400,
nullptr,
nullptr,
"Malformed or invalid caveat", 0);
377 json_object_put(macaroon_req);
379 "Cannot accept caveat with reserved key (name, path, before)\n", 0);
383 json_object_put(macaroon_req);
385 "Cannot accept caveat of unsupported type (supported types: activity)\n", 0);
388 other_caveats.emplace_back(caveat_item_str);
393 json_object_put(macaroon_req);
395 return GenerateMacaroonResponse(req, req.
resource, other_caveats, validity,
false);
400Handler::GenerateMacaroonResponse(
XrdHttpExtReq &req,
const std::string &resource,
401 const std::vector<std::string> &other_caveats, ssize_t validity,
bool oauth_response)
405 if (m_max_duration > 0)
407 validity = (validity > m_max_duration) ? m_max_duration : validity;
411 char utc_time_buf[21];
412 if (!strftime(utc_time_buf, 21,
"%FT%TZ", gmtime(&now)))
414 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing UTC time", 0);
416 std::string utc_time_str(utc_time_buf);
417 std::stringstream ss;
418 ss <<
"before:" << utc_time_str;
419 std::string utc_time_caveat = ss.str();
421 std::string activities = GenerateActivities(req, resource);
425 for (
const auto &caveat : other_caveats) {
426 if (caveat.compare(0, 9,
"activity:") == 0) {
427 std::set<std::string> allowed;
428 { std::stringstream ss(activities.substr(9));
429 for (std::string a; std::getline(ss, a,
','); )
431 std::string result =
"activity:";
433 std::stringstream ss(caveat.substr(9));
434 for (std::string a; std::getline(ss, a,
','); ) {
435 if (allowed.count(a)) {
436 if (!first) result +=
',';
441 if (result.size() > 9)
446 std::string macaroon_id = GenerateID(resource, req.
GetSecEntity(), activities, other_caveats, utc_time_str);
447 enum macaroon_returncode mac_err;
449 struct macaroon *mac = macaroon_create(
reinterpret_cast<const unsigned char*
>(m_location.c_str()),
451 reinterpret_cast<const unsigned char*
>(m_secret.c_str()),
453 reinterpret_cast<const unsigned char*
>(macaroon_id.c_str()),
454 macaroon_id.size(), &mac_err);
456 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error constructing the macaroon", 0);
460 struct macaroon *mac_with_name;
463 std::stringstream name_caveat_ss;
464 name_caveat_ss <<
"name:" << sec_name;
465 std::string name_caveat = name_caveat_ss.str();
466 mac_with_name = macaroon_add_first_party_caveat(mac,
467 reinterpret_cast<const unsigned char*
>(name_caveat.c_str()),
470 macaroon_destroy(mac);
476 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'name' caveat to macaroon", 0);
479 struct macaroon *mac_with_activities = macaroon_add_first_party_caveat(mac_with_name,
480 reinterpret_cast<const unsigned char*
>(activities.c_str()),
483 macaroon_destroy(mac_with_name);
484 if (!mac_with_activities)
486 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'activity' caveat to macaroon", 0);
493 std::string path_caveat =
"path:" + resource;
494 struct macaroon *mac_with_path = macaroon_add_first_party_caveat(mac_with_activities,
495 reinterpret_cast<const unsigned char*
>(path_caveat.c_str()),
498 macaroon_destroy(mac_with_activities);
499 if (!mac_with_path) {
500 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding 'path' caveat to macaroon", 0);
503 struct macaroon *mac_with_date = macaroon_add_first_party_caveat(mac_with_path,
504 reinterpret_cast<const unsigned char*
>(utc_time_caveat.c_str()),
505 utc_time_caveat.size(),
507 macaroon_destroy(mac_with_path);
508 if (!mac_with_date) {
509 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error adding date to macaroon", 0);
512 size_t size_hint = macaroon_serialize_size_hint(mac_with_date);
514 std::vector<char> macaroon_resp; macaroon_resp.resize(size_hint);
515 if (macaroon_serialize(mac_with_date, &macaroon_resp[0], size_hint, &mac_err))
517 printf(
"Returned macaroon_serialize code: %zu\n", size_hint);
518 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Internal error serializing macaroon", 0);
520 macaroon_destroy(mac_with_date);
522 json_object *response_obj = json_object_new_object();
525 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create new JSON response object.", 0);
527 json_object *macaroon_obj = json_object_new_string_len(&macaroon_resp[0], strlen(&macaroon_resp[0]));
530 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON macaroon string.", 0);
532 json_object_object_add(response_obj, oauth_response ?
"access_token" :
"macaroon", macaroon_obj);
534 json_object *expire_in_obj = json_object_new_int64(validity);
537 return req.
SendSimpleResp(500,
nullptr,
nullptr,
"Unable to create a new JSON validity object.", 0);
539 json_object_object_add(response_obj,
"expires_in", expire_in_obj);
541 const char *macaroon_result = json_object_to_json_string_ext(response_obj, JSON_C_TO_STRING_PRETTY);
542 int retval = req.
SendSimpleResp(200,
nullptr,
nullptr, macaroon_result, 0);
543 json_object_put(response_obj);
@ AOP_Any
Special for getting privs.
char * unquote(char *str)
char * unquote(const 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)
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)
std::string NormalizeSlashes(const std::string &input)