Completed
Push — master ( fb5ae7...394d43 )
by Thijs
17s queued 12s
created

MetaLoader::writeState()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
namespace SimpleSAML\Module\metarefresh;
4
5
use Exception;
6
use RobRichards\XMLSecLibs\XMLSecurityDSig;
7
use SAML2\DOMDocumentFactory;
8
use SimpleSAML\Configuration;
9
use SimpleSAML\Logger;
10
use SimpleSAML\Metadata;
11
use SimpleSAML\Utils;
12
use Webmozart\Assert\Assert;
13
14
/**
15
 * @package SimpleSAMLphp
16
 * @author Andreas Åkre Solberg <[email protected]>
17
 */
18
class MetaLoader
19
{
20
    /** @var int|null */
21
    private $expire;
22
23
    /** @var array */
24
    private $metadata = [];
25
26
    /** @var object|null */
27
    private $oldMetadataSrc;
28
29
    /** @var string|null */
30
    private $stateFile = null;
31
32
    /** @var bool*/
33
    private $changed = false;
34
35
    /** @var array */
36
    private $state = [];
37
38
    /** @var array */
39
    private $types = [
40
        'saml20-idp-remote',
41
        'saml20-sp-remote',
42
        'attributeauthority-remote'
43
    ];
44
45
46
    /**
47
     * Constructor
48
     *
49
     * @param int|null $expire
50
     * @param string|null  $stateFile
51
     * @param object|null  $oldMetadataSrc
52
     */
53
    public function __construct(int $expire = null, string $stateFile = null, object $oldMetadataSrc = null)
54
    {
55
        $this->expire = $expire;
56
        $this->oldMetadataSrc = $oldMetadataSrc;
57
        $this->stateFile = $stateFile;
58
59
        // Read file containing $state from disk
60
        /** @psalm-var array|null */
61
        $state = null;
62
        if (!is_null($stateFile) && is_readable($stateFile)) {
63
            include($stateFile);
64
        }
65
66
        if (!empty($state)) {
0 ignored issues
show
introduced by
The condition empty($state) is always false.
Loading history...
67
            $this->state = $state;
68
        }
69
    }
70
71
72
    /**
73
     * Get the types of entities that will be loaded.
74
     *
75
     * @return array The entity types allowed.
76
     */
77
    public function getTypes(): array
78
    {
79
        return $this->types;
80
    }
81
82
83
    /**
84
     * Set the types of entities that will be loaded.
85
     *
86
     * @param string|array $types Either a string with the name of one single type allowed, or an array with a list of
87
     * types. Pass an empty array to reset to all types of entities.
88
     * @return void
89
     */
90
    public function setTypes($types): void
91
    {
92
        if (!is_array($types)) {
93
            $types = [$types];
94
        }
95
        $this->types = $types;
96
    }
97
98
99
    /**
100
     * This function processes a SAML metadata file.
101
     *
102
     * @param $source array
103
     * @return void
104
     */
105
    public function loadSource(array $source): void
106
    {
107
        if (preg_match('@^https?://@i', $source['src'])) {
108
            // Build new HTTP context
109
            $context = $this->createContext($source);
110
111
            // GET!
112
            try {
113
                /** @var array $response  We know this because we set the third parameter to `true` */
114
                $response = Utils\HTTP::fetch($source['src'], $context, true);
115
                list($data, $responseHeaders) = $response;
116
            } catch (Exception $e) {
117
                Logger::warning('metarefresh: ' . $e->getMessage());
118
            }
119
120
            // We have response headers, so the request succeeded
121
            if (!isset($responseHeaders)) {
122
                // No response headers, this means the request failed in some way, so re-use old data
123
                Logger::debug('No response from ' . $source['src'] . ' - attempting to re-use cached metadata');
124
                $this->addCachedMetadata($source);
125
                return;
126
            } elseif (preg_match('@^HTTP/1\.[01]\s304\s@', $responseHeaders[0])) {
127
                // 304 response
128
                Logger::debug('Received HTTP 304 (Not Modified) - attempting to re-use cached metadata');
129
                $this->addCachedMetadata($source);
130
                return;
131
            } elseif (!preg_match('@^HTTP/1\.[01]\s200\s@', $responseHeaders[0])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $responseHeaders does not seem to be defined for all execution paths leading up to this point.
Loading history...
132
                // Other error
133
                Logger::debug('Error from ' . $source['src'] . ' - attempting to re-use cached metadata');
134
                $this->addCachedMetadata($source);
135
                return;
136
            }
137
        } else {
138
            // Local file.
139
            $data = file_get_contents($source['src']);
140
            $responseHeaders = null;
141
        }
142
143
        // Everything OK. Proceed.
144
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
145
            // Stale or no metadata, so a fresh copy
146
            Logger::debug('Downloaded fresh copy');
147
        }
148
149
        try {
150
            $entities = $this->loadXML($data, $source);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.
Loading history...
151
        } catch (Exception $e) {
152
            Logger::debug('XML parser error when parsing ' . $source['src'] . ' - attempting to re-use cached metadata');
153
            Logger::debug('XML parser returned: ' . $e->getMessage());
154
            $this->addCachedMetadata($source);
155
            return;
156
        }
157
158
        foreach ($entities as $entity) {
159
            if (isset($source['blacklist'])) {
160
                if (!empty($source['blacklist']) && in_array($entity->getEntityId(), $source['blacklist'], true)) {
161
                    Logger::info('Skipping "' . $entity->getEntityId() . '" - blacklisted.' . "\n");
162
                    continue;
163
                }
164
            }
165
166
            if (isset($source['whitelist'])) {
167
                if (!empty($source['whitelist']) && !in_array($entity->getEntityId(), $source['whitelist'], true)) {
168
                    Logger::info('Skipping "' . $entity->getEntityId() . '" - not in the whitelist.' . "\n");
169
                    continue;
170
                }
171
            }
172
173
            /* Do we have an attribute whitelist? */
174
            if (isset($source['attributewhitelist']) && !empty($source['attributewhitelist'])) {
175
                $idpMetadata = $entity->getMetadata20IdP();
176
                if (!isset($idpMetadata)) {
177
                    /* Skip non-IdPs */
178
                    continue;
179
                }
180
181
                /* Do a recursive comparison for each whitelist of the attributewhitelist with the idpMetadata for this
182
                 * IdP. At least one of these whitelists should match */
183
                $match = false;
184
                foreach ($source['attributewhitelist'] as $whitelist) {
185
                    if ($this->containsArray($whitelist, $idpMetadata)) {
186
                        $match = true;
187
                        break;
188
                    }
189
                }
190
                if (!$match) {
191
                    /* No match found -> next IdP */
192
                    continue;
193
                }
194
                Logger::debug('Whitelisted entityID: ' . $entity->getEntityID());
195
            }
196
197
            if (array_key_exists('certificates', $source) && ($source['certificates'] !== null)) {
198
                if (!$entity->validateSignature($source['certificates'])) {
199
                    Logger::info(
200
                        'Skipping "' . $entity->getEntityId() . '" - could not verify signature using certificate.' . "\n"
201
                    );
202
                    continue;
203
                }
204
            }
205
206
            $template = null;
207
            if (array_key_exists('template', $source)) {
208
                $template = $source['template'];
209
            }
210
211
            if (in_array('saml20-sp-remote', $this->types, true)) {
212
                $this->addMetadata($source['src'], $entity->getMetadata20SP(), 'saml20-sp-remote', $template);
213
            }
214
            if (in_array('saml20-idp-remote', $this->types, true)) {
215
                $this->addMetadata($source['src'], $entity->getMetadata20IdP(), 'saml20-idp-remote', $template);
216
            }
217
            if (in_array('attributeauthority-remote', $this->types, true)) {
218
                $attributeAuthorities = $entity->getAttributeAuthorities();
219
                if (!empty($attributeAuthorities)) {
220
                    $this->addMetadata(
221
                        $source['src'],
222
                        $attributeAuthorities,
223
                        'attributeauthority-remote',
224
                        $template
225
                    );
226
                }
227
            }
228
        }
229
230
        $this->saveState($source, $responseHeaders);
231
    }
