| 1 |
/* |
| 2 |
Copyright (c) 2017 Arun Muralidharan |
| 3 |
|
| 4 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 |
of this software and associated documentation files (the "Software"), to deal |
| 6 |
in the Software without restriction, including without limitation the rights |
| 7 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 |
copies of the Software, and to permit persons to whom the Software is |
| 9 |
furnished to do so, subject to the following conditions: |
| 10 |
|
| 11 |
The above copyright notice and this permission notice shall be included in all |
| 12 |
copies or substantial portions of the Software. |
| 13 |
|
| 14 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 20 |
SOFTWARE. |
| 21 |
*/ |
| 22 |
|
| 23 |
#ifndef JWT_IPP |
| 24 |
#define JWT_IPP |
| 25 |
|
| 26 |
#include "jwt/config.hpp" |
| 27 |
#include "jwt/detail/meta.hpp" |
| 28 |
#include <algorithm> |
| 29 |
#include <iomanip> |
| 30 |
|
| 31 |
namespace jwt { |
| 32 |
|
| 33 |
/** |
| 34 |
*/ |
| 35 |
static inline void jwt_throw_exception(const std::error_code& ec); |
| 36 |
|
| 37 |
template <typename T, typename Cond> |
| 38 |
std::string to_json_str(const T& obj, bool pretty) |
| 39 |
{ |
| 40 |
return pretty ? obj.create_json_obj().dump(2) |
| 41 |
: obj.create_json_obj().dump() |
| 42 |
; |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
template <typename T> |
| 47 |
std::ostream& write(std::ostream& os, const T& obj, bool pretty) |
| 48 |
{ |
| 49 |
pretty ? (os << std::setw(2) << obj.create_json_obj()) |
| 50 |
: (os << obj.create_json_obj()) |
| 51 |
; |
| 52 |
|
| 53 |
return os; |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
template <typename T, typename Cond> |
| 58 |
std::ostream& operator<< (std::ostream& os, const T& obj) |
| 59 |
{ |
| 60 |
os << obj.create_json_obj(); |
| 61 |
return os; |
| 62 |
} |
| 63 |
|
| 64 |
//======================================================================== |
| 65 |
|
| 66 |
inline void jwt_header::decode(const jwt::string_view enc_str, std::error_code& ec) |
| 67 |
{ |
| 68 |
ec.clear(); |
| 69 |
std::string json_str = base64_decode(enc_str); |
| 70 |
|
| 71 |
try { |
| 72 |
payload_ = json_t::parse(std::move(json_str)); |
| 73 |
} catch(const std::exception&) { |
| 74 |
ec = DecodeErrc::JsonParseError; |
| 75 |
return; |
| 76 |
} |
| 77 |
|
| 78 |
//Look for the algorithm field |
| 79 |
auto alg_itr = payload_.find("alg"); |
| 80 |
if (alg_itr == payload_.end()) { |
| 81 |
ec = DecodeErrc::AlgHeaderMiss; |
| 82 |
return; |
| 83 |
} |
| 84 |
|
| 85 |
alg_ = str_to_alg(alg_itr.value().get<std::string>()); |
| 86 |
|
| 87 |
if (alg_ != algorithm::NONE) |
| 88 |
{ |
| 89 |
auto itr = payload_.find("typ"); |
| 90 |
|
| 91 |
if (itr != payload_.end()) { |
| 92 |
const auto& typ = itr.value().get<std::string>(); |
| 93 |
if (strcasecmp(typ.c_str(), "JWT")) { |
| 94 |
ec = DecodeErrc::TypMismatch; |
| 95 |
return; |
| 96 |
} |
| 97 |
|
| 98 |
typ_ = str_to_type(typ); |
| 99 |
} |
| 100 |
} else { |
| 101 |
//TODO: |
| 102 |
} |
| 103 |
|
| 104 |
// Populate header |
| 105 |
for (auto it = payload_.begin(); it != payload_.end(); ++it) { |
| 106 |
auto ret = headers_.insert(it.key()); |
| 107 |
if (!ret.second) { |
| 108 |
ec = DecodeErrc::DuplClaims; |
| 109 |
//ATTN: Dont stop the decode here |
| 110 |
//Not a hard error. |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
return; |
| 115 |
} |
| 116 |
|
| 117 |
inline void jwt_header::decode(const jwt::string_view enc_str) |
| 118 |
{ |
| 119 |
std::error_code ec; |
| 120 |
decode(enc_str, ec); |
| 121 |
if (ec) { |
| 122 |
throw DecodeError(ec.message()); |
| 123 |
} |
| 124 |
return; |
| 125 |
} |
| 126 |
|
| 127 |
inline void jwt_payload::decode(const jwt::string_view enc_str, std::error_code& ec) |
| 128 |
{ |
| 129 |
ec.clear(); |
| 130 |
std::string json_str = base64_decode(enc_str); |
| 131 |
try { |
| 132 |
payload_ = json_t::parse(std::move(json_str)); |
| 133 |
} catch(const std::exception&) { |
| 134 |
ec = DecodeErrc::JsonParseError; |
| 135 |
return; |
| 136 |
} |
| 137 |
//populate the claims set |
| 138 |
for (auto it = payload_.begin(); it != payload_.end(); ++it) { |
| 139 |
auto ret = claim_names_.insert(it.key()); |
| 140 |
if (!ret.second) { |
| 141 |
ec = DecodeErrc::DuplClaims; |
| 142 |
break; |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
return; |
| 147 |
} |
| 148 |
|
| 149 |
inline void jwt_payload::decode(const jwt::string_view enc_str) |
| 150 |
{ |
| 151 |
std::error_code ec; |
| 152 |
decode(enc_str, ec); |
| 153 |
if (ec) { |
| 154 |
throw DecodeError(ec.message()); |
| 155 |
} |
| 156 |
return; |
| 157 |
} |
| 158 |
|
| 159 |
inline std::string jwt_signature::encode(const jwt_header& header, |
| 160 |
const jwt_payload& payload, |
| 161 |
std::error_code& ec) |
| 162 |
{ |
| 163 |
std::string jwt_msg; |
| 164 |
ec.clear(); |
| 165 |
//TODO: Optimize allocations |
| 166 |
|
| 167 |
sign_func_t sign_fn = get_sign_algorithm_impl(header); |
| 168 |
|
| 169 |
std::string hdr_sign = header.base64_encode(); |
| 170 |
std::string pld_sign = payload.base64_encode(); |
| 171 |
std::string data = hdr_sign + '.' + pld_sign; |
| 172 |
|
| 173 |
auto res = sign_fn(key_, data); |
| 174 |
|
| 175 |
if (res.second && res.second != AlgorithmErrc::NoneAlgorithmUsed) { |
| 176 |
ec = res.second; |
| 177 |
return {}; |
| 178 |
} |
| 179 |
|
| 180 |
std::string b64hash; |
| 181 |
|
| 182 |
if (!res.second) { |
| 183 |
b64hash = base64_encode(res.first.c_str(), res.first.length()); |
| 184 |
} |
| 185 |
|
| 186 |
auto new_len = base64_uri_encode(&b64hash[0], b64hash.length()); |
| 187 |
b64hash.resize(new_len); |
| 188 |
|
| 189 |
jwt_msg = data + '.' + b64hash; |
| 190 |
|
| 191 |
return jwt_msg; |
| 192 |
} |
| 193 |
|
| 194 |
inline verify_result_t jwt_signature::verify(const jwt_header& header, |
| 195 |
const jwt::string_view hdr_pld_sign, |
| 196 |
const jwt::string_view jwt_sign) |
| 197 |
{ |
| 198 |
auto check_res = check_for_algo_confusion_attack(header); |
| 199 |
if (check_res.first) { |
| 200 |
return {false, VerificationErrc::AlgoConfusionAttack}; |
| 201 |
} |
| 202 |
|
| 203 |
verify_func_t verify_fn = get_verify_algorithm_impl(header); |
| 204 |
return verify_fn(key_, hdr_pld_sign, jwt_sign); |
| 205 |
} |
| 206 |
|
| 207 |
inline verify_result_t jwt_signature::check_for_algo_confusion_attack( |
| 208 |
const jwt_header& hdr) const |
| 209 |
{ |
| 210 |
switch (hdr.algo()) { |
| 211 |
case algorithm::RS256: |
| 212 |
case algorithm::RS384: |
| 213 |
case algorithm::RS512: |
| 214 |
case algorithm::ES256: |
| 215 |
case algorithm::ES384: |
| 216 |
case algorithm::ES512: |
| 217 |
return {false, std::error_code{}}; |
| 218 |
default: |
| 219 |
// For all other cases make sure that the secret provided |
| 220 |
// is not the public key. |
| 221 |
return is_secret_a_public_key(key_); |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
inline sign_func_t |
| 227 |
jwt_signature::get_sign_algorithm_impl(const jwt_header& hdr) const noexcept |
| 228 |
{ |
| 229 |
sign_func_t ret = nullptr; |
| 230 |
|
| 231 |
switch (hdr.algo()) { |
| 232 |
case algorithm::HS256: |
| 233 |
ret = HMACSign<algo::HS256>::sign; |
| 234 |
break; |
| 235 |
case algorithm::HS384: |
| 236 |
ret = HMACSign<algo::HS384>::sign; |
| 237 |
break; |
| 238 |
case algorithm::HS512: |
| 239 |
ret = HMACSign<algo::HS512>::sign; |
| 240 |
break; |
| 241 |
case algorithm::NONE: |
| 242 |
ret = HMACSign<algo::NONE>::sign; |
| 243 |
break; |
| 244 |
case algorithm::RS256: |
| 245 |
ret = PEMSign<algo::RS256>::sign; |
| 246 |
break; |
| 247 |
case algorithm::RS384: |
| 248 |
ret = PEMSign<algo::RS384>::sign; |
| 249 |
break; |
| 250 |
case algorithm::RS512: |
| 251 |
ret = PEMSign<algo::RS512>::sign; |
| 252 |
break; |
| 253 |
case algorithm::ES256: |
| 254 |
ret = PEMSign<algo::ES256>::sign; |
| 255 |
break; |
| 256 |
case algorithm::ES384: |
| 257 |
ret = PEMSign<algo::ES384>::sign; |
| 258 |
break; |
| 259 |
case algorithm::ES512: |
| 260 |
ret = PEMSign<algo::ES512>::sign; |
| 261 |
break; |
| 262 |
default: |
| 263 |
assert (0 && "Code not reached"); |
| 264 |
}; |
| 265 |
|
| 266 |
return ret; |
| 267 |
} |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
inline verify_func_t |
| 272 |
jwt_signature::get_verify_algorithm_impl(const jwt_header& hdr) const noexcept |
| 273 |
{ |
| 274 |
verify_func_t ret = nullptr; |
| 275 |
|
| 276 |
switch (hdr.algo()) { |
| 277 |
case algorithm::HS256: |
| 278 |
ret = HMACSign<algo::HS256>::verify; |
| 279 |
break; |
| 280 |
case algorithm::HS384: |
| 281 |
ret = HMACSign<algo::HS384>::verify; |
| 282 |
break; |
| 283 |
case algorithm::HS512: |
| 284 |
ret = HMACSign<algo::HS512>::verify; |
| 285 |
break; |
| 286 |
case algorithm::NONE: |
| 287 |
ret = HMACSign<algo::NONE>::verify; |
| 288 |
break; |
| 289 |
case algorithm::RS256: |
| 290 |
ret = PEMSign<algo::RS256>::verify; |
| 291 |
break; |
| 292 |
case algorithm::RS384: |
| 293 |
ret = PEMSign<algo::RS384>::verify; |
| 294 |
break; |
| 295 |
case algorithm::RS512: |
| 296 |
ret = PEMSign<algo::RS512>::verify; |
| 297 |
break; |
| 298 |
case algorithm::ES256: |
| 299 |
ret = PEMSign<algo::ES256>::verify; |
| 300 |
break; |
| 301 |
case algorithm::ES384: |
| 302 |
ret = PEMSign<algo::ES384>::verify; |
| 303 |
break; |
| 304 |
case algorithm::ES512: |
| 305 |
ret = PEMSign<algo::ES512>::verify; |
| 306 |
break; |
| 307 |
default: |
| 308 |
assert (0 && "Code not reached"); |
| 309 |
}; |
| 310 |
|
| 311 |
return ret; |
| 312 |
} |
| 313 |
|
| 314 |
|
| 315 |
// |
| 316 |
template <typename First, typename... Rest, |
| 317 |
typename SFINAE_COND> |
| 318 |
jwt_object::jwt_object( |
| 319 |
First&& first, Rest&&... rest) |
| 320 |
{ |
| 321 |
static_assert (detail::meta::is_parameter_concept<First>::value && |
| 322 |
detail::meta::are_all_params<Rest...>::value, |
| 323 |
"All constructor argument types must model ParameterConcept"); |
| 324 |
|
| 325 |
set_parameters(std::forward<First>(first), std::forward<Rest>(rest)...); |
| 326 |
} |
| 327 |
|
| 328 |
template <typename Map, typename... Rest> |
| 329 |
void jwt_object::set_parameters( |
| 330 |
params::detail::payload_param<Map>&& payload, Rest&&... rargs) |
| 331 |
{ |
| 332 |
for (const auto& elem : payload.get()) { |
| 333 |
payload_.add_claim(std::move(elem.first), std::move(elem.second)); |
| 334 |
} |
| 335 |
set_parameters(std::forward<Rest>(rargs)...); |
| 336 |
} |
| 337 |
|
| 338 |
template <typename... Rest> |
| 339 |
void jwt_object::set_parameters( |
| 340 |
params::detail::secret_param secret, Rest&&... rargs) |
| 341 |
{ |
| 342 |
secret_.assign(secret.get().data(), secret.get().length()); |
| 343 |
set_parameters(std::forward<Rest>(rargs)...); |
| 344 |
} |
| 345 |
|
| 346 |
template <typename... Rest> |
| 347 |
void jwt_object::set_parameters( |
| 348 |
params::detail::algorithm_param alg, Rest&&... rargs) |
| 349 |
{ |
| 350 |
header_.algo(alg.get()); |
| 351 |
set_parameters(std::forward<Rest>(rargs)...); |
| 352 |
} |
| 353 |
|
| 354 |
template <typename Map, typename... Rest> |
| 355 |
void jwt_object::set_parameters( |
| 356 |
params::detail::headers_param<Map>&& header, Rest&&... rargs) |
| 357 |
{ |
| 358 |
for (const auto& elem : header.get()) { |
| 359 |
header_.add_header(std::move(elem.first), std::move(elem.second)); |
| 360 |
} |
| 361 |
|
| 362 |
set_parameters(std::forward<Rest>(rargs)...); |
| 363 |
} |
| 364 |
|
| 365 |
inline void jwt_object::set_parameters() |
| 366 |
{ |
| 367 |
//sentinel call |
| 368 |
return; |
| 369 |
} |
| 370 |
|
| 371 |
inline jwt_object& jwt_object::add_claim(const jwt::string_view name, system_time_t tp) |
| 372 |
{ |
| 373 |
return add_claim( |
| 374 |
name, |
| 375 |
std::chrono::duration_cast< |
| 376 |
std::chrono::seconds>(tp.time_since_epoch()).count() |
| 377 |
); |
| 378 |
} |
| 379 |
|
| 380 |
inline jwt_object& jwt_object::remove_claim(const jwt::string_view name) |
| 381 |
{ |
| 382 |
payload_.remove_claim(name); |
| 383 |
return *this; |
| 384 |
} |
| 385 |
|
| 386 |
inline std::string jwt_object::signature(std::error_code& ec) const |
| 387 |
{ |
| 388 |
ec.clear(); |
| 389 |
|
| 390 |
//key/secret should be set for any algorithm except NONE |
| 391 |
if (header().algo() != jwt::algorithm::NONE) { |
| 392 |
if (secret_.length() == 0) { |
| 393 |
ec = AlgorithmErrc::KeyNotFoundErr; |
| 394 |
return {}; |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
jwt_signature jws{secret_}; |
| 399 |
return jws.encode(header_, payload_, ec); |
| 400 |
} |
| 401 |
|
| 402 |
inline std::string jwt_object::signature() const |
| 403 |
{ |
| 404 |
std::error_code ec; |
| 405 |
std::string res = signature(ec); |
| 406 |
if (ec) { |
| 407 |
throw SigningError(ec.message()); |
| 408 |
} |
| 409 |
return res; |
| 410 |
} |
| 411 |
|
| 412 |
template <typename Params, typename SequenceT> |
| 413 |
std::error_code jwt_object::verify( |
| 414 |
const Params& dparams, |
| 415 |
const params::detail::algorithms_param<SequenceT>& algos) const |
| 416 |
{ |
| 417 |
std::error_code ec{}; |
| 418 |
|
| 419 |
//Verify if the algorithm set in the header |
| 420 |
//is any of the one expected by the client. |
| 421 |
auto fitr = std::find_if(algos.get().begin(), |
| 422 |
algos.get().end(), |
| 423 |
[this](const auto& elem) |
| 424 |
{ |
| 425 |
return jwt::str_to_alg(elem) == this->header().algo(); |
| 426 |
}); |
| 427 |
|
| 428 |
if (fitr == algos.get().end()) { |
| 429 |
ec = VerificationErrc::InvalidAlgorithm; |
| 430 |
return ec; |
| 431 |
} |
| 432 |
|
| 433 |
//Check for the expiry timings |
| 434 |
if (has_claim(registered_claims::expiration)) { |
| 435 |
auto curr_time = |
| 436 |
std::chrono::duration_cast< |
| 437 |
std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); |
| 438 |
|
| 439 |
auto p_exp = payload() |
| 440 |
.get_claim_value<uint64_t>(registered_claims::expiration); |
| 441 |
|
| 442 |
if (static_cast<uint64_t>(curr_time) > static_cast<uint64_t>(p_exp + dparams.leeway)) { |
| 443 |
ec = VerificationErrc::TokenExpired; |
| 444 |
return ec; |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
//Check for issuer |
| 449 |
if (dparams.has_issuer) |
| 450 |
{ |
| 451 |
if (has_claim(registered_claims::issuer)) |
| 452 |
{ |
| 453 |
const std::string& p_issuer = payload() |
| 454 |
.get_claim_value<std::string>(registered_claims::issuer); |
| 455 |
|
| 456 |
if (p_issuer != dparams.issuer) { |
| 457 |
ec = VerificationErrc::InvalidIssuer; |
| 458 |
return ec; |
| 459 |
} |
| 460 |
} else { |
| 461 |
ec = VerificationErrc::InvalidIssuer; |
| 462 |
return ec; |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
//Check for audience |
| 467 |
if (dparams.has_aud) |
| 468 |
{ |
| 469 |
if (has_claim(registered_claims::audience)) |
| 470 |
{ |
| 471 |
const std::string& p_aud = payload() |
| 472 |
.get_claim_value<std::string>(registered_claims::audience); |
| 473 |
|
| 474 |
if (p_aud != dparams.aud) { |
| 475 |
ec = VerificationErrc::InvalidAudience; |
| 476 |
return ec; |
| 477 |
} |
| 478 |
} else { |
| 479 |
ec = VerificationErrc::InvalidAudience; |
| 480 |
return ec; |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
//Check the subject |
| 485 |
if (dparams.has_sub) |
| 486 |
{ |
| 487 |
if (has_claim(registered_claims::subject)) |
| 488 |
{ |
| 489 |
const std::string& p_sub = payload() |
| 490 |
.get_claim_value<std::string>(registered_claims::subject); |
| 491 |
if (p_sub != dparams.sub) { |
| 492 |
ec = VerificationErrc::InvalidSubject; |
| 493 |
return ec; |
| 494 |
} |
| 495 |
} else { |
| 496 |
ec = VerificationErrc::InvalidSubject; |
| 497 |
return ec; |
| 498 |
} |
| 499 |
} |
| 500 |
|
| 501 |
//Check for NBF |
| 502 |
if (has_claim(registered_claims::not_before)) |
| 503 |
{ |
| 504 |
auto curr_time = |
| 505 |
std::chrono::duration_cast< |
| 506 |
std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); |
| 507 |
|
| 508 |
auto p_exp = payload() |
| 509 |
.get_claim_value<uint64_t>(registered_claims::not_before); |
| 510 |
|
| 511 |
if (static_cast<uint64_t>(p_exp - dparams.leeway) > static_cast<uint64_t>(curr_time)) { |
| 512 |
ec = VerificationErrc::ImmatureSignature; |
| 513 |
return ec; |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
//Check IAT validation |
| 518 |
if (dparams.validate_iat) { |
| 519 |
if (!has_claim(registered_claims::issued_at)) { |
| 520 |
ec = VerificationErrc::InvalidIAT; |
| 521 |
return ec; |
| 522 |
} else { |
| 523 |
// Will throw type conversion error |
| 524 |
auto val = payload() |
| 525 |
.get_claim_value<uint64_t>(registered_claims::issued_at); |
| 526 |
(void)val; |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
//Check JTI validation |
| 531 |
if (dparams.validate_jti) { |
| 532 |
if (!has_claim("jti")) { |
| 533 |
ec = VerificationErrc::InvalidJTI; |
| 534 |
return ec; |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
return ec; |
| 539 |
} |
| 540 |
|
| 541 |
|
| 542 |
inline std::array<jwt::string_view, 3> |
| 543 |
jwt_object::three_parts(const jwt::string_view enc_str) |
| 544 |
{ |
| 545 |
std::array<jwt::string_view, 3> result; |
| 546 |
|
| 547 |
size_t fpos = enc_str.find_first_of('.'); |
| 548 |
assert (fpos != jwt::string_view::npos); |
| 549 |
|
| 550 |
result[0] = jwt::string_view{&enc_str[0], fpos}; |
| 551 |
|
| 552 |
size_t spos = enc_str.find_first_of('.', fpos + 1); |
| 553 |
|
| 554 |
result[1] = jwt::string_view{&enc_str[fpos + 1], spos - fpos - 1}; |
| 555 |
|
| 556 |
if (spos + 1 != enc_str.length()) { |
| 557 |
result[2] = jwt::string_view{&enc_str[spos + 1], enc_str.length() - spos - 1}; |
| 558 |
} |
| 559 |
|
| 560 |
return result; |
| 561 |
} |
| 562 |
|
| 563 |
template <typename DecodeParams, typename... Rest> |
| 564 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_param s, Rest&&... args) |
| 565 |
{ |
| 566 |
dparams.secret.assign(s.get().data(), s.get().length()); |
| 567 |
dparams.has_secret = true; |
| 568 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 569 |
} |
| 570 |
|
| 571 |
template <typename DecodeParams, typename T, typename... Rest> |
| 572 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_function_param<T>&& s, Rest&&... args) |
| 573 |
{ |
| 574 |
dparams.secret = s.get(*dparams.payload_ptr); |
| 575 |
dparams.has_secret = true; |
| 576 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 577 |
} |
| 578 |
|
| 579 |
template <typename DecodeParams, typename... Rest> |
| 580 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args) |
| 581 |
{ |
| 582 |
dparams.leeway = l.get(); |
| 583 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 584 |
} |
| 585 |
|
| 586 |
template <typename DecodeParams, typename... Rest> |
| 587 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::verify_param v, Rest&&... args) |
| 588 |
{ |
| 589 |
dparams.verify = v.get(); |
| 590 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 591 |
} |
| 592 |
|
| 593 |
template <typename DecodeParams, typename... Rest> |
| 594 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::issuer_param i, Rest&&... args) |
| 595 |
{ |
| 596 |
dparams.issuer = std::move(i).get(); |
| 597 |
dparams.has_issuer = true; |
| 598 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 599 |
} |
| 600 |
|
| 601 |
template <typename DecodeParams, typename... Rest> |
| 602 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::audience_param a, Rest&&... args) |
| 603 |
{ |
| 604 |
dparams.aud = std::move(a).get(); |
| 605 |
dparams.has_aud = true; |
| 606 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 607 |
} |
| 608 |
|
| 609 |
template <typename DecodeParams, typename... Rest> |
| 610 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::subject_param s, Rest&&... args) |
| 611 |
{ |
| 612 |
dparams.sub = std::move(s).get(); |
| 613 |
dparams.has_sub = true; |
| 614 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 615 |
} |
| 616 |
|
| 617 |
template <typename DecodeParams, typename... Rest> |
| 618 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::validate_iat_param v, Rest&&... args) |
| 619 |
{ |
| 620 |
dparams.validate_iat = v.get(); |
| 621 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 622 |
} |
| 623 |
|
| 624 |
template <typename DecodeParams, typename... Rest> |
| 625 |
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::validate_jti_param v, Rest&&... args) |
| 626 |
{ |
| 627 |
dparams.validate_jti = v.get(); |
| 628 |
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...); |
| 629 |
} |
| 630 |
|
| 631 |
template <typename DecodeParams> |
| 632 |
void jwt_object::set_decode_params(DecodeParams& dparams) |
| 633 |
{ |
| 634 |
(void) dparams; // prevent -Wunused-parameter with gcc |
| 635 |
return; |
| 636 |
} |
| 637 |
|
| 638 |
//================================================================== |
| 639 |
|
| 640 |
template <typename SequenceT, typename... Args> |
| 641 |
jwt_object decode(const jwt::string_view enc_str, |
| 642 |
const params::detail::algorithms_param<SequenceT>& algos, |
| 643 |
std::error_code& ec, |
| 644 |
Args&&... args) |
| 645 |
{ |
| 646 |
ec.clear(); |
| 647 |
jwt_object obj; |
| 648 |
|
| 649 |
if (algos.get().size() == 0) { |
| 650 |
ec = DecodeErrc::EmptyAlgoList; |
| 651 |
return obj; |
| 652 |
} |
| 653 |
|
| 654 |
struct decode_params |
| 655 |
{ |
| 656 |
/// key to decode the JWS |
| 657 |
bool has_secret = false; |
| 658 |
std::string secret; |
| 659 |
|
| 660 |
/// Verify parameter. Defaulted to true. |
| 661 |
bool verify = true; |
| 662 |
|
| 663 |
/// Leeway parameter. Defaulted to zero seconds. |
| 664 |
uint32_t leeway = 0; |
| 665 |
|
| 666 |
///The issuer |
| 667 |
//TODO: optional type |
| 668 |
bool has_issuer = false; |
| 669 |
std::string issuer; |
| 670 |
|
| 671 |
///The audience |
| 672 |
//TODO: optional type |
| 673 |
bool has_aud = false; |
| 674 |
std::string aud; |
| 675 |
|
| 676 |
//The subject |
| 677 |
//TODO: optional type |
| 678 |
bool has_sub = false; |
| 679 |
std::string sub; |
| 680 |
|
| 681 |
//Validate IAT |
| 682 |
bool validate_iat = false; |
| 683 |
|
| 684 |
//Validate JTI |
| 685 |
bool validate_jti = false; |
| 686 |
const jwt_payload* payload_ptr = 0; |
| 687 |
}; |
| 688 |
|
| 689 |
decode_params dparams{}; |
| 690 |
|
| 691 |
|
| 692 |
//Signature must have atleast 2 dots |
| 693 |
auto dot_cnt = std::count_if(std::begin(enc_str), std::end(enc_str), |
| 694 |
[](char ch) { return ch == '.'; }); |
| 695 |
if (dot_cnt < 2) { |
| 696 |
ec = DecodeErrc::SignatureFormatError; |
| 697 |
return obj; |
| 698 |
} |
| 699 |
|
| 700 |
auto parts = jwt_object::three_parts(enc_str); |
| 701 |
|
| 702 |
//throws decode error |
| 703 |
jwt_header hdr{}; |
| 704 |
hdr.decode(parts[0], ec); |
| 705 |
if (ec) { |
| 706 |
return obj; |
| 707 |
} |
| 708 |
//obj.header(jwt_header{parts[0]}); |
| 709 |
obj.header(std::move(hdr)); |
| 710 |
|
| 711 |
//If the algorithm is not NONE, it must not |
| 712 |
//have more than two dots ('.') and the split |
| 713 |
//must result in three strings with some length. |
| 714 |
if (obj.header().algo() != jwt::algorithm::NONE) { |
| 715 |
if (dot_cnt > 2) { |
| 716 |
ec = DecodeErrc::SignatureFormatError; |
| 717 |
return obj; |
| 718 |
} |
| 719 |
if (parts[2].length() == 0) { |
| 720 |
ec = DecodeErrc::SignatureFormatError; |
| 721 |
return obj; |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
//throws decode error |
| 726 |
jwt_payload payload{}; |
| 727 |
payload.decode(parts[1], ec); |
| 728 |
if (ec) { |
| 729 |
return obj; |
| 730 |
} |
| 731 |
obj.payload(std::move(payload)); |
| 732 |
dparams.payload_ptr = & obj.payload(); |
| 733 |
jwt_object::set_decode_params(dparams, std::forward<Args>(args)...); |
| 734 |
if (dparams.verify) { |
| 735 |
try { |
| 736 |
ec = obj.verify(dparams, algos); |
| 737 |
} catch (const json_ns::detail::type_error&) { |
| 738 |
ec = VerificationErrc::TypeConversionError; |
| 739 |
} |
| 740 |
|
| 741 |
if (ec) return obj; |
| 742 |
|
| 743 |
//Verify the signature only if some algorithm was used |
| 744 |
if (obj.header().algo() != algorithm::NONE) |
| 745 |
{ |
| 746 |
if (!dparams.has_secret) { |
| 747 |
ec = DecodeErrc::KeyNotPresent; |
| 748 |
return obj; |
| 749 |
} |
| 750 |
jwt_signature jsign{dparams.secret}; |
| 751 |
|
| 752 |
// Length of the encoded header and payload only. |
| 753 |
// Addition of '1' to account for the '.' character. |
| 754 |
auto l = parts[0].length() + 1 + parts[1].length(); |
| 755 |
|
| 756 |
//MemoryAllocationError is not caught |
| 757 |
verify_result_t res = jsign.verify(obj.header(), enc_str.substr(0, l), parts[2]); |
| 758 |
if (res.second) { |
| 759 |
ec = res.second; |
| 760 |
return obj; |
| 761 |
} |
| 762 |
|
| 763 |
if (!res.first) { |
| 764 |
ec = VerificationErrc::InvalidSignature; |
| 765 |
return obj; |
| 766 |
} |
| 767 |
} else { |
| 768 |
ec = AlgorithmErrc::NoneAlgorithmUsed; |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
return obj; |
| 773 |
} |
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
template <typename SequenceT, typename... Args> |
| 778 |
jwt_object decode(const jwt::string_view enc_str, |
| 779 |
const params::detail::algorithms_param<SequenceT>& algos, |
| 780 |
Args&&... args) |
| 781 |
{ |
| 782 |
std::error_code ec{}; |
| 783 |
auto jwt_obj = decode(enc_str, |
| 784 |
algos, |
| 785 |
ec, |
| 786 |
std::forward<Args>(args)...); |
| 787 |
|
| 788 |
if (ec) { |
| 789 |
jwt_throw_exception(ec); |
| 790 |
} |
| 791 |
|
| 792 |
return jwt_obj; |
| 793 |
} |
| 794 |
|
| 795 |
|
| 796 |
void jwt_throw_exception(const std::error_code& ec) |
| 797 |
{ |
| 798 |
const auto& cat = ec.category(); |
| 799 |
|
| 800 |
if (&cat == &theVerificationErrorCategory || |
| 801 |
std::string(cat.name()) == std::string(theVerificationErrorCategory.name())) |
| 802 |
{ |
| 803 |
switch (static_cast<VerificationErrc>(ec.value())) |
| 804 |
{ |
| 805 |
case VerificationErrc::InvalidAlgorithm: |
| 806 |
{ |
| 807 |
throw InvalidAlgorithmError(ec.message()); |
| 808 |
} |
| 809 |
case VerificationErrc::TokenExpired: |
| 810 |
{ |
| 811 |
throw TokenExpiredError(ec.message()); |
| 812 |
} |
| 813 |
case VerificationErrc::InvalidIssuer: |
| 814 |
{ |
| 815 |
throw InvalidIssuerError(ec.message()); |
| 816 |
} |
| 817 |
case VerificationErrc::InvalidAudience: |
| 818 |
{ |
| 819 |
throw InvalidAudienceError(ec.message()); |
| 820 |
} |
| 821 |
case VerificationErrc::InvalidSubject: |
| 822 |
{ |
| 823 |
throw InvalidSubjectError(ec.message()); |
| 824 |
} |
| 825 |
case VerificationErrc::InvalidIAT: |
| 826 |
{ |
| 827 |
throw InvalidIATError(ec.message()); |
| 828 |
} |
| 829 |
case VerificationErrc::InvalidJTI: |
| 830 |
{ |
| 831 |
throw InvalidJTIError(ec.message()); |
| 832 |
} |
| 833 |
case VerificationErrc::ImmatureSignature: |
| 834 |
{ |
| 835 |
throw ImmatureSignatureError(ec.message()); |
| 836 |
} |
| 837 |
case VerificationErrc::InvalidSignature: |
| 838 |
{ |
| 839 |
throw InvalidSignatureError(ec.message()); |
| 840 |
} |
| 841 |
case VerificationErrc::TypeConversionError: |
| 842 |
{ |
| 843 |
throw TypeConversionError(ec.message()); |
| 844 |
} |
| 845 |
default: |
| 846 |
assert (0 && "Unknown error code"); |
| 847 |
}; |
| 848 |
} |
| 849 |
|
| 850 |
if (&cat == &theDecodeErrorCategory || |
| 851 |
std::string(cat.name()) == std::string(theDecodeErrorCategory.name())) |
| 852 |
{ |
| 853 |
switch (static_cast<DecodeErrc>(ec.value())) |
| 854 |
{ |
| 855 |
case DecodeErrc::SignatureFormatError: |
| 856 |
{ |
| 857 |
throw SignatureFormatError(ec.message()); |
| 858 |
} |
| 859 |
case DecodeErrc::KeyNotPresent: |
| 860 |
{ |
| 861 |
throw KeyNotPresentError(ec.message()); |
| 862 |
} |
| 863 |
case DecodeErrc::KeyNotRequiredForNoneAlg: |
| 864 |
{ |
| 865 |
// Not an error. Just to be ignored. |
| 866 |
break; |
| 867 |
} |
| 868 |
default: |
| 869 |
{ |
| 870 |
throw DecodeError(ec.message()); |
| 871 |
} |
| 872 |
}; |
| 873 |
|
| 874 |
assert (0 && "Unknown error code"); |
| 875 |
} |
| 876 |
|
| 877 |
if (&cat == &theAlgorithmErrCategory || |
| 878 |
std::string(cat.name()) == std::string(theAlgorithmErrCategory.name())) |
| 879 |
{ |
| 880 |
switch (static_cast<AlgorithmErrc>(ec.value())) |
| 881 |
{ |
| 882 |
case AlgorithmErrc::InvalidKeyErr: |
| 883 |
{ |
| 884 |
throw InvalidKeyError(ec.message()); |
| 885 |
} |
| 886 |
case AlgorithmErrc::VerificationErr: |
| 887 |
{ |
| 888 |
throw InvalidSignatureError(ec.message()); |
| 889 |
} |
| 890 |
case AlgorithmErrc::NoneAlgorithmUsed: |
| 891 |
{ |
| 892 |
//Not an error actually. |
| 893 |
break; |
| 894 |
} |
| 895 |
default: |
| 896 |
assert (0 && "Unknown error code or not to be treated as an error"); |
| 897 |
}; |
| 898 |
} |
| 899 |
return; |
| 900 |
} |
| 901 |
|
| 902 |
} // END namespace jwt |
| 903 |
|
| 904 |
|
| 905 |
#endif |