1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
6 #include <boost/utility/string_ref.hpp>
7 #include <boost/container/static_vector.hpp>
9 #include "rgw_swift_auth.h"
12 #include "common/ceph_crypto.h"
13 #include "common/Clock.h"
15 #include "auth/Crypto.h"
17 #include "rgw_client_io.h"
18 #include "rgw_http_client.h"
19 #include "include/str_list.h"
21 #define dout_context g_ceph_context
22 #define dout_subsys ceph_subsys_rgw
24 #define DEFAULT_SWIFT_PREFIX "/swift"
26 using namespace ceph::crypto
;
33 /* TempURL: applier */
34 void TempURLApplier::modify_request_state(req_state
* s
) const /* in/out */
36 bool inline_exists
= false;
37 const std::string
& filename
= s
->info
.args
.get("filename");
39 s
->info
.args
.get("inline", &inline_exists
);
41 s
->content_disp
.override
= "inline";
42 } else if (!filename
.empty()) {
44 url_encode(filename
, fenc
);
45 s
->content_disp
.override
= "attachment; filename=\"" + fenc
+ "\"";
48 url_encode(s
->object
.name
, fenc
);
49 s
->content_disp
.fallback
= "attachment; filename=\"" + fenc
+ "\"";
52 ldout(s
->cct
, 20) << "finished applying changes to req_state for TempURL: "
53 << " content_disp override " << s
->content_disp
.override
54 << " content_disp fallback " << s
->content_disp
.fallback
60 bool TempURLEngine::is_applicable(const req_state
* const s
) const noexcept
62 return s
->info
.args
.exists("temp_url_sig") ||
63 s
->info
.args
.exists("temp_url_expires");
66 void TempURLEngine::get_owner_info(const req_state
* const s
,
67 RGWUserInfo
& owner_info
) const
69 /* We cannot use req_state::bucket_name because it isn't available
70 * now. It will be initialized in RGWHandler_REST_SWIFT::postauth_init(). */
71 const string
& bucket_name
= s
->init_state
.url_bucket
;
73 /* TempURL requires that bucket and object names are specified. */
74 if (bucket_name
.empty() || s
->object
.empty()) {
78 /* TempURL case is completely different than the Keystone auth - you may
79 * get account name only through extraction from URL. In turn, knowledge
80 * about account is neccessary to obtain its bucket tenant. Without that,
81 * the access would be limited to accounts with empty tenant. */
83 if (!s
->account_name
.empty()) {
87 const rgw_user
uid(s
->account_name
);
88 if (uid
.tenant
.empty()) {
89 const rgw_user
tenanted_uid(uid
.id
, uid
.id
);
91 if (rgw_get_user_info_by_uid(store
, tenanted_uid
, uinfo
) >= 0) {
93 bucket_tenant
= uinfo
.user_id
.tenant
;
98 if (!found
&& rgw_get_user_info_by_uid(store
, uid
, uinfo
) < 0) {
101 bucket_tenant
= uinfo
.user_id
.tenant
;
105 /* Need to get user info of bucket owner. */
106 RGWBucketInfo bucket_info
;
107 int ret
= store
->get_bucket_info(*static_cast<RGWObjectCtx
*>(s
->obj_ctx
),
108 bucket_tenant
, bucket_name
,
109 bucket_info
, nullptr);
114 ldout(cct
, 20) << "temp url user (bucket owner): " << bucket_info
.owner
117 if (rgw_get_user_info_by_uid(store
, bucket_info
.owner
, owner_info
) < 0) {
122 bool TempURLEngine::is_expired(const std::string
& expires
) const
125 const utime_t now
= ceph_clock_now();
126 const uint64_t expiration
= (uint64_t)strict_strtoll(expires
.c_str(),
129 dout(5) << "failed to parse temp_url_expires: " << err
<< dendl
;
133 if (expiration
<= (uint64_t)now
.sec()) {
134 dout(5) << "temp url expired: " << expiration
<< " <= " << now
.sec() << dendl
;
141 std::string
extract_swift_subuser(const std::string
& swift_user_name
) {
142 size_t pos
= swift_user_name
.find(':');
143 if (std::string::npos
== pos
) {
144 return swift_user_name
;
146 return swift_user_name
.substr(pos
+ 1);
150 class TempURLEngine::SignatureHelper
153 static constexpr uint32_t output_size
=
154 CEPH_CRYPTO_HMACSHA1_DIGESTSIZE
* 2 + 1;
156 unsigned char dest
[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE
]; // 20
157 char dest_str
[output_size
];
160 SignatureHelper() = default;
162 const char* calc(const std::string
& key
,
163 const boost::string_ref
& method
,
164 const boost::string_ref
& path
,
165 const std::string
& expires
) {
167 using ceph::crypto::HMACSHA1
;
168 using UCHARPTR
= const unsigned char*;
170 HMACSHA1
hmac((UCHARPTR
) key
.c_str(), key
.size());
171 hmac
.Update((UCHARPTR
) method
.data(), method
.size());
172 hmac
.Update((UCHARPTR
) "\n", 1);
173 hmac
.Update((UCHARPTR
) expires
.c_str(), expires
.size());
174 hmac
.Update((UCHARPTR
) "\n", 1);
175 hmac
.Update((UCHARPTR
) path
.data(), path
.size());
178 buf_to_hex((UCHARPTR
) dest
, sizeof(dest
), dest_str
);
183 bool is_equal_to(const std::string
& rhs
) const {
184 /* never allow out-of-range exception */
185 if (rhs
.size() < (output_size
- 1)) {
188 return rhs
.compare(0 /* pos */, output_size
, dest_str
) == 0;
191 }; /* TempURLEngine::SignatureHelper */
193 TempURLEngine::result_t
194 TempURLEngine::authenticate(const req_state
* const s
) const
196 if (! is_applicable(s
)) {
197 return result_t::deny();
200 const string
& temp_url_sig
= s
->info
.args
.get("temp_url_sig");
201 const string
& temp_url_expires
= s
->info
.args
.get("temp_url_expires");
203 if (temp_url_sig
.empty() || temp_url_expires
.empty()) {
204 return result_t::deny();
207 RGWUserInfo owner_info
;
209 get_owner_info(s
, owner_info
);
211 ldout(cct
, 5) << "cannot get user_info of account's owner" << dendl
;
212 return result_t::reject();
215 if (owner_info
.temp_url_keys
.empty()) {
216 ldout(cct
, 5) << "user does not have temp url key set, aborting" << dendl
;
217 return result_t::reject();
220 if (is_expired(temp_url_expires
)) {
221 ldout(cct
, 5) << "temp url link expired" << dendl
;
222 return result_t::reject(-EPERM
);
225 /* We need to verify two paths because of compliance with Swift, Tempest
226 * and old versions of RadosGW. The second item will have the prefix
227 * of Swift API entry point removed. */
229 /* XXX can we search this ONCE? */
230 const size_t pos
= g_conf
->rgw_swift_url_prefix
.find_last_not_of('/') + 1;
231 boost::string_ref ref_uri
= s
->decoded_uri
;
232 const std::array
<boost::string_ref
, 2> allowed_paths
= {
234 ref_uri
.substr(pos
+ 1)
237 /* Account owner calculates the signature also against a HTTP method. */
238 boost::container::static_vector
<boost::string_ref
, 3> allowed_methods
;
239 if (strcmp("HEAD", s
->info
.method
) == 0) {
240 /* HEAD requests are specially handled. */
241 /* TODO: after getting a newer boost (with static_vector supporting
242 * initializers lists), get back to the good notation:
243 * allowed_methods = {"HEAD", "GET", "PUT" };
244 * Just for now let's use emplace_back to construct the vector. */
245 allowed_methods
.emplace_back("HEAD");
246 allowed_methods
.emplace_back("GET");
247 allowed_methods
.emplace_back("PUT");
248 } else if (strlen(s
->info
.method
) > 0) {
249 allowed_methods
.emplace_back(s
->info
.method
);
252 /* Need to try each combination of keys, allowed path and methods. */
253 SignatureHelper sig_helper
;
254 for (const auto& kv
: owner_info
.temp_url_keys
) {
255 const int temp_url_key_num
= kv
.first
;
256 const string
& temp_url_key
= kv
.second
;
258 if (temp_url_key
.empty()) {
262 for (const auto& path
: allowed_paths
) {
263 for (const auto& method
: allowed_methods
) {
264 const char* const local_sig
= sig_helper
.calc(temp_url_key
, method
,
265 path
, temp_url_expires
);
267 ldout(s
->cct
, 20) << "temp url signature [" << temp_url_key_num
268 << "] (calculated): " << local_sig
271 if (sig_helper
.is_equal_to(temp_url_sig
)) {
272 auto apl
= apl_factory
->create_apl_turl(cct
, s
, owner_info
);
273 return result_t::grant(std::move(apl
));
275 ldout(s
->cct
, 5) << "temp url signature mismatch: " << local_sig
276 << " != " << temp_url_sig
<< dendl
;
282 return result_t::reject();
287 bool ExternalTokenEngine::is_applicable(const std::string
& token
) const noexcept
291 } else if (g_conf
->rgw_swift_auth_url
.empty()) {
298 ExternalTokenEngine::result_t
299 ExternalTokenEngine::authenticate(const std::string
& token
,
300 const req_state
* const s
) const
302 if (! is_applicable(token
)) {
303 return result_t::deny();
306 std::string auth_url
= g_conf
->rgw_swift_auth_url
;
307 if (auth_url
.back() != '/') {
308 auth_url
.append("/");
311 auth_url
.append("token");
312 char url_buf
[auth_url
.size() + 1 + token
.length() + 1];
313 sprintf(url_buf
, "%s/%s", auth_url
.c_str(), token
.c_str());
315 RGWHTTPHeadersCollector
validator(cct
, { "X-Auth-Groups", "X-Auth-Ttl" });
317 ldout(cct
, 10) << "rgw_swift_validate_token url=" << url_buf
<< dendl
;
319 int ret
= validator
.process(url_buf
);
324 std::string swift_user
;
326 std::vector
<std::string
> swift_groups
;
327 get_str_vec(validator
.get_header_value("X-Auth-Groups"),
330 if (0 == swift_groups
.size()) {
331 return result_t::deny(-EPERM
);
333 swift_user
= std::move(swift_groups
[0]);
335 } catch (std::out_of_range
) {
336 /* The X-Auth-Groups header isn't present in the response. */
337 return result_t::deny(-EPERM
);
340 if (swift_user
.empty()) {
341 return result_t::deny(-EPERM
);
344 ldout(cct
, 10) << "swift user=" << swift_user
<< dendl
;
346 RGWUserInfo tmp_uinfo
;
347 ret
= rgw_get_user_info_by_swift(store
, swift_user
, tmp_uinfo
);
349 ldout(cct
, 0) << "NOTICE: couldn't map swift user" << dendl
;
353 auto apl
= apl_factory
->create_apl_local(cct
, s
, tmp_uinfo
,
354 extract_swift_subuser(swift_user
));
355 return result_t::grant(std::move(apl
));
358 static int build_token(const string
& swift_user
,
360 const uint64_t nonce
,
361 const utime_t
& expiration
,
364 ::encode(swift_user
, bl
);
366 ::encode(expiration
, bl
);
368 bufferptr
p(CEPH_CRYPTO_HMACSHA1_DIGESTSIZE
);
370 char buf
[bl
.length() * 2 + 1];
371 buf_to_hex((const unsigned char *)bl
.c_str(), bl
.length(), buf
);
372 dout(20) << "build_token token=" << buf
<< dendl
;
374 char k
[CEPH_CRYPTO_HMACSHA1_DIGESTSIZE
];
375 memset(k
, 0, sizeof(k
));
376 const char *s
= key
.c_str();
377 for (int i
= 0; i
< (int)key
.length(); i
++, s
++) {
378 k
[i
% CEPH_CRYPTO_HMACSHA1_DIGESTSIZE
] |= *s
;
380 calc_hmac_sha1(k
, sizeof(k
), bl
.c_str(), bl
.length(), p
.c_str());
388 static int encode_token(CephContext
*cct
, string
& swift_user
, string
& key
,
393 int ret
= get_random_bytes((char *)&nonce
, sizeof(nonce
));
397 utime_t expiration
= ceph_clock_now();
398 expiration
+= cct
->_conf
->rgw_swift_token_expiration
;
400 return build_token(swift_user
, key
, nonce
, expiration
, bl
);
404 /* AUTH_rgwtk (signed token): engine */
405 bool SignedTokenEngine::is_applicable(const std::string
& token
) const noexcept
410 return token
.compare(0, 10, "AUTH_rgwtk") == 0;
414 SignedTokenEngine::result_t
415 SignedTokenEngine::authenticate(const std::string
& token
,
416 const req_state
* const s
) const
418 if (! is_applicable(token
)) {
419 return result_t::deny(-EPERM
);
422 /* Effective token string is the part after the prefix. */
423 const std::string etoken
= token
.substr(strlen("AUTH_rgwtk"));
424 const size_t etoken_len
= etoken
.length();
426 if (etoken_len
& 1) {
427 ldout(cct
, 0) << "NOTICE: failed to verify token: odd token length="
428 << etoken_len
<< dendl
;
432 ceph::bufferptr
p(etoken_len
/2);
433 int ret
= hex_to_buf(etoken
.c_str(), p
.c_str(), etoken_len
);
438 ceph::bufferlist tok_bl
;
443 std::string swift_user
;
446 /*const*/ auto iter
= tok_bl
.begin();
448 ::decode(swift_user
, iter
);
449 ::decode(nonce
, iter
);
450 ::decode(expiration
, iter
);
451 } catch (buffer::error
& err
) {
452 ldout(cct
, 0) << "NOTICE: failed to decode token" << dendl
;
456 const utime_t now
= ceph_clock_now();
457 if (expiration
< now
) {
458 ldout(cct
, 0) << "NOTICE: old timed out token was used now=" << now
459 << " token.expiration=" << expiration
461 return result_t::deny(-EPERM
);
464 RGWUserInfo user_info
;
465 ret
= rgw_get_user_info_by_swift(store
, swift_user
, user_info
);
470 ldout(cct
, 10) << "swift_user=" << swift_user
<< dendl
;
472 const auto siter
= user_info
.swift_keys
.find(swift_user
);
473 if (siter
== std::end(user_info
.swift_keys
)) {
474 return result_t::deny(-EPERM
);
477 const auto swift_key
= siter
->second
;
479 bufferlist local_tok_bl
;
480 ret
= build_token(swift_user
, swift_key
.key
, nonce
, expiration
, local_tok_bl
);
485 if (local_tok_bl
.length() != tok_bl
.length()) {
486 ldout(cct
, 0) << "NOTICE: tokens length mismatch:"
487 << " tok_bl.length()=" << tok_bl
.length()
488 << " local_tok_bl.length()=" << local_tok_bl
.length()
490 return result_t::deny(-EPERM
);
493 if (memcmp(local_tok_bl
.c_str(), tok_bl
.c_str(),
494 local_tok_bl
.length()) != 0) {
495 char buf
[local_tok_bl
.length() * 2 + 1];
497 buf_to_hex(reinterpret_cast<const unsigned char *>(local_tok_bl
.c_str()),
498 local_tok_bl
.length(), buf
);
500 ldout(cct
, 0) << "NOTICE: tokens mismatch tok=" << buf
<< dendl
;
501 return result_t::deny(-EPERM
);
504 auto apl
= apl_factory
->create_apl_local(cct
, s
, user_info
,
505 extract_swift_subuser(swift_user
));
506 return result_t::grant(std::move(apl
));
509 } /* namespace swift */
510 } /* namespace auth */
511 } /* namespace rgw */
514 void RGW_SWIFT_Auth_Get::execute()
518 const char *key
= s
->info
.env
->get("HTTP_X_AUTH_KEY");
519 const char *user
= s
->info
.env
->get("HTTP_X_AUTH_USER");
521 s
->prot_flags
|= RGW_REST_SWIFT
;
526 RGWAccessKey
*swift_key
;
527 map
<string
, RGWAccessKey
>::iterator siter
;
529 string swift_url
= g_conf
->rgw_swift_url
;
530 string swift_prefix
= g_conf
->rgw_swift_url_prefix
;
534 * We did not allow an empty Swift prefix before, but we want it now.
535 * So, we take rgw_swift_url_prefix = "/" to yield the empty prefix.
536 * The rgw_swift_url_prefix = "" is the default and yields "/swift"
537 * in a backwards-compatible way.
539 if (swift_prefix
.size() == 0) {
540 swift_prefix
= DEFAULT_SWIFT_PREFIX
;
541 } else if (swift_prefix
== "/") {
542 swift_prefix
.clear();
544 if (swift_prefix
[0] != '/') {
545 swift_prefix
.insert(0, "/");
549 if (swift_url
.size() == 0) {
550 bool add_port
= false;
551 const char *server_port
= s
->info
.env
->get("SERVER_PORT_SECURE");
552 const char *protocol
;
554 add_port
= (strcmp(server_port
, "443") != 0);
557 server_port
= s
->info
.env
->get("SERVER_PORT");
558 add_port
= (strcmp(server_port
, "80") != 0);
561 const char *host
= s
->info
.env
->get("HTTP_HOST");
563 dout(0) << "NOTICE: server is misconfigured, missing rgw_swift_url_prefix or rgw_swift_url, HTTP_HOST is not set" << dendl
;
567 swift_url
= protocol
;
568 swift_url
.append("://");
569 swift_url
.append(host
);
570 if (add_port
&& !strchr(host
, ':')) {
571 swift_url
.append(":");
572 swift_url
.append(server_port
);
581 if ((ret
= rgw_get_user_info_by_swift(store
, user_str
, info
)) < 0)
587 siter
= info
.swift_keys
.find(user_str
);
588 if (siter
== info
.swift_keys
.end()) {
592 swift_key
= &siter
->second
;
594 if (swift_key
->key
.compare(key
) != 0) {
595 dout(0) << "NOTICE: RGW_SWIFT_Auth_Get::execute(): bad swift key" << dendl
;
600 if (!g_conf
->rgw_swift_tenant_name
.empty()) {
601 tenant_path
= "/AUTH_";
602 tenant_path
.append(g_conf
->rgw_swift_tenant_name
);
603 } else if (g_conf
->rgw_swift_account_in_url
) {
604 tenant_path
= "/AUTH_";
605 tenant_path
.append(info
.user_id
.to_str());
608 dump_header(s
, "X-Storage-Url", swift_url
+ swift_prefix
+ "/v1" +
611 using rgw::auth::swift::encode_token
;
612 if ((ret
= encode_token(s
->cct
, swift_key
->id
, swift_key
->key
, bl
)) < 0)
616 static constexpr size_t PREFIX_LEN
= sizeof("AUTH_rgwtk") - 1;
617 char token_val
[PREFIX_LEN
+ bl
.length() * 2 + 1];
619 snprintf(token_val
, PREFIX_LEN
+ 1, "AUTH_rgwtk");
620 buf_to_hex((const unsigned char *)bl
.c_str(), bl
.length(),
621 token_val
+ PREFIX_LEN
);
623 dump_header(s
, "X-Storage-Token", token_val
);
624 dump_header(s
, "X-Auth-Token", token_val
);
627 ret
= STATUS_NO_CONTENT
;
630 set_req_state_err(s
, ret
);
635 int RGWHandler_SWIFT_Auth::init(RGWRados
*store
, struct req_state
*state
,
636 rgw::io::BasicClient
*cio
)
638 state
->dialect
= "swift-auth";
639 state
->formatter
= new JSONFormatter
;
640 state
->format
= RGW_FORMAT_JSON
;
642 return RGWHandler::init(store
, state
, cio
);
645 int RGWHandler_SWIFT_Auth::authorize()
650 RGWOp
*RGWHandler_SWIFT_Auth::op_get()
652 return new RGW_SWIFT_Auth_Get
;