2012年11月5日 星期一

PHP 在APACHE 一些常用設定

不讓上傳的目錄執行PHP

httpd.conf 在網站的上傳目錄設定下
<Directory "/var/www/html/upload">
    AllowOverride None
    php_flag engine off
    Allow from all
</Directory>

.html 也能執行 PHP

# vim /etc/httpd/conf.d/php.conf

AddHandler php5-script .php .html .htm
AddType    text/html .php
AddType    application/x-httpd-php .html .htm

隱藏 Apache server information

# vim /etc/http/conf/httpd.conf
ServerSignature Off
ServerTokens Prod

隱藏 PHP version (X-Powered-By)

# vim /etc/php.ini

expose_php = Off







Prod or ProductOnly – Server sends (e.g.): Server: Apache
ServerTokens Prod

Major – Server sends (e.g.): Server: Apache/2
ServerTokens Major

Minor – Server sends (e.g.): Server: Apache/2.2
ServerTokens Minor

Min or Minimal – Server sends (e.g.): Server: Server: Apache/2.2.4
ServerTokens Min

OS – Server sends (e.g.): Server: Apache/2.2.4 (CentOS)
ServerTokens OS

Full or not specified – Server sends (e.g.): Server: Apache/2.2.4 (CentOS) PHP/5.2.3-Fedroa ServerTokens Full
ServerTokens setting applies to the entire server, and cannot be enabled or disabled on a virtualhost-by-virtualhost basis.


Web 控制 Browser Cache 的方式


 http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
 http-equiv="Pragma" content="no-cache" />
 http-equiv="Expires" content="0" />

2012年10月31日 星期三

NTOP dump data 以多種格式匯出統計資料,使用PHP計算超流量主機


 NTOP 3  “DUMP DATA”的功能可以將統計資料轉換, PHP、XML、TXT、Perl、Python格式,選擇你會用的格式,在 利用WGET排程下載檔案, 基本上也不用再做什麼加工動作,就可以拿來用每天計算,一天一個檔案,一個月目錄,當然匯入MySQL也OK。

#wget -O ntop-20121031-2350.php "http://127.0.0.1:3000/dumpData.html?language=php&view=short"


