summaryrefslogtreecommitdiffstats
path: root/src/rgw/rgw_keystone.cc
blob: 3b78b642cc78a75acffc3b74500fd7f0f7526c9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp

#include <errno.h>
#include <fnmatch.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>

#include "common/errno.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "include/str_list.h"

#include "rgw_common.h"
#include "rgw_keystone.h"
#include "common/armor.h"
#include "common/Cond.h"
#include "rgw_perf_counters.h"

#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
#define PKI_ANS1_PREFIX "MII"

using namespace std;

bool rgw_is_pki_token(const string& token)
{
  return token.compare(0, sizeof(PKI_ANS1_PREFIX) - 1, PKI_ANS1_PREFIX) == 0;
}

void rgw_get_token_id(const string& token, string& token_id)
{
  if (!rgw_is_pki_token(token)) {
    token_id = token;
    return;
  }

  unsigned char m[CEPH_CRYPTO_MD5_DIGESTSIZE];

  MD5 hash;
  // Allow use of MD5 digest in FIPS mode for non-cryptographic purposes
  hash.SetFlags(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  hash.Update((const unsigned char *)token.c_str(), token.size());
  hash.Final(m);

  char calc_md5[CEPH_CRYPTO_MD5_DIGESTSIZE * 2 + 1];
  buf_to_hex(m, CEPH_CRYPTO_MD5_DIGESTSIZE, calc_md5);
  token_id = calc_md5;
}


namespace rgw {
namespace keystone {

std::string CephCtxConfig::get_endpoint_url() const noexcept
{
  static const std::string url = g_ceph_context->_conf->rgw_keystone_url;

  if (url.empty() || boost::algorithm::ends_with(url, "/")) {
    return url;
  } else {
    static const std::string url_normalised = url + '/';
    return url_normalised;
  }
}

/* secrets */
const std::string CephCtxConfig::empty{""};

static inline std::string read_secret(const std::string& file_path)
{
  using namespace std;

  constexpr int16_t size{1024};
  char buf[size];
  string s;

  s.reserve(size);
  ifstream ifs(file_path, ios::in | ios::binary);
  if (ifs) {
    while (true) {
      auto sbuf = ifs.rdbuf();
      auto len =  sbuf->sgetn(buf, size);
      if (!len)
	break;
      s.append(buf, len);
    }
    boost::algorithm::trim(s);
    if (s.back() == '\n')
      s.pop_back();
  }
  return s;
}

std::string CephCtxConfig::get_admin_token() const noexcept
{
  auto& atv = g_ceph_context->_conf->rgw_keystone_admin_token_path;
  if (!atv.empty()) {
    return read_secret(atv);
  } else {
    auto& atv = g_ceph_context->_conf->rgw_keystone_admin_token;
    if (!atv.empty()) {
      return atv;
    }
  }
  return empty;
}

std::string CephCtxConfig::get_admin_password() const noexcept  {
  auto& apv = g_ceph_context->_conf->rgw_keystone_admin_password_path;
  if (!apv.empty()) {
    return read_secret(apv);
  } else {
    auto& apv = g_ceph_context->_conf->rgw_keystone_admin_password;
    if (!apv.empty()) {
      return apv;
    }
  }
  return empty;
}

int Service::get_admin_token(const DoutPrefixProvider *dpp,
                             TokenCache& token_cache,
                             const Config& config,
                             optional_yield y,
                             std::string& token,
                             bool& token_cached)
{
  /* Let's check whether someone uses the deprecated "admin token" feature
   * based on a shared secret from keystone.conf file. */
  const auto& admin_token = config.get_admin_token();
  if (! admin_token.empty()) {
    token = std::string(admin_token.data(), admin_token.length());
    return 0;
  }

  TokenEnvelope t;

  /* Try cache first before calling Keystone for a new admin token. */
  if (token_cache.find_admin(t)) {
    ldpp_dout(dpp, 20) << "found cached admin token" << dendl;
    token = t.token.id;
    token_cached = true;
    return 0;
  }

  /* Call Keystone now. */
  const auto ret = issue_admin_token_request(dpp, config, y, t);
  if (! ret) {
    token_cache.add_admin(t);
    token = t.token.id;
  }

  return ret;
}

int Service::issue_admin_token_request(const DoutPrefixProvider *dpp,
                                       const Config& config,
                                       optional_yield y,
                                       TokenEnvelope& t)
{
  std::string token_url = config.get_endpoint_url();
  if (token_url.empty()) {
    return -EINVAL;
  }

  bufferlist token_bl;
  RGWGetKeystoneAdminToken token_req(dpp->get_cct(), "POST", "", &token_bl);
  token_req.append_header("Content-Type", "application/json");
  JSONFormatter jf;

  AdminTokenRequest req_serializer(config);
  req_serializer.dump(&jf);

  std::stringstream ss;
  jf.flush(ss);
  token_req.set_post_data(ss.str());
  token_req.set_send_length(ss.str().length());
  token_url.append("v3/auth/tokens");

  token_req.set_url(token_url);

  int ret = token_req.process(dpp, y);

  /* Detect rejection earlier than during the token parsing step. */
  if (token_req.get_http_status() ==
          RGWGetKeystoneAdminToken::HTTP_STATUS_UNAUTHORIZED) {
    return -EACCES;
  }

  // throw any other http or connection errors
  if (ret < 0) {
    return ret;
  }

  ret = t.parse(dpp, token_req.get_subject_token(), token_bl);
  if (ret != 0) {
    return -EINVAL;
  }

  return 0;
}

int Service::get_keystone_barbican_token(const DoutPrefixProvider *dpp,
                                         optional_yield y,
                                         std::string& token)
{
  using keystone_config_t = rgw::keystone::CephCtxConfig;
  using keystone_cache_t = rgw::keystone::TokenCache;

  CephContext* cct = dpp->get_cct();
  auto& config = keystone_config_t::get_instance();
  auto& token_cache = keystone_cache_t::get_instance<keystone_config_t>();

  std::string token_url = config.get_endpoint_url();
  if (token_url.empty()) {
    return -EINVAL;
  }

  rgw::keystone::TokenEnvelope t;

  /* Try cache first. */
  if (token_cache.find_barbican(t)) {
    ldpp_dout(dpp, 20) << "found cached barbican token" << dendl;
    token = t.token.id;
    return 0;
  }

  bufferlist token_bl;
  RGWKeystoneHTTPTransceiver token_req(cct, "POST", "", &token_bl);
  token_req.append_header("Content-Type", "application/json");
  JSONFormatter jf;

  BarbicanTokenRequest req_serializer(cct);
  req_serializer.dump(&jf);

  std::stringstream ss;
  jf.flush(ss);
  token_req.set_post_data(ss.str());
  token_req.set_send_length(ss.str().length());
  token_url.append("v3/auth/tokens");

  token_req.set_url(token_url);

  ldpp_dout(dpp, 20) << "Requesting secret from barbican url=" << token_url << dendl;
  int ret = token_req.process(dpp, y);
  if (ret < 0) {
    ldpp_dout(dpp, 20) << "Barbican process error:" << token_bl.c_str() << dendl;
    return ret;
  }

  /* Detect rejection earlier than during the token parsing step. */
  if (token_req.get_http_status() ==
      RGWKeystoneHTTPTransceiver::HTTP_STATUS_UNAUTHORIZED) {
    return -EACCES;
  }

  ret = t.parse(dpp, token_req.get_subject_token(), token_bl);
  if (ret != 0) {
    return -EINVAL;
  }

  token_cache.add_barbican(t);
  token = t.token.id;
  return 0;
}


bool TokenEnvelope::has_role(const std::string& r) const
{
  list<Role>::const_iterator iter;
  for (iter = roles.cbegin(); iter != roles.cend(); ++iter) {
      if (fnmatch(r.c_str(), ((*iter).name.c_str()), 0) == 0) {
        return true;
      }
  }
  return false;
}

int TokenEnvelope::parse(const DoutPrefixProvider *dpp,
                         const std::string& token_str,
                         ceph::bufferlist& bl)
{
  JSONParser parser;
  if (! parser.parse(bl.c_str(), bl.length())) {
    ldpp_dout(dpp, 0) << "Keystone token parse error: malformed json" << dendl;
    return -EINVAL;
  }

  JSONObjIter token_iter = parser.find_first("token");

  try {
    if (! token_iter.end()) {
      decode(*token_iter);
      token.id = token_str;
    } else {
      return -EINVAL;
    }
  } catch (const JSONDecoder::err& err) {
    ldpp_dout(dpp, 0) << "Keystone token parse error: " << err.what() << dendl;
    return -EINVAL;
  }

  return 0;
}

/*
 * Maybe one day we'll have the parser find this in Keystone replies.
 * But for now, we use the confguration to augment the list of roles.
 */
void TokenEnvelope::update_roles(const std::vector<std::string> & admin,
                                 const std::vector<std::string> & reader)
{
  for (auto& iter: roles) {
    for (const auto& r : admin) {
      if (fnmatch(r.c_str(), iter.name.c_str(), 0) == 0) {
        iter.is_admin = true;
        break;
      }
    }
    for (const auto& r : reader) {
      if (fnmatch(r.c_str(), iter.name.c_str(), 0) == 0) {
        iter.is_reader = true;
        break;
      }
    }
  }
}

bool TokenCache::find(const std::string& token_id,
                      rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};
  return find_locked(token_id, token, tokens, tokens_lru);
}

bool TokenCache::find_service(const std::string& token_id,
                              rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};
  return find_locked(token_id, token, service_tokens, service_tokens_lru);
}

bool TokenCache::find_locked(const std::string& token_id, rgw::keystone::TokenEnvelope& token,
                             std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru)
{
  ceph_assert(ceph_mutex_is_locked_by_me(lock));
  map<string, token_entry>::iterator iter = tokens.find(token_id);
  if (iter == tokens.end()) {
    if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_miss);
    return false;
  }

  token_entry& entry = iter->second;
  tokens_lru.erase(entry.lru_iter);

  if (entry.token.expired()) {
    tokens.erase(iter);
    if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_hit);
    return false;
  }
  token = entry.token;

  tokens_lru.push_front(token_id);
  entry.lru_iter = tokens_lru.begin();

  if (perfcounter) perfcounter->inc(l_rgw_keystone_token_cache_hit);

  return true;
}

