Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

C++ How to validate Google JWT (RS256) using OpenSSL

I am trying to validate a JWT token using OpenSSL and c++.

As an exercise for experimentation and learning, please do not suggest to use 3rd party libraries to do the job.

The token has the usual form Header.Payload.Signature that I can Base64URL decode but I am not able to validate the signature.

Following the RFC does not mention how to procceed with RS256:

Validate the JWS Signature against the JWS Signing Input ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload)) in the manner defined for the algorithm being used, which MUST be accurately represented by the value of the "alg" (algorithm) Header Parameter, which MUST be present.

I am following JWT: The Complete Guide to JSON Web Tokens:

How does the receiver check RS256 Signatures? The receiver of the JWT will then:

  • take the header and the payload, and hash everything with SHA-256
  • decrypt the signature using the public key, and obtain the signature hash
  • the receiver compares the signature hash with the hash that he calculated himself based on the Header and the Payload

Do the two hashes match? Then this proves that the JWT was indeed created by the Authentication server!

When decoding the header using Base64Url I got a valid JSON. Payload is also valid JSON:

{"alg":"RS256","kid":"03b2d22c2fecf873ed19e5b8cf704afb7e2ed4be","typ":"JWT"}

Then I recovered the proper certificate from Google for the given kid.

My test code is:

// Split fields for convenience
static std::string GTOKEN_B64URL_HEADER ("eyJhb...shortened...V1QifQ");
static std::string GTOKEN_B64URL_PAYLOAD("eyJpc...shortened...MzExfQ");
static std::string GTOKEN_B64URL_SIGN   ("k7Ppq...shortened...TJCTdQ");

// From https://www.googleapis.com/oauth2/v1/certs using the specified "kid"
static const char* CERT =
        "-----BEGIN CERTIFICATE-----
"
        "MIIDJjCCAg6gAwIBAgIIHdBXKdu8rS4wDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UE
"
        ...
        "MB7mbimIU22061HCjFbdlEscy26X/BXtxPpQjEwbkzJ5wy2bVu2AIIdo
"
        "-----END CERTIFICATE-----
";

// Preparation: Get the public key from the PEM cert
//
BIO *memCert = BIO_new_mem_buf(CERT, -1);
X509* cert= PEM_read_bio_X509(memCert, nullptr, nullptr, nullptr);
if (nullptr == cert) {
    showOpenSSLErrors("Unable to load CERT: ");
    return;
}

EVP_PKEY* key = X509_get_pubkey(cert);
if (nullptr == key) {
    showOpenSSLErrors("Unable to get pubkey from cert: ");
    return;
}

int idKey = EVP_PKEY_id(key);
int type = EVP_PKEY_type(idKey);
if (type != EVP_PKEY_RSA && type != EVP_PKEY_RSA2) {
    std::cout << "Key type is not RSA" << std::endl;
    return;
}

RSA* rsa = EVP_PKEY_get1_RSA(key);
if (nullptr == rsa) {
    showOpenSSLErrors("Invalid RSA: ");
    return;
}

// 1) take the header and the payload, and hash everything with SHA-256
//
std::string whatToValidate;
computeHashSHA256(GTOKEN_B64URL_HEADER+"."+GTOKEN_B64URL_PAYLOAD, whatToValidate);

// 2) decrypt the signature using the public key ...
//
std::string signatureB64 = decodeBase64URL(GTOKEN_B64URL_SIGN);

std::string signature;
signature.resize( RSA_size(rsa) );
int len = RSA_public_decrypt(
    signatureB64.size(),
    (unsigned char*)signatureB64.data(), 
    (unsigned char*)signature.data(),
    rsa, RSA_NO_PADDING);
if (len == -1) {
    std::cout << "Decrypt failed" << std::endl;
    return;
}

signature.resize(len);

// 2) ... and obtain the signature hash
std::string signatureHash;
computeHashSHA256(signature, signatureHash);

