茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1674662 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
HoneyMoon_Day3_00089.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

PHP特區 : [轉載]PHP SQL Injection 和 XSS 的偵測程式 和 程式撰寫注意事項

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉載]PHP SQL Injection 和 XSS 的偵測程式 和 程式撰寫注意事項

PHP SQL Injection 和 XSS 的偵測程式 和 程式撰寫注意事項 - 2008

程式的安全, 除了本身自己該注意的事項外, 還有不少偵測程式, 可以幫你避免掉意外狀況.

此文章加上年份的資料, 主要是因為安全性會隨著時間演變, 原本安全的程式也會變的不安全(ex: XSS), 所以本篇文章是 2008 年寫的, 或許到 2009 年就過時囉, 請把此篇當參考, 再去看最新的安全資訊會比較保險.(不過就算過時, 請還是不要把它遺漏掉, 過時的漏洞還是漏洞, 還是會有安全性的問題產生)

關於安全的資訊, 先講結論就是: 網路是危險的. 大家能做到的就是盡可能的保護, 但是無法保證絕對的安全.(另外 安全方便 通常是呈反比的)

這兩篇文章/簡報都蠻值得看看, 有助於瞭解下面為何要做那些事, 和其它的防範:

下述先就幾方面做整理:

  1. PHP 程式撰寫上該注意到的事項
  2. SQL Injection/XSS(Cross-site scripting attacks) 偵測程式(白箱/黑箱測試)
  3. PHP 系統上的注意事項

  4. 相關文章整理

PHP 程式撰寫上該注意到的事項

首先對於安全的認知, 就是 外部拉到的資料(使用者送出的資料), 都是不安全的, 都要做嚴謹的檢查.

哪些是外部拉到的資料(使用者送出的資料)?

  • GET: $_GET (Form submit/網址列參數)
  • POST: $_POST
  • REQUEST: $_REQUEST
  • COOKIE: $_COOKIE
  • JSON/AJAX/合作廠商送的資料/讀取檔案, 要將資料寫入 DB 的 Data 等.

有人常會說用 Framework 就可以避免掉這種事情, 個人認為這是不太正確的想法, 因為太依賴 Framework, 反而有可能造成安全上的漏洞.(註: 並不是指不要用 Framework, 而是用 Framework 還是要注意下述的安全問題)

ex: Framework 通常會幫你做好 SQL Injection 預防的處理, 但是於 XSS 的處理上, 這通常還是得要有自己的認知, 哪些地方能使用 HTML, 秀出來的 HTML 要做過哪些處理? 允許哪些 HTML Tag? 要怎麼過濾? 這些一般 Framework 並沒辦法幫你做決定, 處理上也沒那麼容易.

PHP 本身已經提供預防各類安全問題的處理方法, 下述就簡單列出來, 不過隨時代演進, 會跟著改變, 就看當下的狀況來處理囉~

