/
HTTPRedirect.php
194 lines (164 loc) · 6.63 KB
/
HTTPRedirect.php
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
<?php
declare(strict_types=1);
namespace SimpleSAML\SAML2;
use DOMElement;
use Exception;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Compat\ContainerSingleton;
use SimpleSAML\SAML2\Constants as C;
use SimpleSAML\XMLSecurity\Exception\SignatureVerificationFailedException;
use SimpleSAML\SAML2\XML\samlp\AbstractMessage;
use SimpleSAML\SAML2\XML\samlp\AbstractRequest;
use SimpleSAML\SAML2\XML\samlp\MessageFactory;
use SimpleSAML\XML\DOMDocumentFactory;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PublicKey;
use SimpleSAML\XMLSecurity\TestUtils\PEMCertificatesMock;
use SimpleSAML\XMLSecurity\Utils\Security;
use function array_key_exists;
use function base64_decode;
use function base64_encode;
use function gzdeflate;
use function gzinflate;
use function sprintf;
use function strlen;
use function str_contains;
use function urlencode;
/**
* Class which implements the HTTP-Redirect binding.
*
* @package simplesamlphp/saml2
*/
class HTTPRedirect extends Binding
{
/**
* Create the redirect URL for a message.
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message The message.
* @return string The URL the user should be redirected to in order to send a message.
*/
public function getRedirectURL(AbstractMessage $message): string
{
if ($this->destination === null) {
$destination = $message->getDestination();
if ($destination === null) {
throw new Exception('Cannot build a redirect URL, no destination set.');
}
} else {
$destination = $this->destination;
}
$relayState = $message->getRelayState();
$msgStr = $message->toXML();
Utils::getContainer()->debugMessage($msgStr, 'out');
$msgStr = $msgStr->ownerDocument?->saveXML($msgStr);
$msgStr = gzdeflate($msgStr);
$msgStr = base64_encode($msgStr);
/* Build the query string. */
if ($message instanceof AbstractRequest) {
$msg = 'SAMLRequest=';
} else {
$msg = 'SAMLResponse=';
}
$msg .= urlencode($msgStr);
if ($relayState !== null) {
$msg .= '&RelayState=' . urlencode($relayState);
}
$signature = $message->getSignature();
if ($signature !== null) { // add the signature
$msg .= '&SigAlg=' . urlencode($signature->getSignedInfo()->getSignatureMethod()->getAlgorithm());
$msg .= '&Signature=' . urlencode($signature->getSignatureValue()->getContent());
}
if (str_contains($destination, '?')) {
$destination .= '&' . $msg;
} else {
$destination .= '?' . $msg;
}
return $destination;
}
/**
* Send a SAML 2 message using the HTTP-Redirect binding.
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message
* @return \Psr\Http\Message\ResponseInterface
*/
public function send(AbstractMessage $message): ResponseInterface
{
$destination = $this->getRedirectURL($message);
Utils::getContainer()->getLogger()->debug(
'Redirect to ' . strlen($destination) . ' byte URL: ' . $destination
);
return new Response(303, ['Location' => $destination]);
}
/**
* Receive a SAML 2 message sent using the HTTP-Redirect binding.
*
* Throws an exception if it is unable receive the message.
*
* @param \Psr\Http\Message\ServerRequestInterface $request
* @return \SimpleSAML\SAML2\XML\samlp\AbstractMessage The received message.
* @throws \Exception
*
* NPath is currently too high but solving that just moves code around.
*/
public function receive(ServerRequestInterface $request): AbstractMessage
{
$query = $request->getQueryParams();
if (array_key_exists('SAMLRequest', $query)) {
$message = $query['SAMLRequest'];
$signedQuery = 'SAMLRequest=' . urlencode($query['SAMLRequest']);
} elseif (array_key_exists('SAMLResponse', $query)) {
$message = $query['SAMLResponse'];
$signedQuery = 'SAMLResponse=' . urlencode($query['SAMLResponse']);
} else {
throw new Exception('Missing SAMLRequest or SAMLResponse parameter.');
}
if (isset($query['SAMLEncoding']) && $query['SAMLEncoding'] !== C::BINDING_HTTP_REDIRECT_DEFLATE) {
throw new Exception(sprintf('Unknown SAMLEncoding: %s', $query['SAMLEncoding']));
}
$message = base64_decode($message);
if ($message === false) {
throw new Exception('Error while base64 decoding SAML message.');
}
$message = gzinflate($message);
if ($message === false) {
throw new Exception('Error while inflating SAML message.');
}
$document = DOMDocumentFactory::fromString($message);
Utils::getContainer()->debugMessage($document->documentElement, 'in');
$message = MessageFactory::fromXML($document->documentElement);
if (array_key_exists('RelayState', $query)) {
$message->setRelayState($query['RelayState']);
$signedQuery .= '&RelayState=' . urlencode($query['RelayState']);
}
if (!array_key_exists('Signature', $query)) {
return $message;
}
/**
* 3.4.5.2 - SAML Bindings
*
* If the message is signed, the Destination XML attribute in the root SAML element of the protocol
* message MUST contain the URL to which the sender has instructed the user agent to deliver the
* message.
*/
Assert::notNull($message->getDestination()); // Validation of the value must be done upstream
if (!array_key_exists('SigAlg', $query)) {
throw new Exception('Missing signature algorithm.');
} else {
$signedQuery .= '&SigAlg=' . urlencode($query['SigAlg']);
}
$container = ContainerSingleton::getInstance();
$blacklist = $container->getBlacklistedEncryptionAlgorithms();
$verifier = (new SignatureAlgorithmFactory($blacklist))->getAlgorithm(
$query['SigAlg'],
// TODO: Need to use the key from the metadata
PEMCertificatesMock::getPublicKey(PEMCertificatesMock::SELFSIGNED_PUBLIC_KEY),
);
if ($verifier->verify($signedQuery, base64_decode($query['Signature'])) === false) {
throw new SignatureVerificationFailedException('Failed to verify signature.');
}
return $message;
}
}