232
233
234
    /*
235
     * Recursively checks whether array $dst contains array $src. If $src
236
     * is not an array, a literal comparison is being performed.
237
     */
238
    private function containsArray($src, $dst): bool
239
    {
240
        if (is_array($src)) {
241
            if (!is_array($dst)) {
242
                return false;
243
            }
244
            $dstKeys = array_keys($dst);
245
246
            /* Loop over all src keys */
247
            foreach ($src as $srcKey => $srcval) {
248
                if (is_int($srcKey)) {
249
                    /* key is number, check that the key appears as one
250
                     * of the destination keys: if not, then src has
251
                     * more keys than dst */
252
                    if (!array_key_exists($srcKey, $dst)) {
253
                        return false;
254
                    }
255
256
                    /* loop over dest keys, to find value: we don't know
257
                     * whether they are in the same order */
258
                    $submatch = false;
259
                    foreach ($dstKeys as $dstKey) {
260
                        if ($this->containsArray($srcval, $dst[$dstKey])) {
261
                            $submatch = true;
262
                            break;
263
                        }
264
                    }
265
                    if (!$submatch) {
266
                        return false;
267
                    }
268
                } else {
269
                    /* key is regexp: find matching keys */
270
                    /** @var array|false $matchingDstKeys */
271
                    $matchingDstKeys = preg_grep($srcKey, $dstKeys);
272
                    if (!is_array($matchingDstKeys)) {
273
                        return false;
274
                    }
275
276
                    $match = false;
277
                    foreach ($matchingDstKeys as $dstKey) {
278
                        if ($this->containsArray($srcval, $dst[$dstKey])) {
279
                            /* Found a match */
280
                            $match = true;
281
                            break;
282
                        }
283
                    }
284
                    if (!$match) {
285
                        /* none of the keys has a matching value */
286
                        return false;
287
                    }
288
                }
289
            }
290
            /* each src key/value matches */
291
            return true;
292
        } else {
293
            /* src is not an array, do a regexp match against dst */
294
            return (preg_match($src, $dst) === 1);
295
        }
296
    }