PHP 設定檔(php.ini)
  • 轉載 LAMP 攻防簡報裡的內容, 不過 magic_quotes_gpc 做個修改
  • register_global = off (全域變數)
  • magic_quotes_gpc = off (' => \' , " => \" , %00 => \ 0) (建議 magic_quotes_gpc = off 自己處理)
  • display_error = off (在網頁上顯示錯誤訊息)
  • log_error = on (紀錄錯誤訊息)

  • allow_url_fopen = off (可開啟遠端網頁)
  • expose_php = off (顯示PHP 版本資訊)
  • open_basedir = (允許開啟的目錄)
  • safe_mode = on (安全模式)
  • disable_function = (禁止使用的函數)
  • safe_mode_include_dir = (允許include的目錄)
PHP 接收參數 GET/POST/REQUEST/COOKIE/SERVER/ENV.

PHP Filter Functions(要安裝 Pecl filter)

沒有使用此 Filter 也無所謂, 重點是要做嚴謹的檢查.(ex: integer, 年月日.. 等)

PHP 於寫入 DB 階段:( SQL Injection)
PHP 於 HTML 頁面的呈現(無法讓 User 使用 HTML 情況)
PHP 於 HTML 頁面的呈現(讓 User 使用 HTML 情況)
PHP 於 Shell script command(呼叫外部程式帶入參數, ex: system, exec)
瀏覽器 URL列 GET 的參數傳送



urlencode
: 將要傳的參數值都要經過 urlencode, 這主要是符合標準 ( RFC 1738).

PHP Source code 加密(Encrypt), 某些商業用途採用
SQL Injection/XSS(Cross-site scripting attacks) 偵測程式(白箱/黑箱測試)

註: 這些工具請不要拿去玩其它網站, 只做自己程式/網站的掃描測試用.

程式本身需要加 mysql_escape_string/htmlspecialchars 等(上述挑其一方法做), 總會有不小心漏掉, 或者那是外來程式 等, 下述的工具可以來做簡單的檢測~ (我目前使用 Wapiti 和 Pixy, 其它就不太熟了.)

PHP 系統上的注意事項

系統上該注意的, 就是本身系統要更新, 然後 PHP 部份, 就是把 Suhosin 裝起來.

安裝方法有下述兩種:

相關文章整理

上述感覺不到危險的, 這幾篇文章可以自己試著測試自己寫的程式看看.(請不要拿來測試非自己的網站/程式)

下述就比較偏向其它相關文章整理


原文出處:PHP SQL Injection 和 XSS 的偵測程式 和 程式撰寫注意事項 - 2008 - Tsung's Blog
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉載]input 所有過濾與攻擊

[PHP] input所有過濾與攻擊

SQL注入攻擊(SQL injection attack)

在password部分輸入’ or ’1′=’1,這將會造成整個SQL query 呈現以下的形式,使得
WHERE中整個判斷式為真,所以此使用者即便沒有帳號密碼也順利登入系統。



$sql = "select count(*) as ctr from users where
username='foo' and password='' or '1'='1' limit 1";

可以簡單地用PHP內建的函式mysql_real_escape_string()來解決
,mysql_real_escape_string()是用來脫逸資料庫語法中的特殊字元,像是\ ,’,」。



$sql = "select count(*) as ctr from users where
username='".mysql_real_escape_string($username)."'
and password='". mysql_real_escape_string($pw)."' limit 1";

緩衝器溢位攻擊(buffer overflow attack)

主要是藉由 overflow the memory allocation buffer,造成網頁應用程式 denial of
service、資料損毀或藉機對主機執行惡意的程式。要防止 buffer overflow attack 最大
的重點就是檢查使用者輸入資料的長度。



<input id="name" type="text" maxlength="40" name="name" size="20" />

除此之外



$name = substr($_POST['name'],0,20);

這可以擷取從0到第20個字元的字 後面太長的就不要了 避免塞進去sql會有問題
跨站腳本攻擊(cross-site scripting)

可利用 PHP 內建的函式 strip_tags() 去除字串中的 HTML 和 PHP 標籤,同時這函式也
可以自己設定可接受的 tags(例如:<b>、<i>)。

如果你開放使用者使用 HTML 標籤來發表內容的話,就必須使用 htmlspecialchars() 讓
使用者輸入的 HTML 標籤保留它的意義,例如此函式會將 ampersand (&) 轉化成 &amp ;
將 < 和 > 視為 HTML entities。



$name = strip_tags($_POST['name']);
$name = substr($name,0,40);

操縱瀏覽器內的資料(manipulating data inside the browser)

就是利用一些工具來修改form的資料,這我常幹所以就不用多說了,不過話說回來
這就表示 儘量不要使用 hidden 的方式傳送變數,避免透露過多和系統操作相關的訊息

沒其他解 就這樣

遠程表格遞交(remote form posting)

使用者瀏覽網頁時,任何人都可以用「另存新檔」的方式複製一份網頁檔案到自己電腦中
這時對方的 server 會把它視為合法的資料,但這個 request並非由本身 server 所發出。
這個我也很常玩學校 portal我就玩過了

