2011年2月18日 星期五

Web troubleshooting分析常用的命令

系統連接狀態
1.查看TCP連接狀態
netstat -nat |awk '{print $6}'|sort|uniq -c|sort -rn
netstat -n | awk '/^tcp/ {++S[$NF]};END {for(a in S) print a, S[a]}'
netstat -n | awk '/^tcp/ {++state[$NF]}; END {for(key in state) print key,"\t",state[key]}'
netstat -n | awk '/^tcp/ {++arr[$NF]};END {for(k in arr) print k,"\t",arr[k]}'
netstat -n |awk '/^tcp/ {print $NF}'|sort|uniq -c|sort -rn
netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c

2.查看請求數前20個IP
netstat -anlp|grep 80|grep tcp|awk '{print $5}'|awk -F: '{print $1}'|sort|uniq -c|sort -nr|head -n20
netstat -ant |awk '/:80/{split($5,ip,":");++A[ip[1]]}END{for(i in A) print A[i],i}' |sort -rn|head -n20

3.用tcpdump嗅探80埠的存取前20幾名
tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr |head -20

4.查看前20名較多time_wait連接
netstat -n|grep TIME_WAIT|awk '{print $5}'|sort|uniq -c|sort -rn|head -n20

5.找查較多的SYN連接
netstat -an | grep SYN | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -nr | more

6.根據埠列進程
netstat -ntlp | grep 80 | awk '{print $7}' | cut -d/ -f1

網站日誌分析篇(Apache Log)
1.獲得存取前10位的ip位址
cat access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -10
cat access.log|awk '{counts[$(11)]+=1}; END {for(url in counts) print counts[url], url}'


2.存取次數最多前20名的檔案或頁面
cat access.log|awk '{print $11}'|sort|uniq -c|sort -nr|head -20

3.列出傳輸最大前20名的幾個exe檔案(分析下載站的時候常用)
cat access.log |awk '($7~/\.exe/){print $10 " " $1 " " $4 " " $7}'|sort -nr|head -20

4.列出輸出大於200000byte(約200kb)的exe檔以及對應檔案發生次數
cat access.log |awk '($10 > 200000 && $7~/\.exe/){print $7}'|sort -n|uniq -c|sort -nr|head -100

5.列出到用戶端最耗時的頁面
cat access.log |awk  '($7~/\.php/){print $NF " " $1 " " $4 " " $7}'|sort -nr|head -100

6.列出最最耗時的頁面(超過60秒的)的以及對應頁面發生次數
cat access.log |awk '($NF > 60 && $7~/\.php/){print $7}'|sort -n|uniq -c|sort -nr|head -100

7.列出傳輸時間超過 30 秒的檔案
cat access.log |awk '($NF > 30){print $7}'|sort -n|uniq -c|sort -nr|head -20

8.統計網站流量(G)
cat access.log |awk '{sum+=$10} END {print sum/1024/1024/1024}'

9.統計代碼404的連接
awk '($9 ~/404/)' access.log | awk '{print $9,$7}' | sort

10. 統計http status
cat access.log |awk '{counts[$(9)]+=1}; END {for(code in counts) print code, counts[code]}'
cat access.log |awk '{print $9}'|sort|uniq -c|sort -rn

11.查看是哪些蜘蛛在抓取內容
/usr/sbin/tcpdump -i eth0 -l -s 0 -w - dst port 80 | strings | grep -i user-agent | grep -i -E 'bot|crawler|slurp|spider'

12.統計各HTTP 狀態數
cat tmp.log | awk -F' ' '$9 == "400" || $9 == "408" || $9 == "499" || $9 == "500" || $9 =="502" || $9 =="504" {print $9}' | sort | uniq -c | more

13.過濾出訪問網站的IP
grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' access.log >ip.txt

網站日分析(Squid篇)
按域統計流量
zcat squid_access.log.tar.gz| awk '{print $10,$7}' |awk 'BEGIN{FS="[ /]"}{trfc[$4]+=$1}END{for(domain in trfc){printf "%s\t%d\n",domain,trfc[domain]}}'

查看資料庫執行的sql
/usr/sbin/tcpdump -i eth0 -s 0 -l -w - dst port 3306 | strings | egrep -i 'SELECT|UPDATE|DELETE|INSERT|SET|COMMIT|ROLLBACK|CREATE|DROP|ALTER|CALL'

系統Debug分析篇
1.調試命令strace -p pid
2.跟蹤指定進程的PIDgdb -p pid

更多的請參考:
http://bbs.linuxtone.org/forum-14-1.html

計算網站併發數

Request Per Second + Simultaneous Browser connections + Thinking Time = Concurrent User 
其中
Concurrent User  表示網站併發用戶數
Request Per Second [RPS] 表示每秒請求數(輸送量)
Simultaneous Browser connections [SBC] 表示併發連接數
Thinking Time  表示平均用戶思考時間


然來一直以為網站併發用戶數就是指的併發連接數 還是概念的東西沒搞清楚
特作記錄 以後做性能分析指標報告用的著

[root@]#  netstat -na | grep 80 | awk '{print $6}' | sort | uniq -c | sort -rn
  17175 ESTABLISHED
  14537 FIN_WAIT1
   2917 TIME_WAIT
    603 FIN_WAIT2
    501 SYN_RECV
     76 LAST_ACK
      8 CLOSING
      1 LISTEN


如發現系統存在大量TIME_WAIT狀態的連接,通過調整內核參數解決,

vim /etc/sysctl.conf
編輯檔,加入以下內容:
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
然後執行 /sbin/sysctl -p 讓參數生效。



net.ipv4.tcp_syncookies = 1
表示開啟SYN Cookies。當出現SYN等待佇列溢出時,啟用cookies來處理,可防範少量SYN攻擊,默認為0,表示關閉


net.ipv4.tcp_tw_reuse = 1
表示開啟重用。允許將TIME-WAIT sockets重新用於新的TCP連接,默認為0,表示關閉


net.ipv4.tcp_tw_recycle = 1
表示開啟TCP連接中TIME-WAIT sockets的快速回收,默認為0,表示關閉。


net.ipv4.tcp_fin_timeout 修改系統默認的 TIMEOUT 時間
下面附上TIME_WAIT狀態的意義:
用戶端與伺服器端建立TCP/IP連接後關閉SOCKET後,伺服器端連接的埠
狀態為TIME_WAIT是不是所有執行主動關閉的socket都會進入TIME_WAIT狀態呢?
有沒有什麼情況使主動關閉的socket直接進入CLOSED狀態呢?

主動關閉的一方在發送最後一個 ack 後就會進入 TIME_WAIT 狀態 停留2MSL(max segment lifetime)時間這個是TCP/IP必不可少的,也就是“解決”不了的。
也就是TCP/IP設計者本來是這麼設計的


