thephpleague / oauth2-server

A spec compliant, secure by default PHP OAuth 2.0 Server
https://oauth2.thephpleague.com
MIT License
6.52k stars 1.12k forks source link

Validate key with openssl #1215

Closed eugene-borovov closed 3 years ago

eugene-borovov commented 3 years ago

Added key validation using phpseclib. RSA and EC keys are supported. In the future, I would like to make separate types for Public and Private keys to check this aspect as well.

Fixes #1214

Sephster commented 3 years ago

Is there a way to make this a non-BC change? If not, I think we'd need to target this for v9. Also would be good to do something when we encounter an exception. Thank you for this

Spomky commented 3 years ago

You don't need PHPSECLIB at all (which is a big fat dep from my POV). As openssl is already required, you just need to get the key details to ensure it is valid: https://www.php.net/manual/fr/function.openssl-pkey-get-details.php

eugene-borovov commented 3 years ago

I returned the RSA_KEY_PATTERN constant that the backward compatibility check passed.

eugene-borovov commented 3 years ago

Version of the key verification using OpenSSL. @Sephster , maybe we should try OpenSSL directly?

function isValidKey($contents, $passPhrase)
{
    $pkey = openssl_pkey_get_private($contents, $passPhrase) ?: openssl_pkey_get_public($contents);
    if ($pkey === false) {
        return false;
    }
    $details = openssl_pkey_get_details($pkey);

    return $details !== false && in_array(
        $details['type'] ?? -1,
        [OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_EC],
        true
    );
}
Spomky commented 3 years ago

Excellent!

Looks way more clear and efficient compared to pure PHP functions. Well done @eugene-borovov!

Sephster commented 3 years ago

Thank you @eugene-borovov - looks great. Happy to merge!