[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: Скрипт защиты от XSS, SQL
Neom
Доброго всем дня. Посоветуйте пожалуйста готовый скрипт защиты от XSS, SQL инъекций. Интересует именно готовое решение в виде скрипта, чтобы можно было удобно подсоединить к другим продуктам.

Одно из исловий - поддержка PHP 4. Сам много чего перепробовал: is, sec, phpids, CrawlProtect и CrawlTrack.. но.. чтобы нормально функционировало, такое увы..

Спасибо.



Спустя 2 минуты, 45 секунд (30.06.2011 - 07:56) Семён написал(а):
Если были бы готовые решения, то и взломов как таковых не было бы)

Спустя 55 минут, 38 секунд (30.06.2011 - 08:52) inpost написал(а):
Neom
есть готовые функции: mysql_real_escape_string, (int),htmlspecialchars =)

Спустя 17 минут, 1 секунда (30.06.2011 - 09:09) XCross написал(а):
Насчет (int). Мне кто-то(уже не помню кто) писал, что она старая и нужно использовать (intval). Правильно?

Спустя 6 минут, 45 секунд (30.06.2011 - 09:15) Invis1ble написал(а):
kmaks
имхо - нет ) пруфлинк не давал?
По крайней мере depricate не выскакивает - значит все норм =)

Спустя 2 минуты, 12 секунд (30.06.2011 - 09:18) XCross написал(а):
Цитата
kmaks
имхо - нет ) пруфлинк не давал?
По крайней мере depricate не выскакивает - значит все норм =)


Не понял о чем речь. По-моему это nugle посоветовал.

Спустя 3 минуты, 20 секунд (30.06.2011 - 09:21) Invis1ble написал(а):
kmaks
Я говорю, аргументация была какая-то, кроме слов "она старая и нужно использовать (intval)" ?
Например (хотя бы), ссылка на источник, где содержится такое утверждение.
Насчет depricate - устанавливаешь уровень отображения ошибок E_ALL | E_STRICT и интерпретатор выводит предупреждения об устаревших функциях, используемых в коде.

Спустя 1 минута, 57 секунд (30.06.2011 - 09:23) XCross написал(а):
Цитата
Я говорю, аргументация была какая-то, кроме слов "она старая и нужно использовать (intval)" ?


"В новых версиях ее не будет"

Спустя 2 минуты, 40 секунд (30.06.2011 - 09:25) T1grOK написал(а):
Вот метод из kohana фреймворка, который чистит данные во избежание xss. Немного переделав можно использовать.

public static function xss_clean($str)
{
// http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.php
// +----------------------------------------------------------------------+
// | Copyright © 2001-2006 Bitflux GmbH |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License"); |
// | you may not use this file except in compliance with the License. |
// | You may obtain a copy of the License at |
// | http://www.apache.org/licenses/LICENSE-2.0 |
// | Unless required by applicable law or agreed to in writing, software |
// | distributed under the License is distributed on an "AS IS" BASIS, |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
// | implied. See the License for the specific language governing |
// | permissions and limitations under the License. |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch> |
// +----------------------------------------------------------------------+
//
// Kohana Modifications:
// * Changed double quotes to single quotes, changed indenting and spacing
// * Removed magic_quotes stuff
// * Increased regex readability:
// * Used delimeters that aren't found in the pattern
// * Removed all unneeded escapes
// * Deleted U modifiers and swapped greediness where needed
// * Increased regex speed:
// * Made capturing parentheses non-capturing where possible
// * Removed parentheses where possible
// * Split up alternation alternatives
// * Made some quantifiers possessive
// * Handle arrays recursively


if (is_array($str) OR is_object($str))
{
foreach ($str as $k => $s)
{
$str[$k] = Security::xss_clean($s);
}

return $str;
}

// Remove all NULL bytes
$str = str_replace("\0", '', $str);

// Fix &entity\n;
$str = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $str);
$str = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $str);
$str = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $str);
$str = html_entity_decode($str, ENT_COMPAT, Kohana::$charset);

// Remove any attribute starting with "on" or xmlns
$str = preg_replace('#(?:on[a-z]+|xmlns)\s*=\s*[\'"\x00-\x20]?[^\'>"]*[\'"\x00-\x20]?\s?#iu', '', $str);

// Remove javascript: and vbscript: protocols
$str = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $str);
$str = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $str);
$str = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $str);

// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#is', '$1>', $str);
$str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#is', '$1>', $str);
$str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#ius', '$1>', $str);

// Remove namespaced elements (we do not need them)
$str = preg_replace('#</*\w+:\w[^>]*+>#i', '', $str);

do
{
// Remove really unwanted tags
$old = $str;
$str = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|objec t|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $str);
}
while ($old !== $str);

return $str;
}

Спустя 11 минут, 9 секунд (30.06.2011 - 09:37) Invis1ble написал(а):
kmaks
хз, вот мини-проверка:
error_reporting(E_ALL | E_STRICT);
ereg('##', '');
(
int)'10';