主要有兩個原因
1。防止上一次連接中的包,迷路後重新出現,影響新連接
(經過2MSL,上一次連接中所有的重複包都會消失)
2。可靠的關閉TCP連接
在主動關閉方發送的最後一個 ack(fin) ,有可能丟失,這時被動方會重新發
fin, 如果這時主動方處於 CLOSED 狀態 ,就會回應 rst 而不是 ack。所以
主動方要處於 TIME_WAIT 狀態,而不能是 CLOSED 。
TIME_WAIT 並不會佔用很大資源的,除非受到攻擊。
還有,如果一方 send 或 recv 超時,就會直接進入 CLOSED 狀態

2011年2月13日 星期日

建置WAF(Web Application Firewall)

ModSecurity是一個入侵偵測與防護引擎,它主要是用於Web application,所以也被稱為Web應用程式防火牆。 WAF是針對網頁應用程式攻擊深入分析之設備或軟體, 可補足傳統IDS/IPS 對網頁攻擊偵測效果不佳之問題。
它可以作為Apache Web Server的模組或是單獨的應用程式來運作。ModSecurity的功能是增強Web application的安全性和並保護Web application以避免遭受來自已知與未知的攻擊。

為什麼需要WAF ?
1. 目前受入侵的情況中由網頁應用程式攻擊成功的機率最大.
2. 傳統資安設備無法有效阻擋.
3. 經過SSL加密的通訊, 無法解析.


WAF 特點
1. Input validation check for all client input data
2. Ouput check also available
3. Buffer overflow protection
4. Flexible
5. Anti-Evasion built in
6. Encoding validation built in
7. Up on attack detection, variety action to do: Log/Alert/Block/..call scripts


ModSecurity的部署架構
1. 與Web Server結合
2. 與Apache結合部署為network gateway,當作一個reverse proxy


其防護的概念如下圖所

WAF 軟體 modsecurity
網址:
http://modsecurity.org/

解壓縮
[root@snort darwin]# tar zxvf modsecurity-apache_2.5.12.tar.gz
[root@snort darwin]# cd  modsecurity-apache_2.5.12/apache2
注意: 需要apxs, apxs套件放在httpd-devel 內, 如沒有要自行安裝


[root@snort Server]# rpm -ivh httpd-devel-2.2.3-6.el5.i386.rpm
warning: httpd-devel-2.2.3-6.el5.i386.rpm: Header V3 DSA signature: NOKEY, key ID 37017186
Preparing...                ########################################### [100%]
   1:httpd-devel            ########################################### [100%]


編譯/安裝
[root@snort apache2]# ./configure
[root@snort apache2]#make && make install
[root@snort apache2]# cd ..
[root@snort modsecurity-apache_2.5.12]# cp modsecurity.conf-minimal /etc/httpd/conf.d/modsecurity.conf


編輯 modsecurity.conf檔案
[root@snort modsecurity-apache_2.5.12]# vi /etc/httpd/conf.d/modsecurity.conf
內容如下
在開頭加入前3行
LoadFile /usr/lib/libxml2.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so
上述modules如有載入就不用再重load !


