Passed
Push — master ( d35d41...ea9798 )
by Tim
02:36
created

HTTPRedirect::parseQuery()   B

Complexity

Conditions 10
Paths 24

Size

Total Lines 50
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 30
c 0
b 0
f 0
nc 24
nop 0
dl 0
loc 50
rs 7.6666

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
declare(strict_types=1);
4
5
namespace SimpleSAML\SAML2\Binding;
6
7
use Exception;
8
use Nyholm\Psr7\Response;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use SimpleSAML\Assert\Assert;
12
use SimpleSAML\SAML2\Binding;
13
use SimpleSAML\SAML2\Compat\ContainerSingleton;
14
use SimpleSAML\SAML2\Constants as C;
15
use SimpleSAML\SAML2\Exception\ProtocolViolationException;
16
use SimpleSAML\SAML2\Utils;
17
use SimpleSAML\SAML2\XML\samlp\AbstractMessage;
18
use SimpleSAML\SAML2\XML\samlp\AbstractRequest;
19
use SimpleSAML\SAML2\XML\samlp\MessageFactory;
20
use SimpleSAML\XML\DOMDocumentFactory;
21
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
22
use SimpleSAML\XMLSecurity\Exception\SignatureVerificationFailedException;
23
use SimpleSAML\XMLSecurity\TestUtils\PEMCertificatesMock;
24
25
use function array_key_exists;
26
use function base64_decode;
27
use function base64_encode;
28
use function gzdeflate;
29
use function gzinflate;
30
use function sprintf;
31
use function str_contains;
32
use function strlen;
33
use function urlencode;
34
35
/**
36
 * Class which implements the HTTP-Redirect binding.
37
 *
38
 * @package simplesamlphp/saml2
39
 */