要防制 remote form posting 的攻擊可產生一個 token,為一個獨特的字串或者是一個
timestamp,再將這個 token 存進 session 以及放入表單中,藉由檢查這兩個 tokens 是
否相同,來判定是否是 remote的表單發出的request。



<!--?php <br ?-->session_start();
if ($_POST['submit'] == "go"){
//check token
if ($_POST['token'] == $_SESSION['token']){正確}else{錯誤}
$token = md5(uniqid(rand(), true));
$_SESSION['token']= $token;
<input type="hidden" name="token" value=""<?php" />"/>

——————————————————————

nl2br函數的功能在於把字串裡的換行\n換成<br>

//去掉開始和結束的空白
$str = trim($str);
//去掉跟隨別的擠在一塊的空白
$str = preg_replace(‘/\s(?=\s)/’, “, $str);
//最後,去掉非space 的空白,用一個空格代替
$str = preg_replace(‘/[\n\r\t]/’, ‘ ‘, $str);

———————————————————————–

我知道平常一定懶得看 所以來個總結

$name =substr( strip_tags(addslashes(trim($_POST['name']))),0,40);

預防過長字串(除HTML PHP標籤(引號前加上跳脫(除去前後空白)))

一般input收到的資料 直接套用上面這些就好 如果還有想到其他的在用吧
或是更簡單一點 把她寫成一個function 會比較乾淨
→ davidou:不過SQL injection 那個我記得測試過apache會直接檔掉了 09/21


原文出處:[PHP] input所有過濾與攻擊 各種駭客攻擊手法 | Davidou's Blog
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉載]PHP通用的XSS攻擊過濾函數,Discuz系統中 防止XSS漏洞攻擊,過濾HTML危險標籤屬性的PHP函數
PHP通用的XSS攻擊過濾函數,Discuz系統中 防止XSS漏洞攻擊,過濾HTML危險標籤屬性的PHP函數

作者:SNSGOU 發佈於:2013-07-01 21:13:18 分類:網絡基礎/Web安全

XSS攻擊在最近很是流行,往往在某段代碼裡一不小心就會被人放上XSS攻擊的代碼,看到國外有人寫上了函數,咱也偷偷懶,悄悄的貼上來。。。
原文如下:

The goal of this function is to be a generic function that can be used to parse almost any input and render it XSS safe. For more information on actual XSS attacks, check out http://ha.ckers.org/xss.html. Another excellent site is the XSS Database which details each attack and how it works.

01	<?php
02	function RemoveXSS($val) {
03	   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
04	   // this prevents some character re-spacing such as <javascript>
05	   // note that you have to handle splits with
06	,
07	, and    later since they *are* allowed in some inputs
08	   $val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);
09
10	   // straight replacements, the user should never need these since they're normal characters
11	   // this prevents like <IMG SRC=@avascript:alert('XSS')>
12	   $search = 'abcdefghijklmnopqrstuvwxyz';
13	   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
14	   $search .= '1234567890!@#$%^&*()';
15	   $search .= '~`";:?+/={}[]-_|'\';
16	   for ($i = 0; $i < strlen($search); $i++) {
17	      // ;? matches the ;, which is optional
18	      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
19
20	      // @ @ search for the hex values
21	      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
22	      // @ @ 0{0,7} matches '0' zero to seven times
23	      $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
24	   }
25
26	   // now the only remaining whitespace attacks are     ,
27	, and
28
29	   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml',
              'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame',
              'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
30	   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate',
              'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus',
              'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate',
              'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu',
              'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged',
              'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend',
              'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
              'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus',
              'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup',
              'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter',
              'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup',
              'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange',
              'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
              'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll',
              'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop',
              'onsubmit', 'onunload');
