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 };
104 return static_cast<XrdAccPrivs>(new_privs);
105}
106
107// Accept any value of the path, name, or activity caveats
108int validate_verify_empty(void *emsg_ptr,
109 const unsigned char *pred,
110 size_t pred_sz)
111{
112 if ((pred_sz >= 5) && (!memcmp(reinterpret_cast<const char *>(pred), "path:", 5) ||
113 !memcmp(reinterpret_cast<const char *>(pred), "name:", 5)))
114 {
115 return 0;
116 }
117 if ((pred_sz >= 9) && (!memcmp(reinterpret_cast<const char *>(pred), "activity:", 9)))
118 {
119 return 0;
120 }
121 return 1;
122}
123
124} // unnamed namespace
125
126Authz::Authz(XrdSysLogger *log, char const *config, XrdAccAuthorize *chain)
127 : m_max_duration(86400),
128 m_chain(chain),
129 m_log(log, "macarons_"),
130 m_authz_behavior(static_cast<int>(Handler::AuthzBehavior::PASSTHROUGH))
131{
133 XrdOucEnv env;
134 if (!Handler::Config(config, &env, &m_log, m_location, m_secret, m_max_duration, behavior))
135 {
136 throw std::runtime_error("Macaroon authorization config failed.");
137 }
138 m_authz_behavior = static_cast<int>(behavior);
139}
140
142Authz::OnMissing(const XrdSecEntity *Entity, const char *path,
143 const Access_Operation oper, XrdOucEnv *env)
144{
145 switch (m_authz_behavior) {
147 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
149 return AddPriv(oper, XrdAccPriv_None);;
151 return XrdAccPriv_None;
152 }
153 // Code should be unreachable.
154 return XrdAccPriv_None;
155}
156
158Authz::Access(const XrdSecEntity *Entity, const char *path,
159 const Access_Operation oper, XrdOucEnv *env)
160{
161 // We don't allow any testing to occur in this authz module, preventing
162 // a macaroon to be used to receive further macaroons.
163 if (oper == AOP_Any)
164 {
165 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
166 }
167
168 const char *authz = env ? env->Get("authz") : nullptr;
169 if (authz && !strncmp(authz, "Bearer%20", 9))
170 {
171 authz += 9;
172 }
173 else if (!authz && (authz = env ? env->Get("access_token") : nullptr) && !strncmp(authz, "Bearer%20", 9))
174 {
175 authz += 9;
176 }
177
178 // If there's no request-specific token, check for a ZTN session token
179 if (!authz && Entity && !strcmp("ztn", Entity->prot) && Entity->creds &&
180 Entity->credslen && Entity->creds[Entity->credslen] == '\0')
181 {
182 authz = Entity->creds;
183 }
184
185 if (!authz) {
186 return OnMissing(Entity, path, oper, env);
187 }
188
189 macaroon_returncode mac_err = MACAROON_SUCCESS;
190 struct macaroon* macaroon = macaroon_deserialize(
191 authz,
192 &mac_err);
193 if (!macaroon)
194 {
195 // Do not log - might be other token type!
196 //m_log.Emsg("Access", "Failed to parse the macaroon");
197 return OnMissing(Entity, path, oper, env);
198 }
199
200 struct macaroon_verifier *verifier = macaroon_verifier_create();
201 if (!verifier)
202 {
203 m_log.Emsg("Access", "Failed to create a new macaroon verifier");
204 return XrdAccPriv_None;
205 }
206 if (!path)
207 {
208 m_log.Emsg("Access", "Request with no provided path.");
209 macaroon_verifier_destroy(verifier);
210 return XrdAccPriv_None;
211 }
212
213 AuthzCheck check_helper(path, oper, m_max_duration, m_log);
214
215 if (macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_before_s, &check_helper, &mac_err) ||
216 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_activity_s, &check_helper, &mac_err) ||
217 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_name_s, &check_helper, &mac_err) ||
218 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_path_s, &check_helper, &mac_err))
219 {
220 m_log.Emsg("Access", "Failed to configure caveat verifier:");
221 macaroon_verifier_destroy(verifier);
222 return XrdAccPriv_None;
223 }
224
225 const unsigned char *macaroon_loc;
226 size_t location_sz;
227 macaroon_location(macaroon, &macaroon_loc, &location_sz);
228 if (strncmp(reinterpret_cast<const char *>(macaroon_loc), m_location.c_str(), location_sz))
229 {
230 std::string location_str(reinterpret_cast<const char *>(macaroon_loc), location_sz);
231 m_log.Emsg("Access", "Macaroon is for incorrect location", location_str.c_str());
232 macaroon_verifier_destroy(verifier);
233 macaroon_destroy(macaroon);
234 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
235 }
236
237 if (macaroon_verify(verifier, macaroon,
238 reinterpret_cast<const unsigned char *>(m_secret.c_str()),
239 m_secret.size(),
240 nullptr, 0, // discharge macaroons
241 &mac_err))
242 {
243 m_log.Log(LogMask::Debug, "Access", "Macaroon verification failed");
244 macaroon_verifier_destroy(verifier);
245 macaroon_destroy(macaroon);
246 // This token is from our server (location matched) but caveats or HMAC
247 // failed. Falling through to the chain would let a path-restricted
248 // macaroon bypass its own restrictions. Deny unconditionally.
249 return 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
343AuthzCheck::AuthzCheck(const char *req_path, const Access_Operation req_oper, ssize_t max_duration, XrdSysError &log)
344 : m_max_duration(max_duration),
345 m_log(log),
346 m_path(NormalizeSlashes(req_path)),
347 m_oper(req_oper),
348 m_now(time(nullptr))
349{
350 switch (m_oper)
351 {
352 case AOP_Any:
353 break;
354 case AOP_Chmod:
355 case AOP_Chown:
356 m_desired_activity = "UPDATE_METADATA";
357 break;
358 case AOP_Insert:
359 case AOP_Lock:
360 case AOP_Mkdir:
361 case AOP_Update:
362 case AOP_Create:
363 m_desired_activity = "MANAGE";
364 break;
365 case AOP_Rename:
366 case AOP_Excl_Create:
367 case AOP_Excl_Insert:
368 m_desired_activity = "UPLOAD";
369 break;
370 case AOP_Delete:
371 m_desired_activity = "DELETE";
372 break;
373 case AOP_Read:
374 m_desired_activity = "DOWNLOAD";
375 break;
376 case AOP_Readdir:
377 m_desired_activity = "LIST";
378 break;
379 case AOP_Stat:
380 m_desired_activity = "READ_METADATA";
381 };
382}
383
384int
385AuthzCheck::verify_before_s(void *authz_ptr,
386 const unsigned char *pred,
387 size_t pred_sz)
388{
389 return static_cast<AuthzCheck*>(authz_ptr)->verify_before(pred, pred_sz);
390}
391
392int
393AuthzCheck::verify_activity_s(void *authz_ptr,
394 const unsigned char *pred,
395 size_t pred_sz)
396{
397 return static_cast<AuthzCheck*>(authz_ptr)->verify_activity(pred, pred_sz);
398}
399
400int
401AuthzCheck::verify_path_s(void *authz_ptr,
402 const unsigned char *pred,
403 size_t pred_sz)
404{
405 return static_cast<AuthzCheck*>(authz_ptr)->verify_path(pred, pred_sz);
406}
407
408int
409AuthzCheck::verify_name_s(void *authz_ptr,
410 const unsigned char *pred,
411 size_t pred_sz)
412{
413 return static_cast<AuthzCheck*>(authz_ptr)->verify_name(pred, pred_sz);
414}
415
416int
417AuthzCheck::verify_before(const unsigned char * pred, size_t pred_sz)
418{
419 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
420 if (strncmp("before:", pred_str.c_str(), 7))
421 {
422 return 1;
423 }
424 m_log.Log(LogMask::Debug, "AuthzCheck", "Checking macaroon for expiration; caveat:", pred_str.c_str());
425
426 struct tm caveat_tm;
427 if (strptime(&pred_str[7], "%Y-%m-%dT%H:%M:%SZ", &caveat_tm) == nullptr)
428 {
429 m_emsg = "Failed to parse time string: " + pred_str.substr(7);
430 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
431 return 1;
432 }
433 caveat_tm.tm_isdst = -1;
434
435 time_t caveat_time = timegm(&caveat_tm);
436 if (-1 == caveat_time)
437 {
438 m_emsg = "Failed to generate unix time: " + pred_str.substr(7);
439 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
440 return 1;
441 }
442 if ((m_max_duration > 0) && (caveat_time > m_now + m_max_duration))
443 {
444 m_emsg = "Max token age is greater than configured max duration; rejecting";
445 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
446 return 1;
447 }
448
449 int result = (m_now >= caveat_time);
450 if (!result)
451 {
452 m_log.Log(LogMask::Debug, "AuthzCheck", "Macaroon has not expired.");
453 }
454 else
455 {
456 m_emsg = "Macaroon expired at " + pred_str.substr(7);
457 m_log.Log(LogMask::Debug, "AuthzCheck", m_emsg.c_str());
458 }
459 return result;
460}
461
462int
463AuthzCheck::verify_activity(const unsigned char * pred, size_t pred_sz)
464{
465 if (!m_desired_activity.size()) {return 1;}
466 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
467 if (strncmp("activity:", pred_str.c_str(), 9)) {return 1;}
468 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify activity", pred_str.c_str());
469
470 std::stringstream ss(pred_str.substr(9));
471 for (std::string activity; std::getline(ss, activity, ','); )
472 {
473 // Any allowed activity also implies "READ_METADATA"
474 if (m_desired_activity == "READ_METADATA") {return 0;}
475 if ((activity == m_desired_activity) || ((m_desired_activity == "UPLOAD") && (activity == "MANAGE")))
476 {
477 m_log.Log(LogMask::Debug, "AuthzCheck", "macaroon has desired activity", activity.c_str());
478 return 0;
479 }
480 }
481 m_log.Log(LogMask::Info, "AuthzCheck", "macaroon does NOT have desired activity", m_desired_activity.c_str());
482 return 1;
483}
484
485int
486AuthzCheck::verify_path(const unsigned char * pred, size_t pred_sz)
487{
488 std::string pred_str_raw(reinterpret_cast<const char *>(pred), pred_sz);
489 if (strncmp("path:", pred_str_raw.c_str(), 5)) {return 1;}
490 std::string pred_str = NormalizeSlashes(pred_str_raw.substr(5));
491 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify path", pred_str.c_str());
492
493 if ((m_path.find("/./") != std::string::npos) ||
494 (m_path.find("/../") != std::string::npos))
495 {
496 m_log.Log(LogMask::Info, "AuthzCheck", "invalid requested path", m_path.c_str());
497 return 1;
498 }
499
500 // Allow operations under subdirectories and not substrings
501 // For e.g. pred_str = "/data/sudir/mydir"
502 // Allows m_path = /data/subdir/mydir/newdir
503 // But rejects, m_path = /data/subdir/mydirmycoolname/newdir
504 int is_subdir = is_subdirectory(pred_str, m_path);
505 if (is_subdir)
506 {
507 m_log.Log(LogMask::Debug, "AuthzCheck", "path request verified for", m_path.c_str());
508 }
509
510 // READ_METADATA (i.e AOP_Stat) permission for /foo/bar automatically implies permission
511 // to READ_METADATA for /foo.
512 // Similarly, MKDIR Pemissions for a parent path is implied.
513 else if (m_oper == AOP_Stat || m_oper == AOP_Mkdir)
514 {
515 is_subdir = is_subdirectory(m_path, pred_str);
516 const char *opName = (m_oper == AOP_Stat) ? "READ_METADATA" : "MKDIR";
517 m_log.Log(LogMask::Debug, "AuthzCheck",
518 (std::string(opName) + (is_subdir? " Path request verified for" : " Path request NOT allowed for")).c_str(),
519 m_path.c_str());
520 }
521 else
522 {
523 m_log.Log(LogMask::Debug, "AuthzCheck", "path request NOT allowed", m_path.c_str());
524 }
525
526 return !is_subdir;
527}
528
529int
530AuthzCheck::verify_name(const unsigned char * pred, size_t pred_sz)
531{
532 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
533 if (strncmp("name:", pred_str.c_str(), 5)) {return 1;}
534 if (pred_str.size() < 6) {return 1;}
535 m_log.Log(LogMask::Debug, "AuthzCheck", "Verifying macaroon with", pred_str.c_str());
536
537 // Make a copy of the name for the XrdSecEntity; this will be used later.
538 m_sec_name = pred_str.substr(5);
539
540 return 0;
541}
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_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)