Completed
Push — master ( 4b394d...0ca4f0 )
by Damien
09:55
created

SecurityHelper::getPemAlgorithm()   C

Complexity

Conditions 16
Paths 52

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 43
rs 5.5666
c 0
b 0
f 0
nc 52
cc 16
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace flipbox\saml\core\helpers;
4
5
use flipbox\saml\core\AbstractPlugin;
6
use RobRichards\XMLSecLibs\XMLSecurityKey;
7
use SAML2\EncryptedAssertion;
8
use SAML2\Utilities\Certificate;
9
10
class SecurityHelper
11
{
12
13
    const XMLDSIG_DIGEST_MD5 = 'http://www.w3.org/2001/04/xmldsig-more#md5';
14
15
    private static $typeMap = [
16
        'RSA-SHA1' => XMLSecurityKey::RSA_SHA1,
17
        'RSA-SHA256' => XMLSecurityKey::RSA_SHA256,
18
        'RSA-SHA384' => XMLSecurityKey::RSA_SHA384,
19
        'RSA-SHA512' => XMLSecurityKey::RSA_SHA512,
20
    ];
21
22
    public static $validEncryptionMethods = [
23
        XMLSecurityKey::TRIPLEDES_CBC,
24
        // Prefered
25
        XMLSecurityKey::AES128_CBC,
26
        XMLSecurityKey::AES192_CBC,
27
        XMLSecurityKey::AES256_CBC,
28
29
        XMLSecurityKey::RSA_1_5,
30
        XMLSecurityKey::RSA_OAEP_MGF1P,
31
    ];
32
33
    /**
34
     * @param string $certificate
35
     * @return string
36
     */
37
    public static function convertToCertificate(string $certificate)
38
    {
39
        return Certificate::convertToCertificate(
40
            static::cleanCertificate($certificate)
0 ignored issues
show
Bug introduced by
It seems like static::cleanCertificate($certificate) targeting flipbox\saml\core\helper...per::cleanCertificate() can also be of type array<integer,string> or null; however, SAML2\Utilities\Certific...:convertToCertificate() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
41
        );
42
    }
43
44
    /**
45
     * @param string $certificate
46
     * @return string|string[]|null
47
     */
48
    public static function cleanCertificate(string $certificate)
49
    {
50
        if (false == preg_match(Certificate::CERTIFICATE_PATTERN, $certificate, $matches)) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match(\SAML2\Utilit...$certificate, $matches) of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
51
            throw new \InvalidArgumentException('Invalid PEM encoded certificate');
52
        }
53
54
        return static::cleanCertificateWhiteSpace($matches[1]);
55
    }
56
57
    /**
58
     * @param string $certificate
59
     * @return string|string[]|null
60
     */
61
    public static function cleanCertificateWhiteSpace(string $certificate)
62
    {
63
        return preg_replace('/\s+/', '', $certificate);
64
    }
65
66
    /**
67
     * @param $pem
68
     * @return mixed|string|null
69
     * @throws \Exception
70
     * Thank you lightsaml/lightsaml
71
     */
72
    public static function getPemAlgorithm($pem)
73
    {
74
        $res = openssl_x509_read($pem);
75
        $info = openssl_x509_parse($res);
76
        $signatureAlgorithm = null;
77
        $signatureType = isset($info['signatureTypeSN']) ? $info['signatureTypeSN'] : '';
78
        if ($signatureType && isset(self::$typeMap[$signatureType])) {
79
            $signatureAlgorithm = self::$typeMap[$signatureType];
80
        } else {
81
            openssl_x509_export($res, $out, false);
82
            if (preg_match('/^\s+Signature Algorithm:\s*(.*)\s*$/m', $out, $match)) {
83
                switch ($match[1]) {
84
                    case 'sha1WithRSAEncryption':
85
                    case 'sha1WithRSA':
86
                        $signatureAlgorithm = XMLSecurityKey::RSA_SHA1;
87
                        break;
88
                    case 'sha256WithRSAEncryption':
89
                    case 'sha256WithRSA':
90
                        $signatureAlgorithm = XMLSecurityKey::RSA_SHA256;
91
                        break;
92
                    case 'sha384WithRSAEncryption':
93
                    case 'sha384WithRSA':
94
                        $signatureAlgorithm = XMLSecurityKey::RSA_SHA384;
95
                        break;
96
                    case 'sha512WithRSAEncryption':
97
                    case 'sha512WithRSA':
98
                        $signatureAlgorithm = XMLSecurityKey::RSA_SHA512;
99
                        break;
100
                    case 'md5WithRSAEncryption':
101
                    case 'md5WithRSA':
102
                        $signatureAlgorithm = static::XMLDSIG_DIGEST_MD5;
103
                        break;
104
                    default:
105
                }
106
            }
107
        }
108
109
        if (! $signatureAlgorithm) {
110
            throw new \Exception('Unrecognized signature algorithm');
111
        }
112
113
        return $signatureAlgorithm;
114
    }
115
116
    /**
117
     * @param EncryptedAssertion $encryptedAssertion
118
     * @param $pemString
119
     * @param array $blacklist
120
     * @return \SAML2\Assertion
121
     * @throws \Exception
122
     */
123
    public static function decryptAssertion(EncryptedAssertion $encryptedAssertion, $pemString, array $blacklist = [])
124
    {
125
126
        $lastException = null;
127
        foreach (static::$validEncryptionMethods as $method) {
128
129
            if (in_array($method, $blacklist)) {
130
                \Craft::debug('Decryption with key #' . $method . ' blacklisted.', AbstractPlugin::SAML_CORE_HANDLE);
131
                continue;
132
            }
133
            $xmlSecurityKey = new XMLSecurityKey($method, [
134
                'type' => 'public',
135
            ]);
136
137
            $xmlSecurityKey->loadKey(
138
                $pemString,
139
                false,
140
                true
141
            );
142
143
            try {
144
                $assertion = $encryptedAssertion->getAssertion(
145
                    $xmlSecurityKey
146
                );
147
                \Craft::debug('Decryption with key #' . $method . ' succeeded.', AbstractPlugin::SAML_CORE_HANDLE);
148
                return $assertion;
149
            } catch (\Exception $e) {
150
                $lastException = $e;
151
                \Craft::debug('Decryption with key #' . $method . ' failed.', AbstractPlugin::SAML_CORE_HANDLE);
152
            }
153
        }
154
155
        // Finally, throw it
156
        throw $lastException;
157
158
    }
159
160
}
161