297
298
    /**
299
     * Create HTTP context, with any available caches taken into account
300
     *
301
     * @param array $source
302
     * @return array
303
     */
304
    private function createContext(array $source): array
305
    {
306
        $config = Configuration::getInstance();
307
        $name = $config->getString('technicalcontact_name', null);
308
        $mail = $config->getString('technicalcontact_email', null);
309
310
        $rawheader = "User-Agent: SimpleSAMLphp metarefresh, run by $name <$mail>\r\n";
311
312
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
313
            if (array_key_exists($source['src'], $this->state)) {
314
                $sourceState = $this->state[$source['src']];
315
316
                if (isset($sourceState['last-modified'])) {
317
                    $rawheader .= 'If-Modified-Since: ' . $sourceState['last-modified'] . "\r\n";
318
                }
319
320
                if (isset($sourceState['etag'])) {
321
                    $rawheader .= 'If-None-Match: ' . $sourceState['etag'] . "\r\n";
322
                }
323
            }
324
        }
325
326
        return ['http' => ['header' => $rawheader]];
327
    }
328
329
330
    /**
331
     * @param array $source
332
     * @return void
333
     */
334
    private function addCachedMetadata(array $source): void
335
    {
336
        if (isset($this->oldMetadataSrc)) {
337
            foreach ($this->types as $type) {
338
                foreach ($this->oldMetadataSrc->getMetadataSet($type) as $entity) {
0 ignored issues
show
Bug introduced by
The method getMetadataSet() does not exist on null. ( Ignorable by Annotation )

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

338
                foreach ($this->oldMetadataSrc->/** @scrutinizer ignore-call */ getMetadataSet($type) as $entity) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
339
                    if (array_key_exists('metarefresh:src', $entity)) {
340
                        if ($entity['metarefresh:src'] == $source['src']) {
341
                            $this->addMetadata($source['src'], $entity, $type);
342
                        }
343
                    }
344
                }
345
            }
346
        }
347
    }
348
349
350
    /**
351
     * Store caching state data for a source
352
     *
353
     * @param array $source
354
     * @param array|null $responseHeaders
355
     * @return void
356
     */
357
    private function saveState(array $source, ?array $responseHeaders): void
358
    {
359
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
360
            // Headers section
361
            if ($responseHeaders !== null) {
0 ignored issues
show
introduced by
The condition $responseHeaders !== null is always true.
Loading history...
362
                $candidates = ['last-modified', 'etag'];
363
364
                foreach ($candidates as $candidate) {
365
                    if (array_key_exists($candidate, $responseHeaders)) {
366
                        $this->state[$source['src']][$candidate] = $responseHeaders[$candidate];
367
                    }
368
                }
369
            }
370
371
            if (!empty($this->state[$source['src']])) {
372
                // Timestamp when this src was requested.
373
                $this->state[$source['src']]['requested_at'] = $this->getTime();
374
                $this->changed = true;
375
            }
376
        }
377
    }
378
379
380
    /**
381
     * Parse XML metadata and return entities
382
     *
383
     * @param string $data
384
     * @param array $source
385
     * @return \SimpleSAML\Metadata\SAMLParser[]
386
     * @throws \Exception
387
     */
