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
174 // If there's no request-specific token, check for a ZTN session token
175 if (!authz && Entity && !strcmp("ztn", Entity->prot) && Entity->creds &&
176 Entity->credslen && Entity->creds[Entity->credslen] == '\0')
177 {
178 authz = Entity->creds;
179 }
180
181 if (!authz) {
182 return OnMissing(Entity, path, oper, env);
183 }
184
185 macaroon_returncode mac_err = MACAROON_SUCCESS;
186 struct macaroon* macaroon = macaroon_deserialize(
187 authz,
188 &mac_err);
189 if (!macaroon)
190 {
191 // Do not log - might be other token type!
192 //m_log.Emsg("Access", "Failed to parse the macaroon");
193 return OnMissing(Entity, path, oper, env);
194 }
195
196 struct macaroon_verifier *verifier = macaroon_verifier_create();
197 if (!verifier)
198 {
199 m_log.Emsg("Access", "Failed to create a new macaroon verifier");
200 return XrdAccPriv_None;
201 }
202 if (!path)
203 {
204 m_log.Emsg("Access", "Request with no provided path.");
205 macaroon_verifier_destroy(verifier);
206 return XrdAccPriv_None;
207 }
208
209 AuthzCheck check_helper(path, oper, m_max_duration, m_log);
210
211 if (macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_before_s, &check_helper, &mac_err) ||
212 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_activity_s, &check_helper, &mac_err) ||
213 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_name_s, &check_helper, &mac_err) ||
214 macaroon_verifier_satisfy_general(verifier, AuthzCheck::verify_path_s, &check_helper, &mac_err))
215 {
216 m_log.Emsg("Access", "Failed to configure caveat verifier:");
217 macaroon_verifier_destroy(verifier);
218 return XrdAccPriv_None;
219 }
220
221 const unsigned char *macaroon_loc;
222 size_t location_sz;
223 macaroon_location(macaroon, &macaroon_loc, &location_sz);
224 if (strncmp(reinterpret_cast<const char *>(macaroon_loc), m_location.c_str(), location_sz))
225 {
226 std::string location_str(reinterpret_cast<const char *>(macaroon_loc), location_sz);
227 m_log.Emsg("Access", "Macaroon is for incorrect location", location_str.c_str());
228 macaroon_verifier_destroy(verifier);
229 macaroon_destroy(macaroon);
230 return m_chain ? m_chain->Access(Entity, path, oper, env) : XrdAccPriv_None;
231 }
232
233 if (macaroon_verify(verifier, macaroon,
234 reinterpret_cast<const unsigned char *>(m_secret.c_str()),
235 m_secret.size(),
236 nullptr, 0, // discharge macaroons
237 &mac_err))
238 {
239 m_log.Log(LogMask::Debug, "Access", "Macaroon verification failed");
240 macaroon_verifier_destroy(verifier);
241 macaroon_destroy(macaroon);
242 // This token is from our server (location matched) but caveats or HMAC
243 // failed. Falling through to the chain would let a path-restricted
244 // macaroon bypass its own restrictions. Deny unconditionally.
245 return XrdAccPriv_None;
246 }
247 macaroon_verifier_destroy(verifier);
248
249 const unsigned char *macaroon_id;
250 size_t id_sz;
251 macaroon_identifier(macaroon, &macaroon_id, &id_sz);
252
253 std::string macaroon_id_str(reinterpret_cast<const char *>(macaroon_id), id_sz);
254 m_log.Log(LogMask::Info, "Access", "Macaroon verification successful; ID", macaroon_id_str.c_str());
255 macaroon_destroy(macaroon);
256
257 // Copy the name, if present into the macaroon, into the credential object.
258 if (Entity && check_helper.GetSecName().size()) {
259 const std::string &username = check_helper.GetSecName();
260 m_log.Log(LogMask::Debug, "Access", "Setting the request name to", username.c_str());
261 Entity->eaAPI->Add("request.name", username,true);
262 }
263
264 // We passed verification - give the correct privilege.
265 return AddPriv(oper, XrdAccPriv_None);
266}
267
268bool Authz::Validate(const char *token,
269 std::string &emsg,
270 long long *expT,
271 XrdSecEntity *entP)
272{
273 macaroon_returncode mac_err = MACAROON_SUCCESS;
274 std::unique_ptr<struct macaroon, decltype(&macaroon_destroy)> macaroon(
275 macaroon_deserialize(token, &mac_err),
276 &macaroon_destroy);
277
278 if (!macaroon)
279 {
280 emsg = "Failed to deserialize the token as a macaroon";
281 // Purposely log at debug level in case if this validation is ever
282 // chained so we don't have overly-chatty logs.
283 m_log.Log(LogMask::Debug, "Validate", emsg.c_str());
284 return false;
285 }
286
287 std::unique_ptr<struct macaroon_verifier, decltype(&macaroon_verifier_destroy)> verifier(
288 macaroon_verifier_create(), &macaroon_verifier_destroy);
289 if (!verifier)
290 {
291 emsg = "Internal error: failed to create a verifier.";
292 m_log.Log(LogMask::Error, "Validate", emsg.c_str());
293 return false;
294 }
295
296 // Note the path and operation here are ignored as we won't use those validators
297 AuthzCheck check_helper("/", AOP_Read, m_max_duration, m_log);
298
299 if (macaroon_verifier_satisfy_general(verifier.get(), AuthzCheck::verify_before_s, &check_helper, &mac_err) ||
300 macaroon_verifier_satisfy_general(verifier.get(), validate_verify_empty, nullptr, &mac_err))
301 {
302 emsg = "Failed to configure the verifier";
303 m_log.Log(LogMask::Error, "Validate", emsg.c_str());
304 return false;
305 }
306
307 const unsigned char *macaroon_loc;
308 size_t location_sz;
309 macaroon_location(macaroon.get(), &macaroon_loc, &location_sz);
310 if (strncmp(reinterpret_cast<const char *>(macaroon_loc), m_location.c_str(), location_sz))
311 {
312 emsg = "Macaroon contains incorrect location: " +
313 std::string(reinterpret_cast<const char *>(macaroon_loc), location_sz);
314 m_log.Log(LogMask::Warning, "Validate", emsg.c_str(), ("all.sitename is " + m_location).c_str());
315 return false;
316 }
317
318 if (macaroon_verify(verifier.get(), macaroon.get(),
319 reinterpret_cast<const unsigned char *>(m_secret.c_str()),
320 m_secret.size(),
321 nullptr, 0,
322 &mac_err))
323 {
324 emsg = "Macaroon verification error" + (check_helper.GetErrorMessage().size() ?
325 (", " + check_helper.GetErrorMessage()) : "");
326 m_log.Log(LogMask::Warning, "Validate", emsg.c_str());
327 return false;
328 }
329
330 const unsigned char *macaroon_id;
331 size_t id_sz;
332 macaroon_identifier(macaroon.get(), &macaroon_id, &id_sz);
333 m_log.Log(LogMask::Info, "Validate", ("Macaroon verification successful; ID " +
334 std::string(reinterpret_cast<const char *>(macaroon_id), id_sz)).c_str());
335
336 return true;
337}
338
339AuthzCheck::AuthzCheck(const char *req_path, const Access_Operation req_oper, ssize_t max_duration, XrdSysError &log)
340 : m_max_duration(max_duration),
341 m_log(log),
342 m_path(NormalizeSlashes(req_path)),
343 m_oper(req_oper),
344 m_now(time(nullptr))
345{
346 switch (m_oper)
347 {
348 case AOP_Any:
349 break;
350 case AOP_Chmod:
351 case AOP_Chown:
352 m_desired_activity = "UPDATE_METADATA";
353 break;
354 case AOP_Insert:
355 case AOP_Lock:
356 case AOP_Mkdir:
357 case AOP_Update:
358 case AOP_Create:
359 m_desired_activity = "MANAGE";
360 break;
361 case AOP_Rename:
362 case AOP_Excl_Create:
363 case AOP_Excl_Insert:
364 m_desired_activity = "UPLOAD";
365 break;
366 case AOP_Delete:
367 m_desired_activity = "DELETE";
368 break;
369 case AOP_Read:
370 m_desired_activity = "DOWNLOAD";
371 break;
372 case AOP_Readdir:
373 m_desired_activity = "LIST";
374 break;
375 case AOP_Stat:
376 m_desired_activity = "READ_METADATA";
377 };
378}
379
380int
381AuthzCheck::verify_before_s(void *authz_ptr,
382 const unsigned char *pred,
383 size_t pred_sz)
384{
385 return static_cast<AuthzCheck*>(authz_ptr)->verify_before(pred, pred_sz);
386}
387
388int
389AuthzCheck::verify_activity_s(void *authz_ptr,
390 const unsigned char *pred,
391 size_t pred_sz)
392{
393 return static_cast<AuthzCheck*>(authz_ptr)->verify_activity(pred, pred_sz);
394}
395
396int
397AuthzCheck::verify_path_s(void *authz_ptr,
398 const unsigned char *pred,
399 size_t pred_sz)
400{
401 return static_cast<AuthzCheck*>(authz_ptr)->verify_path(pred, pred_sz);
402}
403
404int
405AuthzCheck::verify_name_s(void *authz_ptr,
406 const unsigned char *pred,
407 size_t pred_sz)
408{
409 return static_cast<AuthzCheck*>(authz_ptr)->verify_name(pred, pred_sz);
410}
411
412int
413AuthzCheck::verify_before(const unsigned char * pred, size_t pred_sz)
414{
415 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
416 if (strncmp("before:", pred_str.c_str(), 7))
417 {
418 return 1;
419 }
420 m_log.Log(LogMask::Debug, "AuthzCheck", "Checking macaroon for expiration; caveat:", pred_str.c_str());
421
422 struct tm caveat_tm;
423 if (strptime(&pred_str[7], "%Y-%m-%dT%H:%M:%SZ", &caveat_tm) == nullptr)
424 {
425 m_emsg = "Failed to parse time string: " + pred_str.substr(7);
426 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
427 return 1;
428 }
429 caveat_tm.tm_isdst = -1;
430
431 time_t caveat_time = timegm(&caveat_tm);
432 if (-1 == caveat_time)
433 {
434 m_emsg = "Failed to generate unix time: " + pred_str.substr(7);
435 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
436 return 1;
437 }
438 if ((m_max_duration > 0) && (caveat_time > m_now + m_max_duration))
439 {
440 m_emsg = "Max token age is greater than configured max duration; rejecting";
441 m_log.Log(LogMask::Warning, "AuthzCheck", m_emsg.c_str());
442 return 1;
443 }
444
445 int result = (m_now >= caveat_time);
446 if (!result)
447 {
448 m_log.Log(LogMask::Debug, "AuthzCheck", "Macaroon has not expired.");
449 }
450 else
451 {
452 m_emsg = "Macaroon expired at " + pred_str.substr(7);
453 m_log.Log(LogMask::Debug, "AuthzCheck", m_emsg.c_str());
454 }
455 return result;
456}
457
458int
459AuthzCheck::verify_activity(const unsigned char * pred, size_t pred_sz)
460{
461 if (!m_desired_activity.size()) {return 1;}
462 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
463 if (strncmp("activity:", pred_str.c_str(), 9)) {return 1;}
464 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify activity", pred_str.c_str());
465
466 std::stringstream ss(pred_str.substr(9));
467 for (std::string activity; std::getline(ss, activity, ','); )
468 {
469 // Any allowed activity also implies "READ_METADATA"
470 if (m_desired_activity == "READ_METADATA") {return 0;}
471 if ((activity == m_desired_activity) || ((m_desired_activity == "UPLOAD") && (activity == "MANAGE")))
472 {
473 m_log.Log(LogMask::Debug, "AuthzCheck", "macaroon has desired activity", activity.c_str());
474 return 0;
475 }
476 }
477 m_log.Log(LogMask::Info, "AuthzCheck", "macaroon does NOT have desired activity", m_desired_activity.c_str());
478 return 1;
479}
480
481int
482AuthzCheck::verify_path(const unsigned char * pred, size_t pred_sz)
483{
484 std::string pred_str_raw(reinterpret_cast<const char *>(pred), pred_sz);
485 if (strncmp("path:", pred_str_raw.c_str(), 5)) {return 1;}
486 std::string pred_str = NormalizeSlashes(pred_str_raw.substr(5));
487 m_log.Log(LogMask::Debug, "AuthzCheck", "running verify path", pred_str.c_str());
488
489 if ((m_path.find("/./") != std::string::npos) ||
490 (m_path.find("/../") != std::string::npos))
491 {
492 m_log.Log(LogMask::Info, "AuthzCheck", "invalid requested path", m_path.c_str());
493 return 1;
494 }
495
496 // Allow operations under subdirectories and not substrings
497 // For e.g. pred_str = "/data/sudir/mydir"
498 // Allows m_path = /data/subdir/mydir/newdir
499 // But rejects, m_path = /data/subdir/mydirmycoolname/newdir
500 int is_subdir = is_subdirectory(pred_str, m_path);
501 if (is_subdir)
502 {
503 m_log.Log(LogMask::Debug, "AuthzCheck", "path request verified for", m_path.c_str());
504 }
505
506 // READ_METADATA (i.e AOP_Stat) permission for /foo/bar automatically implies permission
507 // to READ_METADATA for /foo.
508 // Similarly, MKDIR Pemissions for a parent path is implied.
509 else if (m_oper == AOP_Stat || m_oper == AOP_Mkdir)
510 {
511 is_subdir = is_subdirectory(m_path, pred_str);
512 const char *opName = (m_oper == AOP_Stat) ? "READ_METADATA" : "MKDIR";
513 m_log.Log(LogMask::Debug, "AuthzCheck",
514 (std::string(opName) + (is_subdir? " Path request verified for" : " Path request NOT allowed for")).c_str(),
515 m_path.c_str());
516 }
517 else
518 {
519 m_log.Log(LogMask::Debug, "AuthzCheck", "path request NOT allowed", m_path.c_str());
520 }
521
522 return !is_subdir;
523}
524
525int
526AuthzCheck::verify_name(const unsigned char * pred, size_t pred_sz)
527{
528 std::string pred_str(reinterpret_cast<const char *>(pred), pred_sz);
529 if (strncmp("name:", pred_str.c_str(), 5)) {return 1;}
530 if (pred_str.size() < 6) {return 1;}
531 m_log.Log(LogMask::Debug, "AuthzCheck", "Verifying macaroon with", pred_str.c_str());
532
533 // Make a copy of the name for the XrdSecEntity; this will be used later.
534 m_sec_name = pred_str.substr(5);
535
536 return 0;
537}
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)