Failed to load external entity xml php

Разъяснения по уязвимостям XXE в версиях PHP

Я задаю вопрос здесь в качестве крайней меры, я просмотрел веб-страницы и прошел множество попыток, но не смог. Репликация атаки XXE — это то, что я пытаюсь сделать, чтобы предотвратить их, но я не могу понять, как работает PHP с объектами XML. Для записи я использую PHP 5.5.10 на Ubuntu 12.04, но я провел несколько тестов на 5.4 и 5.3, а libxml2, похоже, имеет версию 2.7.8 (которая, похоже, не включает дефолт по умолчанию, чтобы не разрешать сущности). В следующем примере вызов функции libxml_disable_entity_loader() с true или false не имеет никакого эффекта, или я делаю что-то неправильно.

$xml =  ]> Test &c;  XML; libxml_disable_entity_loader(true); $dom = new DOMDocument(); $dom->loadXML($xml); // Prints Test. print $dom->textContent; 

Но я мог бы специально передать некоторые аргументы loadXML(), чтобы разрешить некоторые параметры, и это работает, когда объект является локальным файлом, а не когда он является внешним URL-адресом.

$xml =  ]> Test &c;  XML; $dom = new DOMDocument(); $dom->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD); // Prints Test. print $dom->textContent; 

Теперь, если мы меняем объект на что-то еще, как в следующем примере, объект разрешен, но я вообще не мог отключить его с помощью параметров или функции. Что происходит?!

$xml =  ]> Test &c;  XML; $dom = new DOMDocument(); $dom->loadXML($xml); // Prints Test. print $dom->textContent; 

Затем они разрешаются или нет.

Итак, чтобы обобщить, я бы очень хотел понять, что я, очевидно, не понимаю. Почему эти параметры и функции кажутся неэффективными? Является ли libxml2 приоритетом над PHP?

Независимо от того, что я пытаюсь, я получаю только «Предупреждение: DOMDocument :: loadXML (): предупреждение ввода-вывода: не удалось загрузить внешнюю сущность» файл: // путь / к / полностью / квалифицирован / путь / решен / к / php / script /the/xml/is/loaded/in/file.xml «в script.php в строке, где $dom->loadXML($xml); « — это работает с наличием собственного libxml_set_external_entity_loader который принимает вслепую. Может быть, это был отключен из-за проблем с безопасностью? может быть файл catalog.xml отсутствует / используется? — Итог: проверьте ваши сообщения об ошибках вкл. Предупреждения и уведомления, вы можете узнать больше, чем в вашем случае.

Читайте также:  Failed to launch java

Я также столкнулся с этой ошибкой, но, похоже, это происходило только тогда, когда я использовал simplexml_load_file() .

У меня есть это с DOMDocument. У меня не было каталога через настроенные переменные среды. NOENT необходимо установить на loadXML. Если я напишу свой собственный загрузчик entieties, который обрабатывает файлы на диске, я могу инициировать атаку, когда она загружается из файловой системы (хотя в моей системе не было /etc/passwd но я знаю, что вы ищете 🙂 )

@FMC Насколько я знаю, libxml_disable_entity_loader() отключает поддержку внешних объектов и предотвращает атаки XEE. Вы говорите нам, что это не работает?

Что ж, я говорю о том, что «включение» загрузчика сущностей, похоже, не работает с этой функцией. Так что это немного затрудняет симуляцию проблемы. Или, по крайней мере, мне не удалось. Я также теперь узнал, что эта функция не является поточно-ориентированной, что означает, что вы фактически воздействуете на все остальные потоки, когда вызываете ее .

Безопасность потоков является проблемой только в том случае, если вы используете определенные PHP SAPI, которые я обычно не рекомендую использовать в PHP (читай: mod_php в Apache или, что еще хуже, некоторые грубые M $ IIS) — @Evert: Это также то, что я вижу из пространства пользователей PHP.

Источник

How to Fix «simplexml_load_file(): I/O warning: failed to load external entity ‘. ‘» PHP Warning?

If you see the following error/warning when using the simplexml_load_file() function:

Warning: simplexml_load_file(): I/O warning : failed to load external entity ". " in /path/to/file.php on line .

Then it means that you have likely provided the XML you wish to load from a file as a string to the simplexml_load_file() function argument (instead of the path to that XML file). It could, for example, happen in the following case:

$xmlStr = file_get_contents('/path/to/file.xml'); $xml = simplexml_load_file($xmlStr); // .

