10 #include "XrdVersion.hh"
21 #include <unordered_map>
26 #include "INIReader.h"
29 #include "scitokens/scitokens.h"
58 bool has_entry =
false;
65 ss << (has_entry ?
", " :
"") <<
"info";
69 ss << (has_entry ?
", " :
"") <<
"warning";
73 ss << (has_entry ?
", " :
"") <<
"error";
79 typedef std::vector<std::pair<Access_Operation, std::string>> AccessRulesRaw;
81 inline uint64_t monotonic_time() {
83 #ifdef CLOCK_MONOTONIC_COARSE
84 clock_gettime(CLOCK_MONOTONIC_COARSE, &tp);
86 clock_gettime(CLOCK_MONOTONIC, &tp);
88 return tp.tv_sec + (tp.tv_nsec >= 500000000);
93 int new_privs = privs;
160 std::string AccessRuleStr(
const AccessRulesRaw &rules) {
161 std::unordered_map<std::string, std::unique_ptr<std::stringstream>> rule_map;
162 for (
const auto &rule : rules) {
163 auto iter = rule_map.find(rule.second);
164 if (iter == rule_map.end()) {
165 auto result = rule_map.insert(std::make_pair(rule.second, std::make_unique<std::stringstream>()));
167 *(iter->second) << OpToName(rule.first);
169 *(iter->second) <<
"," << OpToName(rule.first);
172 std::stringstream ss;
174 for (
const auto &val : rule_map) {
175 ss << (first ?
"" :
";") << val.first <<
":" << val.second->str();
185 bool IsSafeUsername(
const std::string &name) {
186 if (name.empty() || name[0] ==
'-')
return false;
187 for (
unsigned char c : name) {
188 if (!isalnum(c) && c !=
'_' && c !=
'.' && c !=
'@' && c !=
'-')
194 bool MakeCanonical(
const std::string &path, std::string &result)
196 if (path.empty() || path[0] !=
'/') {
return false;}
199 std::vector<std::string> components;
201 while (path.size() > pos && path[pos] ==
'/') {pos++;}
202 auto next_pos = path.find_first_of(
"/", pos);
203 auto next_component = path.substr(pos, next_pos - pos);
205 if (next_component.empty() || next_component ==
".") {
continue;}
206 else if (next_component ==
"..") {
207 if (!components.empty()) {
208 components.pop_back();
211 components.emplace_back(next_component);
213 }
while (pos != std::string::npos);
214 if (components.empty()) {
218 std::stringstream ss;
219 for (
const auto &comp : components) {
226 void ParseCanonicalPaths(
const std::string &path, std::vector<std::string> &results)
230 while (path.size() > pos && (path[pos] ==
',' || path[pos] ==
' ')) {pos++;}
231 auto next_pos = path.find_first_of(
", ", pos);
232 auto next_path = path.substr(pos, next_pos - pos);
234 if (!next_path.empty()) {
235 std::string canonical_path;
236 if (MakeCanonical(next_path, canonical_path)) {
237 results.emplace_back(std::move(canonical_path));
240 }
while (pos != std::string::npos);
245 MapRule(
const std::string &sub,
246 const std::string &username,
247 const std::string &path_prefix,
248 const std::string &group,
249 const std::string &result)
251 m_username(username),
252 m_path_prefix(path_prefix),
259 const std::string match(
const std::string &sub,
260 const std::string &username,
261 const std::string &req_path,
262 const std::vector<std::string> &groups)
const
264 if (!m_sub.empty() && sub != m_sub) {
return "";}
266 if (!m_username.empty() && username != m_username) {
return "";}
268 if (!m_path_prefix.empty() && !
is_subdirectory(m_path_prefix, req_path))
271 if (!m_group.empty()) {
272 for (
const auto &group : groups) {
273 if (group == m_group)
282 std::string m_username;
283 std::string m_path_prefix;
285 std::string m_result;
290 IssuerConfig(
const std::string &issuer_name,
291 const std::string &issuer_url,
292 const std::vector<std::string> &base_paths,
293 const std::vector<std::string> &restricted_paths,
295 uint32_t authz_strategy,
296 const std::string &default_user,
297 const std::string &username_claim,
298 const std::string &groups_claim,
299 const std::vector<MapRule> rules)
300 : m_map_subject(map_subject || !username_claim.empty()),
301 m_authz_strategy(authz_strategy),
304 m_default_user(default_user),
305 m_username_claim(username_claim),
306 m_groups_claim(groups_claim),
307 m_base_paths(base_paths),
308 m_restricted_paths(restricted_paths),
312 const bool m_map_subject;
313 const uint32_t m_authz_strategy;
314 const std::string m_name;
315 const std::string m_url;
316 const std::string m_default_user;
317 const std::string m_username_claim;
318 const std::string m_groups_claim;
319 const std::vector<std::string> m_base_paths;
320 const std::vector<std::string> m_restricted_paths;
321 const std::vector<MapRule> m_map_rules;
330 _error = ini_parse(filename.c_str(),
ValueHandler,
this);
349 inline static int ValueHandler(
void* user,
const char* section,
const char* name,
352 std::string key = MakeKey(section, name);
355 reader->_values[key] = value;
356 reader->_sections.insert(section);
365 XrdAccRules(uint64_t expiry_time,
const std::string &username,
const std::string &token_subject,
366 const std::string &issuer,
const std::vector<MapRule> &rules,
const std::vector<std::string> &
groups,
367 uint32_t authz_strategy) :
368 m_authz_strategy(authz_strategy),
369 m_expiry_time(expiry_time),
370 m_username(username),
371 m_token_subject(token_subject),
380 for (
const auto & rule : m_rules) {
382 if (rule.first != oper)
386 if (rule.second ==
"/")
402 bool expired()
const {
return monotonic_time() > m_expiry_time;}
404 void parse(
const AccessRulesRaw &rules) {
405 m_rules.reserve(rules.size());
406 for (
const auto &entry : rules) {
407 m_rules.emplace_back(entry.first, entry.second);
413 for (
const auto &rule : m_map_rules) {
414 std::string name = rule.match(m_token_subject, m_username, req_path, m_groups);
422 const std::string
str()
const
424 std::stringstream ss;
425 ss <<
"mapped_username=" << m_username <<
", subject=" << m_token_subject
426 <<
", issuer=" << m_issuer;
427 if (!m_groups.empty()) {
430 for (
const auto &group : m_groups) {
431 ss << (first ?
"" :
",") << group;
435 if (!m_rules.empty()) {
436 ss <<
", authorizations=" << AccessRuleStr(m_rules);
451 size_t size()
const {
return m_rules.size();}
452 const std::vector<std::string> &
groups()
const {
return m_groups;}
455 uint32_t m_authz_strategy;
456 AccessRulesRaw m_rules;
457 uint64_t m_expiry_time{0};
458 const std::string m_username;
459 const std::string m_token_subject;
460 const std::string m_issuer;
461 const std::vector<MapRule> m_map_rules;
462 const std::vector<std::string> m_groups;
474 enum class AuthzBehavior {
483 m_parms(parms ? parms :
""),
484 m_next_clean(monotonic_time() + m_expiry_secs),
485 m_log(lp,
"scitokens_")
487 pthread_rwlock_init(&m_config_lock,
nullptr);
488 m_config_lock_initialized =
true;
489 m_log.
Say(
"++++++ XrdAccSciTokens: Initialized SciTokens-based authorization.");
491 throw std::runtime_error(
"Failed to configure SciTokens authorization.");
496 if (m_config_lock_initialized) {
497 pthread_rwlock_destroy(&m_config_lock);
506 const char *authz = env ? env->
Get(
"authz") :
nullptr;
511 if (authz && !strncmp(authz,
"Bearer%20", 9)) {
516 if (!authz && Entity && !strcmp(
"ztn", Entity->
prot) && Entity->
creds &&
519 authz = Entity->
creds;
521 if (authz ==
nullptr) {
522 return OnMissing(Entity, path, oper, env);
525 std::shared_ptr<XrdAccRules> access_rules;
526 uint64_t now = monotonic_time();
529 std::lock_guard<std::mutex> guard(m_mutex);
530 const auto iter = m_map.find(authz);
531 if (iter != m_map.end() && !iter->second->expired()) {
532 access_rules = iter->second;
536 m_log.
Log(
LogMask::Debug,
"Access",
"Token not found in recent cache; parsing.");
538 uint64_t cache_expiry;
539 AccessRulesRaw rules;
540 std::string username;
541 std::string token_subject;
543 std::vector<MapRule> map_rules;
544 std::vector<std::string> groups;
545 uint32_t authz_strategy;
546 if (GenerateAcls(authz, cache_expiry, rules, username, token_subject, issuer, map_rules, groups, authz_strategy)) {
547 access_rules.reset(
new XrdAccRules(now + cache_expiry, username, token_subject, issuer, map_rules, groups, authz_strategy));
548 access_rules->parse(rules);
551 return OnMissing(Entity, path, oper, env);
554 m_log.
Log(
LogMask::Debug,
"Access",
"New valid token", access_rules->str().c_str());
556 }
catch (std::exception &exc) {
557 m_log.
Log(
LogMask::Warning,
"Access",
"Error generating ACLs for authorization", exc.what());
558 return OnMissing(Entity, path, oper, env);
560 std::lock_guard<std::mutex> guard(m_mutex);
561 m_map[authz] = access_rules;
563 m_log.
Log(
LogMask::Debug,
"Access",
"Cached token", access_rules->str().c_str());
578 new_secentity.
vorg =
nullptr;
579 new_secentity.
grps =
nullptr;
580 new_secentity.
role =
nullptr;
583 const auto &issuer = access_rules->get_issuer();
584 if (!issuer.empty()) {
585 new_secentity.
vorg = strdup(issuer.c_str());
587 bool group_success =
false;
588 if ((access_rules->get_authz_strategy() & IssuerAuthz::Group) && access_rules->groups().size()) {
589 std::stringstream ss;
590 for (
const auto &grp : access_rules->groups()) {
593 const auto &groups_str = ss.str();
594 new_secentity.
grps =
static_cast<char*
>(malloc(groups_str.size() + 1));
595 if (new_secentity.
grps) {
596 memcpy(new_secentity.
grps, groups_str.c_str(), groups_str.size());
597 new_secentity.
grps[groups_str.size()] =
'\0';
598 group_success =
true;
602 std::string username;
603 bool mapping_success =
false;
604 bool scope_success =
false;
605 username = access_rules->get_username(path);
607 mapping_success = (access_rules->get_authz_strategy() & IssuerAuthz::Mapping) && !username.empty();
608 scope_success = (access_rules->get_authz_strategy() & IssuerAuthz::Capability) && access_rules->apply(oper, path);
610 std::stringstream ss;
611 ss <<
"Grant authorization based on scopes for operation=" << OpToName(oper) <<
", path=" << path;
615 if (!scope_success && !mapping_success && !group_success) {
616 auto returned_accs = OnMissing(&new_secentity, path, oper, env);
618 if (new_secentity.
vorg !=
nullptr) free(new_secentity.
vorg);
619 if (new_secentity.
grps !=
nullptr) free(new_secentity.
grps);
620 if (new_secentity.
role !=
nullptr) free(new_secentity.
role);
622 return returned_accs;
626 if (scope_success && username.empty()) {
627 username = access_rules->get_default_username();
632 if (scope_success || mapping_success) {
634 Entity->
eaAPI->
Add(
"request.name", username,
true);
635 new_secentity.
eaAPI->
Add(
"request.name", username,
true);
644 const auto &token_subject = access_rules->get_token_subject();
645 if (!token_subject.empty()) {
646 Entity->
eaAPI->
Add(
"token.subject", token_subject,
true);
655 if (Entity->
secMon && scope_success && returned_op &&
Mon_isIO(oper))
656 Mon_Report(new_secentity, token_subject, username);
659 if (new_secentity.
vorg !=
nullptr) free(new_secentity.
vorg);
660 if (new_secentity.
grps !=
nullptr) free(new_secentity.
grps);
661 if (new_secentity.
role !=
nullptr) free(new_secentity.
role);
677 pthread_rwlock_rdlock(&m_config_lock);
679 for (
const auto &it: m_issuers) {
680 issuers.push_back({it.first, it.second.m_url});
683 pthread_rwlock_unlock(&m_config_lock);
686 pthread_rwlock_unlock(&m_config_lock);
691 virtual bool Validate(
const char *token, std::string &
emsg,
long long *expT,
699 if (!strncmp(token,
"Bearer%20", 9)) token += 9;
700 pthread_rwlock_rdlock(&m_config_lock);
701 auto retval = scitoken_deserialize(token, &scitoken, &m_valid_issuers_array[0], &err_msg);
702 pthread_rwlock_unlock(&m_config_lock);
716 {
char *value =
nullptr;
717 if (!scitoken_get_claim_string(scitoken,
"sub", &value, &err_msg)) {
718 Entity->
name = strdup(value);
727 if (expT && scitoken_get_expiration(scitoken, expT, &err_msg)) {
730 scitoken_destroy(scitoken);
736 scitoken_destroy(scitoken);
754 return (m_chain ? m_chain->
Test(priv, oper) : 0);
765 switch (m_authz_behavior) {
766 case AuthzBehavior::PASSTHROUGH:
768 case AuthzBehavior::ALLOW:
770 case AuthzBehavior::DENY:
777 bool GenerateAcls(
const std::string &authz, uint64_t &cache_expiry, AccessRulesRaw &rules, std::string &username, std::string &token_subject, std::string &issuer, std::vector<MapRule> &map_rules, std::vector<std::string> &groups, uint32_t &authz_strategy) {
780 bool looks_good =
true;
781 int separator_count = 0;
782 for (
auto cur_char = authz.c_str(); *cur_char; cur_char++) {
783 if (*cur_char ==
'.') {
785 if (separator_count > 2) {
789 if (!(*cur_char >= 65 && *cur_char <= 90) &&
790 !(*cur_char >= 97 && *cur_char <= 122) &&
791 !(*cur_char >= 48 && *cur_char <= 57) &&
792 (*cur_char != 43) && (*cur_char != 47) &&
793 (*cur_char != 45) && (*cur_char != 95))
799 if ((separator_count != 2) || (!looks_good)) {
800 m_log.
Log(
LogMask::Debug,
"Parse",
"Token does not appear to be a valid JWT; skipping.");
805 SciToken token =
nullptr;
806 pthread_rwlock_rdlock(&m_config_lock);
807 auto retval = scitoken_deserialize(authz.c_str(), &token, &m_valid_issuers_array[0], &err_msg);
808 pthread_rwlock_unlock(&m_config_lock);
817 if (scitoken_get_expiration(token, &expiry, &err_msg)) {
818 m_log.
Log(
LogMask::Warning,
"GenerateAcls",
"Unable to determine token expiration:", err_msg);
820 scitoken_destroy(token);
824 const auto now_wall =
static_cast<long long>(std::time(
nullptr));
825 const auto remaining = expiry - now_wall;
826 if (remaining <= 0) {
828 scitoken_destroy(token);
831 expiry = std::min(
static_cast<int64_t
>(remaining),
832 static_cast<int64_t
>(m_expiry_secs));
834 expiry = m_expiry_secs;
837 char *value =
nullptr;
838 if (scitoken_get_claim_string(token,
"iss", &value, &err_msg)) {
840 scitoken_destroy(token);
844 std::string token_issuer(value);
847 pthread_rwlock_rdlock(&m_config_lock);
848 auto enf = enforcer_create(token_issuer.c_str(), &m_audiences_array[0], &err_msg);
849 pthread_rwlock_unlock(&m_config_lock);
852 scitoken_destroy(token);
858 if (enforcer_generate_acls(enf, token, &acls, &err_msg)) {
859 scitoken_destroy(token);
860 enforcer_destroy(enf);
861 m_log.
Log(
LogMask::Warning,
"GenerateAcls",
"ACL generation from SciToken failed:", err_msg);
865 enforcer_destroy(enf);
869 ~AclGuard() {
if (ptr) enforcer_acl_free(ptr); }
872 pthread_rwlock_rdlock(&m_config_lock);
873 auto iter = m_issuers.find(token_issuer);
874 if (iter == m_issuers.end()) {
875 pthread_rwlock_unlock(&m_config_lock);
877 scitoken_destroy(token);
880 const auto config = iter->second;
881 pthread_rwlock_unlock(&m_config_lock);
885 std::vector<std::string> groups_parsed;
886 if (scitoken_get_claim_string_list(token, config.m_groups_claim.c_str(), &group_list, &err_msg) == 0) {
887 for (
int idx=0; group_list[idx]; idx++) {
888 groups_parsed.emplace_back(group_list[idx]);
890 scitoken_free_string_list(group_list);
897 if (scitoken_get_claim_string(token,
"sub", &value, &err_msg)) {
900 scitoken_destroy(token);
903 token_subject = std::string(value);
906 auto tmp_username = token_subject;
907 if (!config.m_username_claim.empty()) {
908 if (scitoken_get_claim_string(token, config.m_username_claim.c_str(), &value, &err_msg)) {
911 scitoken_destroy(token);
914 tmp_username = std::string(value);
916 if (!IsSafeUsername(tmp_username)) {
917 m_log.
Log(
LogMask::Warning,
"GenerateAcls",
"Token username claim contains unsafe characters; rejecting:", tmp_username.c_str());
918 scitoken_destroy(token);
921 }
else if (!config.m_map_subject) {
922 tmp_username = config.m_default_user;
925 for (
auto rule : config.m_map_rules) {
926 for (
auto path : config.m_base_paths) {
927 auto path_rule = rule;
928 path_rule.m_path_prefix = path + rule.m_path_prefix;
929 auto pos = path_rule.m_path_prefix.find(
"//");
930 if (pos != std::string::npos) {
931 path_rule.m_path_prefix.erase(pos + 1, 1);
933 map_rules.emplace_back(path_rule);
937 AccessRulesRaw xrd_rules;
939 std::set<std::string> paths_write_seen;
940 std::set<std::string> paths_create_or_modify_seen;
941 std::vector<std::string> acl_paths;
942 acl_paths.reserve(config.m_restricted_paths.size() + 1);
943 while (acls[idx].resource && acls[idx++].authz) {
945 const auto &acl_path = acls[idx-1].resource;
946 const auto &acl_authz = acls[idx-1].authz;
947 if (config.m_restricted_paths.empty()) {
948 acl_paths.push_back(acl_path);
950 auto acl_path_size = strlen(acl_path);
951 for (
const auto &restricted_path : config.m_restricted_paths) {
954 if (!strncmp(acl_path, restricted_path.c_str(), restricted_path.size())) {
957 if (acl_path_size > restricted_path.size() && acl_path[restricted_path.size()] !=
'/') {
960 acl_paths.push_back(acl_path);
966 if (!strncmp(acl_path, restricted_path.c_str(), acl_path_size)) {
973 if ((restricted_path.size() > acl_path_size && restricted_path[acl_path_size] !=
'/') && (acl_path_size != 1)) {
976 acl_paths.push_back(restricted_path);
980 for (
const auto &acl_path : acl_paths) {
981 for (
const auto &base_path : config.m_base_paths) {
982 if (!acl_path[0] || acl_path[0] !=
'/') {
continue;}
984 MakeCanonical(base_path + acl_path, path);
985 if (!strcmp(acl_authz,
"read")) {
986 xrd_rules.emplace_back(
AOP_Read, path);
988 xrd_rules.emplace_back(
AOP_Stat, path);
989 }
else if (!strcmp(acl_authz,
"create")) {
990 paths_create_or_modify_seen.insert(path);
995 xrd_rules.emplace_back(
AOP_Stat, path);
996 }
else if (!strcmp(acl_authz,
"modify")) {
997 paths_create_or_modify_seen.insert(path);
1003 xrd_rules.emplace_back(
AOP_Chmod, path);
1004 xrd_rules.emplace_back(
AOP_Stat, path);
1006 }
else if (!strcmp(acl_authz,
"write")) {
1007 paths_write_seen.insert(path);
1012 for (
const auto &write_path : paths_write_seen) {
1013 if (paths_create_or_modify_seen.find(write_path) == paths_create_or_modify_seen.end()) {
1015 xrd_rules.emplace_back(
AOP_Create, write_path);
1016 xrd_rules.emplace_back(
AOP_Mkdir, write_path);
1017 xrd_rules.emplace_back(
AOP_Rename, write_path);
1018 xrd_rules.emplace_back(
AOP_Insert, write_path);
1019 xrd_rules.emplace_back(
AOP_Update, write_path);
1020 xrd_rules.emplace_back(
AOP_Stat, write_path);
1021 xrd_rules.emplace_back(
AOP_Chmod, write_path);
1022 xrd_rules.emplace_back(
AOP_Delete, write_path);
1025 authz_strategy = config.m_authz_strategy;
1027 cache_expiry = expiry;
1028 rules = std::move(xrd_rules);
1029 username = std::move(tmp_username);
1030 issuer = std::move(token_issuer);
1031 groups = std::move(groups_parsed);
1032 scitoken_destroy(token);
1042 char *config_filename =
nullptr;
1049 m_log.
Emsg(
"Config", -result,
"parsing config file", config_filename);
1054 std::string map_filename;
1055 while (scitokens_conf.GetLine()) {
1057 scitokens_conf.GetToken();
1058 if (!(val = scitokens_conf.GetToken())) {
1059 m_log.
Emsg(
"Config",
"scitokens.trace requires an argument. Usage: scitokens.trace [all|error|warning|info|debug|none]");
1068 else if (!strcmp(val,
"none")) {m_log.
setMsgMask(0);}
1069 else {m_log.
Emsg(
"Config",
"scitokens.trace encountered an unknown directive:", val);
return false;}
1070 }
while ((val = scitokens_conf.GetToken()));
1075 auto tlsCtx =
static_cast<XrdTlsContext*
>(xrdEnv ? xrdEnv->GetPtr(
"XrdTlsContext*") :
nullptr);
1078 if (params && !params->cafile.empty()) {
1079 #ifdef HAVE_SCITOKEN_CONFIG_SET_STR
1080 scitoken_config_set_str(
"tls.ca_file", params->cafile.c_str(),
nullptr);
1082 m_log.
Log(
LogMask::Warning,
"Config",
"tls.ca_file is set but the platform's libscitokens.so does not support setting config parameters");
1090 bool ParseMapfile(
const std::string &filename, std::vector<MapRule> &rules)
1092 std::stringstream ss;
1093 std::ifstream mapfile(filename);
1094 if (!mapfile.is_open())
1096 ss <<
"Error opening mapfile (" << filename <<
"): " << strerror(errno);
1100 picojson::value val;
1101 auto err = picojson::parse(val, mapfile);
1103 ss <<
"Unable to parse mapfile (" << filename <<
") as json: " << err;
1107 if (!val.is<picojson::array>()) {
1108 ss <<
"Top-level element of the mapfile " << filename <<
" must be a list";
1112 const auto& rule_list = val.get<picojson::array>();
1113 for (
const auto &rule : rule_list)
1115 if (!rule.is<picojson::object>()) {
1116 ss <<
"Mapfile " << filename <<
" must be a list of JSON objects; found non-object";
1123 std::string username;
1125 bool ignore =
false;
1126 for (
const auto &entry : rule.get<picojson::object>()) {
1127 if (!entry.second.is<std::string>()) {
1128 if (entry.first !=
"result" && entry.first !=
"group" && entry.first !=
"sub" && entry.first !=
"path") {
continue;}
1129 ss <<
"In mapfile " << filename <<
", rule entry for " << entry.first <<
" has non-string value";
1133 if (entry.first ==
"result") {
1134 result = entry.second.get<std::string>();
1136 else if (entry.first ==
"group") {
1137 group = entry.second.get<std::string>();
1139 else if (entry.first ==
"sub") {
1140 sub = entry.second.get<std::string>();
1141 }
else if (entry.first ==
"username") {
1142 username = entry.second.get<std::string>();
1143 }
else if (entry.first ==
"path") {
1144 std::string norm_path;
1145 if (!MakeCanonical(entry.second.get<std::string>(), norm_path)) {
1146 ss <<
"In mapfile " << filename <<
" encountered a path " << entry.second.get<std::string>()
1147 <<
" that cannot be normalized";
1152 }
else if (entry.first ==
"ignore") {
1157 if (ignore)
continue;
1160 ss <<
"In mapfile " << filename <<
" encountered a rule without a 'result' attribute";
1164 rules.emplace_back(sub, username, path, group, result);
1173 std::string new_cfg_file =
"/etc/xrootd/scitokens.cfg";
1174 if (!m_parms.empty()) {
1176 std::vector<std::string> arg_list;
1178 while ((m_parms.size() > pos) && (m_parms[pos] ==
' ')) {pos++;}
1179 auto next_pos = m_parms.find_first_of(
", ", pos);
1180 auto next_arg = m_parms.substr(pos, next_pos - pos);
1182 if (!next_arg.empty()) {
1183 arg_list.emplace_back(std::move(next_arg));
1185 }
while (pos != std::string::npos);
1187 for (
const auto &arg : arg_list) {
1188 if (strncmp(arg.c_str(),
"config=", 7)) {
1189 m_log.
Log(
LogMask::Error,
"Reconfig",
"Ignoring unknown configuration argument:", arg.c_str());
1192 new_cfg_file = std::string(arg.c_str() + 7);
1195 m_log.
Log(
LogMask::Info,
"Reconfig",
"Parsing configuration file:", new_cfg_file.c_str());
1198 if (reader.ParseError() < 0) {
1199 std::stringstream ss;
1200 ss <<
"Error opening config file (" << m_cfg_file <<
"): " << strerror(errno);
1203 }
else if (reader.ParseError()) {
1204 std::stringstream ss;
1205 ss <<
"Parse error on line " << reader.ParseError() <<
" of file " << m_cfg_file;
1209 std::vector<std::string> audiences;
1210 std::unordered_map<std::string, IssuerConfig> issuers;
1211 AuthzBehavior new_authz_behavior = m_authz_behavior;
1212 for (
const auto §ion : reader.Sections()) {
1213 std::string section_lower;
1214 std::transform(section.begin(), section.end(), std::back_inserter(section_lower),
1215 [](
unsigned char c){ return std::tolower(c); });
1217 if (section_lower.substr(0, 6) ==
"global") {
1218 auto audience = reader.Get(section,
"audience",
"");
1219 if (!audience.empty()) {
1222 while (audience.size() > pos && (audience[pos] ==
',' || audience[pos] ==
' ')) {pos++;}
1223 auto next_pos = audience.find_first_of(
", ", pos);
1224 auto next_aud = audience.substr(pos, next_pos - pos);
1226 if (!next_aud.empty()) {
1227 audiences.push_back(next_aud);
1229 }
while (pos != std::string::npos);
1231 audience = reader.Get(section,
"audience_json",
"");
1232 if (!audience.empty()) {
1233 picojson::value json_obj;
1234 auto err = picojson::parse(json_obj, audience);
1236 m_log.
Log(
LogMask::Error,
"Reconfig",
"Unable to parse audience_json:", err.c_str());
1239 if (!json_obj.is<picojson::value::array>()) {
1240 m_log.
Log(
LogMask::Error,
"Reconfig",
"audience_json must be a list of strings; not a list.");
1243 for (
const auto &val : json_obj.get<picojson::value::array>()) {
1244 if (!val.is<std::string>()) {
1245 m_log.
Log(
LogMask::Error,
"Reconfig",
"audience must be a list of strings; value is not a string.");
1248 audiences.push_back(val.get<std::string>());
1251 auto onmissing = reader.Get(section,
"onmissing",
"");
1252 if (onmissing ==
"passthrough") {
1253 new_authz_behavior = AuthzBehavior::PASSTHROUGH;
1254 }
else if (onmissing ==
"allow") {
1255 new_authz_behavior = AuthzBehavior::ALLOW;
1256 }
else if (onmissing ==
"deny") {
1257 new_authz_behavior = AuthzBehavior::DENY;
1258 }
else if (!onmissing.empty()) {
1259 m_log.
Log(
LogMask::Error,
"Reconfig",
"Unknown value for onmissing key:", onmissing.c_str());
1264 if (section_lower.substr(0, 7) !=
"issuer ") {
continue;}
1266 auto issuer = reader.Get(section,
"issuer",
"");
1267 if (issuer.empty()) {
1268 m_log.
Log(
LogMask::Error,
"Reconfig",
"Ignoring section because 'issuer' attribute is not set:",
1274 std::vector<MapRule> rules;
1275 auto name_mapfile = reader.Get(section,
"name_mapfile",
"");
1276 if (!name_mapfile.empty()) {
1277 if (!ParseMapfile(name_mapfile, rules)) {
1278 m_log.
Log(
LogMask::Error,
"Reconfig",
"Failed to parse mapfile; failing (re-)configuration", name_mapfile.c_str());
1281 m_log.
Log(
LogMask::Info,
"Reconfig",
"Successfully parsed SciTokens mapfile:", name_mapfile.c_str());
1285 auto base_path = reader.Get(section,
"base_path",
"");
1286 if (base_path.empty()) {
1287 m_log.
Log(
LogMask::Error,
"Reconfig",
"Ignoring section because 'base_path' attribute is not set:",
1293 while (section.size() > pos && std::isspace(section[pos])) {pos++;}
1295 auto name = section.substr(pos);
1297 m_log.
Log(
LogMask::Error,
"Reconfig",
"Invalid section name:", section.c_str());
1301 std::vector<std::string> base_paths;
1302 ParseCanonicalPaths(base_path, base_paths);
1304 auto restricted_path = reader.Get(section,
"restricted_path",
"");
1305 std::vector<std::string> restricted_paths;
1306 if (!restricted_path.empty()) {
1307 ParseCanonicalPaths(restricted_path, restricted_paths);
1310 auto default_user = reader.Get(section,
"default_user",
"");
1311 auto map_subject = reader.GetBoolean(section,
"map_subject",
false);
1312 auto username_claim = reader.Get(section,
"username_claim",
"");
1313 auto groups_claim = reader.Get(section,
"groups_claim",
"wlcg.groups");
1315 auto authz_strategy_str = reader.Get(section,
"authorization_strategy",
"");
1316 uint32_t authz_strategy = 0;
1317 if (authz_strategy_str.empty()) {
1318 authz_strategy = IssuerAuthz::Default;
1320 std::istringstream authz_strategy_stream(authz_strategy_str);
1321 std::string authz_str;
1322 while (
std::getline(authz_strategy_stream, authz_str,
' ')) {
1323 if (!strcasecmp(authz_str.c_str(),
"capability")) {
1324 authz_strategy |= IssuerAuthz::Capability;
1325 }
else if (!strcasecmp(authz_str.c_str(),
"group")) {
1326 authz_strategy |= IssuerAuthz::Group;
1327 }
else if (!strcasecmp(authz_str.c_str(),
"mapping")) {
1328 authz_strategy |= IssuerAuthz::Mapping;
1330 m_log.
Log(
LogMask::Error,
"Reconfig",
"Unknown authorization strategy (ignoring):", authz_str.c_str());
1335 issuers.emplace(std::piecewise_construct,
1336 std::forward_as_tuple(issuer),
1337 std::forward_as_tuple(name, issuer, base_paths, restricted_paths,
1338 map_subject, authz_strategy, default_user, username_claim, groups_claim, rules));
1341 if (issuers.empty()) {
1345 pthread_rwlock_wrlock(&m_config_lock);
1347 m_authz_behavior = new_authz_behavior;
1348 m_cfg_file = std::move(new_cfg_file);
1349 m_audiences = std::move(audiences);
1351 m_audiences_array.resize(m_audiences.size() + 1);
1352 for (
const auto &audience : m_audiences) {
1353 m_audiences_array[idx++] = audience.c_str();
1355 m_audiences_array[idx] =
nullptr;
1357 m_issuers = std::move(issuers);
1358 m_valid_issuers_array.resize(m_issuers.size() + 1);
1360 for (
const auto &issuer : m_issuers) {
1361 m_valid_issuers_array[idx++] = issuer.first.c_str();
1363 m_valid_issuers_array[idx] =
nullptr;
1365 pthread_rwlock_unlock(&m_config_lock);
1368 pthread_rwlock_unlock(&m_config_lock);
1372 void Check(uint64_t now)
1374 if (now <= m_next_clean) {
return;}
1375 std::lock_guard<std::mutex> guard(m_mutex);
1377 for (
auto iter = m_map.begin(); iter != m_map.end(); ) {
1378 if (iter->second->expired()) {
1379 iter = m_map.erase(iter);
1386 m_next_clean = monotonic_time() + m_expiry_secs;
1389 bool m_config_lock_initialized{
false};
1391 pthread_rwlock_t m_config_lock;
1392 std::vector<std::string> m_audiences;
1393 std::vector<const char *> m_audiences_array;
1394 std::map<std::string, std::shared_ptr<XrdAccRules>> m_map;
1396 const std::string m_parms;
1397 std::vector<const char*> m_valid_issuers_array;
1398 std::unordered_map<std::string, IssuerConfig> m_issuers;
1399 uint64_t m_next_clean{0};
1401 AuthzBehavior m_authz_behavior{AuthzBehavior::PASSTHROUGH};
1402 std::string m_cfg_file;
1404 static constexpr uint64_t m_expiry_secs = 60;
1413 }
catch (std::exception &) {
Access_Operation
The following are supported operations.
@ AOP_Delete
rm() or rmdir()
@ AOP_Update
open() r/w or append
@ AOP_Create
open() with create
@ AOP_Any
Special for getting privs.
@ AOP_Stat
exists(), stat()
@ AOP_Rename
mv() for source
@ AOP_Read
open() r/o, prepare()
@ AOP_Excl_Create
open() with O_EXCL|O_CREAT
@ AOP_Insert
mv() for target
@ AOP_Excl_Insert
mv() where destination doesn't exist.
static bool is_subdirectory(const std::string_view dir, const std::string_view subdir)
XrdAccSciTokens * accSciTokens
XrdSciTokensHelper * SciTokensHelper
XrdVERSIONINFO(XrdAccAuthorizeObject, XrdAccSciTokens)
void InitAccSciTokens(XrdSysLogger *lp, const char *cfn, const char *parm, XrdAccAuthorize *accP, XrdOucEnv *envP)
XrdAccAuthorize * XrdAccAuthorizeObjAdd(XrdSysLogger *lp, const char *cfn, const char *parm, XrdOucEnv *envP, XrdAccAuthorize *accP)
XrdAccAuthorize * XrdAccAuthorizeObject(XrdSysLogger *lp, const char *cfn, const char *parm)
XrdAccAuthorize * XrdAccAuthorizeObject2(XrdSysLogger *lp, const char *cfn, const char *parm, XrdOucEnv *envP)
void getline(uchar *buff, int blen)
int emsg(int rc, char *msg)
OverrideINIReader(FILE *file)
OverrideINIReader(std::string filename)
static int ValueHandler(void *user, const char *section, const char *name, const char *value)
virtual int Test(const XrdAccPrivs priv, const Access_Operation oper)=0
virtual XrdAccPrivs Access(const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *Env=0)=0
const std::vector< std::string > & groups() const
XrdAccRules(uint64_t expiry_time, const std::string &username, const std::string &token_subject, const std::string &issuer, const std::vector< MapRule > &rules, const std::vector< std::string > &groups, uint32_t authz_strategy)
const std::string & get_issuer() const
bool apply(Access_Operation oper, std::string path)
uint32_t get_authz_strategy() const
void parse(const AccessRulesRaw &rules)
const std::string & get_default_username() const
const std::string & get_token_subject() const
const std::string str() const
std::string get_username(const std::string &req_path) const
virtual int Audit(const int accok, const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *Env=0) override
virtual XrdAccPrivs Access(const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *env) override
XrdAccSciTokens(XrdSysLogger *lp, const char *parms, XrdAccAuthorize *chain, XrdOucEnv *envP)
virtual Issuers IssuerList() override
virtual bool Validate(const char *token, std::string &emsg, long long *expT, XrdSecEntity *Entity) override
virtual int Test(const XrdAccPrivs priv, const Access_Operation oper) override
std::string GetConfigFile()
virtual ~XrdAccSciTokens()
static bool Import(const char *var, char *&val)
void * GetPtr(const char *varname)
char * Get(const char *varname)
@ trim_lines
Prefix trimmed lines.
std::vector< ValidIssuer > Issuers
bool Mon_isIO(const Access_Operation oper)
void Mon_Report(const XrdSecEntity &Entity, const std::string &subject, const std::string &username)
bool Add(XrdSecAttr &attr)
char * vorg
Entity's virtual organization(s)
int credslen
Length of the 'creds' data.
XrdNetAddrInfo * addrInfo
Entity's connection details.
XrdSecEntityAttr * eaAPI
non-const API to attributes
char prot[XrdSecPROTOIDSIZE]
Auth protocol used (e.g. krb5)
char * creds
Raw entity credentials or cert.
XrdSecMonitor * secMon
If !0 security monitoring enabled.
char * grps
Entity's group name(s)
char * name
Entity's name.
char * role
Entity's role(s)
int Emsg(const char *esfx, int ecode, const char *text1, const char *text2=0)
void Say(const char *text1, const char *text2=0, const char *txt3=0, const char *text4=0, const char *text5=0, const char *txt6=0)
void setMsgMask(int mask)
void Log(int mask, const char *esfx, const char *text1, const char *text2=0, const char *text3=0)
const CTX_Params * GetParams()
std::string LogMaskToString(int mask)