388
    private function loadXML(string $data, array $source): array
389
    {
390
        try {
391
            $doc = DOMDocumentFactory::fromString($data);
392
        } catch (Exception $e) {
393
            throw new Exception('Failed to read XML from ' . $source['src']);
394
        }
395
        return Metadata\SAMLParser::parseDescriptorsElement($doc->documentElement);
396
    }
397
398
399
    /**
400
     * This function writes the state array back to disk
401
     *
402
     * @return void
403
     */
404
    public function writeState(): void
405
    {
406
        if ($this->changed && !is_null($this->stateFile)) {
407
            Logger::debug('Writing: ' . $this->stateFile);
408
            Utils\System::writeFile(
409
                $this->stateFile,
410
                "<?php\n/* This file was generated by the metarefresh module at " . $this->getTime() . ".\n" .
411
                " Do not update it manually as it will get overwritten. */\n" .
412
                '$state = ' . var_export($this->state, true) . ";\n?>\n",
413
                0644
414
            );
415
        }
416
    }
417
418
419
    /**
420
     * This function writes the metadata to stdout.
421
     *
422
     * @return void
423
     */
424
    public function dumpMetadataStdOut(): void
425
    {
426
        foreach ($this->metadata as $category => $elements) {
427
            echo '/* The following data should be added to metadata/' . $category . '.php. */' . "\n";
428
429
            foreach ($elements as $m) {
430
                $filename = $m['filename'];
431
                $entityID = $m['metadata']['entityid'];
432
433
                echo "\n";
434
                echo '/* The following metadata was generated from ' . $filename . ' on ' . $this->getTime() . '. */' . "\n";
435
                echo '$metadata[\'' . addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n";
436
            }
437
438
            echo "\n";
439
            echo '/* End of data which should be added to metadata/' . $category . '.php. */' . "\n";
440
            echo "\n";
441
        }
442
    }
443
444
445
    /**
446
     * This function adds metadata from the specified file to the list of metadata.
447
     * This function will return without making any changes if $metadata is NULL.
448
     *
449
     * @param string $filename The filename the metadata comes from.
450
     * @param \SAML2\XML\md\AttributeAuthorityDescriptor[]|null $metadata The metadata.
451
     * @param string $type The metadata type.
452
     * @param array|null $template The template.
453
     * @return void
454
     */
455
    private function addMetadata(string $filename, ?array $metadata, string $type, array $template = null): void
456
    {
457
        if ($metadata === null) {
0 ignored issues
show
introduced by
The condition $metadata === null is always false.
Loading history...
458
            return;
459
        }
460
461
        if (isset($template)) {
462
            $metadata = array_merge($metadata, $template);
463
        }
464
465
        $metadata['metarefresh:src'] = $filename;
466
        if (!array_key_exists($type, $this->metadata)) {
467
            $this->metadata[$type] = [];
468
        }
469
470
        // If expire is defined in constructor...
471
        if (!empty($this->expire)) {
472
            // If expire is already in metadata
473
            if (array_key_exists('expire', $metadata)) {
474
                // Override metadata expire with more restrictive global config
475
                if ($this->expire < $metadata['expire']) {
476
                    $metadata['expire'] = $this->expire;
477
                }
478
479
                // If expire is not already in metadata use global config
480
            } else {
481
                $metadata['expire'] = $this->expire;
482
            }
483
        }
484
        $this->metadata[$type][] = ['filename' => $filename, 'metadata' => $metadata];
485
    }
486
487
488
    /**
489
     * This function writes the metadata to an ARP file
490
     *
491
     * @param \SimpleSAML\Configuration $config
492
     * @return void
493
     */
494
    public function writeARPfile(Configuration $config): void
495
    {
496
        $arpfile = $config->getValue('arpfile');
497
        $types = ['saml20-sp-remote'];
498
499
        $md = [];
500
        foreach ($this->metadata as $category => $elements) {
501
            if (!in_array($category, $types, true)) {
502
                continue;
503
            }
504
            $md = array_merge($md, $elements);
505
        }
506
507
        // $metadata, $attributemap, $prefix, $suffix
508
        $arp = new ARP(
509
            $md,
510
            $config->getValue('attributemap', ''),
511
            $config->getValue('prefix', ''),
512
            $config->getValue('suffix', '')
513
        );
514
515
516
        $arpxml = $arp->getXML();
517
518
        Logger::info('Writing ARP file: ' . $arpfile . "\n");
519
        file_put_contents($arpfile, $arpxml);
520
    }