bool TokenCache::find_admin(rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};

  return find_locked(admin_token_id, token, tokens, tokens_lru);
}

bool TokenCache::find_barbican(rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};

  return find_locked(barbican_token_id, token, tokens, tokens_lru);
}

void TokenCache::add(const std::string& token_id,
                     const rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};
  add_locked(token_id, token, tokens, tokens_lru);
}

void TokenCache::add_service(const std::string& token_id,
                             const rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};
  add_locked(token_id, token, service_tokens, service_tokens_lru);
}

void TokenCache::add_locked(const std::string& token_id, const rgw::keystone::TokenEnvelope& token,
                            std::map<std::string, token_entry>& tokens, std::list<std::string>& tokens_lru)
{
  ceph_assert(ceph_mutex_is_locked_by_me(lock));
  map<string, token_entry>::iterator iter = tokens.find(token_id);
  if (iter != tokens.end()) {
    token_entry& e = iter->second;
    tokens_lru.erase(e.lru_iter);
  }

  tokens_lru.push_front(token_id);
  token_entry& entry = tokens[token_id];
  entry.token = token;
  entry.lru_iter = tokens_lru.begin();

  while (tokens_lru.size() > max) {
    list<string>::reverse_iterator riter = tokens_lru.rbegin();
    iter = tokens.find(*riter);
    ceph_assert(iter != tokens.end());
    tokens.erase(iter);
    tokens_lru.pop_back();
  }
}