40
class HTTPRedirect extends Binding
41
{
42
    /**
43
     * Create the redirect URL for a message.
44
     *
45
     * @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message The message.
46
     * @return string The URL the user should be redirected to in order to send a message.
47
     */
48
    public function getRedirectURL(AbstractMessage $message): string
49
    {
50
        if ($this->destination === null) {
51
            $destination = $message->getDestination();
52
            if ($destination === null) {
53
                throw new Exception('Cannot build a redirect URL, no destination set.');
54
            }
55
        } else {
56
            $destination = $this->destination;
57
        }
58
59
        $relayState = $this->getRelayState();
60
        $msgStr = $message->toXML();
61
62
        Utils::getContainer()->debugMessage($msgStr, 'out');
63
        $msgStr = $msgStr->ownerDocument?->saveXML($msgStr);
64
65
        $msgStr = gzdeflate($msgStr);
66
        $msgStr = base64_encode($msgStr);
67
68
        /* Build the query string. */
69
70
        if ($message instanceof AbstractRequest) {
71
            $msg = 'SAMLRequest=';
72
        } else {
73
            $msg = 'SAMLResponse=';
74
        }
75
        $msg .= urlencode($msgStr);
76
77
        if ($relayState !== null) {
78
            $msg .= '&RelayState=' . urlencode($relayState);
79
        }
80
81
        $signature = $message->getSignature();
82
        if ($signature !== null) { // add the signature
83
            $msg .= '&SigAlg=' . urlencode($signature->getSignedInfo()->getSignatureMethod()->getAlgorithm());
84
            $msg .= '&Signature=' . urlencode($signature->getSignatureValue()->getContent());
85
        }
86
87
        if (str_contains($destination, '?')) {
88
            $destination .= '&' . $msg;
89
        } else {
90
            $destination .= '?' . $msg;
91
        }
92
93
        return $destination;
94
    }
95
96
97
    /**
98
     * Send a SAML 2 message using the HTTP-Redirect binding.
99
     *
100
     * @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message
101
     * @return \Psr\Http\Message\ResponseInterface
102
     */
103
    public function send(AbstractMessage $message): ResponseInterface
104
    {
105
        $destination = $this->getRedirectURL($message);
106
        Utils::getContainer()->getLogger()->debug(
107
            'Redirect to ' . strlen($destination) . ' byte URL: ' . $destination,
108
        );
109
        return new Response(303, ['Location' => $destination]);
110
    }
111
112
113
    /**
114
     * Receive a SAML 2 message sent using the HTTP-Redirect binding.
115
     *
116
     * Throws an exception if it is unable receive the message.
117
     *
118
     * @param \Psr\Http\Message\ServerRequestInterface $request
119
     * @return \SimpleSAML\SAML2\XML\samlp\AbstractMessage The received message.
120
     * @throws \Exception
121
     *
122
     * NPath is currently too high but solving that just moves code around.
123
     */
124
    public function receive(ServerRequestInterface $request): AbstractMessage
125
    {
126
        $query = $request->getQueryParams();
127
128
        /**
129
         * Put the SAMLRequest/SAMLResponse from the actual query string into $message,
130
         * and assert that the result from parseQuery() in $query and the parsing of the SignedQuery in $res agree
131
         */
132
        if (array_key_exists('SAMLRequest', $query)) {
133
            $message = $query['SAMLRequest'];
134
            $signedQuery = 'SAMLRequest=' . urlencode($query['SAMLRequest']);
135
        } elseif (array_key_exists('SAMLResponse', $query)) {
136
            $message = $query['SAMLResponse'];
137
            $signedQuery = 'SAMLResponse=' . urlencode($query['SAMLResponse']);
138
        } else {
139
            throw new Exception('Missing SAMLRequest or SAMLResponse parameter.');
140
        }
141
142
        if (array_key_exists('SAMLRequest', $query) && array_key_exists('SAMLResponse', $query)) {
143
            throw new Exception('Both SAMLRequest and SAMLResponse provided.');
144
        }
145
146
        if (isset($query['SAMLEncoding']) && $query['SAMLEncoding'] !== C::BINDING_HTTP_REDIRECT_DEFLATE) {
147
            throw new Exception(sprintf('Unknown SAMLEncoding: %s', $query['SAMLEncoding']));
148
        }
149
150
        $message = base64_decode($message, true);
151
        if ($message === false) {
152
            throw new Exception('Error while base64 decoding SAML message.');
153
        }
154
155
        $message = gzinflate($message);
156
        if ($message === false) {
157
            throw new Exception('Error while inflating SAML message.');
158
        }
159
160
        $document = DOMDocumentFactory::fromString($message);
161
        Utils::getContainer()->debugMessage($document->documentElement, 'in');
162
        $message = MessageFactory::fromXML($document->documentElement);
163
164
        if (array_key_exists('RelayState', $query)) {
165
            $this->setRelayState($query['RelayState']);
166
            $signedQuery .= '&RelayState=' . urlencode($query['RelayState']);
167
        }
168
169
        if (!array_key_exists('Signature', $query)) {
170
            return $message;
171
        }
172
173
        /**
174
         * 3.4.5.2 - SAML Bindings
175
         *
176
         * If the message is signed, the Destination XML attribute in the root SAML element of the protocol
177
         * message MUST contain the URL to which the sender has instructed the user agent to deliver the
178
         * message.
179
         */
180
        Assert::notNull($message->getDestination(), ProtocolViolationException::class);
181
        // Validation of the Destination must be done upstream
182
183
        if (!array_key_exists('SigAlg', $query)) {
184
            throw new Exception('Missing signature algorithm.');
185
        } else {
186
            $signedQuery .= '&SigAlg=' . urlencode($query['SigAlg']);
187
        }
188
189
        $container = ContainerSingleton::getInstance();
190
        $blacklist = $container->getBlacklistedEncryptionAlgorithms();
191
        $verifier = (new SignatureAlgorithmFactory($blacklist))->getAlgorithm(
0 ignored issues
show
Bug introduced by
It seems like $blacklist can also be of type null; however, parameter $blacklist of SimpleSAML\XMLSecurity\A...mFactory::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

191
        $verifier = (new SignatureAlgorithmFactory(/** @scrutinizer ignore-type */ $blacklist))->getAlgorithm(
Loading history...
192
            $query['SigAlg'],
193
            // TODO:  Need to use the key from the metadata
194
            PEMCertificatesMock::getPublicKey(PEMCertificatesMock::SELFSIGNED_PUBLIC_KEY),
195
        );
196
197
        if ($verifier->verify($signedQuery, base64_decode($query['Signature'])) === false) {
198
            throw new SignatureVerificationFailedException('Failed to verify signature.');
199
        }
200
201
        return $message;
202
    }
203
}
204