521
522
523
    /**
524
     * This function writes the metadata to to separate files in the output directory.
525
     *
526
     * @param string $outputDir
527
     * @return void
528
     */
529
    public function writeMetadataFiles(string $outputDir): void
530
    {
531
        while (strlen($outputDir) > 0 && $outputDir[strlen($outputDir) - 1] === '/') {
532
            $outputDir = substr($outputDir, 0, strlen($outputDir) - 1);
533
        }
534
535
        if (!file_exists($outputDir)) {
536
            Logger::info('Creating directory: ' . $outputDir . "\n");
537
            $res = @mkdir($outputDir, 0777, true);
538
            if ($res === false) {
539
                throw new Exception('Error creating directory: ' . $outputDir);
540
            }
541
        }
542
543
        foreach ($this->types as $type) {
544
            $filename = $outputDir . '/' . $type . '.php';
545
546
            if (array_key_exists($type, $this->metadata)) {
547
                $elements = $this->metadata[$type];
548
                Logger::debug('Writing: ' . $filename);
549
550
                $content  = '<?php' . "\n" . '/* This file was generated by the metarefresh module at ';
551
                $content .= $this->getTime() . "\nDo not update it manually as it will get overwritten\n" . '*/' . "\n";
552
553
                foreach ($elements as $m) {
554
                    $entityID = $m['metadata']['entityid'];
555
                    $content .= "\n" . '$metadata[\'';
556
                    $content .= addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n";
557
                }
558
559
                $content .= "\n" . '?>';
560
561
                Utils\System::writeFile($filename, $content, 0644);
562
            } elseif (is_file($filename)) {
563
                if (unlink($filename)) {
564
                    Logger::debug('Deleting stale metadata file: ' . $filename);
565
                } else {
566
                    Logger::warning('Could not delete stale metadata file: ' . $filename);
567
                }
568
            }
569
        }
570
    }
571
572
573
    /**
574
     * Save metadata for loading with the 'serialize' metadata loader.
575
     *
576
     * @param string $outputDir  The directory we should save the metadata to.
577
     * @return void
578
     */
579
    public function writeMetadataSerialize(string $outputDir): void
580
    {
581
        $metaHandler = new Metadata\MetaDataStorageHandlerSerialize(['directory' => $outputDir]);
582
583
        // First we add all the metadata entries to the metadata handler
584
        foreach ($this->metadata as $set => $elements) {
585
            foreach ($elements as $m) {
586
                $entityId = $m['metadata']['entityid'];
587
588
                Logger::debug(
589
                    'metarefresh: Add metadata entry ' .
590
                    var_export($entityId, true) . ' in set ' . var_export($set, true) . '.'
591
                );
592
                $metaHandler->saveMetadata($entityId, $set, $m['metadata']);
593
            }
594
        }
595
596
        // Then we delete old entries which should no longer exist
597
        $ct = time();
598
        foreach ($metaHandler->getMetadataSets() as $set) {
599
            foreach ($metaHandler->getMetadataSet($set) as $entityId => $metadata) {
600
                if (!array_key_exists('expire', $metadata) || !is_int($metadata['expire'])) {
601
                    Logger::warning(
602
                        'metarefresh: Metadata entry without valid expire timestamp: ' . var_export($entityId, true) .
603
                        ' in set ' . var_export($set, true) . '.'
604
                    );
605
                    continue;
606
                }
607
608
                $expire = $metadata['expire'];
609
                if ($expire > $ct) {
610
                    continue;
611
                }
612
613
                /** @var int $stamp */
614
                $stamp = date('l jS \of F Y h:i:s A', $expire);
615
                Logger::debug('metarefresh: ' . $entityId . ' expired ' . $stamp);
616
                Logger::debug(
617
                    'metarefresh: Delete expired metadata entry ' .
618
                    var_export($entityId, true) . ' in set ' . var_export($set, true) .
619
                    '. (' . ($ct - $expire) . ' sec)'
620
                );
621
                $metaHandler->deleteMetadata($entityId, $set);
622
            }
623
        }
624
    }
625
626
627
    /**
628
     * @return string
629
     */
630
    private function getTime(): string
631
    {
632
        // The current date, as a string
633
        date_default_timezone_set('UTC');
634
        return date('Y-m-d\\TH:i:s\\Z');
635
    }
636
}
637