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
|
/*
Copyright (c) 2017 Arun Muralidharan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef CPP_JWT_ALGORITHM_HPP
#define CPP_JWT_ALGORITHM_HPP
/*!
* Most of the signing and verification code has been taken
* and modified for C++ specific use from the C implementation
* JWT library, libjwt.
* https://github.com/benmcollins/libjwt/tree/master/libjwt
*/
#include <cassert>
#include <memory>
#include <system_error>
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/ecdsa.h>
#include <openssl/buffer.h>
#include <openssl/opensslv.h>
#include "jwt/assertions.hpp"
#include "jwt/exceptions.hpp"
#include "jwt/string_view.hpp"
#include "jwt/error_codes.hpp"
#include "jwt/base64.hpp"
#include "jwt/config.hpp"
namespace jwt {
/// The result type of the signing function
using sign_result_t = std::pair<std::string, std::error_code>;
/// The result type of verification function
using verify_result_t = std::pair<bool, std::error_code>;
/// The function pointer type for the signing function
using sign_func_t = sign_result_t (*) (const jwt::string_view key,
const jwt::string_view data);
/// The function pointer type for the verifying function
using verify_func_t = verify_result_t (*) (const jwt::string_view key,
const jwt::string_view head,
const jwt::string_view jwt_sign);
namespace algo {
//Me: TODO: All these can be done using code generaion.
//Me: NO. NEVER. I hate Macros.
//Me: You can use templates too.
//Me: No. I would rather prefer explicit.
//Me: Ok. You win.
//Me: Same to you.
/**
* HS256 algorithm.
*/
struct HS256
{
const EVP_MD* operator()() noexcept
{
return EVP_sha256();
}
};
/**
* HS384 algorithm.
*/
struct HS384
{
const EVP_MD* operator()() noexcept
{
return EVP_sha384();
}
};
/**
* HS512 algorithm.
*/
struct HS512
{
const EVP_MD* operator()() noexcept
{
return EVP_sha512();
}
};
/**
* NONE algorithm.
*/
struct NONE
{
void operator()() noexcept
{
return;
}
};
/**
* RS256 algorithm.
*/
struct RS256
{
static const int type = EVP_PKEY_RSA;
const EVP_MD* operator()() noexcept
{
return EVP_sha256();
}
};
/**
* RS384 algorithm.
*/
struct RS384
{
static const int type = EVP_PKEY_RSA;
const EVP_MD* operator()() noexcept
{
return EVP_sha384();
}
};
/**
* RS512 algorithm.
*/
struct RS512
{
static const int type = EVP_PKEY_RSA;
const EVP_MD* operator()() noexcept
{
return EVP_sha512();
}
};
/**
* ES256 algorithm.
*/
struct ES256
{
static const int type = EVP_PKEY_EC;
const EVP_MD* operator()() noexcept
{
return EVP_sha256();
}
};
/**
* ES384 algorithm.
*/
struct ES384
{
static const int type = EVP_PKEY_EC;
const EVP_MD* operator()() noexcept
{
return EVP_sha384();
}
};
/**
* ES512 algorithm.
*/
struct ES512
{
static const int type = EVP_PKEY_EC;
const EVP_MD* operator()() noexcept
{
return EVP_sha512();
}
};
} //END Namespace algo
/**
* JWT signing algorithm types.
*/
enum class algorithm
{
NONE = 0,
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
ES512,
UNKN,
TERM,
};
/**
* Convert the algorithm enum class type to
* its stringified form.
*/
inline jwt::string_view alg_to_str(SCOPED_ENUM algorithm alg) noexcept
{
switch (alg) {
case algorithm::HS256: return "HS256";
case algorithm::HS384: return "HS384";
case algorithm::HS512: return "HS512";
case algorithm::RS256: return "RS256";
case algorithm::RS384: return "RS384";
case algorithm::RS512: return "RS512";
case algorithm::ES256: return "ES256";
case algorithm::ES384: return "ES384";
case algorithm::ES512: return "ES512";
case algorithm::TERM: return "TERM";
case algorithm::NONE: return "NONE";
case algorithm::UNKN: return "UNKN";
default: assert (0 && "Unknown Algorithm");
};
return "UNKN";
JWT_NOT_REACHED("Code not reached");
}
/**
* Convert stringified algorithm to enum class.
* The string comparison is case insesitive.
*/
inline SCOPED_ENUM algorithm str_to_alg(const jwt::string_view alg) noexcept
{
if (!alg.length()) return algorithm::UNKN;
if (!strcasecmp(alg.data(), "NONE")) return algorithm::NONE;
if (!strcasecmp(alg.data(), "HS256")) return algorithm::HS256;
if (!strcasecmp(alg.data(), "HS384")) return algorithm::HS384;
if (!strcasecmp(alg.data(), "HS512")) return algorithm::HS512;
if (!strcasecmp(alg.data(), "RS256")) return algorithm::RS256;
if (!strcasecmp(alg.data(), "RS384")) return algorithm::RS384;
if (!strcasecmp(alg.data(), "RS512")) return algorithm::RS512;
if (!strcasecmp(alg.data(), "ES256")) return algorithm::ES256;
if (!strcasecmp(alg.data(), "ES384")) return algorithm::ES384;
if (!strcasecmp(alg.data(), "ES512")) return algorithm::ES512;
return algorithm::UNKN;
JWT_NOT_REACHED("Code not reached");
}
/**
*/
inline void bio_deletor(BIO* ptr)
{
if (ptr) BIO_free_all(ptr);
}
/**
*/
inline void evp_md_ctx_deletor(EVP_MD_CTX* ptr)
{
if (ptr) EVP_MD_CTX_destroy(ptr);
}
/**
*/
inline void ec_key_deletor(EC_KEY* ptr)
{
if (ptr) EC_KEY_free(ptr);
}
/**
*/
inline void ec_sig_deletor(ECDSA_SIG* ptr)
{
if (ptr) ECDSA_SIG_free(ptr);
}
/**
*/
inline void ev_pkey_deletor(EVP_PKEY* ptr)
{
if (ptr) EVP_PKEY_free(ptr);
}
/// Useful typedefs
using bio_deletor_t = decltype(&bio_deletor);
using BIO_uptr = std::unique_ptr<BIO, bio_deletor_t>;
using evp_mdctx_deletor_t = decltype(&evp_md_ctx_deletor);
using EVP_MDCTX_uptr = std::unique_ptr<EVP_MD_CTX, evp_mdctx_deletor_t>;
using eckey_deletor_t = decltype(&ec_key_deletor);
using EC_KEY_uptr = std::unique_ptr<EC_KEY, eckey_deletor_t>;
using ecsig_deletor_t = decltype(&ec_sig_deletor);
using EC_SIG_uptr = std::unique_ptr<ECDSA_SIG, ecsig_deletor_t>;
using evpkey_deletor_t = decltype(&ev_pkey_deletor);
using EC_PKEY_uptr = std::unique_ptr<EVP_PKEY, evpkey_deletor_t>;
/**
* OpenSSL HMAC based signature and verfication.
*
* The template type `Hasher` takes the type representing
* the HMAC algorithm type from the `jwt::algo` namespace.
*
* The struct is specialized for NONE algorithm. See the
* details of that class as well.
*/
template <typename Hasher>
struct HMACSign
{
/// The type of Hashing algorithm
using hasher_type = Hasher;
/**
* Signs the input using the HMAC algorithm using the
* provided key.
*
* Arguments:
* @key : The secret/key to use for the signing.
* Cannot be empty string.
* @data : The data to be signed.
*
* Exceptions:
* Any allocation failure will result in jwt::MemoryAllocationException
* being thrown.
*/
static sign_result_t sign(const jwt::string_view key, const jwt::string_view data)
{
std::string sign;
sign.resize(EVP_MAX_MD_SIZE);
std::error_code ec{};
uint32_t len = 0;
unsigned char* res = HMAC(Hasher{}(),
key.data(),
static_cast<int>(key.length()),
reinterpret_cast<const unsigned char*>(data.data()),
data.length(),
reinterpret_cast<unsigned char*>(&sign[0]),
&len);
if (!res) {
ec = AlgorithmErrc::SigningErr;
}
sign.resize(len);
return { std::move(sign), ec };
}
/**
* Verifies the JWT string against the signature using
* the provided key.
*
* Arguments:
* @key : The secret/key to use for the signing.
* Cannot be empty string.
* @head : The part of JWT encoded string representing header
* and the payload claims.
* @sign : The signature part of the JWT encoded string.
*
* Returns:
* verify_result_t
* verify_result_t::first set to true if verification succeeds.
* false otherwise.
* verify_result_t::second set to relevant error if verification fails.
*
* Exceptions:
* Any allocation failure will result in jwt::MemoryAllocationException
* being thrown.
*/
static verify_result_t
verify(const jwt::string_view key, const jwt::string_view head, const jwt::string_view sign);
};
/**
* Specialization of `HMACSign` class
* for NONE algorithm.
*
* This specialization is selected for even
* PEM based algorithms.
*
* The signing and verification APIs are
* basically no-op except that they would
* set the relevant error code.
*
* NOTE: error_code would be set in the case
* of usage of NONE algorithm.
* Users of this API are expected to check for
* the case explicitly.
*/
template <>
struct HMACSign<algo::NONE>
{
using hasher_type = algo::NONE;
/**
* Basically a no-op. Sets the error code to NoneAlgorithmUsed.
*/
static sign_result_t sign(const jwt::string_view key, const jwt::string_view data)
{
(void)key;
(void)data;
std::error_code ec{};
ec = AlgorithmErrc::NoneAlgorithmUsed;
return { std::string{}, ec };
}
/**
* Basically a no-op. Sets the error code to NoneAlgorithmUsed.
*/
static verify_result_t
verify(const jwt::string_view key, const jwt::string_view head, const jwt::string_view sign)
{
(void)key;
(void)head;
(void)sign;
std::error_code ec{};
ec = AlgorithmErrc::NoneAlgorithmUsed;
return { true, ec };
}
};
/**
* OpenSSL PEM based signature and verfication.
*
* The template type `Hasher` takes the type representing
* the PEM algorithm type from the `jwt::algo` namespace.
*
* For NONE algorithm, HMACSign<> specialization is used.
* See that for more details.
*/
template <typename Hasher>
struct PEMSign
{
public:
/// The type of Hashing algorithm
using hasher_type = Hasher;
/**
* Signs the input data using PEM encryption algorithm.
*
* Arguments:
* @key : The key/secret to be used for signing.
* Cannot be an empty string.
* @data: The data to be signed.
*
* Exceptions:
* Any allocation failure would be thrown out as
* jwt::MemoryAllocationException.
*/
static sign_result_t sign(const jwt::string_view key, const jwt::string_view data)
{
std::error_code ec{};
std::string ii{data.data(), data.length()};
EC_PKEY_uptr pkey{load_key(key, ec), ev_pkey_deletor};
if (ec) return { std::string{}, ec };
//TODO: Use stack string here ?
std::string sign = evp_digest(pkey.get(), data, ec);
if (ec) return { std::string{}, ec };
if (Hasher::type == EVP_PKEY_EC) {
sign = public_key_ser(pkey.get(), sign, ec);
}
return { std::move(sign), ec };
}
/**
*/
static verify_result_t
verify(const jwt::string_view key, const jwt::string_view head, const jwt::string_view sign);
private:
/*!
*/
static EVP_PKEY* load_key(const jwt::string_view key, std::error_code& ec);
/*!
*/
static std::string evp_digest(EVP_PKEY* pkey, const jwt::string_view data, std::error_code& ec);
/*!
*/
static std::string public_key_ser(EVP_PKEY* pkey, jwt::string_view sign, std::error_code& ec);
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L
//ATTN: Below 2 functions
//are Taken from https://github.com/nginnever/zogminer/issues/39
/**
*/
static void ECDSA_SIG_get0(const ECDSA_SIG* sig, const BIGNUM** pr, const BIGNUM** ps)
{
if (pr != nullptr) *pr = sig->r;
if (ps != nullptr) *ps = sig->s;
};
/**
*/
static int ECDSA_SIG_set0(ECDSA_SIG* sig, BIGNUM* r, BIGNUM* s)
{
if (r == nullptr || s == nullptr) return 0;
BN_clear_free(sig->r);
BN_clear_free(sig->s);
sig->r = r;
sig->s = s;
return 1;
}
#endif
};
} // END namespace jwt
#include "jwt/impl/algorithm.ipp"
#endif
|