In the example above, using the file_get_contents() function returns a string of loaded XML. When you provide that as an argument to the simplexml_load_file() function, it throws a warning because it is expecting the path of the XML file as an argument and not a string. To solve this, you can do any of the following:

Читайте также:  Hello world program with java

Use the XML String With SimpleXMLElement Object Instance

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the SimpleXMLElement object instance. For example:

$xmlStr = file_get_contents('/path/to/file.xml'); $xml = new SimpleXMLElement($xmlStr); // .

Load the XML File Directly With simplexml_load_file()

You could directly provide the XML file path to the simplexml_load_file() function, and it will return a SimpleXMLElement object instance on success (and false on failure). For example:

$xml = simplexml_load_file('/path/to/file.xml'); // .

Use the XML String With simplexml_load_string()

You could, for example, use file_get_contents() to first load the XML file into a string, and then provide that as an argument to the simplexml_load_string() function — which would interpret the string of XML into a SimpleXMLElement object instance on success (and return false on failure). For example:

$xmlStr = file_get_contents('/path/to/file.xml'); $xml = simplexml_load_string($xmlStr); // .

Hope you found this post useful. It was published 26 Aug, 2022 . Please show your love and support by sharing this post.

Источник

Warning: simplexml_load_file(): I/O Magento warning : failed to load external entity “/var/www/app/etc/local.xml”

I have this issue in my magento installation Warning: simplexml_load_file(): I/O warning : failed to load external entity «/var/www/app/etc/local.xml» in /var/www/app/Mage.php on line 767 setting libxml_disable_entity_loader(false); solves this issue but I will have to do it for every simplexml_load_file() Is there any better solution and also if anyone could shed some light on how this issue might have occurred?

The community can provide better/more details answers for you if you provide mor information (Magento/PHP versions, extensions, latest changes), otherwise it’s difficult to guess. Regarding your problem: * app/etc/local.xml is maye not readable: Check file permissions, * Possible XML-Error in config files? Did you make changes lately? * PHP Bug with PHP Version master-Git-2012-07-16: bugs.php.net/bug.php?id=62577

The XML is missing in your question as well. You for sure need to provide more information here. Also it’s not clear from your question what your understanding of the error message is.

Читайте также:  Css background png base64

2 Answers 2

As a followup on this: I have the same issue as well — randomly — when loading any XML file using simplexml_load_file() on the same server with any application (WordPress, Magento, Joomla). The reason is definitely not that the XML file contains bad characters, bad formatting or does not exist. The issue seems to be related to a pending PHP bug, that occurs when too many PHP applications rely on SimpleXML on the same server.

On a deeper level, the SimpleXML library uses kind of caching that is persistent across multiple requests within the same PHP thread (PHP-FPM instance, mod_php instance, etcetera). It is said to be fixed by updating PHP 5.4, but that hasn’t worked yet for me. It does not occur with PHP 5.5 or higher.

One fix is to override app/Mage.php with the following — locate the commented line and replace it with 3 lines. Core hack, ugly, should not be done, wash your mouth. But it works.

//$localConfig = simplexml_load_file($localConfigFile); $xmlString = file_get_contents($localConfigFile); $localConfig = simplexml_load_string($xmlString);

Источник

ошибка Simplexml

Fatal error: Uncaught exception ‘Exception’ with message ‘String could not be parsed as XML’ in O:\home\localhost\www\index.php:12 Stack trace: #0 O:\home\localhost\www\index.php(12): SimpleXMLElement->__construct(») #1 thrown in O:\home\localhost\www\index.php on line 12.

Может у меня не установлено расширение для использования ?

Не могу разобарться с simplexml
Добрый день. У меня сайт на html+php, и в директории лежит xml файл. Пытаюсь с помощью simplexml.

SimpleXML, обращение к элемнту
Как мне обращаться, например, к элементу <File><track type="General"><Format> ? echo.

Foreach simpleXml непонятно
Доброго времени суток. Объясните мне кто-нибудь таку. вещь: есть xml файл <?xml version="1.0".

Simplexml не обрабатывает xml
$smpl_xml=simplexml_load_file($_SERVER.’/prod.xml’) не может обработать xml, файл слишком большой.

Эксперт HTML/CSSЭксперт PHP

ЦитатаСообщение от koza4ok Посмотреть сообщение

$xmlstr=simplexml_load_file(xml.xml);
$xmlstr=simplexml_load_file('xml.xml');
$xmlstr=simplexml_load_file('xml.xml');

Добавлено через 1 час 20 минут
Вопрос читал что Dom способ парсинга очень грузит систему.
Сейчас используют SAX или DOM?

Источник

Оцените статью