forked from simplesamlphp/saml2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSOAPClient.php
More file actions
377 lines (323 loc) · 13.3 KB
/
Copy pathSOAPClient.php
File metadata and controls
377 lines (323 loc) · 13.3 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
declare(strict_types=1);
namespace SimpleSAML\SAML2;
use DOMDocument;
use Exception;
use OpenSSLAsymmetricKey;
use SimpleSAML\Configuration;
use SimpleSAML\SAML2\Compat\ContainerSingleton;
use SimpleSAML\SAML2\XML\samlp\AbstractMessage;
use SimpleSAML\SAML2\XML\samlp\MessageFactory;
use SimpleSAML\SOAP11\Utils\XPath;
use SimpleSAML\SOAP11\XML\Body;
use SimpleSAML\SOAP11\XML\Envelope;
use SimpleSAML\SOAP11\XML\Fault;
use SimpleSAML\Utils\Config;
use SimpleSAML\Utils\Crypto;
use SimpleSAML\XML\Chunk;
use SimpleSAML\XML\DOMDocumentFactory;
use SimpleSAML\XMLSchema\Type\AnyURIValue;
use SoapClient as BuiltinSoapClient;
use function chunk_split;
use function file_exists;
use function is_object;
use function is_string;
use function method_exists;
use function openssl_pkey_get_details;
use function openssl_pkey_get_public;
use function property_exists;
use function sha1;
use function sprintf;
use function stream_context_create;
use function stream_context_get_options;
use function trim;
/**
* Implementation of the SAML 2.0 SOAP binding.
*
* @package simplesamlphp/saml2
*/
class SOAPClient
{
/**
* This function sends the SOAP message to the service location and returns SOAP response
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $msg The request that should be sent.
* @param \SimpleSAML\Configuration $srcMetadata The metadata of the issuer of the message.
* @param \SimpleSAML\Configuration $dstMetadata The metadata of the destination of the message.
* @throws \Exception
* @return \SimpleSAML\SAML2\XML\samlp\AbstractMessage The response we received.
*/
public function send(
AbstractMessage $msg,
Configuration $srcMetadata,
?Configuration $dstMetadata = null,
): AbstractMessage {
$issuer = $msg->getIssuer();
$ctxOpts = [
'ssl' => [
'capture_peer_cert' => true,
'allow_self_signed' => true,
],
];
$container = ContainerSingleton::getInstance();
// Determine if we are going to do a MutualSSL connection between the IdP and SP - Shoaib
if ($srcMetadata->hasValue('saml.SOAPClient.certificate')) {
$cert = $srcMetadata->getValue('saml.SOAPClient.certificate');
if ($cert !== false) {
$configUtils = new Config();
$ctxOpts['ssl']['local_cert'] = $configUtils->getCertPath(
$srcMetadata->getString('saml.SOAPClient.certificate'),
);
if ($srcMetadata->hasValue('saml.SOAPClient.privatekey_pass')) {
$ctxOpts['ssl']['passphrase'] = $srcMetadata->getString('saml.SOAPClient.privatekey_pass');
}
}
} else {
/* Use the SP certificate and privatekey if it is configured. */
$cryptoUtils = new Crypto();
$privateKey = $cryptoUtils->loadPrivateKey($srcMetadata);
$publicKey = $cryptoUtils->loadPublicKey($srcMetadata);
if ($privateKey !== null && $publicKey !== null && isset($publicKey['PEM'])) {
$keyCertData = $privateKey['PEM'] . $publicKey['PEM'];
$file = $container->getTempDir() . '/' . sha1($keyCertData) . '.pem';
if (!file_exists($file)) {
$container->writeFile($file, $keyCertData);
}
$ctxOpts['ssl']['local_cert'] = $file;
if (isset($privateKey['password'])) {
$ctxOpts['ssl']['passphrase'] = $privateKey['password'];
}
}
}
// do peer certificate verification
if ($dstMetadata !== null) {
$peerPublicKeys = $dstMetadata->getPublicKeys('signing', true);
$certData = '';
foreach ($peerPublicKeys as $key) {
if ($key['type'] !== 'X509Certificate') {
continue;
}
$certData .= "-----BEGIN CERTIFICATE-----\n" .
chunk_split($key['X509Certificate'], 64) .
"-----END CERTIFICATE-----\n";
}
$peerCertFile = $container->getTempDir() . '/' . sha1($certData) . '.pem';
if (!file_exists($peerCertFile)) {
$container->writeFile($peerCertFile, $certData);
}
// create ssl context
$ctxOpts['ssl']['verify_peer'] = true;
$ctxOpts['ssl']['verify_depth'] = 1;
$ctxOpts['ssl']['cafile'] = $peerCertFile;
}
if ($srcMetadata->hasValue('saml.SOAPClient.stream_context.ssl.peer_name')) {
$ctxOpts['ssl']['peer_name'] = $srcMetadata->getString('saml.SOAPClient.stream_context.ssl.peer_name');
}
$context = stream_context_create($ctxOpts);
$options = [
'uri' => $issuer?->getContent(),
'location' => $msg->getDestination(),
'stream_context' => $context,
];
if ($srcMetadata->hasValue('saml.SOAPClient.proxyhost')) {
$options['proxy_host'] = $srcMetadata->getValue('saml.SOAPClient.proxyhost');
}
if ($srcMetadata->hasValue('saml.SOAPClient.proxyport')) {
$options['proxy_port'] = $srcMetadata->getValue('saml.SOAPClient.proxyport');
}
$destination = $msg->getDestination();
if ($destination === null) {
throw new Exception('Cannot send SOAP message, no destination set.');
}
// Add soap-envelopes
$env = (new Envelope(new Body([new Chunk($msg->toXML())])))->toXML();
$request = $env->ownerDocument?->saveXML();
$container->debugMessage($request, 'out');
$action = 'http://www.oasis-open.org/committees/security';
/* Perform SOAP Request over HTTP */
$x = $this->createSoapClient($options);
$soapresponsexml = $this->doSoapRequest($x, $request, $destination, $action);
if (empty($soapresponsexml)) {
throw new Exception('Empty SOAP response, check peer certificate.');
}
Utils::getContainer()->debugMessage($soapresponsexml, 'in');
$dom = DOMDocumentFactory::fromString($soapresponsexml);
$env = Envelope::fromXML($dom->documentElement);
$container->debugMessage($env->toXML()->ownerDocument?->saveXML(), 'in');
$soapfault = $this->getSOAPFault($dom);
if ($soapfault !== null) {
throw new Exception(
sprintf(
"Actor: '%s'; Message: '%s'; Code: '%s'",
$soapfault->getFaultActor()?->getContent(),
$soapfault->getFaultString()->getContent(),
$soapfault->getFaultCode()->getContent(),
),
);
}
// Extract the message from the response
/** @var \SimpleSAML\XML\SerializableElementInterface[] $messages */
$messages = $env->getBody()->getElements();
$samlresponse = MessageFactory::fromXML($messages[0]->toXML());
/* Add validator to message which uses the SSL context. */
self::addSSLValidator($samlresponse, $context);
$container->getLogger()->debug("Valid ArtifactResponse received from IdP");
return $samlresponse;
}
/**
* Factory method to create the built-in SoapClient. Overridable for testing.
*
* @param array $options
* @return \SoapClient
*/
protected function createSoapClient(array $options): BuiltinSoapClient
{
return new BuiltinSoapClient(null, $options);
}
/**
* Wrapper around __doRequest(), overridable for testing.
*
* NOTE: $destination is a generic xs:anyURI value (XMLSchema), since the SOAP endpoint URI
* is transport-level and not necessarily subject to SAML-layer URI restrictions.
*
* @param \SoapClient $client
* @param string|null $request
* @param \SimpleSAML\XMLSchema\Type\AnyURIValue $destination
* @param string $action
* @return string
*/
protected function doSoapRequest(
BuiltinSoapClient $client,
?string $request,
AnyURIValue $destination,
string $action,
): string {
return (string) $client->__doRequest(
$request,
(string) $destination,
$action,
SOAP_1_1,
);
}
/**
* Add a signature validator based on a SSL context.
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $msg The message we should add a validator to.
* @param resource $context The stream context.
*/
private static function addSSLValidator(AbstractMessage $msg, $context): void
{
$options = stream_context_get_options($context);
if (!isset($options['ssl']['peer_certificate'])) {
return;
}
$container = ContainerSingleton::getInstance();
$key = openssl_pkey_get_public($options['ssl']['peer_certificate']);
if ($key === false) {
$container->getLogger()->warning('Unable to get public key from peer certificate.');
return;
}
$keyInfo = openssl_pkey_get_details($key);
if ($keyInfo === false) {
$container->getLogger()->warning('Unable to get key details from public key.');
return;
}
if (!isset($keyInfo['key']) || !is_string($keyInfo['key'])) {
$container->getLogger()->warning('Missing key in public key details.');
return;
}
$msg->addValidator([SOAPClient::class, 'validateSSL'], $keyInfo['key']);
}
/**
* Validate a SOAP message against the certificate on the SSL connection.
*
* @param string $data The public key (PEM) that was used on the connection.
* @param mixed $key The key we should validate the certificate against.
* @throws \Exception
*/
public static function validateSSL(string $data, mixed $key): void
{
$container = ContainerSingleton::getInstance();
$pem = self::extractPublicKeyPem($key);
if (trim($pem) !== trim($data)) {
throw new Exception('Key on SSL connection did not match key we validated against.');
}
$container->getLogger()->debug('Message validated based on SSL certificate.');
}
/**
* Extract a PEM-encoded public key from different key representations.
*
* This avoids coupling to a specific XML security backend.
*
* @param mixed $key
* @throws \Exception
*/
private static function extractPublicKeyPem(mixed $key): string
{
// If the validating key is already PEM, normalize it by re-loading through OpenSSL.
if (is_string($key)) {
$opensslKey = openssl_pkey_get_public($key);
if ($opensslKey === false) {
throw new Exception('Unable to load validating public key from PEM string.');
}
$keyInfo = openssl_pkey_get_details($opensslKey);
if ($keyInfo === false || !isset($keyInfo['key']) || !is_string($keyInfo['key'])) {
throw new Exception('Unable to get key details from validating PEM key.');
}
return $keyInfo['key'];
}
// Some key implementations may expose PEM via a method.
if (is_object($key)) {
foreach (['getPublicKeyPem', 'getPem', 'toPEM', 'toPem'] as $method) {
if (method_exists($key, $method)) {
/** @var mixed $pem */
$pem = $key->{$method}();
if (is_string($pem) && $pem !== '') {
return self::extractPublicKeyPem($pem);
}
}
}
// Common compatibility case: an object wraps an OpenSSL key or PEM in a public "key" property.
if (property_exists($key, 'key')) {
/** @var mixed $inner */
$inner = $key->key;
if (is_string($inner)) {
return self::extractPublicKeyPem($inner);
}
if ($inner instanceof OpenSSLAsymmetricKey) {
$keyInfo = openssl_pkey_get_details($inner);
if ($keyInfo !== false && isset($keyInfo['key']) && is_string($keyInfo['key'])) {
return $keyInfo['key'];
}
}
}
}
// Last attempt: OpenSSL might accept the value directly (OpenSSLAsymmetricKey).
if ($key instanceof OpenSSLAsymmetricKey) {
$keyInfo = openssl_pkey_get_details($key);
if ($keyInfo !== false && isset($keyInfo['key']) && is_string($keyInfo['key'])) {
return $keyInfo['key'];
}
}
throw new Exception('Unable to extract public key PEM from validating key.');
}
/**
* Extracts the SOAP Fault from SOAP message
*
* @param \DOMDocument $soapMessage Soap response needs to be type DOMDocument
* @return \SimpleSAML\SOAP11\XML\Fault|null
*/
private function getSOAPFault(DOMDocument $soapMessage): ?Fault
{
$soapFault = XPath::xpQuery(
$soapMessage->firstChild,
'/env:Envelope/env:Body/env:Fault',
XPath::getXPath($soapMessage->firstChild),
);
if (empty($soapFault)) {
/* No fault. */
return null;
}
return Fault::fromXML($soapFault[0]);
}
}