S
S
superpupervest2019-07-11 17:45:45
Burglary protection
superpupervest, 2019-07-11 17:45:45

How to make universal protection against xss attacks and sql injections?

I do not provide technical support for sites, but it so happened that I am often asked for help. On the one hand, it’s inconvenient to refuse, and it’s not profitable from a commercial point of view, on the other hand, you won’t pay for a big thank you in the store either. Therefore, I decided to write a universal solution, but I ran into some problems.
The essence of the solution is to catch POST, GET, COOKIE data and process them before the site performs any actions with them.
Here is the actual code

$jsxss="onabort,oncanplay,oncanplaythrough,ondurationchange,onemptied,onended,onerror,onloadeddata,onloadedmetadata,onloadstart,onpause,onplay,onplaying,onprogress,onratechange,onseeked,onseeking,onstalled,onsuspend,ontimeupdate,onvolumechange,onwaiting,oncopy,oncut,onpaste,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,onblur,onfocus,onfocusin,onfocusout,onchange,oninput,oninvalid,onreset,onsearch,onselect,onsubmit,onabort,onbeforeunload,onerror,onhashchange,onload,onpageshow,onpagehide,onresize,onscroll,onunload,onkeydown,onkeypress,onkeyup,altKey,ctrlKey,shiftKey,metaKey,key,keyCode,which,charCode,location,onclick,ondblclick,oncontextmenu,onmouseover,onmouseenter,onmouseout,onmouseleave,onmouseup,onmousemove,onwheel,altKey,ctrlKey,shiftKey,metaKey,button,buttons,which,clientX,clientY,detail,relatedTarget,screenX,screenY,deltaX,deltaY,deltaZ,deltaMode,animationstart,animationend,animationiteration,animationName,elapsedTime,propertyName,elapsedTime,transitionend,onerror,onmessage,onopen,ononline,onoffline,onstorage,onshow,ontoggle,onpopstate,ontouchstart,ontouchmove,ontouchend,ontouchcancel,persisted,javascript";
$jsxss = explode(",",$jsxss);
foreach($_POST as $k=>$v)
{
  if(is_array($v))
  {
    foreach($v as $Kk=>$Vv)
    {
      $Vv = preg_replace ( "'<script[^>]*?>.*?</script>'si", "", $Vv );
      $Vv = str_replace($jsxss,"",$Vv);
      $Vv = str_replace (array("*","\\"), "", $Vv );
      $Vv = strip_tags($Vv);
      $Vv = htmlentities($Vv, ENT_QUOTES, "UTF-8");
      $Vv = htmlspecialchars($Vv, ENT_QUOTES);
      $_POST[$k][$Kk] = $Vv;
    }
  }
  ELSE
  {
    //Сначала удаляем любые скрипты для защиты от xss-атак
    $v = preg_replace ( "'<script[^>]*?>.*?</script>'si", "", $v );
    //Вырезаем все известные javascript события для защиты от xss-атак
    $v = str_replace($jsxss,"",$v);
    //Удаляем экранированание для защиты от SQL-иньекций
    $v = str_replace (array("*","\\"), "", $v );
    //Экранируем специальные символы в строках для использования в выражениях SQL
    $v = mysql_real_escape_string( $v );
    //Удаляем другие лишние теги.	
    $v = strip_tags($v);
    //Преобразуеv все возможные символы в соответствующие HTML-сущности
    $v = htmlentities($v, ENT_QUOTES, "UTF-8");
    $v = htmlspecialchars($v, ENT_QUOTES);
    //Перезаписываем GET массив
    $_POST[$k] = $v;
  }
  
}

I did the same by analogy with _GET and _COOKIE
. Main disadvantages.
1) I never managed to process, or rather rewrite them inside the function and pass _POST, _GET and _COOKIE as variables, and most importantly, as a result, process multidimensional data arrays recursively. Accordingly, $_POST[][], $_POST[][][] and so on cannot be processed, and each such array must be inserted separately. The array can be infinitely large, and the code will be infinitely cumbersome.
2) You don't want to remove the mysql_real_escape_string function because you never know where they forgot to mention it, but the problem of excessive character escaping arises.
3) strip_tags removes all tags. I would not want to remove everything, but only the most dangerous tags, but the trouble is that in the additional parameters you can specify only the tags that you need to leave. Of course, you can use regular expressions, but unfortunately, there is no guarantee that you will not forget something important, so if someone has a great replacement for this, then I suggest collecting everything in a heap and getting rid of strip_tags
4) Well, I'm waiting other advice on the subject.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2019-07-11
@sim3x

WAF
Или переписать дырявую реализацию нормально

X
xmoonlight, 2019-07-11
@xmoonlight

Как защитить сайты от взлома?

Алексей Николаев, 2019-07-11
@Heian

Ничего не нужно фильтровать. Просто перед тем, как выводить контент, заменяете html-сущности (для предотвращения xss) на соотв. символы и используете PDO (для предотвращения инъекций).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question