最後行再加入
Include mod_security/*.conf

解壓/安裝rules
[root@snort darwin]# tar zxvf modsecurity-crs_2.0.5.tar.gz
[root@snort darwin]# cd modsecurity-crs_2.0.5
[root@snort modsecurity-crs_2.0.5]# mkdir /etc/httpd/mod_security
[root@snort modsecurity-crs_2.0.5]# mv base_rules/* /etc/httpd/mod_security/
[root@snort modsecurity-crs_2.0.5]# \mv optional_rules/* /etc/httpd/mod_security/
[root@snort mod_security]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                              [  OK  ]


檢查WAF 模組


檢查WAF log檔
[root@snort mod_security]# ls -l /etc/httpd/logs/modsec_*
-rw-r----- 1 root root 1395544 Mar 21 20:41 /etc/httpd/logs/modsec_audit.log
-rw-r----- 1 root root       0 Mar 21 20:37 /etc/httpd/logs/modsec_debug.log


modsecurity設定檔
Mod Securit的四種主要的設定指令。


General configuration options
一般的設定,包括裝規則引擎(rule engineer)開啟等基本指令,常見的設定如下:
#Basic configuration options
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On

#Handling of uploaded files
SecUploadDir /opt/apache-fronted/tmp/
SecUploadKeepFiles Off

#Max request body size for buffering
SecRequestBodyLimit 131072

#Store up to 128KB in memory
SecRequestBodyInMemoryLimit 131072

#Buffer response body up to 512KB in length
SecResponseBodyLimit 524288


Debug logging options
設定Mod Security如何執行debug的log部分,常見的設定如下:
#Debug log
SecDebugLog logs/modsec_debug.log
SecDebugLogLevel 0


Audit logging options
設定Mod Security如何執行audit的log部分,常見的設定如下:
#Serial Audit log
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus ^5
SecAuditLogParts ABIFHZ
SecAuditLogType Serial
SecAuditLog logs/modsec_audit.log


Rules 基礎
Mod Security最主要的設定部分,為一個以事件為基礎的語言
語法:SecRule VARIABLES OPERATOR [ACTIONS]
VARIABLES:指定哪些變數要進行處理
OPERATOR:要如何處理這些變數取得我們想要的
ACTIONS (optional):當達到上述的處理時,要做什麼動作


Rule處理的階段 Mod Security會在http的五個transaction進行處理.
Phase:1-Request Headers
Phase:2-Request Body
Phase:3-Response Headers、
Phase:4-Response Body
Phase:5-logging

因此,在rule的部分即可指定你要transaction的哪一部份進行處理。

VARIABLES 
一些常見的變數:
ARGS、ARGS_NAMES、ARGS_GET、ARGS_GET_NAMES、ARGS_POST、ARGS_POST_NAMES
AUTH_TYPE
REQBODY_PROCESSOR、REQBODY_PROCESSOR_ERROR
FILES、FILES_NAMES、FILE_SIZES
REMOTE_ADDR、REMOTE_HOST、REMOTE_PORT
REQUEST_BODY、REQUEST_COOKIES、REQUEST_COOKIES_NAMES、REQUEST_FILENAME
RESPONSE_BODY

Rule中的變數部分可以一個以上, 以”|”來區隔即可,如果設定的規則超過多行,則可用”\”來進行分隔。

OPERATOR
預設的OPERATOR是正規表示法(Regular Expression),但其實ModSecurity提供不少可用的OPERATOR,利用”@”即可指定要用何種OPERATOR,例如SecRule REQUEST_URI
“@rx iii”。

以下是一些範例:
SecRule REMOTE_ADDR "^192\.168\.1\.101$"
REMOTE_ADDR:指定變數對象為遠端連線的IP位址
"^192\.168\.1\.101$":針對上述的變數進行比對,如果非192.168.1.101,則符合,可指定要做何種動作
SecRule ARGS "@validateUtf8Encoding"
ARGS:指定變數為http傳遞的參數
"@validateUtf8Encoding":指定OPERATOR為對這些參數進行Utf8編碼進行檢查
SecRule FILES_TMPNAMES "@inspectFile /path/to/inspect_script.pl"
FILES_TMPNAMES:指定變數為上傳檔案的暫存名稱
"@inspectFile /path/to/inspect_script.pl":指定利用inspect_script.pl檔案的語法來檢查上傳檔案
ACTIONS
指定如果VARIABLE有符合OPERATOR的情況時,要執行何種動作。


ACTIONS主要區分為五種型態:
Disruptive actions (中斷目前的transaction)

deny、drop、redirect、proxy、pause…
Non-disruptive actions (改變狀態)
Append、auditlog、exec…
Flow actions (改變規則流動)
allow、chain、pass、skip…
Meta-data actions (包含規則的metadata)
id、rev、severity、msg、phase、log, nolog、…
Data actions (可放置內容給其他action用)
capture、status、t、xmlns…

測試WAF
寫一支小php程式測試
[root@snort mod_security]# vi /var/www/html/checkmd.php
內容如下
<?
 file $text=$_GET['file'];
 echo "Content of File $text";
 echo `cat $text`;
?>


在網頁上輸入 http://主機/checkcmd.php?file=/etc/passwd
如果出現畫面所示, 表示ModSecurity2有在running .


使用一些工具作測試
Browser Extension –IE
1. TamperIE  http://www.bayden.com/Other 
用於竄改瀏覽器送出的參數; 可繞過Javascript檢測
2. HTTPWatch  http://www.httpwatch.com/
顯示IE的每一個Request/Response; 攻擊/除錯兩相宜
3. HTTP Analyzer http://www.ieinspector.com/httpanalyzer
類似HTTPWatch

  Browser Extension –Firefox
1. Tamper Data  https://addons.mozilla.org/firefox/966/
2. Add N Edit Cookies  https://addons.mozilla.org/firefox/573
3. Live HTTP Headers  https://livehttpheaders.modzdev.org/
4. HttpFox  https://addons.mozilla.org/firefox/addon/6647/
5. RefControl  https://addons.mozilla.org/firefox/953/
6. HackBar  https://addons.mozilla.org/firefox/addon/3899/

 Web Proxy
1. Paros  http://www.parosproxy.org/
2. Odysseus  http://www.bindshell.net/tools/odysseus
3. Fiddler  http://www.fiddlertool.com/fiddler/
4. Burp suit  http://portswigger.net/suite/
5. WebScarab  http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project
6. Charles  http://www.charlesproxy.com/
7. SPIKE Proxy  http://www.immunitysec.com/resource-freesoftware.shtml

  Brute Force Attack
1. THC-Hydra  http://www.thc.org/thc-hydra/
2. Brutus AET2  http://www.hoobie.net/brutus/
3. Unsecure
4. ObiWaN
5. Cain & Abel
6. Authforce
7. WebCracker
8. Lophtcrack

Web Vulnerability Scanner
1. Nikto (free)
2. Wikto (free)
3. Acunetix- Web Vulnerability Scanner (Commericial)
4. IBM AppScan  (Commericial)  
5. HP WebInspect  (Commericial)  較準但價格超貴
6. N-Stalker – Web Application Security Scanner  (Commericial)

Web Stress Test
1. ab (Apache Benchmark)  http://httpd.apache.org/
2. JMeter  http://jakarta.apache.org/jmeter/
3. Microsoft Web Application Stress Tool
4. Many Tools  http://www.softwareqatest.com/qatweb1.html

註: 上述皆可對modsecurity module作測試

Mod_security內建許多RULE
1. Protocol Violation
2. Protocol Anomalies
3. Request Limit
4. Http Policy
5. Bad Robots
6. Generic Attacks
7. Trojans
8. Outbound
9. etc……. 
  
怎麼自行加入/設定rule是很重要的
 一些範例
使用範例1
SecRule REQBODY_PROCESSOR_ERROR "!@eq 0“ "phase:2,log,deny,msg:'Failed to parse request body.',severity:2“

說明:
REQBODY_PROCESSOR_ERROR:指定針對request body發生的processor發生的錯誤的代碼
"!@eq 0“:當不等於0時,即有錯誤發生時
處理動作 "phase:2,log,deny,msg:'Failed to parse request body.',severity:2“
phase:2:由於對象為request body,因此指定在phase:2進行
log:當情況符合(發生錯誤),將錯誤log起來
deny:將這個transaction拒絕
msg:'Failed to parse request body':網頁上並顯示出這樣的錯誤訊息
severity:2:將此狀況列為嚴重程度為2

使用範例2
SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
"phase:2,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"


說明:
MULTIPART_UNMATCHED_BOUNDARY:指定針對multipart發生unmatched boundary的錯誤
"!@eq 0“:當不等於0時,即有錯誤發生時
處理動作 "phase:2,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"
phase:2:由於對象為request body,因此指定在phase:2進行
log:當情況符合(發生錯誤),將錯誤log起來
deny:將這個transaction拒絕
msg:'Multipart parser detected a possible unmatched boundary.':網頁上並顯示出這樣的錯誤訊息
The Core rule sets
此一系列的規則可防護一般網頁應用程式常見已知的弱點或其他未知的弱點。
這一系列的規則使用下列的技術:
HTTP protection
Detect all abnormal HTTP request
Common Web Attacks Protection
SQL Injection、Cross-Site Scripting (XSS) …
Automation detection
crawler
Trojan Protection
Error Hiding
Detect errors sent by the web server

其它範例
SecRule REMOTE_ADDR “!^192.168.1.1$” deny  //限制登入來源
SecRule REMOTE_ADDR "^192\.168\.1\.3$" redirect:http://www.google.com.tw
SecServerSignature "Microsoft-IIS/6.0"  //可隱藏伺服器版本,或任一填其它版本欺騙hacker
SecRule ARGS “(insert|select|update|delete)” deny  //避免SQL Injection
SecRule ARGS “<.+>” deny   //避免HTML Tags Injection
SecRule “\.\./” deny   //避免Directory Traversal
SecRule “\.\./” redirect:http://www.google.com 或者SecRule “\.\./” log, redirect:/
SecRule ARGS_NAMES  “^admin$”  deny   //限制管理者
SecRule OUTPUT “\d{4}-\d{4}-\d{4}-d{4}” “deny,phase:4”   //避免信用卡號外露
SecRule OUTPUT “Warning:” “deny,phase:4,exec:mailadm.pl” //避免php錯誤訊息外露
SecRule OUTPUT “ODBC Drivers” “deny,phase:4,exec:mailadmin.pl”   //避免asp sql error外露

將上述加入 modsecurity.conf 檔案內即可生效
註. 以上為簡易範例,供參考!!
如何設定mod_security rule是相當重要的!
不錯的snort討論區
https://forums.snort.org/forums/snort-newbies
以上皆為較基本的實作,日後可好好研究snort rule語法及modsecurity rule如何設定, 對該網站安全有很好保護!!!

大功告成!!

Apache log傳送至syslog

[root@snort ]# vi /usr/local/sbin/apache2syslog_error
內容如下
#!/usr/bin/perl
use Sys::Syslog qw (:DEFAULT setlogsock);

setlogsock('unix');
# open our log socket
openlog('httpd', 'pid', 'local7');

# log all our input
while (<STDIN>) {
       syslog('ERR', $_);
}

# close the log socket
closelog;

[root@snort ]#vi /usr/local/sbin/apache2syslog
#!/usr/bin/perl
use Sys::Syslog qw (:DEFAULT setlogsock);
setlogsock('unix');
# open our log socket
openlog('httpd', 'pid', 'local7');

# log all our input
while (<STDIN>) {
       syslog('info', $_);
}

# close the log socket
closelog;


[root@snort ]# chown root:root /usr/local/sbin/apache2sys*
[root@snort ]# chmod 700 /usr/local/sbin/apache2sys*

編輯httpd.conf檔案[root@snort phplogcon]# vi /etc/httpd/conf/httpd.conf
ErrorLog  | /usr/local/sbin/apache2syslog_error
CustomLog | /usr/local/sbin/apache2syslog  combined
[root@snort phplogcon]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                             [  OK  ]


 

內建syslog置換成rsyslog並將log匯入資料庫

[root@snort darwin]# wget http://www.bitbull.ch/dl/rpm/rsyslog-mysql-4.4.1-el5.i386.rpm
[root@snort darwin]# wget http://www.bitbull.ch/dl/rpm/rsyslog-4.4.1-el5.i386.rpm


[root@snort darwin]# rpm -e sysklogd-1.4.1-39.2 --nodeps
[root@snort darwin]# rpm -ivh rsyslog-4.4.1-el5.i386.rpm
Preparing...                ########################################### [100%]
   1:rsyslog                ########################################### [100%]
[root@snort darwin]# rpm -ivh rsyslog-mysql-4.4.1-el5.i386.rpm
Preparing...                ########################################### [100%]
   1:rsyslog-mysql          ######################################### [100%]


[root@snort log]# mysql < /usr/share/doc/rsyslog-mysql-4.4.1/createDB.sql -p
Enter password:
[root@snort log]# mysql Syslog -e "ALTER TABLE SystemEvents ADD COLUMN ProcessID char(8) default NULL;" -p
Enter password:

[root@snort log]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> grant ALL ON Syslog.* to rsyslog@localhost identified by 'gh8Q6prt';
Query OK, 0 rows affected (0.02 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql>quit;

編輯 /etc/sysconfig/rsyslog 檔案
[root@snort ]# vi /etc/sysconfig/rsyslog
---
SYSLOGD_OPTIONS="-c4 -4"


設定 rsyslog 檔案
$ModLoad ommysql.so  mysql module
$ModLoad imudp.so
$UDPServerRun 514

$template OurDBLog,"INSERT INTO SystemEvents (Message, Facility, FromHost, Priority,DeviceReportedTime, ReceivedAt, InfoUnitID, SysLogTag, ProcessID) values ( '%msg%',%syslogfacility%,'%HOSTNAME%',%syslogpriority%,'%timereported:::date-mysql%','%timegenerated:::date-mysql%',%iut%,'%programname%','%procid:R,ERE,0,ZERO:[0-9]+--end%')",SQL
*.* :ommysql:localhost,Syslog,rsyslog,gh8Q6prt;OurDBLog

編輯 constants_logstream.php 檔案
[root@snort ]# vi /var/www/html/phplogcon/include/constants_logstream.php
$dbmapping['monitorware']['DBMAPPINGS'][SYSLOG_EVENT_USER] = "EventUser";
$dbmapping['monitorware']['DBMAPPINGS'][SYSLOG_PROCESSID] = "ProcessID";  將註解取消


重啟rsyslog及MySQL
[root@snort phplogcon]# service rsyslog start
Starting system logger:                                        [  OK  ]
[root@snort phplogcon]# service mysqld restart
Stopping MySQL:                                                [  OK  ]
Starting MySQL:                                                  [  OK  ]


下載phplogcon

打開瀏覽器
http://192.168.1.100/phplogcon/install.php











編輯 config檔案  //可編輯或可忽略
[root@snort ]# vi /var/www/html/phplogcon/config.php
$CFG['PrependTitle'] = "";                 
$CFG['ViewUseTodayYesterday'] = 1;        
$CFG['ViewMessageCharacterLimit'] = 150;    .
$CFG['ViewStringCharacterLimit'] = 30;  .
$CFG['ViewEntriesPerPage'] = 35;      
$CFG['ViewEnableDetailPopups'] = 0;   
$CFG['ViewDefaultTheme'] = "default";                                                                        
$CFG['ViewDefaultLanguage'] = "en";          
$CFG['ViewEnableAutoReloadSeconds'] = 120;  
$CFG['SearchCustomButtonCaption'] = "I'd like to feel sad";    
$CFG['SearchCustomButtonSearch'] = "severity:-=NOTICE severity:-=INFO severity:-=DEBUG severity:-=WARNING";                 
$CFG['EnableIPAddressResolve'] = 1;      
$CFG['SuppressDuplicatedMessages'] = 0;   .
$CFG['TreatNotFoundFiltersAsTrue'] = 0;   
$CFG['PopupMenuTimeout'] = 3000;       
$CFG['PhplogconLogoUrl'] = "";     

這樣就完成了!!

使用Web Log Analyzer 工具

PHPLOGCON
網址: http://www.phplogcon.org/downloads


解壓縮/安裝
[root@snort darwin]# tar zxvf phplogcon-2.8.1.tar.gz
[root@snort darwin]# cd phplogcon-2.8.1
[root@snort phplogcon-2.8.1]# mv src/ /var/www/html/phplogcon
[root@snort phplogcon-2.8.1]# cp contrib/* /var/www/html/phplogcon/
[root@snort phplogcon-2.8.1]# chown -R apache.apache /var/www/html/phplogcon
[root@snort phplogcon]# cd /var/www/html/phplogcon/
[root@snort phplogcon]# chmod +x configure.sh
[root@snort phplogcon]# chmod +x secure.sh


[root@snort phplogcon]# ./configure.sh    //產生config.php (等下我們所有設定皆會記錄在這裡)
[root@snort log]# ls -l /var/log/snort.alert  //確認 /var/log/snort.alert檔案讀取權限(要有read權限)
-rwxr-xr-x 1 root root 3671 Mar 21 12:00 /var/log/snort.alert

打開瀏覽器
http://192.168.1.100/phplogcon/install.php

只要Step by step 即可輕鬆完成安裝,(4,5,6 步驟系統會略過)




這步驟我們 Syslog file選擇 /var/log/snort.alert檔案記錄

選擇Finish, 最後完成!!



註:  我們也可以改成 /var/log/messages 檔案, 這樣所有log都會經由web介面呈現,方便管理!
如果log 是存在資料庫, 也可讀取資料庫的log資料!!


Linux - Apache+MySQL+PHP(手動安裝)

環境RedHat AS5 for x86

安裝Apache2
下載網址 http://httpd.apache.org/download.cgi

解壓縮/ 編譯Apache2
# tar jxvf httpd-2.2.17.tar.bz2
# cd httpd-2.2.17
# ./configure --prefix=/usr/local/apache2 --enable-so --enable-ssl=static --enable-mods-shared=all --enable-modules=most --with-mpm=worker
# make && make install


編輯配置httpd.conf檔案
# vi /usr/local/apache2/conf/httpd.conf
User apache   //Apache 的使用者及群組
Group apache
ServerAdmin darwin@catchlink.com  //管理E-mail位址
ServerName  192.168.11.200:80  //伺服器位址:80


<IfModule dir_module>
    DirectoryIndex index.html index.htm index.php index.php3
</IfModule>


啟動apache2
# /usr/local/apache2/bin/apachectl start   //啟動Apache2

# ps -ef |grep httpd
root     15785     1  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start
apache   15786 15785  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start
apache   15787 15785  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start
apache   15789 15785  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start
apache   15791 15785  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start
apache   15968 15785  0 12:43 ?        00:00:00 /usr/local/apache2/bin/httpd -k start


測試網頁
http://webserver/ IP/index.html
出現 It Work!代表成功了 ; 如果沒出現,可能firewall被檔住..
# /usr/local/apache2/bin/apachectl stop   //Apach2停止


調整Apache效能
編輯httpd-default檔案
# vi /usr/local/apache2/conf/extra/httpd-default.conf
內容如下
Timeout 60
KeepAlive On
MaxKeepAliveRequests 800
KeepAliveTimeout 5
HostnameLookups Off


編輯httpd-mpm檔案
bash-3.00# vi /usr/local/apache2/conf/extra/httpd-mpm.conf
內容如下
<IfModule mpm_worker_module>
    StartServers          2
    MaxClients          800
    MinSpareThreads      25
    MaxSpareThreads      100
    ThreadsPerChild      50
    MaxRequestsPerChild  100
</IfModule>


修改httpd.conf檔案
#vi /usr/local/apache2/conf/httpd.conf


將httpd-mpm.conf及httpd-default註解取消 , 沒有此2行的就自行加入
Include conf/extra/httpd-mpm.conf
Include conf/extra/httpd-default.conf


自動啟動和關閉Apache Server
# ln –s /usr/local/apache2/bin/apachectl  /etc/rc3.d/S85httpd
# ln –s /usr/local/apache2/bin/apachectl  /etc/rc0.d/K85httpd
# ln –s /usr/local/apache2/bin/apachectl  /etc/rc1.d/K85httpd
# ln -s /usr/local/apache2/bin/apachectl  /etc/rc2.d/K85httpd


編譯及安裝Mysql5
下載網址 http://dev.mysql.com/downloads/mirror.php?id=401062#mirrors


安裝cmake
# cd/usr/local/src/tarbag
# wget  -c  http://www.cmake.org/files/v2.8/cmake-2.8.3.tar.gz
# tar zxvf cmake-2.8.3.tar.gz
# cd ../software/cmake-2.8.3
# ./bootstrap
# make &&  make  install


解壓縮 /編譯Mysql5
# groupadd mysql
# useradd –g mysql –s /sbin/nologin  mysql


# tar  zxvf  mysql-5.5.9.tar.gz
# cd  mysql-5.5.9/
# cmake  .  -DCMAKE_INSTALL_PREFIX=/usr/local/mysql  \
-DDEFAULT_CHARSET=utf8  \
-DDEFAULT_COLLATION=utf8_general_ci   \
-DEXTRA_CHARSETS=all  \
-DWITH_EMBEDDED_SERVER=1  \
-DENABLED_LOCAL_INFILE=1   \
-DWITH_MYISAM_STORAGE_ENGINE=1
# make &&  make install


編譯選項說明
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql  //安裝目錄
-DDEFAULT_CHARSET=utf8 //使用utf8字元
-DDEFAULT_COLLATION=utf8_general_ci  //校驗字元
-DEXTRA_CHARSETS=all  //安裝所有擴展字元集
-DWITH_EMBEDDED_SERVER=1 //編譯成embedded mysql library
-DENABLED_LOCAL_INFILE=1 //允許從本地導入資料
-DWITH_MYISAM_STORAGE_ENGINE=1 //安裝myisam引擎


配置
# chown -R mysql..mysql /usr/local/mysql
# cd /usr/local/mysql
# cp ./support-files/my-medium.cnf /etc/my.cnf
# ./scripts/mysql_install_db --user=mysql
# ./bin/mysqld_safe --user=mysql &


自動啟動和關閉Mysql Server
# cp ./support-files/mysql.server /etc/init.d/mysqld
# chmod +x /etc/init.d/mysqld
# chkconfig --add mysqld
# chkconfig mysqld on
# service mysqld restart

# export PATH=$PATH:/usr/local/mysql/bin
# export LD_LIBRARY_PATH=/usr/local/mysql/lib:/lib:/usr/local/lib:/var/lib


查看mysql
Mysql預設使用的Port是3306
# netstat -na | grep 3306
  *.3306               *.*                0      0 49152      0 LISTEN


設定 MySQL 的 root user密碼
# mysqladmin -u root password xxxxx
# mysqladmin -u root -h `hostname` password -p
Enter password:
New password:
Confirm new password:

測試 Mysql Server
# mysqladmin version -p
Enter password:    //輸入剛加入的root 密碼

mysqladmin  Ver 8.42 Distrib 5.5.9, for Linux on i686
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.9-log
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /tmp/mysql.sock
Uptime:                 5 min 11 sec
Threads: 1  Questions: 19  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.61

如出現上面的有關mysql5相關資訊 , 則表示安裝成功!

查看mysql 內所有資料庫
# mysqlshow -p
Enter password:
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| mysql                 |
| performance_schema |
| test                    |
+--------------------+


進入 mysql 模式
# mysql -uroot -p
Enter password:   //輸入root 密碼
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.5.9-log Source distribution

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database       |
+--------------------+
| information_schema |
| mysql            |
| performance_schema |
| test              |
+--------------------+
4 rows in set (0.00 sec)
mysql> quit;
Bye


PHP5
下載網址  http://www.php.net/
# tar jxvf php-5.3.5.tar.bz2
# cd php-5.3.5


編譯及安裝php 
# ./configure  --prefix=/usr/local/php5 --with-apxs2=/usr/local/apache2/bin/apxs
--with-mysql=/usr/local/mysql –with-gd –with-zlib-dir
# make && make install


將php.ini設定檔copy至/usr/local/php5/lib目錄內
cp php.ini-production /usr/local/php5/php.ini


編輯Apache 設定檔 , 讓Apache可以看得懂PHP Script 並使PHP模組去解析它們
# vi /usr/local/apache2/conf/httpd.conf


檢查所下, 如沒有自行加入
DirectoryIndex  index.html index.htm index.php index.php3
LoadModule php5_module        modules/libphp5.so
AddType application/x-httpd-php-source .phps
AddType application/x-httpd-php .php .phtml

測試php5
# vi /usr/local/apache2/htdocs/info.php
<? php
phpinfo();
?>


打開IE測試:http://192.168.11.200/info.php



重啟動 Apache2
# usr/local/apache2/bin/apachectl restart  //重新啟動Apache2

安裝 phpMyAdmin
下載網址  http://www.phpmyadmin.net/

解壓縮phpMyAdmin
#tar zxvf phpMyAdmin-3.3.9.2-all-languages.tar.gz -C /usr/local/apache2/htdocs/
#mv phpMyAdmin-3.3.9.2-all-languages/ phpMyAdmin

打開IE測試 http://192.168.11.200/phpMyAdmin/

輸入mysql 資料庫的帳號及密碼即可.

2011年2月9日 星期三

Linux - 設定TimeZone

查看目前時區
[root@darwin-test ~]# date
Wed Feb  9 05:20:22 EST 2011


[root@darwin-test ~]# cat /etc/sysconfig/clock
# The ZONE parameter is only evaluated by system-config-date.
# The timezone of the system is defined by the contents of /etc/localtime.
ZONE="America/New_York"   //目前是New York時區
UTC=true
ARC=false


暫時設定台灣時區
[root@darwin-test ~]# export TZ='Asia/Taipei'
[root@darwin-test ~]# date
Wed Feb  9 18:22:24 CST 2011


永久設定時區
[root@darwin-test ~]# system-config-date
[root@darwin-test ~]# cat /etc/sysconfig/clock
# The ZONE parameter is only evaluated by system-config-date.
# The timezone of the system is defined by the contents of /etc/localtime.
ZONE="Asia/Taipei"

UTC=true
ARC=false


[root@darwin-test ~]# date
Wed Feb  9 18:26:16 CST 2011


另一作法-永久設定時區
編輯家目錄.profile or $HOME/.bash_profile
#vi $HOME/.profile
內容如下
export TZ='Asia/Taipei'


另一命令可供參考
[root@darwin-test ~]# tzselect
Please identify a location so that time zone rules can be set correctly.
Please select a continent or ocean.
 1) Africa
 2) Americas
 3) Antarctica
 4) Arctic Ocean
 5) Asia
 6) Atlantic Ocean
 7) Australia
 8) Europe
 9) Indian Ocean
10) Pacific Ocean
11) none - I want to specify the time zone using the Posix TZ format.
#? 5

Please select a country.
 1) Afghanistan           18) Israel                35) Palestine
 2) Armenia               19) Japan                 36) Philippines
 3) Azerbaijan            20) Jordan                37) Qatar
 4) Bahrain               21) Kazakhstan            38) Russia
 5) Bangladesh            22) Korea (North)         39) Saudi Arabia
 6) Bhutan                23) Korea (South)         40) Singapore
 7) Brunei                24) Kuwait                41) Sri Lanka
 8) Cambodia              25) Kyrgyzstan            42) Syria
 9) China                 26) Laos                  43) Taiwan
10) Cyprus                27) Lebanon               44) Tajikistan
11) East Timor            28) Macau                 45) Thailand
12) Georgia               29) Malaysia              46) Turkmenistan
13) Hong Kong             30) Mongolia              47) United Arab Emirates
14) India                 31) Myanmar (Burma)       48) Uzbekistan
15) Indonesia             32) Nepal                 49) Vietnam
16) Iran                  33) Oman                  50) Yemen
17) Iraq                  34) Pakistan
#? 43

The following information has been given:
        Taiwan
Therefore TZ='Asia/Taipei' will be used.
Local time is now:      Wed Feb  9 18:21:13 CST 2011.
Universal Time is now:  Wed Feb  9 10:21:13 UTC 2011.
Is the above information OK?
1) Yes
2) No
#? 1

You can make this change permanent for yourself by appending the line
        TZ='Asia/Taipei'; export TZto the file '.profile' in your home directory;

then log out and log in again.
Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Taipei

Linux - 檢查記憶體Type和速率

[root@xen02-13 ~]# dmidecode --type memory | less

輸出如下
# dmidecode 2.10
SMBIOS 2.6 present.

Handle 0x1000, DMI type 16, 15 bytes
Physical Memory Array
Location: System Board Or Motherboard
Use: System Memory
Error Correction Type: Multi-bit ECC
Maximum Capacity: 192 GB         //最大記憶容量

Error Information Handle: Not Provided
Number Of Devices: 12

Handle 0x1100, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 1
Locator: DIMM_A1
Bank Locator: Not Specified
Type: DDR3      

Type Detail: Synchronous
Speed: Unknown
Manufacturer:            
Serial Number:        
Asset Tag:        
Part Number:                  
Rank: Unknown

Handle 0x1101, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB

Form Factor: DIMM
Set: 1
Locator: DIMM_A2

Bank Locator: Not Specified
Type: DDR3 

Type Detail: Synchronous
Speed: 1333 MHz   
Manufacturer: 002C04B3802C
Serial Number: E06A1C26
Asset Tag: 08101903
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x1102, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 2
Locator: DIMM_A3
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C04B3802C
Serial Number: E06A1C1E
Asset Tag: 08101903
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x1103, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 2
Locator: DIMM_A4
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer:            
Serial Number:        
Asset Tag:        
Part Number:                  
Rank: Unknown

Handle 0x1104, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 3
Locator: DIMM_A5
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C00B3802C
Serial Number: DA60A217
Asset Tag: 08102961
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x1105, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 3
Locator: DIMM_A6
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C04B3802C
Serial Number: DA603015
Asset Tag: 08102803
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x1109, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 5
Locator: DIMM_B1
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer:            
Serial Number:        
Asset Tag:        
Part Number:                  
Rank: Unknown

Handle 0x110A, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 6
Locator: DIMM_B2
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C04B3802C
Serial Number: E06A1C20
Asset Tag: 08101903
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x110B, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 6
Locator: DIMM_B3
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C04B3802C
Serial Number: E06A1C23
Asset Tag: 08101903
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x110C, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: No Module Installed
Form Factor: DIMM
Set: 4
Locator: DIMM_B4
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: Unknown
Manufacturer:            
Serial Number:        
Asset Tag:        
Part Number:                  
Rank: Unknown

Handle 0x110D, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 5
Locator: DIMM_B5
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C00B3802C
Serial Number: DA60A20F
Asset Tag: 08102961
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

Handle 0x110E, DMI type 17, 28 bytes
Memory Device
Array Handle: 0x1000
Error Information Handle: Not Provided
Total Width: 72 bits
Data Width: 64 bits
Size: 4096 MB
Form Factor: DIMM
Set: 6
Locator: DIMM_B6
Bank Locator: Not Specified
Type: DDR3
Type Detail: Synchronous
Speed: 1333 MHz
Manufacturer: 002C04B3802C
Serial Number: DA603010
Asset Tag: 08102803
Part Number: 36JSZF51272PZ1G4F1
Rank: 2

2011年2月8日 星期二

使用Web Log Analyzer 工具

在遠端log server使用Web Log Analyzer 工具, 分析來自於local5 的alert 記錄檔

PHPLOGCON網址: http://www.phplogcon.org/downloads

解壓縮/安裝[root@snort darwin]# tar zxvf phplogcon-2.8.1.tar.gz
[root@snort darwin]# cd phplogcon-2.8.1
[root@snort phplogcon-2.8.1]# mv src/ /var/www/html/phplogcon
[root@snort phplogcon-2.8.1]# cp contrib/* /var/www/html/phplogcon/
[root@snort phplogcon-2.8.1]# chown -R apache.apache /var/www/html/phplogcon
[root@snort phplogcon]# cd /var/www/html/phplogcon/
[root@snort phplogcon]# chmod +x configure.sh
[root@snort phplogcon]# chmod +x secure.sh
[root@snort phplogcon]# ./configure.sh   產生config.php (等下我們所有設定皆會記錄在這裡)
[root@snort log]# ls -l /var/log/snort.alert  確認 /var/log/snort.alert檔案讀取權限(要有read權限)
-rwxr-xr-x 1 root root 3671 Mar 21 12:00 /var/log/snort.alert


打開瀏覽器http://192.168.1.100/phplogcon/install.php
只要Step by step 即可輕鬆完成安裝,(4,5,6 步驟系統會略過)




這步驟我們 Syslog file選擇 /var/log/snort.alert檔案記錄


選擇Finish, 最後完成!!



註:  我們也可以改成 /var/log/messages 檔案, 這樣所有log都會經由web介面呈現,方便管理!
如果log 是存在資料庫, 也可讀取資料庫的log資料!!

將Snort alert log傳送到遠端 Log server

編輯 /etc/snort/snort.conf 檔案output alert_syslog: LOG_LOCAL5 LOG_ALERT

編輯 /etc/syslog.conf 檔案local5.*      @192.168.1.1  遠方log server

重啟syslog[root@snort log]# service syslog restart

編輯遠端 log server的  /etc/syslog.conf 檔案local5.*  /var/log/snort.log

重啟遠端syslog[root@snort log]# service syslog restart

備忘: 也可記錄於本機log file
編輯 /etc/snort/snort.conf 檔案output alert_syslog: LOG_LOCAL5  LOG_ALERT

編輯 /etc/syslog.conf 檔案local5.alert       /var/log/snort.alert

啟動snort [root@snort log]# /usr/local/bin/snort -c /etc/snort/snort.conf -i eth0 -g snort -p –D

注意:如果要將alert log放到另外的地方 (預設是在/var/log/snort/alert) ,
例如 /var/log/snort.alert,  Snort 啟動時不能加 –A fast(是產生alert檔的) , 所以snort就會以 /var/log/snort.alert檔案了, /var/log/snort/alert檔就不會產生了.

註: 如果要產生/var/log/snort/alert檔案, 又要送log至遠端log server 或本機的 /var/log/messages檔案時, 要加上 –s –A fast 參數, [root@snort log]# /usr/local/bin/snort -c /etc/snort/snort.conf -i eth0 -g snort  –s  –A fast -D

2011年2月4日 星期五

Snort - Web頁面啟動管理功能

SnortCenter是一個基於Web的snort探針和規則管理系統,用於遠端修改snort探針的配置,起動、停止探針,編輯、分發snort特徵碼規則。   我們可以將來自於各snort agent集中管理,控制。

下載地址:
網址: http://users.pandora.be/larc/download/


解壓縮/安裝[root@snort darwin]# tar zxvf snortcenter-console-3-31-05.tar.gz
[root@snort darwin]# mv snortcenter-release  /var/www/html/snortcenter
[root@snort darwin]# cd /var/www/html/snortcenter

建立snortcenter的資料庫
[root@snort snortcenter]# echo "CREATE DATABASE snortcenter;" | mysql -u root -p
Enter password:   //輸入密碼


編輯 snortcenter config 檔案
[root@snort sc]# vi config.php 
內容如下:
$DBlib_path = "/usr/local/lib/adodb/";
$curl_path = "/usr/bin/";
$DBtype = "mysql";
$DB_dbname   = "snortcenter";       // $DB_dbname   : MySQL database name of  SnortCenter DB
$DB_host     = "localhost";              // $DB_host     : host on which the DB is stored
$DB_user     = "root";                      // $DB_user     : login to the database with this user
$DB_password = "gh8Q6prt";      // $DB_password  : password of the DB user
$DB_port     = "";                            // $DB_port      : port on which to access the DB (blank is default)
$hidden_key_num      = "4322";
$alert_console = "http://192.168.1.100/base/";  //加入base 連結


編輯database.php
 [root@snort snortcenter]# vi database.php
內容如下
大約294行  "CREATE TABLE schema" to "CREATE TABLE `schema` " 加上`  `
大約304行  "INSERT INTO schema" to "INSERT INTO `schema` "


打開瀏覽器
http://192.168.1.100/snortcenter




預設帳號/密碼: admin/change


安裝Snortcenter-agent
網址: http://sourceforge.net/projects/snortcenter2/files/

解壓縮/安裝
[root@snort darwin]# tar zxvf snortcenter-agent-v2.x.linux.tar.gz
[root@snort darwin]# mv sensor/ /opt/snortagent
[root@snort darwin]# cd /opt/snortagent/
[root@snort darwin]# ./setup.sh


回答一些問題
 ***********************************************************************************
*       Welcome to the SnortCenter Sensor Agent setup script, version 1.0 RC1        *
***********************************************************************************

Installing Sensor in /opt/snortagent ...
*************************************************************************************
The Sensor Agent uses separate directories for configuration files and log files.
Unless you want to place them in a other directory, you can just accept the defaults.

Config file directory [/opt/snortagent/conf]:
Log file directory [/opt/snortagent/log]:

****************************************************************************************
SnortCenter Sensor Agent is written entirely in Perl. Please enter the full path to the
Perl 5 interpreter on your system.

Full path to perl (default /usr/bin/perl):
Testing Perl ...
Perl seems to be installed ok

*********************************************************************************
SnortCenter Sensor Agent needs Snort to be installed, 'As if you didn't know :-)'
Please enter the full path to snort binary.

Full path to snort (default /usr/local/bin/):
Ok, found Snort   o"  )~   Version 2.8.5.3 (Build 124)
           Using PCRE version: 6.6 06-Feb-2006

Snort Rule config file directory [/opt/snortagent/rules/]:  /etc/snort/rules
***********************************************************************
For Webmin to work properly, it needs to know which operating system
type and version you are running. Please select your system type by
entering the number next to it from the list below
---------------------------------------------------------------------------
  1) Sun Solaris            2) Caldera OpenLinux eS   3) Caldera OpenLinux
  4) Redhat Linux           5) Slackware Linux        6) Debian Linux
  7) SuSE Linux             8) United Linux           9) Corel Linux
 10) TurboLinux            11) Cobalt Linux          12) Mandrake Linux
 13) Mandrake Linux Corpo  14) Delix DLD Linux       15) Conectiva Linux
 16) ThizLinux Desktop     17) ThizServer            18) MSC Linux
 19) MkLinux               20) LinuxPPC              21) XLinux
 22) LinuxPL               23) Trustix               24) Cendio LBS Linux
 25) Ute Linux             26) Lanthan Linux         27) Yellow Dog Linux
 28) Corvus Latinux        29) Immunix Linux         30) Gentoo Linux
 31) Lycoris Desktop/LX    32) Secure Linux          33) Generic Linux
 34) FreeBSD               35) OpenBSD               36) NetBSD
 37) BSDI                  38) HP/UX                 39) SGI Irix
 40) DEC/Compaq OSF/1      41) IBM AIX               42) SCO UnixWare
 43) SCO OpenServer        44) Darwin                45) Mac OS X
 46) Mac OS X / OS X Serv  47) Cygwin
---------------------------------------------------------------------------
Operating system: 4
Please choose which version of Redhat Linux you are running, by entering
the number next to it from the list below
---------------------------------------------------------------------------
  1) Redhat Linux 4.0                     2) Redhat Linux 4.1
  3) Redhat Linux 4.2                     4) Redhat Linux 5.0
  5) Redhat Linux 5.1                     6) Redhat Linux 5.2
  7) Redhat Linux 6.0                     8) Redhat Linux 6.1
  9) Redhat Linux 6.2                    10) Redhat Linux 7.0
 11) Redhat Linux 7.1                    12) Redhat Linux 7.2
 13) Redhat Linux 7.3                    14) Redhat Linux 2.1AS
 15) Redhat Linux 2.1ES                  16) Redhat Linux 2.1WS
 17) Redhat Linux 8.0                    18) Redhat Linux 8.1
 19) Redhat Linux 9.0
---------------------------------------------------------------------------
Version: 4
Operating system name:    Redhat Linux
Operating system version: 5.0

********************************************************************
SnortCenter Sensor Agent uses its own password protected web server
The setup script needs to know :
 - What port to run the Sensor Agent on. There must not be another
   service already using this port.
 - What ip address to listen on.
 - The login name required to access the Sensor Agent.
 - The password required to access the Sensor Agent.
 - The hostname of this system that the Sensor Agent should use.
 - If the Sensor Agent should use SSL (if your system supports it).
 - Whether to use ip access control.
 - Whether to start Snortcenter Sensor Agent at boot time.

Sensor port (default 2525):

If this host has multiple IP addresses,
the server can be configured to listen on
only one address (default any): 192.168.1.100  Login name (default admin):
Login password:
Password again:
Sensor host name (default snort.catchlink.com): snort
Use SSL (y/n): n

*********************************************************************************************
The Sensor Agent can be configured allow access only from certain IP addresses.
Hostnames (like foo.bar.com) and IP networks (like 10.254.3.0 or 10.254.1.0/255.255.255.128)
can also be entered.
You should limit access to your sensor to trusted addresses like the
SnortCenter Management Console, especially if it is accessible from the Internet.
Otherwise, anyone who guesses your password will have complete control of your system.
You can enter multiple addresses by typing a space between them like (127.0.0.1 foo.bar.com)


Allowed IP addresses (default localhost):192.168.1.0
Start Sensor at boot time (y/n): y
***********************************************************************
Creating Sensor Agent config files..
..done

Inserting path to perl into scripts..
..done

Creating start and stop scripts..
..done

Copying config files..
..done

Configuring SnortCenter Sensor Agent to start at boot time..
Created init script /etc/rc.d/init.d/sensor
..done

Creating uninstall script /opt/snortagent/conf/uninstall.sh ..
..done

Changing ownership and permissions ..
..done

Attempting to start Sensor Agent..
Starting SnortCenter Sensor Agent server in /opt/snortagent
..done

**********************************************************************************
SnortCenter Sensor Agent has been installed and started successfully.
You can now create and configure the sensor in the SnortCenter Management Console.
Or use your webbrowser to go to


 http://snort.catchlink.com:2525/

and login with the name and password you entered previously.
-----------------------------------------------------------------------------------------------------------------------------
大致完成 !!


[root@snort snort]# cp /etc/snort/snort.conf /etc/snort/snort.eth0.conf

打開瀏覽器 agent port 2525

註: 可遠端設定agent的snort process 啟用/關閉

啟用agent[root@snort conf]# /opt/snortagent/conf/start
Starting SnortCenter Sensor Agent server in /opt/snortagent
[root@snort conf]# netstat -na |grep -w 2525
tcp        0      0 192.168.1.100:2525          0.0.0.0:*          LISTEN


停用agent
[root@snort conf]# /opt/snortagent/conf/stop


移除snort agent
[root@snort snortcenter]# cd conf
[root@snort conf]# ./uninstall.sh
Are you sure you want to uninstall SnortCenter Sensor Agent? (y/n) : y


開機自動啟用agent
[root@snort snortagent]# chkconfig --level 35 sensor on
[root@snort snortagent]# chkconfig --list sensor
sensor          0:off   1:off   2:off   3:on    4:off   5:on    6:off


將snort agent納入中央管控



也可由中央管控對snort 開啟/關閉


以上SnortCenter 設定ok!

2011年2月1日 星期二

WinServer2008R2 Hyper-V安裝Linux系統整合服務 (Integration Components)-續

如果使用GUI介面在Hyper-V安裝Linux, 你會發現mouse,網卡,都沒支援, 一開始安裝系統只能暂時用鍵盤, 等安裝完成後再進去安裝支援網卡及mouse套件!
因當初安裝系統是以GUI介面安裝,故開機進去時會以GUI介面呈現,但又沒mouse,又沒網卡支援,所以先Ctrl+Alt+F1 以文字介面進去先設定網路及mouse

1. 安裝網卡同WinServer2008R2 Hyper-V安裝Linux系統整合服務 (Integration Components)文章步驟作法即可
2. 安裝支援mouse套件

下載

mount Linux VMISO檔案


Linux VM
                   註: 如果沒安裝xorg-X11-server-sdk套件要先安裝

   # mkdir /mnt/dvd
   # mount /dev/dvd /mnt/dvd
   # mkdir /opt/linux_inputdriver
   # cp –R /mnt/dvd/* /opt/linux_inputdriver
   # cd /opt/linux_inputdriver/
   # ./setup.pl inputdriver
   # reboot