ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
AuthnResponse.php
Go to the documentation of this file.
1 <?php
2 
10 namespace SimpleSAML\XML\Shib13;
11 
12 use DOMDocument;
13 use DOMNode;
15 use SAML2\Utils;
20 
22 {
23 
27  private $validator = null;
28 
29 
33  private $messageValidated = false;
34 
35 
36  const SHIB_PROTOCOL_NS = 'urn:oasis:names:tc:SAML:1.0:protocol';
37  const SHIB_ASSERT_NS = 'urn:oasis:names:tc:SAML:1.0:assertion';
38 
39 
43  private $dom;
44 
48  private $relayState = null;
49 
50 
57  {
58  assert(is_bool($messageValidated));
59 
60  $this->messageValidated = $messageValidated;
61  }
62 
63 
64  public function setXML($xml)
65  {
66  assert(is_string($xml));
67 
68  try {
69  $this->dom = DOMDocumentFactory::fromString(str_replace("\r", "", $xml));
70  } catch (\Exception $e) {
71  throw new \Exception('Unable to parse AuthnResponse XML.');
72  }
73  }
74 
75  public function setRelayState($relayState)
76  {
77  $this->relayState = $relayState;
78  }
79 
80  public function getRelayState()
81  {
82  return $this->relayState;
83  }
84 
85  public function validate()
86  {
87  assert($this->dom instanceof DOMDocument);
88 
89  if ($this->messageValidated) {
90  // This message was validated externally
91  return true;
92  }
93 
94  // Validate the signature
95  $this->validator = new Validator($this->dom, array('ResponseID', 'AssertionID'));
96 
97  // Get the issuer of the response
98  $issuer = $this->getIssuer();
99 
100  // Get the metadata of the issuer
102  $md = $metadata->getMetaDataConfig($issuer, 'shib13-idp-remote');
103 
104  $publicKeys = $md->getPublicKeys('signing');
105  if (!empty($publicKeys)) {
106  $certFingerprints = array();
107  foreach ($publicKeys as $key) {
108  if ($key['type'] !== 'X509Certificate') {
109  continue;
110  }
111  $certFingerprints[] = sha1(base64_decode($key['X509Certificate']));
112  }
113  $this->validator->validateFingerprint($certFingerprints);
114  } elseif ($md->hasValue('certFingerprint')) {
115  $certFingerprints = $md->getArrayizeString('certFingerprint');
116 
117  // Validate the fingerprint
118  $this->validator->validateFingerprint($certFingerprints);
119  } elseif ($md->hasValue('caFile')) {
120  // Validate against CA
121  $this->validator->validateCA(Config::getCertPath($md->getString('caFile')));
122  } else {
123  throw new \SimpleSAML_Error_Exception('Missing certificate in Shibboleth 1.3 IdP Remote metadata for identity provider [' . $issuer . '].');
124  }
125 
126  return true;
127  }
128 
129 
136  private function isNodeValidated($node)
137  {
138  if ($this->messageValidated) {
139  // This message was validated externally
140  return true;
141  }
142 
143  if ($this->validator === null) {
144  return false;
145  }
146 
147  // Convert the node to a DOM node if it is an element from SimpleXML
148  if ($node instanceof \SimpleXMLElement) {
149  $node = dom_import_simplexml($node);
150  }
151 
152  assert($node instanceof DOMNode);
153 
154  return $this->validator->isNodeValidated($node);
155  }
156 
157 
166  private function doXPathQuery($query, $node = null)
167  {
168  assert(is_string($query));
169  assert($this->dom instanceof DOMDocument);
170 
171  if ($node === null) {
172  $node = $this->dom->documentElement;
173  }
174 
175  assert($node instanceof DOMNode);
176 
177  $xPath = new \DOMXpath($this->dom);
178  $xPath->registerNamespace('shibp', self::SHIB_PROTOCOL_NS);
179  $xPath->registerNamespace('shib', self::SHIB_ASSERT_NS);
180 
181  return $xPath->query($query, $node);
182  }
183 
189  public function getSessionIndex()
190  {
191  assert($this->dom instanceof DOMDocument);
192 
193  $query = '/shibp:Response/shib:Assertion/shib:AuthnStatement';
194  $nodelist = $this->doXPathQuery($query);
195  if ($node = $nodelist->item(0)) {
196  return $node->getAttribute('SessionIndex');
197  }
198 
199  return null;
200  }
201 
202 
203  public function getAttributes()
204  {
206  $md = $metadata->getMetadata($this->getIssuer(), 'shib13-idp-remote');
207  $base64 = isset($md['base64attributes']) ? $md['base64attributes'] : false;
208 
209  if (! ($this->dom instanceof \DOMDocument)) {
210  return array();
211  }
212 
213  $attributes = array();
214 
215  $assertions = $this->doXPathQuery('/shibp:Response/shib:Assertion');
216 
217  foreach ($assertions as $assertion) {
218  if (!$this->isNodeValidated($assertion)) {
219  throw new \Exception('Shib13 AuthnResponse contained an unsigned assertion.');
220  }
221 
222  $conditions = $this->doXPathQuery('shib:Conditions', $assertion);
223  if ($conditions && $conditions->length > 0) {
224  $condition = $conditions->item(0);
225 
226  $start = $condition->getAttribute('NotBefore');
227  $end = $condition->getAttribute('NotOnOrAfter');
228 
229  if ($start && $end) {
230  if (!self::checkDateConditions($start, $end)) {
231  error_log('Date check failed ... (from ' . $start . ' to ' . $end . ')');
232  continue;
233  }
234  }
235  }
236 
237  $attribute_nodes = $this->doXPathQuery('shib:AttributeStatement/shib:Attribute/shib:AttributeValue', $assertion);
239  foreach ($attribute_nodes as $attribute) {
240  $value = $attribute->textContent;
241  $name = $attribute->parentNode->getAttribute('AttributeName');
242 
243  if ($attribute->hasAttribute('Scope')) {
244  $scopePart = '@' . $attribute->getAttribute('Scope');
245  } else {
246  $scopePart = '';
247  }
248 
249  if (!is_string($name)) {
250  throw new \Exception('Shib13 Attribute node without an AttributeName.');
251  }
252 
253  if (!array_key_exists($name, $attributes)) {
254  $attributes[$name] = array();
255  }
256 
257  if ($base64) {
258  $encodedvalues = explode('_', $value);
259  foreach ($encodedvalues as $v) {
260  $attributes[$name][] = base64_decode($v) . $scopePart;
261  }
262  } else {
263  $attributes[$name][] = $value . $scopePart;
264  }
265  }
266  }
267 
268  return $attributes;
269  }
270 
271 
272  public function getIssuer()
273  {
274  $query = '/shibp:Response/shib:Assertion/@Issuer';
275  $nodelist = $this->doXPathQuery($query);
276 
277  if ($attr = $nodelist->item(0)) {
278  return $attr->value;
279  } else {
280  throw new \Exception('Could not find Issuer field in Authentication response');
281  }
282  }
283 
284  public function getNameID()
285  {
286  $nameID = array();
287 
288  $query = '/shibp:Response/shib:Assertion/shib:AuthenticationStatement/shib:Subject/shib:NameIdentifier';
289  $nodelist = $this->doXPathQuery($query);
290 
291  if ($node = $nodelist->item(0)) {
292  $nameID["Value"] = $node->nodeValue;
293  $nameID["Format"] = $node->getAttribute('Format');
294  }
295 
296  return $nameID;
297  }
298 
299 
310  {
311  assert(is_string($shire));
312  assert($attributes === null || is_array($attributes));
313 
314  if ($sp->hasValue('scopedattributes')) {
315  $scopedAttributes = $sp->getArray('scopedattributes');
316  } elseif ($idp->hasValue('scopedattributes')) {
317  $scopedAttributes = $idp->getArray('scopedattributes');
318  } else {
319  $scopedAttributes = array();
320  }
321 
323 
324  $issueInstant = Time::generateTimestamp();
325 
326  // 30 seconds timeskew back in time to allow differing clocks
327  $notBefore = Time::generateTimestamp(time() - 30);
328 
329 
330  $assertionExpire = Time::generateTimestamp(time() + 60 * 5);# 5 minutes
331  $assertionid = Random::generateID();
332 
333  $spEntityId = $sp->getString('entityid');
334 
335  $audience = $sp->getString('audience', $spEntityId);
336  $base64 = $sp->getBoolean('base64attributes', false);
337 
338  $namequalifier = $sp->getString('NameQualifier', $spEntityId);
340  $subjectNode =
341  '<Subject>' .
342  '<NameIdentifier' .
343  ' Format="urn:mace:shibboleth:1.0:nameIdentifier"' .
344  ' NameQualifier="' . htmlspecialchars($namequalifier) . '"' .
345  '>' .
346  htmlspecialchars($nameid) .
347  '</NameIdentifier>' .
348  '<SubjectConfirmation>' .
349  '<ConfirmationMethod>' .
350  'urn:oasis:names:tc:SAML:1.0:cm:bearer' .
351  '</ConfirmationMethod>' .
352  '</SubjectConfirmation>' .
353  '</Subject>';
354 
355  $encodedattributes = '';
356 
357  if (is_array($attributes)) {
358  $encodedattributes .= '<AttributeStatement>';
359  $encodedattributes .= $subjectNode;
360 
361  foreach ($attributes as $name => $value) {
362  $encodedattributes .= $this->enc_attribute($name, $value, $base64, $scopedAttributes);
363  }
364 
365  $encodedattributes .= '</AttributeStatement>';
366  }
367 
368  /*
369  * The SAML 1.1 response message
370  */
371  $response = '<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol"
372  xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
373  xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
374  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" IssueInstant="' . $issueInstant. '"
375  MajorVersion="1" MinorVersion="1"
376  Recipient="' . htmlspecialchars($shire) . '" ResponseID="' . $id . '">
377  <Status>
378  <StatusCode Value="samlp:Success" />
379  </Status>
380  <Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion"
381  AssertionID="' . $assertionid . '" IssueInstant="' . $issueInstant. '"
382  Issuer="' . htmlspecialchars($idp->getString('entityid')) . '" MajorVersion="1" MinorVersion="1">
383  <Conditions NotBefore="' . $notBefore. '" NotOnOrAfter="'. $assertionExpire . '">
384  <AudienceRestrictionCondition>
385  <Audience>' . htmlspecialchars($audience) . '</Audience>
386  </AudienceRestrictionCondition>
387  </Conditions>
388  <AuthenticationStatement AuthenticationInstant="' . $issueInstant. '"
389  AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:unspecified">' .
390  $subjectNode . '
391  </AuthenticationStatement>
392  ' . $encodedattributes . '
393  </Assertion>
394 </Response>';
395 
396  return $response;
397  }
398 
399 
409  private function enc_attribute($name, $values, $base64, $scopedAttributes)
410  {
411  assert(is_string($name));
412  assert(is_array($values));
413  assert(is_bool($base64));
414  assert(is_array($scopedAttributes));
415 
416  if (in_array($name, $scopedAttributes, true)) {
417  $scoped = true;
418  } else {
419  $scoped = false;
420  }
421 
422  $attr = '<Attribute AttributeName="' . htmlspecialchars($name) . '" AttributeNamespace="urn:mace:shibboleth:1.0:attributeNamespace:uri">';
423  foreach ($values as $value) {
424  $scopePart = '';
425  if ($scoped) {
426  $tmp = explode('@', $value, 2);
427  if (count($tmp) === 2) {
428  $value = $tmp[0];
429  $scopePart = ' Scope="' . htmlspecialchars($tmp[1]) . '"';
430  }
431  }
432 
433  if ($base64) {
434  $value = base64_encode($value);
435  }
436 
437  $attr .= '<AttributeValue' . $scopePart . '>' . htmlspecialchars($value) . '</AttributeValue>';
438  }
439  $attr .= '</Attribute>';
440 
441  return $attr;
442  }
443 
461  protected static function checkDateConditions($start = null, $end = null)
462  {
463  $currentTime = time();
464 
465  if (!empty($start)) {
466  $startTime = Utils::xsDateTimeToTimestamp($start);
467  // allow for a 10 minute difference in time
468  if (($startTime < 0) || (($startTime - 600) > $currentTime)) {
469  return false;
470  }
471  }
472  if (!empty($end)) {
474  if (($endTime < 0) || ($endTime <= $currentTime)) {
475  return false;
476  }
477  }
478  return true;
479  }
480 }
static generateID()
Generate a random identifier, ID_LENGTH bytes long.
Definition: Random.php:26
generate(\SimpleSAML_Configuration $idp, \SimpleSAML_Configuration $sp, $shire, $attributes)
Build a authentication response.
static getMetadataHandler()
This function retrieves the current instance of the metadata handler.
getArray($name, $default=self::REQUIRED_OPTION)
This function retrieves an array configuration option.
isNodeValidated($node)
Checks if the given node is validated by the signature on this response.
$spEntityId
hasValue($name)
Check whether a key in the configuration exists or not.
if(!array_key_exists('StateId', $_REQUEST)) $id
enc_attribute($name, $values, $base64, $scopedAttributes)
Format a shib13 attribute.
setMessageValidated($messageValidated)
Set whether this message was validated externally.
$metadata['__DYNAMIC:1__']
static generateTimestamp($instant=null)
This function generates a timestamp on the form used by the SAML protocols.
Definition: Time.php:31
$start
Definition: bench.php:8
$values
$nameid
Definition: status.php:36
$query
getBoolean($name, $default=self::REQUIRED_OPTION)
This function retrieves a boolean configuration option.
if(array_key_exists('yes', $_REQUEST)) $attributes
Definition: getconsent.php:85
catch(Exception $e) if(!($request instanceof \SAML2\ArtifactResolve)) $issuer
static xsDateTimeToTimestamp($time)
This function converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(.s+)?Z to a UNIX timestamp...
Definition: Utils.php:721
$idp
Definition: prp.php:13
getString($name, $default=self::REQUIRED_OPTION)
This function retrieves a string configuration option.
static checkDateConditions($start=null, $end=null)
Check if we are currently between the given date & time conditions.
static getCertPath($path)
Resolves a path that may be relative to the cert-directory.
Definition: Config.php:22
getSessionIndex()
Retrieve the session index of this response.
doXPathQuery($query, $node=null)
This function runs an xPath query on this authentication response.
$response
$key
Definition: croninfo.php:18