void TokenCache::add_admin(const rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};

  rgw_get_token_id(token.token.id, admin_token_id);
  add_locked(admin_token_id, token, tokens, tokens_lru);
}

void TokenCache::add_barbican(const rgw::keystone::TokenEnvelope& token)
{
  std::lock_guard l{lock};

  rgw_get_token_id(token.token.id, barbican_token_id);
  add_locked(barbican_token_id, token, tokens, tokens_lru);
}

void TokenCache::invalidate(const DoutPrefixProvider *dpp, const std::string& token_id)
{
  std::lock_guard l{lock};
  map<string, token_entry>::iterator iter = tokens.find(token_id);
  if (iter == tokens.end())
    return;

  ldpp_dout(dpp, 20) << "invalidating revoked token id=" << token_id << dendl;
  token_entry& e = iter->second;
  tokens_lru.erase(e.lru_iter);
  tokens.erase(iter);
}

void TokenCache::invalidate_admin(const DoutPrefixProvider *dpp)
{
  invalidate(dpp, admin_token_id);
}

bool TokenCache::going_down() const
{
  return down_flag;
}

}; /* namespace keystone */
}; /* namespace rgw */

void rgw::keystone::TokenEnvelope::Token::decode_json(JSONObj *obj)
{
  string expires_iso8601;
  struct tm t;

  JSONDecoder::decode_json("id", id, obj, true);
  JSONDecoder::decode_json("expires", expires_iso8601, obj, true);

  if (parse_iso8601(expires_iso8601.c_str(), &t)) {
    expires = internal_timegm(&t);
  } else {
    expires = 0;
    throw JSONDecoder::err("Failed to parse ISO8601 expiration date from Keystone response.");
  }
}

