PageRenderTime 26ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/magento/zendframework1/library/Zend/Xml/Security.php

https://gitlab.com/yousafsyed/easternglamor
PHP | 488 lines | 306 code | 29 blank | 153 comment | 21 complexity | da26132400aeea2e1449a681d23c25ef MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Xml
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @category Zend
  23. * @package Zend_Xml_SecurityScan
  24. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  25. * @license http://framework.zend.com/license/new-bsd New BSD License
  26. */
  27. class Zend_Xml_Security
  28. {
  29. const ENTITY_DETECT = 'Detected use of ENTITY in XML, disabled to prevent XXE/XEE attacks';
  30. /**
  31. * Heuristic scan to detect entity in XML
  32. *
  33. * @param string $xml
  34. * @throws Zend_Xml_Exception If entity expansion or external entity declaration was discovered.
  35. */
  36. protected static function heuristicScan($xml)
  37. {
  38. foreach (self::getEntityComparison($xml) as $compare) {
  39. if (strpos($xml, $compare) !== false) {
  40. throw new Zend_Xml_Exception(self::ENTITY_DETECT);
  41. }
  42. }
  43. }
  44. /**
  45. * @param integer $errno
  46. * @param string $errstr
  47. * @param string $errfile
  48. * @param integer $errline
  49. * @return bool
  50. */
  51. public static function loadXmlErrorHandler($errno, $errstr, $errfile, $errline)
  52. {
  53. if (substr_count($errstr, 'DOMDocument::loadXML()') > 0) {
  54. return true;
  55. }
  56. return false;
  57. }
  58. /**
  59. * Scan XML string for potential XXE and XEE attacks
  60. *
  61. * @param string $xml
  62. * @param DomDocument $dom
  63. * @throws Zend_Xml_Exception
  64. * @return SimpleXMLElement|DomDocument|boolean
  65. */
  66. public static function scan($xml, DOMDocument $dom = null)
  67. {
  68. // If running with PHP-FPM we perform an heuristic scan
  69. // We cannot use libxml_disable_entity_loader because of this bug
  70. // @see https://bugs.php.net/bug.php?id=64938
  71. if (self::isPhpFpm()) {
  72. self::heuristicScan($xml);
  73. }
  74. if (null === $dom) {
  75. $simpleXml = true;
  76. $dom = new DOMDocument();
  77. }
  78. if (!self::isPhpFpm()) {
  79. $loadEntities = libxml_disable_entity_loader(true);
  80. $useInternalXmlErrors = libxml_use_internal_errors(true);
  81. }
  82. // Load XML with network access disabled (LIBXML_NONET)
  83. // error disabled with @ for PHP-FPM scenario
  84. set_error_handler(array('Zend_Xml_Security', 'loadXmlErrorHandler'), E_WARNING);
  85. $result = $dom->loadXml($xml, LIBXML_NONET);
  86. restore_error_handler();
  87. if (!$result) {
  88. // Entity load to previous setting
  89. if (!self::isPhpFpm()) {
  90. libxml_disable_entity_loader($loadEntities);
  91. libxml_use_internal_errors($useInternalXmlErrors);
  92. }
  93. return false;
  94. }
  95. // Scan for potential XEE attacks using ENTITY, if not PHP-FPM
  96. if (!self::isPhpFpm()) {
  97. foreach ($dom->childNodes as $child) {
  98. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  99. if ($child->entities->length > 0) {
  100. #require_once 'Exception.php';
  101. throw new Zend_Xml_Exception(self::ENTITY_DETECT);
  102. }
  103. }
  104. }
  105. }
  106. // Entity load to previous setting
  107. if (!self::isPhpFpm()) {
  108. libxml_disable_entity_loader($loadEntities);
  109. libxml_use_internal_errors($useInternalXmlErrors);
  110. }
  111. if (isset($simpleXml)) {
  112. $result = simplexml_import_dom($dom);
  113. if (!$result instanceof SimpleXMLElement) {
  114. return false;
  115. }
  116. return $result;
  117. }
  118. return $dom;
  119. }
  120. /**
  121. * Scan XML file for potential XXE/XEE attacks
  122. *
  123. * @param string $file
  124. * @param DOMDocument $dom
  125. * @throws Zend_Xml_Exception
  126. * @return SimpleXMLElement|DomDocument
  127. */
  128. public static function scanFile($file, DOMDocument $dom = null)
  129. {
  130. if (!file_exists($file)) {
  131. #require_once 'Exception.php';
  132. throw new Zend_Xml_Exception(
  133. "The file $file specified doesn't exist"
  134. );
  135. }
  136. return self::scan(file_get_contents($file), $dom);
  137. }
  138. /**
  139. * Return true if PHP is running with PHP-FPM
  140. *
  141. * This method is mainly used to determine whether or not heuristic checks
  142. * (vs libxml checks) should be made, due to threading issues in libxml;
  143. * under php-fpm, threading becomes a concern.
  144. *
  145. * However, PHP versions 5.5.22+ and 5.6.6+ contain a patch to the
  146. * libxml support in PHP that makes the libxml checks viable; in such
  147. * versions, this method will return false to enforce those checks, which
  148. * are more strict and accurate than the heuristic checks.
  149. *
  150. * @return boolean
  151. */
  152. public static function isPhpFpm()
  153. {
  154. $isVulnerableVersion = (
  155. version_compare(PHP_VERSION, '5.5.22', 'lt')
  156. || (
  157. version_compare(PHP_VERSION, '5.6', 'gte')
  158. && version_compare(PHP_VERSION, '5.6.6', 'lt')
  159. )
  160. );
  161. if (substr(php_sapi_name(), 0, 3) === 'fpm' && $isVulnerableVersion) {
  162. return true;
  163. }
  164. return false;
  165. }
  166. /**
  167. * Determine and return the string(s) to use for the <!ENTITY comparison.
  168. *
  169. * @param string $xml
  170. * @return string[]
  171. */
  172. protected static function getEntityComparison($xml)
  173. {
  174. $encodingMap = self::getAsciiEncodingMap();
  175. return array_map(
  176. array(__CLASS__, 'generateEntityComparison'),
  177. self::detectXmlEncoding($xml, self::detectStringEncoding($xml))
  178. );
  179. }
  180. /**
  181. * Determine the string encoding.
  182. *
  183. * Determines string encoding from either a detected BOM or a
  184. * heuristic.
  185. *
  186. * @param string $xml
  187. * @return string File encoding
  188. */
  189. protected static function detectStringEncoding($xml)
  190. {
  191. $encoding = self::detectBom($xml);
  192. return ($encoding) ? $encoding : self::detectXmlStringEncoding($xml);
  193. }
  194. /**
  195. * Attempt to match a known BOM.
  196. *
  197. * Iterates through the return of getBomMap(), comparing the initial bytes
  198. * of the provided string to the BOM of each; if a match is determined,
  199. * it returns the encoding.
  200. *
  201. * @param string $string
  202. * @return false|string Returns encoding on success.
  203. */
  204. protected static function detectBom($string)
  205. {
  206. foreach (self::getBomMap() as $criteria) {
  207. if (0 === strncmp($string, $criteria['bom'], $criteria['length'])) {
  208. return $criteria['encoding'];
  209. }
  210. }
  211. return false;
  212. }
  213. /**
  214. * Attempt to detect the string encoding of an XML string.
  215. *
  216. * @param string $xml
  217. * @return string Encoding
  218. */
  219. protected static function detectXmlStringEncoding($xml)
  220. {
  221. foreach (self::getAsciiEncodingMap() as $encoding => $generator) {
  222. $prefix = call_user_func($generator, '<' . '?xml');
  223. if (0 === strncmp($xml, $prefix, strlen($prefix))) {
  224. return $encoding;
  225. }
  226. }
  227. // Fallback
  228. return 'UTF-8';
  229. }
  230. /**
  231. * Attempt to detect the specified XML encoding.
  232. *
  233. * Using the file's encoding, determines if an "encoding" attribute is
  234. * present and well-formed in the XML declaration; if so, it returns a
  235. * list with both the ASCII representation of that declaration and the
  236. * original file encoding.
  237. *
  238. * If not, a list containing only the provided file encoding is returned.
  239. *
  240. * @param string $xml
  241. * @param string $fileEncoding
  242. * @return string[] Potential XML encodings
  243. */
  244. protected static function detectXmlEncoding($xml, $fileEncoding)
  245. {
  246. $encodingMap = self::getAsciiEncodingMap();
  247. $generator = $encodingMap[$fileEncoding];
  248. $encAttr = call_user_func($generator, 'encoding="');
  249. $quote = call_user_func($generator, '"');
  250. $close = call_user_func($generator, '>');
  251. $closePos = strpos($xml, $close);
  252. if (false === $closePos) {
  253. return array($fileEncoding);
  254. }
  255. $encPos = strpos($xml, $encAttr);
  256. if (false === $encPos
  257. || $encPos > $closePos
  258. ) {
  259. return array($fileEncoding);
  260. }
  261. $encPos += strlen($encAttr);
  262. $quotePos = strpos($xml, $quote, $encPos);
  263. if (false === $quotePos) {
  264. return array($fileEncoding);
  265. }
  266. $encoding = self::substr($xml, $encPos, $quotePos);
  267. return array(
  268. // Following line works because we're only supporting 8-bit safe encodings at this time.
  269. str_replace('\0', '', $encoding), // detected encoding
  270. $fileEncoding, // file encoding
  271. );
  272. }
  273. /**
  274. * Return a list of BOM maps.
  275. *
  276. * Returns a list of common encoding -> BOM maps, along with the character
  277. * length to compare against.
  278. *
  279. * @link https://en.wikipedia.org/wiki/Byte_order_mark
  280. * @return array
  281. */
  282. protected static function getBomMap()
  283. {
  284. return array(
  285. array(
  286. 'encoding' => 'UTF-32BE',
  287. 'bom' => pack('CCCC', 0x00, 0x00, 0xfe, 0xff),
  288. 'length' => 4,
  289. ),
  290. array(
  291. 'encoding' => 'UTF-32LE',
  292. 'bom' => pack('CCCC', 0xff, 0xfe, 0x00, 0x00),
  293. 'length' => 4,
  294. ),
  295. array(
  296. 'encoding' => 'GB-18030',
  297. 'bom' => pack('CCCC', 0x84, 0x31, 0x95, 0x33),
  298. 'length' => 4,
  299. ),
  300. array(
  301. 'encoding' => 'UTF-16BE',
  302. 'bom' => pack('CC', 0xfe, 0xff),
  303. 'length' => 2,
  304. ),
  305. array(
  306. 'encoding' => 'UTF-16LE',
  307. 'bom' => pack('CC', 0xff, 0xfe),
  308. 'length' => 2,
  309. ),
  310. array(
  311. 'encoding' => 'UTF-8',
  312. 'bom' => pack('CCC', 0xef, 0xbb, 0xbf),
  313. 'length' => 3,
  314. ),
  315. );
  316. }
  317. /**
  318. * Return a map of encoding => generator pairs.
  319. *
  320. * Returns a map of encoding => generator pairs, where the generator is a
  321. * callable that accepts a string and returns the appropriate byte order
  322. * sequence of that string for the encoding.
  323. *
  324. * @return array
  325. */
  326. protected static function getAsciiEncodingMap()
  327. {
  328. return array(
  329. 'UTF-32BE' => array(__CLASS__, 'encodeToUTF32BE'),
  330. 'UTF-32LE' => array(__CLASS__, 'encodeToUTF32LE'),
  331. 'UTF-32odd1' => array(__CLASS__, 'encodeToUTF32odd1'),
  332. 'UTF-32odd2' => array(__CLASS__, 'encodeToUTF32odd2'),
  333. 'UTF-16BE' => array(__CLASS__, 'encodeToUTF16BE'),
  334. 'UTF-16LE' => array(__CLASS__, 'encodeToUTF16LE'),
  335. 'UTF-8' => array(__CLASS__, 'encodeToUTF8'),
  336. 'GB-18030' => array(__CLASS__, 'encodeToUTF8'),
  337. );
  338. }
  339. /**
  340. * Binary-safe substr.
  341. *
  342. * substr() is not binary-safe; this method loops by character to ensure
  343. * multi-byte characters are aggregated correctly.
  344. *
  345. * @param string $string
  346. * @param int $start
  347. * @param int $end
  348. * @return string
  349. */
  350. protected static function substr($string, $start, $end)
  351. {
  352. $substr = '';
  353. for ($i = $start; $i < $end; $i += 1) {
  354. $substr .= $string[$i];
  355. }
  356. return $substr;
  357. }
  358. /**
  359. * Generate an entity comparison based on the given encoding.
  360. *
  361. * This patch is internal only, and public only so it can be used as a
  362. * callable to pass to array_map.
  363. *
  364. * @internal
  365. * @param string $encoding
  366. * @return string
  367. */
  368. public static function generateEntityComparison($encoding)
  369. {
  370. $encodingMap = self::getAsciiEncodingMap();
  371. $generator = isset($encodingMap[$encoding]) ? $encodingMap[$encoding] : $encodingMap['UTF-8'];
  372. return call_user_func($generator, '<!ENTITY');
  373. }
  374. /**
  375. * Encode an ASCII string to UTF-32BE
  376. *
  377. * @internal
  378. * @param string $ascii
  379. * @return string
  380. */
  381. public static function encodeToUTF32BE($ascii)
  382. {
  383. return preg_replace('/(.)/', "\0\0\0\\1", $ascii);
  384. }
  385. /**
  386. * Encode an ASCII string to UTF-32LE
  387. *
  388. * @internal
  389. * @param string $ascii
  390. * @return string
  391. */
  392. public static function encodeToUTF32LE($ascii)
  393. {
  394. return preg_replace('/(.)/', "\\1\0\0\0", $ascii);
  395. }
  396. /**
  397. * Encode an ASCII string to UTF-32odd1
  398. *
  399. * @internal
  400. * @param string $ascii
  401. * @return string
  402. */
  403. public static function encodeToUTF32odd1($ascii)
  404. {
  405. return preg_replace('/(.)/', "\0\\1\0\0", $ascii);
  406. }
  407. /**
  408. * Encode an ASCII string to UTF-32odd2
  409. *
  410. * @internal
  411. * @param string $ascii
  412. * @return string
  413. */
  414. public static function encodeToUTF32odd2($ascii)
  415. {
  416. return preg_replace('/(.)/', "\0\0\\1\0", $ascii);
  417. }
  418. /**
  419. * Encode an ASCII string to UTF-16BE
  420. *
  421. * @internal
  422. * @param string $ascii
  423. * @return string
  424. */
  425. public static function encodeToUTF16BE($ascii)
  426. {
  427. return preg_replace('/(.)/', "\0\\1", $ascii);
  428. }
  429. /**
  430. * Encode an ASCII string to UTF-16LE
  431. *
  432. * @internal
  433. * @param string $ascii
  434. * @return string
  435. */
  436. public static function encodeToUTF16LE($ascii)
  437. {
  438. return preg_replace('/(.)/', "\\1\0", $ascii);
  439. }
  440. /**
  441. * Encode an ASCII string to UTF-8
  442. *
  443. * @internal
  444. * @param string $ascii
  445. * @return string
  446. */
  447. public static function encodeToUTF8($ascii)
  448. {
  449. return $ascii;
  450. }
  451. }