Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Security.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Framework\Xml;
7 
8 use DOMDocument;
9 
13 class Security
14 {
21  private function heuristicScan($xmlContent)
22  {
23  return strpos($xmlContent, '<!ENTITY') === false;
24  }
25 
31  private function isPhpFpm()
32  {
33  return substr(php_sapi_name(), 0, 3) === 'fpm';
34  }
35 
44  public function scan($xmlContent)
45  {
51  if ($this->isPhpFpm()) {
52  return $this->heuristicScan($xmlContent);
53  }
54 
55  $document = new DOMDocument();
56 
57  $loadEntities = libxml_disable_entity_loader(true);
58  $useInternalXmlErrors = libxml_use_internal_errors(true);
59 
64  set_error_handler(
65  function ($errno, $errstr) {
66  if (substr_count($errstr, 'DOMDocument::loadXML()') > 0) {
67  return true;
68  }
69  return false;
70  },
71  E_WARNING
72  );
73 
74  $result = (bool)$document->loadXML($xmlContent, LIBXML_NONET);
75  restore_error_handler();
76  // Entity load to previous setting
77  libxml_disable_entity_loader($loadEntities);
78  libxml_use_internal_errors($useInternalXmlErrors);
79 
80  if (!$result) {
81  return false;
82  }
83 
84  foreach ($document->childNodes as $child) {
85  if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
86  if ($child->entities->length > 0) {
87  return false;
88  }
89  }
90  }
91 
92  return true;
93  }
94 }