у меня PHP 5.3.2 - насчет (int) не ругается
Да, кстати насчет E_STRICT - это не то :) Deprecated и без него выскакивает

Спустя 1 месяц, 3 дня, 9 часов, 19 минут, 33 секунды (3.08.2011 - 18:56) AlexanderC написал(а):

final class SecurityCore
{
// just init vars
private $XSSHashe = '';
private $CurrentKey;

// never allowed, string replacement
private $NeverAllowedStr = array
(
'document.cookie' => '[removed]',
'document.write' => '[removed]',
'.parentNode' => '[removed]',
'.innerHTML' => '[removed]',
'window.location' => '[removed]',
'-moz-binding' => '[removed]',
'<!--' => '<!--',
'-->' => '-->',
'<![CDATA[' => '<![CDATA['
);

// never allowed, regex replacement
private $NeverAllowedRegex = array
(
"javascript\s*:" => '[removed]',
"expression\s*(\(|&\#40;)" => '[removed]', // CSS and IE
"vbscript\s*:" => '[removed]', // IE, surprise!
"Redirect\s+302" => '[removed]'
);

private $NougthyTags = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|h ead|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|vid eo|xml|xss';

/**
* clean incomming data
*
@access public
*
@param mix, bool
*
@return mix
*
@todo rename stupid named vars and others and beatify the code
*/

function SafeData($str, $is_image = false, $denyOnlyNoughty = false )
{
// safe data recursively
if (is_array($str))
{
while (list($key) = each($str))
{
unset( $this->CurrentKey );
$this->CurrentKey = $key;
$str[$key] = $this->SafeData($str[$key]);
}
return $str;
}
// case no tags
if ( !$denyOnlyNoughty && !$is_image)
{
return strip_tags($str);
}
// remove invisible characters
$str = $this->ric($str);

// start regexp
$str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->XSSHashe()."\\1=\\2", $str);

$str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);

$str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str);

$str = str_replace($this->XSSHashe(), '&', $str);

$str = rawurldecode($str);

$str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, 'conv_attr'), $str);

$str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, 'html_edc'), $str);

// remove invisible characters
$str = $this->ric($str);

if (strpos($str, "\t") !== false)
{
$str = str_replace("\t", ' ', $str);
}

$converted_string = $str;

foreach ($this->NeverAllowedStr as $key => $val)
{
$str = str_replace($key, $val, $str);
}

foreach ($this->NeverAllowedRegex as $key => $val)
{
$str = preg_replace("#".$key."#i", $val, $str);
}

if ($is_image === true)
{
$str = preg_replace('/<\?(php)/i', "<?\\1", $str);
}
else
{
$str = str_replace(array('<?', '?'.'>'), array('<?', '?>'), $str);
}

$words = array('javascript', 'expression', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');
foreach ($words as $word)
{
$temp = '';

for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++)
{
$temp .= substr($word, $i, 1)."\s*";
}

$str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, 'comp_ex_w'), $str);
}

do
{
$original = $str;

if (preg_match("/<a/i", $str))
{
$str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", array($this, 'js_lr'), $str);
}

if (preg_match("/<img/i", $str))
{
$str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", array($this, 'js_imgr'), $str);
}

if (preg_match("/script/i", $str) || preg_match("/xss/i", $str))
{
$str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str);
}
}

while($original != $str);

unset($original);

$event_handlers = array('[^a-z_\-]on\w*','xmlns');

if ($is_image === true)
{
unset($event_handlers[array_search('xmlns', $event_handlers)]);
}

$str = preg_replace("#<([^><]+?)(".implode('|', $event_handlers).")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);

$naughty = $this->NougthyTags;
$str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, 'san_html'), $str);

$str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|un link)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);

foreach ($this->NeverAllowedStr as $key => $val)
{
$str = str_replace($key, $val, $str);
}

foreach ($this->NeverAllowedRegex as $key => $val)
{
$str = preg_replace("#".$key."#i", $val, $str);
}
if ($is_image === true)
{
if ($str == $converted_string)
{
return true;
}
else
{
return true;
}
}

return $str;
}

// remove invisible characters from a string
function ric($str, $url_encoded = true)
{
$non_displayables = array();

// every control character except newline (dec 10)
// carriage return (dec 13), and horizontal tab (dec 09)


if ($url_encoded)
{
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}

$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127

do
{
$str = preg_replace($non_displayables, '', $str, -1, $count);
}
while ($count);

return $str;
}

// random hash for protecting url
public function XSSHashe()
{
if ($this->XSSHashe == '')
{
if (phpversion() >= 4.2)
{
mt_srand();
}
else
{
mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
}

$this->XSSHashe = md5(time() + mt_rand(0, 1999999999));
}

return $this->XSSHashe;
}