if (whatToValidate.size() != signatureHash.size()) {
    printf("Len does not match! (%d vs %d) 
", whatToValidate.size(), signatureHash.size());
    return;
}

std::cout << "whatToValidate: " << whatToValidate << std::endl;
std::cout << "signatureHash:  " << signatureHash << std::endl;

// 3) the receiver compares the signature hash with the hash that he
//    calculated himself based on the Header and the Payload
if (signatureHash != whatToValidate) {
    printf("    comparison FAILED!!!
");
}

// Extra check: Ensure SHA256 algorithm is working
//
const std::string decodedHeader(decodeBase64URL(GTOKEN_B64URL_HEADER));

std::string headerSHA256;
computeHashSHA256(decodedHeader, headerSHA256);

std::cout << "Header:         " << decodedHeader << std::endl;
std::cout << "Header SHA256:  " << headerSHA256 << std::endl;
std::cout << "Signature size: " << signature.size() << "(" << GTOKEN_B64URL_SIGN.size() << " base64Url)" << std::endl;
std::cout << "Validate:       " << whatToValidate.size() << std::endl;
std::cout << std::endl;

Output of this code is:

whatToValidate: d4981a11b8d9a686e7f9919cf7d6477c5e7c0e35fcd61133ad2fdb8cb845b49a
signatureHash:  e79eee72dcc4412601689f03c0c83e6958b87447172f5109bffebbc7f009c38d
    comparison FAILED!!!
Header:         {"alg":"RS256","kid":"03b2d22c2fecf873ed19e5b8cf704afb7e2ed4be","typ":"JWT"}
Header SHA256:  5b53315f0b0424c866ff364e9f7bd2f882c61e4460aa1f503c2abd1ad753426e
Signature size: 256(342 base64Url)
Validate:       64

Header SHA256 proves that computeHashSHA256() works as expected.

What am I doing wrong?

Is there any alternative approach I can use? (Also tried RSA_verify() with no luck since I do not really know how)


Edit

SHA256 for JWS Signing Input will be 32 bytes. whatToValidate (ASCII representation of SHA256) will be 64 bytes. signature is 256 bytes long.

Signature does not look like a SHA256 either raw or ASCII.

Hence the question: shall whatToValidate be the SHA256 on the JWS Signing Input?


Edit - Base64URL decoded Signature (Binary):

0x93 0xB3 0xE9 0xA8 0x40 0xBA 0x03 0xB8 0x26 0x5C 0x84 0x97 0xD0 0x66 0xA5 0xF2
0x21 0x90 0x34 0x77 0x03 0x79 0x61 0xEE 0x06 0xC4 0xCD 0x81 0x06 0x22 0x7B 0x59
0xF7 0x2B 0x13 0x5B 0xEC 0x21 0x29 0xD6 0x81 0xB5 0xE1 0x18 0x64 0xE7 0xB2 0x0E
0xE1 0xF6 0x8F 0xB5 0x39 0x98 0xF5 0x28 0x65 0xBC 0xB5 0x5D 0x02 0x0E 0x80 0x8B
0x07 0x7A 0xF0 0x14 0x57 0x6E 0xF6 0x2C 0x9D 0xEE 0x7A 0x2E 0x2D 0xA0 0x1C 0xFD
0xC6 0x45 0xBC 0xE3 0x60 0xA9 0x67 0x05 0x84 0x05 0xBA 0xDC 0x34 0xBC 0x97 0xF1
0x51 0x3E 0x30 0x73 0xEA 0x4D 0x4F 0xF1 0x33 0xE2 0x1C 0x44 0x8E 0x6F 0x3F 0x0B
0xE6 0x62 0xA8 0x9E 0xFE 0x27 0xB3 0xF3 0x41 0xFB 0x5C 0xA0 0xC1 0x06 0x6B 0x91
0x4A 0xA5 0x7C 0xB8 0x85 0xEF 0xB3 0xAE 0x28 0x1C 0xC1 0x74 0x91 0xBB 0xB8 0xF9
0xAD 0xB0 0x13 0x34 0x96 0x4C 0xBF 0x6C 0xD2 0x5A 0x55 0x0D 0x4C 0x2D 0x01 0xC7
0x8D 0xBF 0x4B 0x8E 0x9B 0x31 0xAB 0x2B 0x1B 0x9A 0x8F 0x7A 0x32 0xB5 0x91 0x52
0x7E 0xE7 0xA8 0x7F 0x49 0x3F 0xCF 0x2C 0xAA 0x9B 0xE3 0x11 0x08 0x20 0x4E 0x5D
0x68 0x2B 0x75 0xEB 0xB4 0xE7 0xDA 0x23 0xDA 0xE0 0xCD 0xF7 0xD9 0x0D 0x42 0x15
0x27 0x94 0x86 0xA3 0xCE 0xF5 0xAF 0xD0 0x38 0x32 0xD7 0x05 0xD2 0xB2 0xED 0x7E
0xEC 0xB1 0x3D 0x3C 0xFA 0xE8 0xA4 0x14 0xE1 0x67 0x0E 0x16 0xF5 0x57 0x3B 0xAA
0x84 0x31 0x02 0x3F 0x29 0x34 0x1D 0x68 0xCF 0x82 0x23 0x32 0x4C 0x90 0x93 0x75

Edit - Decrypted signature:

0x00 0x01 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff
0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff 0x00 0x30 0x31 0x30
0x0d 0x06 0x09 0x60 0x86 0x48 0x01 0x65 0x03 0x04 0x02 0x01 0x05 0x00 0x04 0x20
0xd4 0x98 0x1a 0x11 0xb8 0xd9 0xa6 0x86 0xe7 0xf9 0x91 0x9c 0xf7 0xd6 0x47 0x7c
0x5e 0x7c 0x0e 0x35 0xfc 0xd6 0x11 0x33 0xad 0x2f 0xdb 0x8c 0xb8 0x45 0xb4 0x9a
question from:https://stackoverflow.com/questions/66066864/c-how-to-validate-google-jwt-rs256-using-openssl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your primary issue is that you're computing a hash of the hash recovered when you call RSA_public_decrypt.

An RSA signature is just a hash of some data plus some extra info that gets run through the RSA algorithm. When you call RSA_public_decrypt it's that original hash+metadata that you'll recover; not the message that was originally signed. You're treating it like it's the original message that was signed and then computing its hash to compare against the JWT.

The second issue you'll run into is the fact that RSA signatures are padded out to the size of the key modulus before being fed into the RSA algorithm. That's why the output of RSA_public_decrypt is 256 bytes long even though the original hash was only 32 bytes long. The actual recovered hash is the last 32 bytes of the output.

Putting that all together, you need to do something like this:

// 1) Calculate the SHA256 hash of the base64urled header and payload
std::string to_validate = sha256raw(TOKEN_B64URL_HEADER + "." + TOKEN_B64URL_PAYLOAD);

// 2) decrypt the signature
std::string raw_signature = decodeBase64URL(TOKEN_B64URL_SIGNATURE);

std::string decrypted_signature(RSA_size(rsa), '');
int len = RSA_public_decrypt(
    raw_signature.size(),
    reinterpret_cast<unsigned char*>(raw_signature.data()),
    reinterpret_cast<unsigned char*>(decrypted_signature.data()),
    rsa,
    RSA_PKCS1_PADDING // Will verify that the padding is at least structurally correct
);
decrypted_signature.resize(len);

// 3) Extract the last 32 bytes to get the original message hash from the decrypted signature
std::string recovered_hash = decrypted_signature.substr(decrypted_signature.size() - to_validate.size())


// 4) Compare the recovered hash to the hash of the token
if (to_validate == recovered_hash) {
    std::cout << "Signature verified
";
} else {
    std::cout << "Signature validation failed
"
}

Note that this still isn't quite right. Part of the signature padding contains information about the type of hash that was applied to generate the signature (see RFC 8017 section 9.2). The correct way to do the final comparison is to generate the appropriate padding and append to_validate to the end of it rather than strip the padding off of decrypted_signature. OpenSSL doesn't provide a public function do do that however.

That's why you should use RSA_verify instead of fiddling with RSA_public_decrypt at all. It just calls RSA_public_decrypt internally, but it also does the comparison the correct way using a private function to generate the PKCS#1 header (RSA_public_decrypt with RSA_PKCS1_PADDING verifies the rest of the padding is correct). To do that, you would do something like this:

// 1) Calculate the SHA256 hash of the base64urled header and payload
std::string to_validate = sha256raw(TOKEN_B64URL_HEADER + "." + TOKEN_B64URL_PAYLOAD);

// 2) verify the signature
std::string raw_signature = decodeBase64URL(TOKEN_B64URL_SIGNATURE);
int verified = RSA_verify(
    NID_sha256,
    reinterpret_cast<unsigned char*>(to_validate.data()),
    to_validate.size(),
    reinterpret_cast<unsigned char*>(raw_signature.data()),
    raw_signature.size(),
    rsa
);

if (verified) {
    std::cout << "Signature verified
";
} else {
    std::cout << "Signature validation failed
"
}

See here for a live demo of both versions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...