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