// remove some js
function js_lr($match)
{
return preg_replace("#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $match[0]);
}

// remove js
function js_imgr($match)
{
return preg_replace("#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si", "", $match[0]);
}

// remove extra whitespaces
function comp_ex_w($matches)
{
return preg_replace('/\s+/s', '', $matches[1]) . $matches[2];
}
// convert atributes
function conv_attr($match)
{
return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]);
}
// extended html entities decode
function html_edc($match)
{
return $this->html_e_d($match[0]);
}
// native decode html entities
function html_e_d($str, $charset='UTF-8')
{
if (stristr($str, '&') === FALSE) {
return $str;
}

if (
function_exists('html_entity_decode') &&
(

strtolower($charset) != 'utf-8' ||
version_compare(phpversion(), '5.0.0', '>=')
)
)
{
$str = html_entity_decode($str, ENT_COMPAT, $charset);
$str = preg_replace('~&#x([0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
}
// Numeric Entities
$str = preg_replace('~&#x([0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
$str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);
// Literal Entities - Slightly slow so we do another check
if (stristr($str, '&') === FALSE) {
$str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
}
return $str;
}
// sanitize naugthy html
function san_html($matches)
{
$str = '<' . $matches[1] . $matches[2] . $matches[3];
$str .= str_replace(array('>', '<'), array('>', '<'), $matches[4]);
return $str;
}
}


Спустя 52 минуты, 34 секунды (3.08.2011 - 19:49) twin написал(а):

Спустя 4 минуты, 35 секунд (3.08.2011 - 19:53) twin написал(а):
Цитата (kmaks @ 30.06.2011 - 06:09)
Насчет (int). Мне кто-то(уже не помню кто) писал, что она старая и нужно использовать (intval). Правильно?

(int) - языковая конструкция. Она приводит данные к целочисленному виду. intval() - функция. Делает тоже самое. Первая реализована на уровне ядра PHP, вторая - в библиотеке. А значит (int) никогда никуда не денется - раз, на порядок быстрее - два.

Спустя 2 дня, 23 часа, 44 минуты, 46 секунд (6.08.2011 - 19:38) HAKIM написал(а):
вот что я юзаю ;)

function xss($name){
return htmlspecialchars(mysql_escape_string(trim($name)));
}

а для целых чисел

$c = abs(intval($c));

Проблем не вижу.. имхо

Спустя 3 минуты, 41 секунда (6.08.2011 - 19:42) Winston написал(а):
Цитата (HAKIM @ 6.08.2011 - 19:38)
abs(intval($c))

Ну-ну кто-то -5 поставит оно переведет в положительное число, а это не гут.

Спустя 4 минуты, 11 секунд (6.08.2011 - 19:46) Invis1ble написал(а):
Цитата
function xss($name){
return htmlspecialchars(mysql_escape_string(trim($name)));
}

Цитата
$c = abs(intval($c));

очередная хренотень, имхо wink.gif

Спустя 3 минуты, 16 секунд (6.08.2011 - 19:49) Winston написал(а):
Цитата (Invis1ble @ 6.08.2011 - 19:46)
очередная хренотень, имхо

Так будет еще безопасней B)
function xss($name){
return nl2br(htmlspecialchars(mysql_escape_string(strip_tags(trim($name)))));
}


:lol: :lol:

Спустя 9 минут, 42 секунды (6.08.2011 - 19:59) Invis1ble написал(а):
Цитата
nl2br(htmlspecialchars(mysql_escape_string(strip_tags(trim($name)))));

это уже классика :)
можно добавить еще пару приемчиков, чтоб уже наверняка:
nl2br(addslashes(addcslashes(htmlspecialchars(mysql_real_escape_string(mysql_escape_string(strip_tags(rtrim(ltrim(trim($name)))))))))) // to be continued... :)

Спустя 1 минута, 59 секунд (6.08.2011 - 20:01) Winston написал(а):
Цитата (Invis1ble @ 6.08.2011 - 19:59)
nl2br(addslashes(addcslashes(htmlspecialchars(mysql_real_escape_string(mysql_escape_string(strip_ta gs(trim($name)))))))) // to be continued... smile.gif

Ну все, это уже супер-мега защита laugh.gif

Спустя 11 часов, 17 минут, 9 секунд (7.08.2011 - 07:18) HAKIM написал(а):
а зачем тебе ,допустим , запрос в базу, или это постраничная навигация...
я в общем то целенаправлено abs() юзаю

Спустя 3 минуты, 3 секунды (7.08.2011 - 07:21) HAKIM написал(а):
laugh.gif
я вам не говорил что в нужных местах всё равно регулярку юзаю laugh.gif

Спустя 4 минуты, 56 секунд (7.08.2011 - 07:26) Invis1ble написал(а):
HAKIM
Цитата
в нужных местах

например? )

Спустя 2 дня, 12 часов, 43 минуты, 49 секунд (9.08.2011 - 20:10) HAKIM написал(а):
та же проверка мыла wink.gif
Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.