void rgw::keystone::TokenEnvelope::Role::decode_json(JSONObj *obj)
{
  JSONDecoder::decode_json("id", id, obj);
  JSONDecoder::decode_json("name", name, obj, true);
}

void rgw::keystone::TokenEnvelope::Domain::decode_json(JSONObj *obj)
{
  JSONDecoder::decode_json("id", id, obj, true);
  JSONDecoder::decode_json("name", name, obj, true);
}

void rgw::keystone::TokenEnvelope::Project::decode_json(JSONObj *obj)
{
  JSONDecoder::decode_json("id", id, obj, true);
  JSONDecoder::decode_json("name", name, obj, true);
  JSONDecoder::decode_json("domain", domain, obj);
}

void rgw::keystone::TokenEnvelope::User::decode_json(JSONObj *obj)
{
  JSONDecoder::decode_json("id", id, obj, true);
  JSONDecoder::decode_json("name", name, obj, true);
  JSONDecoder::decode_json("domain", domain, obj);
}

void rgw::keystone::TokenEnvelope::decode(JSONObj* const root_obj)
{
  std::string expires_iso8601;

  JSONDecoder::decode_json("user", user, root_obj, true);
  JSONDecoder::decode_json("expires_at", expires_iso8601, root_obj, true);
  JSONDecoder::decode_json("roles", roles, root_obj, true);
  JSONDecoder::decode_json("project", project, root_obj, true);

  struct tm t;
  if (parse_iso8601(expires_iso8601.c_str(), &t)) {
    token.expires = internal_timegm(&t);
  } else {
    token.expires = 0;
    throw JSONDecoder::err("Failed to parse ISO8601 expiration date"
                           "from Keystone response.");
  }
}

/* This utility function shouldn't conflict with the overload of std::to_string
 * provided by string_ref since Boost 1.54 as it's defined outside of the std
 * namespace. I hope we'll remove it soon - just after merging the Matt's PR
 * for bundled Boost. It would allow us to forget that CentOS 7 has Boost 1.53. */
static inline std::string to_string(const std::string_view& s)
{
  return std::string(s.data(), s.length());
}

void rgw::keystone::AdminTokenRequest::dump(Formatter* const f) const
{
  f->open_object_section("token_request");
    f->open_object_section("auth");
      f->open_object_section("identity");
        f->open_array_section("methods");
          f->dump_string("", "password");
        f->close_section();
        f->open_object_section("password");
          f->open_object_section("user");
            f->open_object_section("domain");
              encode_json("name", ::to_string(conf.get_admin_domain()), f);
            f->close_section();
            encode_json("name", ::to_string(conf.get_admin_user()), f);
            encode_json("password", ::to_string(conf.get_admin_password()), f);
          f->close_section();
        f->close_section();
      f->close_section();
      f->open_object_section("scope");
        f->open_object_section("project");
          if (! conf.get_admin_project().empty()) {
            encode_json("name", ::to_string(conf.get_admin_project()), f);
          } else {
            encode_json("name", ::to_string(conf.get_admin_tenant()), f);
          }
          f->open_object_section("domain");
            encode_json("name", ::to_string(conf.get_admin_domain()), f);
          f->close_section();
        f->close_section();
      f->close_section();
    f->close_section();
  f->close_section();
}

void rgw::keystone::BarbicanTokenRequest::dump(Formatter* const f) const
{
  f->open_object_section("token_request");
    f->open_object_section("auth");
      f->open_object_section("identity");
        f->open_array_section("methods");
          f->dump_string("", "password");
        f->close_section();
        f->open_object_section("password");
          f->open_object_section("user");
            f->open_object_section("domain");
              encode_json("name", cct->_conf->rgw_keystone_barbican_domain, f);
            f->close_section();
            encode_json("name", cct->_conf->rgw_keystone_barbican_user, f);
            encode_json("password", cct->_conf->rgw_keystone_barbican_password, f);
          f->close_section();
        f->close_section();
      f->close_section();
      f->open_object_section("scope");
        f->open_object_section("project");
          if (!cct->_conf->rgw_keystone_barbican_project.empty()) {
            encode_json("name", cct->_conf->rgw_keystone_barbican_project, f);
          } else {
            encode_json("name", cct->_conf->rgw_keystone_barbican_tenant, f);
          }
          f->open_object_section("domain");
            encode_json("name", cct->_conf->rgw_keystone_barbican_domain, f);
          f->close_section();
        f->close_section();
      f->close_section();
    f->close_section();
  f->close_section();
}