$ntopHash = array(
'192.168.1.1' => array(
        'hostSymIpAddress' => 'xxx.ntop.org',
        'pktSent' => '1031',
        'pktRcvd' => '922',
  ...
        'icmpRcvd' => '0',
),
...

由NTOP頁面手動下載:

檔案內容:


PHP 計算總流量超過4G的主機列表





<?php
date_default_timezone_set("Asia/Taipei");

$max=4096000000;
$ntopLogPath="/samba/Report/phpntop";
$filelist=read_dir($ntopLogPath);
rsort($filelist);

if (isset($_GET['list']))
{ $logfile=$_GET['list']; }
else
{ $logfile=$filelist[0]; }
if (file_exists( $ntopLogPath."/".$logfile))
{ include $ntopLogPath."/".$logfile; }
else
{ $ntopHash=''; }

echo "<script src='sorttable.js'></script>" ;
echo "<style type='text/css'>\n";
echo "<!-- \n";
echo "a { \n";
echo " text-decoration: none; \n";
echo "} \n";
echo "--> \n";
echo "</style> \n";

echo "<TABLE>\n ";
echo " <TR>\n";
echo " <TD VALIGN='TOP'>\n";
echo "<TABLE>\n ";
echo " <TR><TD>File List</TD></TR>";
for ($i=0; $i<count($filelist); $i++)
{
echo " <TR onMouseOver=\"this.bgColor = '#F9B7FF'\" onMouseOut =\"this.bgColor = '#FFFFFF'\">\n";
echo "<TD><A HREF='ntop.php?list=".$filelist[$i]."'>
<FONT COLOR='#0000FF'>".substr($filelist[$i],0,-4)."</FONT></A></TD></TR>\n";
}
echo "</TABLE>\n ";
echo " </TD>\n";


echo " <TD VALIGN='TOP'>\n";

$ip=@array_keys($ntopHash);
#http://ntop.example.com/report/Report-201202/ntop-daily/
#$downLoadPath="http://ntop.example.com/report/Report-".date("Ym",time())."/ntop-daily/";
$downLoadPath="http://ntop.example.com/report/Report-".substr($logfile,5,6)."/ntop-daily/";
echo "Date : ".substr($logfile,0,-4);
echo "<A HREF='$downLoadPath'><FONT COLOR='#0000FF'> DownLoad File</FONT></A><BR />\n";
#echo "Total IP:".count($ip);
echo "<HR />\n";
echo "Traffic >4G :";
echo "<TABLE border='1' style='border-collapse:collapse;' borderColor='black' class='sortable'>\n";
echo " <TR>\n";
echo " <TD>IP</TD>\n";
echo " <TD>Total</TD>\n";
echo " <TD>Send</TD>\n";
echo " <TD>Rcvd</TD>\n";
echo " <TD>tcpBytesSent</TD>\n";
echo " <TD>tcpBytesRcvd</TD>\n";
echo " <TD>udpBytesSent</TD>\n";
echo " <TD>udpBytesRcvd</TD>\n";
echo " </TR>\n";

for ($i=0; $i<(count($ip)); $i++)
{
$key=$ip[$i];
$total=$ntopHash[$key]['bytesSent']+$ntopHash[$key]['bytesRcvd'];
if ($total>$max)
{
echo " <TR onMouseOver=\"this.bgColor = '#3BB9FF'\" onMouseOut =\"this.bgColor = '#FFFFFF'\">\n";
echo " <TD>".$ntopHash[$key]['hostResolvedName']."</TD>\n ";
echo " <TD align='right'>".formatBytes($total)."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['bytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['bytesRcvd'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['tcpBytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['tcpBytesRcvd'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['udpBytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['udpBytesRcvd'])."</TD>\n";
echo " </TR>\n";
}
}
echo "</TABLE>\n";

echo " </TD>\n";
echo " </TR>\n";
echo "</TABLE>\n";
###########################################################
function formatBytes($size, $precision = 2)
{
if ($size==null)
return "0";
$base = log($size) / log(1024);
$suffixes = array('', 'k', 'M', 'G', 'T');

return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
function read_dir($dir, $array = array())
{
$dh = opendir($dir);
$files = array();
while (($file = readdir($dh)) !== false) {
$flag = false;
if($file !== '.' && $file !== '..' && !in_array($file, $array)) {
$files[] = $file;
}
}
return $files;
}
?>

2012年8月29日 星期三

PHP-EXPECT SSH應用(TELNET)

使用expect可以簡單達到自動交互作用,之前都在SHELL底下工作,用排程完成相關作業。
最近使用PHP expect 移到WEB介面,可遠端利用WEB更輕鬆完成操作,搭配PHP語法更容控制整個程序,不用考慮SHELL下的權限問題。

底下範例:

使用TELNET連至EXTREME交換設備進行命作操作,針對抓取線上使用者MAC,收集所有MAC,針對異常MAC限制存取。


<?php
function getExtreme($cmd,$ip,$arg='')
{
switch ($cmd)
    {
    case "fdb":
        #取得MAC位置
        $cmdString="show fdb \n \n" ;
        break;
    case "setdenymac":
        #設定ACL
        $aclName="deny-$arg";
        $mac=preg_replace('/-/', ':',$arg);
        $cmdString=" create access-list $aclName \"ethernet-source-address $mac\" \"deny\" \n
        configure access-list add \"$aclName\" first any \n ";
        break;
    case "deldenymac":
        #刪除ACL
        $aclName="deny-$arg";
        $mac=preg_replace('/-/', ':',$arg);
        $cmdString="configure access-list delete \"$aclName\" any \n
        delete access-list \"$aclName\" \n ";
        break;
    default:
        return null;
    }
ini_set("expect.timeout", 3);
ini_set("expect.loguser", "Off");
##訂定常數
@define("LOGIN", 'login:');
@define("PASSWORD", 'password:');
@define("SHELL", '#');
@define("YESNO",'(y/N)');
#EXP_EXACT ..
## login get data
$stream = fopen("expect://telnet $ip", "r");
#$stream = expect_popen("telnet $ip");
$status=1;
while ($status) {
    switch (expect_expectl ($stream, array (
    array ('login:', 1 => LOGIN),
    array ('password:', 1 => PASSWORD),
    array ('#', 1 => SHELL, EXP_EXACT),
    array ('(y/N)', 1 => YESNO)
    ),$result))
    {
        case @LOGIN:
            fwrite ($stream, "cmdadmin\n");
            #echo "login\n" ;
        break;
            case @PASSWORD:
            fwrite ($stream, "cmdadminpw\n");
            #echo "password\n" ;
        break;
            case @SHELL:
            #echo 'shell';
            fwrite ($stream, $cmdString);
            sleep(1);
            fwrite ($stream, "exit\ny\n");
        break 2;
            case @YESNO:
            fwrite ($stream, "y\n");
            #echo "YESNO\n" ;
            break;
            case @EXP_TIMEOUT:
            case @EXP_EOF:
            $status=0;
        break 2;
            default:
            die ("Error has occurred!\n");
        break;
    }
}
## get output messages
$line = stream_get_contents($stream) ;
fclose ($stream);
switch ($cmd)
{
    case "fdb" :
    ## next page
    $tag="/ \[7mPress <SPACE> to continue or <Q> to quit: \[m \[60;D \[K/";
    $line = preg_replace($tag, '', $line);
    # ascii 0d 0a
    $log = explode("\r\n",$line);
    $fdblist = '';
    $pattern = "/([a-f0-9]{2}:){5}[a-f0-9]{2}/";
    for ($i=0; $i<count($log); $i++)
    {
        if (preg_match($pattern,$log[$i]))
        {
            #replace muitl space
            $log[$i]=preg_replace('/\s\s+/', ' ',$log[$i]);
            $fdblist[$i]=explode(' ',$log[$i]);
        }
    }
    return $fdblist;
    break;
    default:
    return true;
}
}
?>

#抓取有IP 192.168.200.253線上MAC(將Switch列在清單,就能一次取得線上所有主機MAC
使用方法:
print_r(getExtreme('fdb', '192.168.200.253')

 



#設定MAC ACL (該MAC就會無法存取)
getExtreme('setdenymac', '192.168.200.253','00:01:e6:b0:e2:a9')

#刪除MAC ACL (解除MAC ACL)
getExtreme('deldenymac', '192.168.200.253','00:01:e6:b0:e2:a9')

應用在WEB,已點選方式快速建立黑白名單,再與L3結合將IP及MAC關連

圖:線上管理

2012年8月7日 星期二

Fortigate disable IPS engines

Version: Fortigate-3240C v4.0,build4188,120620 (MR3)

FG3240C-HA# diag test application ipsmonitor 98
FG3240C-HA# diagnose sys top
Run Time:  1 days, 8 hours and 49 minutes
0U, 0S, 100I; 10956T, 6128F, 193KF
     proxyworker       80      S       0.0     0.9
          cw_acd      116      S       0.0     0.4
         cmdbsvr       57      S       0.0     0.4
          httpsd      168      S       0.0     0.3
          httpsd      122      S       0.0     0.3
       forticron       77      S       0.0     0.2
          httpsd       70      S       0.0     0.2
         miglogd       68      S       0.0     0.2
       scanunitd      130      S <     0.0     0.1
       scanunitd      124      S <     0.0     0.1
       scanunitd      128      S <     0.0     0.1
       scanunitd      129      S <     0.0     0.1
       scanunitd      125      S <     0.0     0.1
       scanunitd      126      S <     0.0     0.1
       scanunitd      127      S <     0.0     0.1
       scanunitd      123      S <     0.0     0.1
       scanunitd       73      S <     0.0     0.1
       urlfilter       79      S       0.0     0.1
       wad_diskd       72      S       0.0     0.1
          newcli     1525      R       0.0     0.1



# diag test application ipsmonitor IPS Engine Test Usage: (Values for >
1: Display IPS engine information
2: Toggle IPS engine enable/disable status
3: Display restart log
4: Clear restart log
5: Toggle bypass status
6: Submit attack characteristics now
97: Start all IPS engines
98: Stop all IPS engines
99: Restart all IPS engines and monitor


The most common command that we issue to deal with the IPS Engine running high is the following which restarts the IPS process:

# diag test application ipsmonitor 99

config ids process (default 8)
#config system global
    set proxy-worker-count 1
end

# diagnose debug crashlog clear
# diagnose debug crashlog get


2012年8月1日 星期三

PHP 查詢已載入模組, 查詢模組功能

##檢查'rrdtool'是否載入, 若不存在就動態載入

<?php
  if (!extension_loaded('rrdtool'))
  {
     if (function_exists('rrdtool')
     {
       dl('rrdtool.so');
     }
  }
  dl('gd.so');
 #列出所有已載入的模組
  print_r(get_loaded_extensions());
  echo "xml modules\n";
  #列出模組XML, 的所有FUNC
  print_r(get_extension_funcs("xml"));

?>


Array
(
    [0] => Core
    [1] => date
    [2] => ereg
    [3] => libxml
...
)
Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
...
)


#列出所有已載入的模組
phpinfo(INFO_MODULES);


##命令 查詢已載模組
# php -m

php.ini , 是否允許動態載入模組
  enable_dl = Off

預設模組載入路徑 /etc/php.d/
# more /etc/php.d/ssh2.ini
   extension=ssh2.so

# ls /usr/lib64/php/modules/
curl.so    fileinfo.so  json.so    mysql.so      pdo.so         phar.so     snmp.so     ssh2.so
expect.so  gd.so        mysqli.so  pdo_mysql.so  pdo_sqlite.so  rrdtool.so  sqlite3.so  zip.so



CentOS6 x86_64

Extreme XOS run pyton scripts

XOS run python scripts v15.7 or high 將交換器上的 IP & MAC 往syslog 丟, 簡單將IP資料保留下 ## 編緝Scripts # vi ip2syslog.py #!/usr/bin/python # ...