|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ADM\QuickDevBar\Observer; |
| 4 | + |
| 5 | +use ADM\QuickDevBar\Service\Dumper; |
| 6 | +use Magento\Csp\Api\PolicyCollectorInterface; |
| 7 | +use Magento\Csp\Model\Policy\FetchPolicy; |
| 8 | +use Magento\Framework\Event\Observer; |
| 9 | +use Magento\Framework\Event\ObserverInterface; |
| 10 | + |
| 11 | + |
| 12 | +class CheckHtmlObserver implements ObserverInterface |
| 13 | +{ |
| 14 | + private Dumper $dumper; |
| 15 | + |
| 16 | + private PolicyCollectorInterface $collector; |
| 17 | + |
| 18 | + public function __construct(Dumper $dumper, |
| 19 | + PolicyCollectorInterface $collector) |
| 20 | + { |
| 21 | + $this->dumper = $dumper; |
| 22 | + $this->collector = $collector; |
| 23 | + } |
| 24 | + |
| 25 | + public function execute(Observer $observer) |
| 26 | + { |
| 27 | + |
| 28 | + $block = $observer->getEvent()->getBlock(); |
| 29 | + $html = $observer->getEvent()->getTransport()->getHtml(); |
| 30 | + $allowedHashes = []; |
| 31 | + $policies = $this->collector->collect(); |
| 32 | + foreach ($policies as $policy) { |
| 33 | + if($policy->getId() =='script-src') { |
| 34 | + if($policy->isInlineAllowed()) { |
| 35 | + //Noting to check |
| 36 | + return null; |
| 37 | + } |
| 38 | + $allowedHashes = $policy->getHashes(); |
| 39 | + break; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + //Without nonce |
| 44 | + $pattern = '/<script(?![^>]*\bnonce\s*=)[^>]*>(.*?)<\/script>/is'; |
| 45 | + |
| 46 | + //Without nonce nor x-magento-init |
| 47 | + $pattern = '/<script(?![^>]*\b(?:nonce|type\s*=\s*["\']text\/x-magento-init["\']))[^>]*>(.*?)<\/script>/is'; |
| 48 | + |
| 49 | + |
| 50 | + if( preg_match_all($pattern, $html, $matches)) { |
| 51 | + foreach ($matches[1] as $scriptContent) { |
| 52 | + $sha256 = $this->generateHashValue($scriptContent); |
| 53 | + if(!empty($allowedHashes[$sha256])) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + $this->dumper->addDump( |
| 57 | + 'Script violating CSP'. '<br>' . |
| 58 | + '<pre>' . htmlspecialchars($scriptContent). '</pre>' . |
| 59 | + '(' . get_class($block) . ' :: '. $block->getTemplateFile() . ')<br>' . |
| 60 | + 'To enable execution use sha256: '. $this->generateHashValue($scriptContent) . '<br><br>', |
| 61 | + [], ""); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private function generateHashValue(string $content): string |
| 67 | + { |
| 68 | + return base64_encode(hash('sha256', $content, true)); |
| 69 | + } |
| 70 | +} |
0 commit comments