31	   $ra = array_merge($ra1, $ra2);
32
33	   $found = true; // keep replacing as long as the previous round replaced something
34	   while ($found == true) {
35	      $val_before = $val;
36	      for ($i = 0; $i < sizeof($ra); $i++) {
37	         $pattern = '/';
38	         for ($j = 0; $j < strlen($ra[$i]); $j++) {
39	            if ($j > 0) {
40	               $pattern .= '(';
41	               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
42	               $pattern .= '|';
43	               $pattern .= '|(�{0,8}([9|10|13]);)';
44	               $pattern .= ')*';
45	            }
46	            $pattern .= $ra[$i][$j];
47	         }
48	         $pattern .= '/i';
49	         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
50	         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
51	         if ($val_before == $val) {
52	            // no replacements were made, so exit the loop
53	            $found = false;
54	         }
55	      }
56	   }
57
58	   return $val;
59	}
60	?>

經過這樣的過濾後,應該被攻擊的機會會少上很多吧?試試看呢?


Discuz系統中 防止XSS漏洞攻擊,過濾HTML危險標籤屬性的PHP函數
01	//屏蔽html
02	function checkhtml($html) {
03	    $html = stripslashes($html);
04	    if(!checkperm('allowhtml')) {
05
06	        preg_match_all("/<([^<]+)>/is", $html, $ms);
07
08	        $searchs[] = '<';
09	        $replaces[] = '<';
10	        $searchs[] = '>';
11	        $replaces[] = '>';
12
13	        if($ms[1]) {
14	            $allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br
15	                        |p|b|strong|i|u|em|span|ol|ul|li|blockquote
16	                        |object|param|embed';//允許的標籤
17	            $ms[1] = array_unique($ms[1]);
18	            foreach ($ms[1] as $value) {
19	                $searchs[] = "<".$value.">";
20	                $value = shtmlspecialchars($value);
21	                $value = str_replace(array('\','/*'), array('.','/.'), $value);
22	                $skipkeys = array(
23	                        'onabort','onactivate','onafterprint','onafterupdate',
24	                        'onbeforeactivate','onbeforecopy','onbeforecut',
25	                        'onbeforedeactivate','onbeforeeditfocus','onbeforepaste',
26	                        'onbeforeprint','onbeforeunload','onbeforeupdate',
27	                        'onblur','onbounce','oncellchange','onchange',
28	                        'onclick','oncontextmenu','oncontrolselect',
29	                        'oncopy','oncut','ondataavailable',
30	                        'ondatasetchanged','ondatasetcomplete','ondblclick',
31	                        'ondeactivate','ondrag','ondragend',
32	                        'ondragenter','ondragleave','ondragover',
33	                        'ondragstart','ondrop','onerror','onerrorupdate',
34	                        'onfilterchange','onfinish','onfocus','onfocusin',
35	                        'onfocusout','onhelp','onkeydown','onkeypress',
36	                        'onkeyup','onlayoutcomplete','onload',
37	                        'onlosecapture','onmousedown','onmouseenter',
38	                        'onmouseleave','onmousemove','onmouseout',
39	                        'onmouseover','onmouseup','onmousewheel',
40	                        'onmove','onmoveend','onmovestart','onpaste',
41	                        'onpropertychange','onreadystatechange','onreset',
42	                        'onresize','onresizeend','onresizestart',
43	                        'onrowenter','onrowexit','onrowsdelete',
44	                        'onrowsinserted','onscroll','onselect',
45	                        'onselectionchange','onselectstart','onstart',
46	                        'onstop','onsubmit','onunload','javascript',
47	                        'script','eval','behaviour','expression',
48	                        'style','class'
49	                    );
50	                $skipstr = implode('|', $skipkeys);
51	                $value = preg_replace(array("/($skipstr)/i"), '.', $value);
52	                if(!preg_match("/^[/|s]?($allowtags)(s+|$)/is", $value)) {
53	                    $value = '';
54	                }
55	                $replaces[] = empty($value)?'':"<".str_replace('"', '"', $value).">";
56	            }
57	        }
58	        $html = str_replace($searchs, $replaces, $html);
59	    }
60	    $html = addslashes($html);
61
62	    return $html;
63	}



原文出處:PHP通用的XSS攻击过滤函数,Discuz系统中 防止XSS漏洞攻击,过滤HTML危险标签属性的PHP函数 - PHP博客|PHP开发|Linux运维|服务器架构|钱运来
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|