XRootD
Loading...
Searching...
No Matches
XrdMacaroonsAuthz.cc
Go to the documentation of this file.
3
4#include "XrdOuc/XrdOucEnv.hh"
8
9#include <ctime>
10#include <sstream>
11#include <stdexcept>
12
13#include <macaroons.h>
14
15using namespace Macaroons;
16
17namespace {
18
19class AuthzCheck
20{
21public:
22 AuthzCheck(const char *req_path, const Access_Operation req_oper, ssize_t max_duration, XrdSysError &log);
23
24 const std::string &GetSecName() const {return m_sec_name;}
25 const std::string &GetErrorMessage() const {return m_emsg;}
26
27 static int verify_before_s(void *authz_ptr,
28 const unsigned char *pred,
29 size_t pred_sz);
30
31 static int verify_activity_s(void *authz_ptr,
32 const unsigned char *pred,
33 size_t pred_sz);
34
35 static int verify_path_s(void *authz_ptr,
36 const unsigned char *pred,
37 size_t pred_sz);
38
39 static int verify_name_s(void *authz_ptr,
40 const unsigned char *pred,
41 size_t pred_sz);
42
43private:
44 int verify_before(const unsigned char *pred, size_t pred_sz);
45 int verify_activity(const unsigned char *pred, size_t pred_sz);
46 int verify_path(const unsigned char *pred, size_t pred_sz);
47 int verify_name(const unsigned char *pred, size_t pred_sz);
48
49 ssize_t m_max_duration;
50 XrdSysError &m_log;
51 std::string m_emsg;
52 const std::string m_path;
53 std::string m_desired_activity;
54 std::string m_sec_name;
55 Access_Operation m_oper;
56 time_t m_now;
57};
58
59static XrdAccPrivs AddPriv(Access_Operation op, XrdAccPrivs privs)
60{
61 int new_privs = privs;
62 switch (op) {
63 case AOP_Any:
64 break;
65 case AOP_Chmod:
66 new_privs |= static_cast<int>(XrdAccPriv_Chmod);
67 break;
68 case AOP_Chown:
69 new_privs |= static_cast<int>(XrdAccPriv_Chown);
70 break;
71 case AOP_Excl_Create: // fallthrough
72 case AOP_Create:
73 new_privs |= static_cast<int>(XrdAccPriv_Create);
74 break;
75 case AOP_Delete:
76 new_privs |= static_cast<int>(XrdAccPriv_Delete);
77 break;
78 case AOP_Excl_Insert: // fallthrough
79 case AOP_Insert:
80 new_privs |= static_cast<int>(XrdAccPriv_Insert);
81 break;
82 case AOP_Lock:
83 new_privs |= static_cast<int>(XrdAccPriv_Lock);
84 break;
85 case AOP_Mkdir:
86 new_privs |= static_cast<int>(XrdAccPriv_Mkdir);
87 break;
88 case AOP_Read:
89 new_privs |= static_cast<int>(XrdAccPriv_Read);
90 break;
91 case AOP_Readdir:
92 new_privs |= static_cast<int>(XrdAccPriv_Readdir);
93 break;
94 case AOP_Rename:
95 new_privs |= static_cast<int>(XrdAccPriv_Rename);
96 break;
97 case AOP_Stat:
98 new_privs |= static_cast<int>(XrdAccPriv_Lookup);
99 break;
100 case AOP_Update:
101 new_privs |= static_cast<int>(XrdAccPriv_Update);
102 break;
103 case AOP_Stage:
104 new_privs |= static_cast<int>(XrdAccPriv_Stage);
105 break;
106 case AOP_Poll:
107 new_privs |= static_cast<int>(XrdAccPriv_Poll);
108 break;
109 };
110 return static_cast<XrdAccPrivs>(new_privs);
111}
112
113// Accept any value of the path, name, or activity caveats
114int validate_verify_empty(void *emsg_ptr,
115 const unsigned char *pred,
116 size_t pred_sz)
117{
118 if ((pred_sz >= 5) && (!memcmp(reinterpret_cast<const char *>(pred), "path:", 5) ||
119 !memcmp(reinterpret_cast<const char *>(pred), "name:", 5)))
120 {
121 return 0;
122 }
123 if ((pred_sz >= 9) && (!memcmp(reinterpret_cast<const char *>(pred), "activity:", 9)))
124 {
125 return 0;
126 }
127 return 1;
128}
129
130} // unnamed namespace
131
132Authz::Authz(XrdSysLogger *log, char const *config, XrdAccAuthorize *chain)
133 : m_max_duration(86400),
134 m_chain(chain),
135 m_log(log, "macarons_"),
136 m_authz_behavior(static_cast<int>(Handler::AuthzBehavior::PASSTHROUGH))
137{
139 XrdOucEnv env;
140 if (!Handler::Config(config, &env, &m_log, m_location, m_secret, m_max_duration, behavior))
141 {
142 throw std::runtime_error("Macaroon authorization config failed.");
143 }
144 m_authz_behavior = static_cast<int>(behavior);
145}
146
148Authz::OnMissing(const XrdSecEntity *Entity, const char *path,
149 const Access_Operation oper, XrdOucEnv *env)
150{
151 switch (m_authz_behavior) {
153 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
155 return AddPriv(oper, XrdAccPriv_None);;
157 return XrdAccPriv_None;
158 }
159 // Code should be unreachable.
160 return XrdAccPriv_None;
161}
162
164Authz::Access(const XrdSecEntity *Entity, const char *path,
165 const Access_Operation oper, XrdOucEnv *env)
166{
167 // We don't allow any testing to occur in this authz module, preventing
168 // a macaroon to be used to receive further macaroons.
169 if (oper == AOP_Any)
170 {
171 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
172 }
173
174 const char *authz = env ? env->Get("authz") : nullptr;
175 if (authz && !strncmp(authz, "Bearer%20", 9))
176 {
177 authz += 9;
178 }
179 else if (!authz && (authz = env ? env->Get("access_token") : nullptr) && !strncmp(authz, "Bearer%20", 9))
180 {
181 authz += 9;
182 }
183
184 // If there's no request-specific token, check for a ZTN session token
185 if (!authz && Entity && !strcmp("ztn", Entity->prot) && Entity->creds &&
186 Entity->credslen && Entity->creds[Entity->credslen] == '\0')
187 {
188 authz = Entity->creds;
189 }
190
191 if (!authz) {
192 return OnMissing(Entity, path, oper, env);
193 }
194
195 macaroon_returncode mac_err = MACAROON_SUCCESS;
196 struct macaroon* macaroon = macaroon_deserialize(
197 authz,
198 &mac_err);
199 if (!macaroon)
200 {
201 // Do not log - might be other token type!
202 //m_log.Emsg("Access", "Failed to parse the macaroon");
203 return OnMissing(Entity, path, oper, env);
204 }
205
206 struct macaroon_verifier *verifier = macaroon_verifier_create();
207 if (!verifier)
208 {
209 m_log.Emsg("Access", "Failed to create a new macaroon verifier");
210 return XrdAccPriv_None;
211 }
212 if (!path)
213 {
214 m_log.Emsg("Access", "Request with no provided path.");
215 macaroon_verifier_destroy(verifier);
216 return XrdAccPriv_None;
217 }
218
219 AuthzCheck check_helper(path, oper, m_max_duration, m_log);
220
221 if (macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_before_s, &check_helper, &mac_err) ||
222 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_activity_s, &check_helper, &mac_err) ||
223 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_name_s, &check_helper, &mac_err) ||
224 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_path_s, &check_helper, &mac_err))
225 {
226 m_log.Emsg("Access", "Failed to configure caveat verifier:");
227 macaroon_verifier_destroy(verifier);
228 return XrdAccPriv_None;
229 }
230
231 const unsigned char *macaroon_loc;
232 size_t location_sz;
233 macaroon_location(macaroon, &macaroon_loc, &location_sz);
234 if (strncmp(reinterpret_cast<const char *>(macaroon_loc), m_location.c_str(), location_sz))
235 {
236 std::string location_str(reinterpret_cast<const char *>(macaroon_loc), location_sz);
237 m_log.Emsg("Access", "Macaroon is for incorrect location", location_str.c_str());
238 macaroon_verifier_destroy(verifier);
239 macaroon_destroy(macaroon);
240 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
241 }
242
243 if (macaroon_verify(verifier, macaroon,
244 reinterpret_cast<const unsigned char *>(m_secret.c_str()),
245 m_secret.size(),
246 nullptr, 0, // discharge macaroons
247 &mac_err))
248 {
249 m_log.Log(LogMask::Debug, "Access", "Macaroon verification failed");
250 macaroon_verifier_destroy(verifier);
251 macaroon_destroy(macaroon);
252 // This token is from our server (location matched) but caveats or HMAC
253 // failed. Falling through to the chain would let a path-restricted
254 // macaroon bypass its own restrictions. Deny unconditionally.
255 return XrdAccPriv_None;
256 }
257 macaroon_verifier_destroy(verifier);
258
259 const unsigned char *macaroon_id;
260 size_t id_sz;
261 macaroon_identifier(macaroon, &macaroon_id, &id_sz);
262
263 std::string macaroon_id_str(reinterpret_cast<const char *>(macaroon_id), id_sz);
264 m_log.Log(LogMask::Info, "Access", "Macaroon verification successful; ID", macaroon_id_str.c_str());
265 macaroon_destroy(macaroon);
266
267 // Copy the name, if present into the macaroon, into the credential object.
268 if (Entity && check_helper.GetSecName().size()) {
269 const std::string &username = check_helper.GetSecName();
270 m_log.Log(LogMask::Debug, "Access", "Setting the request name to", username.c_str());
271 Entity->eaAPI->Add("request.name", username,true);
272 }
273
274 // We passed verification - give the correct privilege.
275 return AddPriv(oper, XrdAccPriv_None);
276}
277
278bool Authz::Validate(const char *token,
279 std::string &emsg,
280 long long *expT,
281 XrdSecEntity *entP)
282{
283 macaroon_returncode mac_err = MACAROON_SUCCESS;
284 std::unique_ptr<struct macaroon, decltype(&macaroon_destroy)> macaroon(
285 macaroon_deserialize(token, &mac_err),
286 &macaroon_destroy);
287
288 if (!macaroon)
289 {
290 emsg = "Failed to deserialize the token as a macaroon";
291 // Purposely log at debug level in case if this validation is ever
292 // chained so we don't have overly-chatty logs.
293 m_log.Log(LogMask::Debug, "Validate", emsg.c_str());
294 return false;
295 }
296
297 std::unique_ptr<struct macaroon_verifier, decltype(&macaroon_verifier_destroy)> verifier(
298 macaroon_verifier_create(), &macaroon_verifier_destroy);
299 if (!verifier)
300 {
301 emsg = "Internal error: failed to create a verifier.";
302 m_log.Log(LogMask::Error, "Validate", emsg.c_str());
303 return false;
304 }
305
306 // Note the path and operation here are ignored as we won't use those validators
307 AuthzCheck check_helper("/", AOP_Read, m_max_duration, m_log);
308
309 if (macaroon_verifier_satisfy_general(verifier.get(), AuthzCheck::verify_before_s, &check_helper, &mac_err) ||
310 macaroon_verifier_satisfy_general(verifier.get(), validate_verify_empty, nullptr, &mac_err))
311 {
312 emsg = "Failed to configure the verifier";
313 m_log.Log(LogMask::Error, "Validate", emsg.c_str());
314 return false;
315 }
316
317 const unsigned char *macaroon_loc;
318 size_t location_sz;
319 macaroon_location(macaroon.get(), &macaroon_loc, &location_sz);
320 if (strncmp(reinterpret_cast<const char *>(macaroon_loc), m_location.c_str(), location_sz))
321 {
322 emsg = "Macaroon contains incorrect location: " +
323 std::string(reinterpret_cast<const char *>(macaroon_loc), location_sz);
324 m_log.Log(LogMask::Warning, "Validate", emsg.c_str(), ("all.sitename is " + m_location).c_str());
325 return false;
326 }
327
328 if (macaroon_verify(verifier.get(), macaroon.get(),
329 reinterpret_cast<const unsigned char *>(m_secret.c_str()),
330 m_secret.size(),
331 nullptr, 0,
332 &mac_err))
333 {
334 emsg = "Macaroon verification error" + (check_helper.GetErrorMessage().size() ?
335 (", " + check_helper.GetErrorMessage()) : "");
336 m_log.Log(LogMask::Warning, "Validate", emsg.c_str());
337 return false;
338 }
339
340 const unsigned char *macaroon_id;
341 size_t id_sz;
342 macaroon_identifier(macaroon.get(), &macaroon_id, &id_sz);
343 m_log.Log(LogMask::Info, "Validate", ("Macaroon verification successful; ID " +
344 std::string(reinterpret_cast<const char *>(macaroon_id), id_sz)).c_str());
345
346 return true;
347}
348
349AuthzCheck::AuthzCheck(const char *req_path, const Access_Operation req_oper, ssize_t max_duration, XrdSysError &log)
350 : m_max_duration(max_duration),
351 m_log(log),
352 m_path(NormalizeSlashes(req_path)),
353 m_oper(req_oper),
354 m_now(time(nullptr))
355{
356 switch (m_oper)
357 {
358 case AOP_Any:
359 break;
360 case AOP_Chmod:
361 case AOP_Chown:
362 m_desired_activity = "UPDATE_METADATA";
363 break;
364 case AOP_Insert:
365 case AOP_Lock:
366 case AOP_Mkdir:
367 case AOP_Update:
368 case AOP_Create:
369 m_desired_activity = "MANAGE";
370 break;
371 case AOP_Rename:
372 case AOP_Excl_Create:
373 case AOP_Excl_Insert:
374 m_desired_activity = "UPLOAD";
375 break;
376 case AOP_Delete:
377 m_desired_activity = "DELETE";
378 break;
379 case AOP_Read:
380 m_desired_activity = "DOWNLOAD";
381 break;
382 case AOP_Readdir:
383 m_desired_activity = "LIST";
384 break;
385 case AOP_Stat:
386 m_desired_activity = "READ_METADATA";
387 break;
388 case AOP_Stage:
389 case AOP_Poll:
390 break;
391 };
392}
393
394int
395AuthzCheck::verify_before_s(void *authz_ptr,
396 const unsigned char *pred,
397 size_t pred_sz)
398{
399 return static_cast<AuthzCheck*>(authz_ptr)->verify_before(pred, pred_sz);
400}
401
402int
403AuthzCheck::verify_activity_s(void *authz_ptr,
404 const unsigned char *pred,
405 size_t pred_sz)
406{
407 return static_cast<AuthzCheck*>(authz_ptr)->verify_activity(pred, pred_sz);
408}
409
410int
411AuthzCheck::verify_path_s(void *authz_ptr,
412 const unsigned char *pred,
413 size_t pred_sz)
414{
415 return static_cast<AuthzCheck*>(authz_ptr)->verify_path(pred, pred_sz);
416}
417
418int
419AuthzCheck::verify_name_s(void *authz_ptr,
420 const unsigned char *pred,
421 size_t pred_sz)
422{
423 return static_cast<AuthzCheck*>(authz_ptr)->verify_name(pred, pred_sz);
424}
425
426int
427AuthzCheck::verify_before(const unsigned char * pred, size_t pred_sz)
428{
429 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
430 if (strncmp("before:", pred_str.c_str(), 7))
431 {
432 return 1;
433 }
434 m_log.Log(LogMask::Debug, "AuthzCheck", "Checking macaroon for expiration; caveat:", pred_str.c_str());
435
436 struct tm caveat_tm;
437 if (strptime(&pred_str[7], "%Y-%m-%dT%H:%M:%SZ", &caveat_tm) == nullptr)
438 {
439 m_emsg = "Failed to parse time string: " + pred_str.substr(7);
440 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
441 return 1;
442 }
443 caveat_tm.tm_isdst = -1;
444
445 time_t caveat_time = timegm(&caveat_tm);
446 if (-1 == caveat_time)
447 {
448 m_emsg = "Failed to generate unix time: " + pred_str.substr(7);
449 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
450 return 1;
451 }
452 if ((m_max_duration > 0) && (caveat_time > m_now + m_max_duration))
453 {
454 m_emsg = "Max token age is greater than configured max duration; rejecting";
455 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
456 return 1;
457 }
458
459 int result = (m_now >= caveat_time);
460 if (!result)
461 {
462 m_log.Log(LogMask::Debug, "AuthzCheck", "Macaroon has not expired.");
463 }
464 else
465 {
466 m_emsg = "Macaroon expired at " + pred_str.substr(7);
467 m_log.Log(LogMask::Debug, "AuthzCheck", m_emsg.c_str());
468 }
469 return result;
470}
471
472int
473AuthzCheck::verify_activity(const unsigned char * pred, size_t pred_sz)
474{
475 if (!m_desired_activity.size()) {return 1;}
476 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
477 if (strncmp("activity:", pred_str.c_str(), 9)) {return 1;}
478 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify activity", pred_str.c_str());
479
480 std::stringstream ss(pred_str.substr(9));
481 for (std::string activity; std::getline(ss, activity, ','); )
482 {
483 // Any allowed activity also implies "READ_METADATA"
484 if (m_desired_activity == "READ_METADATA") {return 0;}
485 if ((activity == m_desired_activity) || ((m_desired_activity == "UPLOAD") && (activity == "MANAGE")))
486 {
487 m_log.Log(LogMask::Debug, "AuthzCheck", "macaroon has desired activity", activity.c_str());
488 return 0;
489 }
490 }
491 m_log.Log(LogMask::Info, "AuthzCheck", "macaroon does NOT have desired activity", m_desired_activity.c_str());
492 return 1;
493}
494
495int
496AuthzCheck::verify_path(const unsigned char * pred, size_t pred_sz)
497{
498 std::string pred_str_raw(reinterpret_cast<const char *>(pred), pred_sz);
499 if (strncmp("path:", pred_str_raw.c_str(), 5)) {return 1;}
500 std::string pred_str = NormalizeSlashes(pred_str_raw.substr(5));
501 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify path", pred_str.c_str());
502
503 if ((m_path.find("/./") != std::string::npos) ||
504 (m_path.find("/../") != std::string::npos))
505 {
506 m_log.Log(LogMask::Info, "AuthzCheck", "invalid requested path", m_path.c_str());
507 return 1;
508 }
509
510 // Allow operations under subdirectories and not substrings
511 // For e.g. pred_str = "/data/sudir/mydir"
512 // Allows m_path = /data/subdir/mydir/newdir
513 // But rejects, m_path = /data/subdir/mydirmycoolname/newdir
514 int is_subdir = is_subdirectory(pred_str, m_path);
515 if (is_subdir)
516 {
517 m_log.Log(LogMask::Debug, "AuthzCheck", "path request verified for", m_path.c_str());
518 }
519
520 // READ_METADATA (i.e AOP_Stat) permission for /foo/bar automatically implies permission
521 // to READ_METADATA for /foo.
522 // Similarly, MKDIR Pemissions for a parent path is implied.
523 else if (m_oper == AOP_Stat || m_oper == AOP_Mkdir)
524 {
525 is_subdir = is_subdirectory(m_path, pred_str);
526 const char *opName = (m_oper == AOP_Stat) ? "READ_METADATA" : "MKDIR";
527 m_log.Log(LogMask::Debug, "AuthzCheck",
528 (std::string(opName) + (is_subdir? " Path request verified for" : " Path request NOT allowed for")).c_str(),
529 m_path.c_str());
530 }
531 else
532 {
533 m_log.Log(LogMask::Debug, "AuthzCheck", "path request NOT allowed", m_path.c_str());
534 }
535
536 return !is_subdir;
537}
538
539int
540AuthzCheck::verify_name(const unsigned char * pred, size_t pred_sz)
541{
542 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
543 if (strncmp("name:", pred_str.c_str(), 5)) {return 1;}
544 if (pred_str.size() < 6) {return 1;}
545 m_log.Log(LogMask::Debug, "AuthzCheck", "Verifying macaroon with", pred_str.c_str());
546
547 // Make a copy of the name for the XrdSecEntity; this will be used later.
548 m_sec_name = pred_str.substr(5);
549
550 return 0;
551}
Access_Operation
The following are supported operations.
@ AOP_Delete
rm() or rmdir()
@ AOP_Mkdir
mkdir()
@ AOP_Update
open() r/w or append
@ AOP_Create
open() with create
@ AOP_Readdir
opendir()
@ AOP_Chmod
chmod()
@ AOP_Any
Special for getting privs.
@ AOP_Stat
exists(), stat()
@ AOP_Poll
stage polling operations
@ 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_Lock
n/a
@ AOP_Chown
chown()
@ AOP_Stage
stage and or read data, plus related operations
@ AOP_Excl_Insert
mv() where destination doesn't exist.
XrdAccPrivs
@ XrdAccPriv_Mkdir
@ XrdAccPriv_Chown
@ XrdAccPriv_Insert
@ XrdAccPriv_Lookup
@ XrdAccPriv_Rename
@ XrdAccPriv_Poll
@ XrdAccPriv_Update
@ XrdAccPriv_Read
@ XrdAccPriv_Lock
@ XrdAccPriv_None
@ XrdAccPriv_Stage
@ XrdAccPriv_Delete
@ XrdAccPriv_Create
@ XrdAccPriv_Readdir
@ XrdAccPriv_Chmod
static bool is_subdirectory(const std::string_view dir, const std::string_view subdir)
int emsg(int rc, char *msg)
virtual bool Validate(const char *token, std::string &emsg, long long *expT, XrdSecEntity *entP) override
Authz(XrdSysLogger *lp, const char *parms, XrdAccAuthorize *chain)
virtual XrdAccPrivs Access(const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *env) override
static bool Config(const char *config, XrdOucEnv *env, XrdSysError *log, std::string &location, std::string &secret, ssize_t &max_duration, AuthzBehavior &behavior)
XrdAccAuthorize()
Constructor.
virtual XrdAccPrivs Access(const XrdSecEntity *Entity, const char *path, const Access_Operation oper, XrdOucEnv *Env=0)=0
char * Get(const char *varname)
Definition XrdOucEnv.hh:69
bool Add(XrdSecAttr &attr)
int credslen
Length of the 'creds' data.
XrdSecEntityAttr * eaAPI
non-const API to attributes
char prot[XrdSecPROTOIDSIZE]
Auth protocol used (e.g. krb5)
char * creds
Raw entity credentials or cert.
std::string NormalizeSlashes(const std::string &input)