Nginx access log and security inspection statistics

I. Introduction

    Due to the recent network protection requirements, in order to ensure the reliability of this offensive and defensive drill, we hereby sort out the relevant security inspections and use commands for the reference of students with relevant needs!
insert image description here

2. Vocabulary Explanation

insert image description here

2.1 The difference between pv and uv

PV (Page View Visits/Post Views): Refers to the calculation every time a user refreshes a web page within a certain statistical period. High PV does not necessarily mean more visitors: PV is directly proportional to the number of visitors, but PV does not directly determine the real number of visitors to the page. For example, even if a website comes in alone, it can create a very high PV by constantly refreshing the page.

UV (Unique Visitor unique visitors): refers to a client (non-export ip) who visits your website is a visitor. UV refers to different natural persons who visit and browse a webpage through the Internet. The same client within 00:00-24:00 is only counted once. On the same day, UV only records the visitors who enter the website for the first time, and does not count if they visit the website again on the same day; the calculation of UV is closely related to the browser's cookie. If the cookie has not changed, even if the ip has changed, but the client has not changed, the UV is still the previous record, and will not repeat the statistics;

2.2, tcp status explanation

CLOSED No connection is active or in progress
LISTEN Server is waiting for an incoming call
SYN_RECV A connection request has arrived, waiting for acknowledgment
SYN_SENT Application has started, open a connection
ESTABLISHED Normal data transfer status/current number of concurrent connections
FIN_WAIT1 Application says it is done
FIN_WAIT2 Else One side has agreed to release
ITMED_WAIT, waiting for all groups to die
CLOSING, both sides try to close
TIME_WAIT at the same time, and the other side has initialized a release
LAST_ACK, waiting for all groups to die

3. Log and network connection inspection

1) Check the TCP connection status

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

Command example description:

netstat -n | awk '/^tcp/ {++arr[$NF]};END {for(k in arr) print k,"\t",arr[k]}'

This command is used to display the network connection status and statistical information of the current system. The purpose is to display the statistics of each TCP connection status in the current system. For example, ESTABLISHED means that the connection has been established, TIME_WAIT means waiting to close the connection, etc. The output will be in the form of connection status and corresponding occurrence count. Let's explain the meaning of this command step by step:

netstat -n: This is an option of the netstat command, which is used to display network connection information. The "-n" option specifies not to resolve IP addresses and port numbers into hostnames and service names, but to display IP addresses and port numbers directly.

|: This symbol is the pipeline operator, used to pass the output of one command as input to another command.

awk '/^tcp/ {++arr[$NF]};END {for(k in arr) print k,"\t",arr[k]}': This part is to use the awk tool to process and count the output of the netstat command.

'/^tcp/ {++arr[$NF]}': This part uses regular expressions to match lines beginning with "tcp", and uses the array arr to record the number of occurrences of each state. $NF indicates the last field of the current line , that is, the connection status. NF The total number of fields per line (Number of Font).

END {for(k in arr) print k,"\t",arr[k]}: After all rows are processed , use a for loop to iterate over the keys (connection status) in the array arr and print out the key and the corresponding value (number of status occurrences).

2) Please search for 20 IPs for the number of requests (mostly used to find the source of the attack):

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
#其他
//获得访问前10位的ip地址
cat access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -n 10
cat access.log|awk '{counts[$(11)]+=1}; END {for(url in counts) print counts[url],url}'
//查看访问次数最多的文件或页面,取前20
cat access.log|awk '{print $11}'|sort|uniq -c|sort -nr|head -n 20
//列出传输最大的几个rar文件
cat access.log |awk '($7~/\.rar/){print $10 " " $1 " " $4 " " $7}'|sort -nr|head -n 20

//列出输出大于200000byte(约200kb)的rar文件以及对应文件发生次数
cat access.log |awk '($10 > 200000 && $7~/\.rar/){print $7}'|sort -n|uniq -c|sort -nr|head -n 100
//如果日志最后一列记录的是页面文件传输时间,则有列出到客户端最耗时的页面
cat access.log |awk '($7~/\.php/){print $NF " " $1 " " $4 " " $7}'|sort -nr|head -n 100
//.列出最最耗时的页面(超过60秒的)的以及对应页面发生次数
cat access.log |awk '($NF > 60 && $7~/\.php/){print $7}'|sort -n|uniq -c|sort -nr|head -n 100
//列出传输时间超过 30 秒的文件
cat access.log |awk '($NF > 30){print $7}'|sort -n|uniq -c|sort -nr|head -n 20

#统计网站流量(GB/s)

cat access.log |awk '{sum+=$10} END {print sum/1024/1024/1024}'
#统计404的连接数

awk '($9 ~/404/)' access.log | awk '{print $9,$7}' | sort

#统计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

#查看是哪些爬虫在抓取内容

tcpdump -i eth0 -l -s 0 -w - dst port 80 | strings | grep -i user-agent | grep -i -E 'bot|crawler|slurp|spider'

#按域统计流量

zcat 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]}}'

cat access.log| awk '{print $10,$7}' |awk 'BEGIN{FS="[ /]"}{trfc[$4]+=$1}END{for(domain in trfc){printf "%s\t%d\n",domain,trfc[domain]}}'

#


3) Use tcpdump to sniff the highest access IP on port 80

tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr |head -20

4) Find more time_wait connections

netstat -n|grep TIME_WAIT|awk '{print $5}'|sort|uniq -c|sort -rn|head -n20

5) Look for more SYN connections

netstat -an | grep SYN | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -nr | more

6) Find the process ID based on the port

netstat -ntlp | grep 80 | awk '{print $7}' | cut -d/ -f1
netstat -b //显示在创建每个连接或侦听端口时涉及到的可执行文件
netstat -o //显示拥有的与每个连接关联的进程ID

7) Database: view the sql executed by the database

/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'

8) Process tracking

System Debug analysis: strace -p pid
track the PID of the specified process:gdb -p pid

9) Log analysis

//查看安全日志/var/log/audit中成功登陆服务器的IP和用户,并统计次数
cat /var/log/audit/audit.log |grep failed -v|awk '{print $10,$13}' |grep '/' -v |grep old -v |grep acct |awk -F "=" '{print $2,$3}' |awk -F "(" '{print $1,$2}'|awk -F "," '{print $1}'|uniq -c |grep ? -v|sort -d

//查看最近20条登陆服务器用户的持续时间、IP、用户
last |awk '{print $1,$3,$4,$5,$6,$7.$8.$9,$10}'|head -n20

#/var/log/secure 日志分析.查看哪些IP扫描过本机
grep "Failed password" /var/log/secure|grep invalid|awk '{print $13}'| sort |uniq

//查看成功登陆本机的记录
cat /var/log/secure |awk '{print $5,$9,$11,$12,$13}'|grep su -v|grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'|awk -F ":" '{print $1,$2}'|uniq -c
cat /var/log/secure |awk '{print $1,$2,$3,$5,$9,$11,$12,$13}'|grep su -v|grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'|less

#定位有多少IP在爆破主机的root帐号
grep "Failed password for root" /var/log/secure|awk'{print $11}'|sort|uniq -c|sort- nr |more
#查看定位有哪些IP在爆破
grep -E "(Failed password)|(incorrect password)" /var/log/secure|grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"|uniq -c
#爆破用户名字典是什么
grep "Failed password" /var/log/secure|perl -e 'while($_=<> ){/for (.*?) from /;print "$1\n";}'|uniq -c|sort -nr
#查看登录成功的IP
grep "Accepted password" /var/log/secure | awk '{print $11}' | sort | uniq -c | sort -nr | more
#查看登录成功的日期、用户名、IP
grep "Accepted password" /var/log/secure | awk '{print $1,$2,$3,$9,$11}'

10) Check the system

dmesg 检查硬盘是否运行在DMA模式
dmesg |grep DMA dmesg 检查网卡是否运行正常
dmesg |grep eth0 dmesg探测系统内核模块的加载情况
dmesg |grep acpi
systemctl list-units --type=service:列出当前系统上所有已启动的服务
chkrootkit:检查系统是否被rootkit攻击。
rkhunter:检查系统的安全性和完整性。rkhunter(Rootkit Hunter)是一款用于检测和报告系统上潜在的Rootkit、后门和可疑文件的工具。安装执行:sudo yum install rkhunter
udo rkhunter --update
//运行系统检查:
sudo rkhunter --check
#查看检查结果:检查结果会被保存在一个日志文件中,通常是/var/log/rkhunter.log。
使用以下命令查看日志文件内容:sudo cat /var/log/rkhunter.log

sudo rkhunter --propupd:更新rkhunter的文件属性数据库,以减少误报。
sudo rkhunter --list propfiles:列出rkhunter监控的文件和目录。

#查询特权用户特权用户(uid 为0)
awk -F: '$3==0 {print $1}' /etc/passwd
#查询可以远程登录的帐号信息
awk '/\$1|\$6/{print $1}' /etc/shadow
#查看sudo权限
more /etc/sudoers|grep -v "^#\|^$" |grep "ALL=(ALL)"
usermod -L user	禁用帐号,帐号无法登录,/etc/shadow第二栏为!开头
userdel user	删除user用户
userdel -r user	将删除user用户,并且将/home目录下的user目录一并删除

#修改histroy记录
sed -i 's/^HISTSIZE=1000/HISTSIZE=10000/g' /etc/profile   //保存1万条命令

#为历史的命令增加登录的IP地址、执行命令时间等信息
vim /etc/profile
######history #########
USER_IP=`who -uam 2>/dev/null|awk '{print $NF}'|sed -e 's/[()]//g'`
if [ $USER_IP="" ]; then
 USER_IP=`hostname`
fi
export HISTTIMEFORMAT="%F %T $USER_IP `whoami`"
shopt -s histappend
export PROMPT_COMMAND="history -a"

#########history########## 
#仅让历史记录中带上命令执行时间
vi /home/$USER/.bash_profile  //新增如下
export HISTTIMEFORMAT='%F %T '   //注意”%T”后面的空格,用来将时间和命令之间分割
或
export HISTTIMEFORMAT="%F %Twho -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'whoami "

#修改bash源码,让history记录通过syslog发送到远程logserver中,下载bash源码
env | grep SHELL  //查看系统当前使用的shell
bash --version
//从https://mirrors.ustc.edu.cn/gnu/bash/或https://ftp.gnu.org/gnu/bash/下载对应版本bash源码包,重新编译
wget https://ftp.gnu.org/gnu/bash/bash-4.2.53.tar.gz
tar -xvf bash-3.2.tar.gz -C /opt/sources/
cd /opt/sources/bash-3.2
vim bashhist.c  //修改如下
syslog (SYSLOG_FACILITY|SYSLOG_LEVEL, "PID=%d UID=%d User=%s Cmd=%s", getpid(), current_user.uid, current_user.user_name, line);
syslog (SYSLOG_FACILITY|SYSLOG_LEVEL, "PID=%d UID=%d User=%s Cmd=%s", getpid(), current_user.uid, current_user.user_name, trunc);

//修改源码config-top.h,取消/\#define SYSLOG_HISTORY/这行的注释
define SYSLOG_HISTORY   #syslog的FACILITY为 LOCAL6,日志级别为NOTICE

./configure --prefix=/opt/bash
#备份源bash
cp -pr /usr/bin/bash /usr/bin/bash_r_`date`
chmod 755 /opt/bash/bin/bash
cp -pr /opt/bash/bin/bash /usr/bin

#验证
tail -f /var/log/message   #这时,发现history记录已经写到了/var/log/message中

#转发到log服务器
vim /etc/rsyslog.conf  //修改
local6.notice /var/log/bash.log
*.info;mail.none;authpriv.none;cron.none;local6.none; /var/log/messages
local6.notice @172.16.1.33:13514

#修改历史记录文件为只能被追加来进行阻止
chattr +a /home/bob/.bash_history
hattr +a /home/bob/.bash_profile
chattr +a /home/bob/.bash_login
chattr +a /home/bob/.profile
chattr +a /home/bob/.bash_logout
chattr +a /home/bob/.bashrc  #只在当non-login交互式shell调用时被读取,其他三个配置文件本身会调用.bashrc

#将此用户的密码最长使用天数设为30,最短使用天数设为0,密码2000年1月1日过期,过期前七天警告用户。
chage -m0 -M30 -E2000-01-01 -W7 <用户名>
设置连续输错三次密码,账号锁定五分钟。使用命令
vi/etc/pam.d/common-auth  //修改配置文件,添加
auth required pam tally.so onerr=fail deny=3 unlock time=300

more /etc/rc.local /etc/rc.d/rc[0~6] .dls-l /etc/rc.d/rc3.d/

//定位有多少IP在爆破主机的root帐号:

grep "Failedpasswordforroot"/var/log/secure|awk'{print$11}'|sort|uniq-c|sort- nr |more

//SHELL中的内置命令约有60个,通过内置的enable命令即可查看所有的内部命
enable
enable -n cd #禁用命令cd在SHELL中的内置功能

chkconfig --list | grep "3:on\|5:on"  //查看系统在3与5级别下的启动项

#系统完整性检查
/rpm -Va > rpm.log  //通过rpm自带的-Va来校验检查所有的rpm软件包,查看哪些命令是否被替换了,如果一切均校验正常将不会产生任何输出,如果有不一致的地方,就会显示出来,输出格式是8位长字符串,每个字符都用以表示文件与RPM数据库中一种属性的比较结果 ,如果是. () 则表示测试通过
rpm	-qf /bin/ls	#查询ls命令属于哪个软件包
rpm2cpio /mnt/cdrom/Packages/coreutils-8.4-19.el6.i686.rpm | cpio-idv ./bin/ls #提取rpm包中ls命令到当前目录的/bin/ls下,-i:copy-in模式,还原;-d:还原时自动新建目录;-v:显示还原过程
cp /root/bin/ls	/bin/ #把ls命令复制到/bin/目录修复文件丢失,最后就按着旧文件授权修改一致即可

#僵尸进程,找到该defunct僵尸进程的父进程,将该进程的父进程杀掉,则此defunct进程将自动消失
ps aux | grep Zs |  grep -v grep
ps -ef | grep defunct
ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]'
ps -ef | grep defunct | grep -v grep | awk {
    
    print "kill -9 " $2,$3}  //谨慎kill
cat /proc/defunct_pid/stack  #查看具体僵尸进程的情况
lsof -p defunct_pid
#查看stopped进程,stopped进程的STAT状态为T
ps -e j | grep T 
ps -A -ostat,ppid,pid,cmd | grep -e '^[T]'
#搜索伪装成病毒的可执行文件
find / -size -1223124c -size +1223122c -exec ls -id {
    
    } \; 搜索1223123大小的文件
ll -h /etc/rc.d/init.d/
less /etc/rc.local  #查看启动文件里是否嵌入启动脚本命令

var/log/cron records the logs related to system timing tasks
/var/log/cups records the logs of printing information
/var/log/dmesg records the information of the kernel self-test when the system is turned on, and you can also use the dmesg command to directly view the kernel Self-test information
/var/log/mailog Record mail information
/var/log/message Record the log of important system information. Most of the important information of the Linux system will be recorded in this log file. If there is a problem with the system
, the log file /var/log/btmp should be checked first to
record the error log. This file is a binary file and cannot be directly Vi to view, but to use the lastb command to view
/var/log/lastlog logs that record the last login time of all users in the system. This file is a binary file, you cannot directly vi, but use the lastlog command to view /var/log/
wtmp
permanently Record the login and logout information of all users, and record the system startup, restart and shutdown events at the same time. Also this file is also
a binary file, you can’t directly vi, but you need to use the last command to view
/var/log/utmp to record the currently logged in user information, this file will change with the user’s login and logout, and only record the current login user information. Similarly, this file cannot be directly vi, but use w, who, users and other commands to query
/var/log/secure record verification and authorization information, as long as the program involving account and password will be recorded, such as SSH login, su switch user

Attachment: SSH brute force cracking, three-way handshake session status review

① TCP initializes the connection with three handshakes: send a SYN packet, then return a SYN/ACK packet, and then send an ACK packet, and the connection is formally established. But there are some exceptions. When the requester receives the SYS/ACK packet, it starts to establish a connection, and the requestee establishes a connection after the third handshake.

② Client TCP state transition:

CLOSED-> SYN_SENT ->ESTABLISHED->FIN_WAIT_1->FIN_WAIT_2->TIME_WAIT->CLOSED
Server TCP state transition:
CLOSED->LISTEN-> SYN_recv ->ESTABLISHED->CLOSE_WAIT->LAST_ACK->CLOSED

③ When the client starts to connect, the server is still in LISTENING. After the client sends a SYN packet, the server receives the client’s SYN and sends an ACK, the server is in the SYN_RECV state, and some abnormalities will occur, and then no more received The client's ACK enters the ESTABLISHED state, but the server display stays in the SYN_RECV state, which is likely to be blasted.

11) MAC spoofing

arp -an  //查看所有连接本地主机的ip和mac地址

12)windows

 netsh wlan show profiles  //查看连接过的wifi点
 netsh wlan show profile name='sdc-qwimq' key=clear //查看wifi key
 net view hostname/ip   //查看对应IP地址共享的资源
 net share //显示本地共享资源
 net share ipc$ /del //删除ipc$共享 
net share c$ /del //删除C:共享 
 net user  //查看用户
 net user 帐户名 //查看帐户的属性 
 net use 
 net start //查看开启了哪些服务
 net time \\目标ip /set #设置本地计算机时间与“目标IP”主机的时间同步,加上参数/yes可取消确认信息
 net config 显示系统网络设置
 finger username @host  //查看最近有哪些用户登陆
 attrib 文件名(目录名) //查看某文件(目录)的属性 
 attrib 文件名 -A -R -S -H 或 +A +R +S +H //去掉(添加)某文件的 存档,只读,系统,隐藏 属性;用+则是添加为某属性
 date /t 、 time /t //将只显示当前日期和时间
 set //显示当前所有的环境变量
 ver //在cmd窗口下显示版本信息
 winver //弹出一个窗口显示版本信息
 type 文件名 显示文本文件的内容 
 more 文件名 逐屏显示输出文件
 msinfo32 //软件环境→正在运行任务”就可以查看到进程的详细信息
 systeminfo  //查看系统信息
 cacls 文件名 /参数  #显示或修改文件访问控制列表(ACL)--针对NTFS格式时。参数:/D 用户名:设定拒绝某用户访问;/P 用户名erm 替换指定用户的访问权限;/G 用户名erm 赋予指定用户访问权限;Perm 可以是: N 无,R 读取, W 写入, C 更改(写入),F 完全控制;
 icacls 文件名
 at  //查看计划任务
 eventvwr.msc  //查看日志
 运行,输入%UserProfile%\Recent  //分析最近打开分析可疑文件
 #好玩的
 color 颜色值 设置cmd控制台前景和背景颜色;0=黑、1=蓝、2=绿、3=浅绿 、4=红、5=紫、6=黄、7=白、8=灰、9=淡蓝、A=淡绿、B=淡浅绿、C=淡红、D=淡紫、E=淡黄、F=亮白 
 wmic process get caption,commandline /value >> tmp.txt  //进程分析
 wmic process where caption=”svchost.exe” get caption,commandline /value  #查询某一个进程的信息,得到进程的可执行文件位置等信息

13) Tools

1. Use WWWGrep to check your website element security

WWWGrep is a tool for HTML security. Search recursively. Header names and values ​​can also be searched recursively in this way.

2. chkrootkit
wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz tar zxvf chkrootkit.tar.gz
cd chkrootkit-0.52
make sense
./chkrootkit //check

3. rkhunter: http://rkhunter.sourceforge.net
wget https://nchc.dl.sourceforge.net/project/rkhunter/rkhunter/1.4.4/rkhunter-1.4.4.tar.gz
tar -zxvfrkhunter-1.4.4.tar .gz
cd rkhunter-1.4.4
./installer.sh --install
rkhunter -c

4. Clamav: virus killing
wget http://nchc.dl.sourceforge.net/project/libpng/zlib/1.2.7/zlib -1.2.7.tar.gz
tar-zxvfzlib-1.2.7.tar.gz
cd zlib-1.2.7
#Install the dependent gcc compilation environment:
yum install gcc -y
CFLAGS="-O3-fPIC" ./configure --prefix=/usr/local/zlib/
make && makeinstall
#Add user group clamav and group member clamav:
groupadd clamav
useradd -g clamav -s /bin/false -c “Clam AntiVirus” clamav
#Install Clamav
tar –zxvf clamav-0.97.6.tar.gz
cd clamav-0.97.6
./configure–prefix=/opt/clamav–disable -clamav-with-zlib=/usr/local/zlib
make
make install
#Configure Clamav
mkdir /opt/clamav/logs
mkdir /opt/clamav/updata
touch /opt/clamav/logs/freshclam.log
touch /opt/clamav/ logs/clamd.log
cd /opt/clamav/logs
chown clamav:clamav clamd.log
chown clamav:clamav freshclam.log5, ClamAV uses:
/opt/clamav/bin/freshclam #Upgrade the virus database./clamscan
–h #View the corresponding help information./clamscan-r/home #Use ./clamscan -r --bell -i
/ to scan the home directory of all users
bin #Scan the bin directory and display the scan results of the problematic files
#Use
yum install -y clamav #Update virus database
freshclam #Scan method
clamscan -r /etc --max-dir-recursion=5 -l /root/etcclamav. log
clamscan -r /bin --max-dir-recursion=5 -l /root/binclamav.log
clamscan -r /us r–max-dir-recursion=5 -l /root/usrclamav.log #Scanning and antivirus
clamscan -r --remove /usr/bin/bsd-port
clamscan -r --remove /usr/bin/
clamscan -r–remove /usr/local/zabbix/sbin #Check the log and find
cat /root/usrclamav.log |grep FOUND

5. Log analysis: use LogParser to extract data from windows logs and analyze

6. 360 ransomware website (http://lesuobingdu.360.cn)

7. D-Shield_Web Antivirus: It can analyze the more hidden WebShell backdoor behavior. It can detect and kill more hidden backdoors, and present the abnormal basic parameters in front of your eyes, so that you can grasp the status of backdoors more quickly.

8. "Reject Ransomware" website: https://www.nomoreransom.org/zh/index.html

9. IpTool packet capture tool

10. Hippo killing: supports multiple platforms, but requires a networked environment
wget http://down .shellpub.com/hm/latest/hm-linux-amd64.tgz
tar xvf hm-linux-amd64.tgz
hm scan /www

4. Log configuration

4.1. Example of Nginx being tampered with

insert image description here
In the figure above, the Nginx configuration file VirtualHost.conf has been tampered with, through the reverse proxy to match the special link with the suffix "sc", and hijacked to http://103.233.248.163, which is a gaming link navigation website.

4.2. Example of Nginx background page js file being tampered with and hijacked

insert image description here

5. Script example

5.1 Nginx script

#!/bin/bash

# Nginx日志路径
LOG_PATH="/var/log/nginx/access.log"

# 检查IP访问频率/次数
check_ip_frequency() {
    
    
    echo "IP访问频率检查结果:"
    awk '{print $1}' $LOG_PATH | sort | uniq -c sort -nr
}

# 检查访问状态码
check_response_codes() {
    
    
    echo "访问状态码检查结果:"
    awk '{print $9}' $LOG_PATH | sort | uniq -c | sort -nr
}

# 检查请求来源URL
check_referers() {
    
    
    echo "请求来源URL检查结果:"
    awk '{print $11}' $LOG_PATH | sort | uniq -c | sort -nr
}

# 检查异常User-Agent
check_user_agents() {
    
    
    echo "异常User-Agent检查结果:"
    awk -F\" '{print $6}' $LOG_PATH | sort | uniq -c | sort -nr
}

# 检查潜在的SQL注入攻击
check_sql_injections() {
    
    
    echo "潜在的SQL注入攻击检查结果:"
    grep -iE "(union|select|from|where|insert|update|delete|drop)" $LOG_PATH
}

# 执行巡检
echo "开始巡检Nginx日志安全性..."
echo ""
check_ip_frequency
echo ""
check_response_codes
echo ""
check_referers
echo ""
check_user_agents
echo ""
check_sql_injections
echo ""
echo "巡检完成!"

5.2. Short connection capture script

Short connection (short connnection) is a concept relative to long connection. It means that in the process of data transmission, a connection is established only when data needs to be sent. After the data is sent, the connection is disconnected, that is, Only one transaction is sent per connection. In system maintenance, it is generally difficult to detect. It needs to use network security equipment or packet capture analysis to find out. It may be seen by refreshing the netstat command several times, but the pid of the process is changeable, it is not easy to be captured, and it is difficult to capture the corresponding process and source file;

#!/bin/bash 
ip=外连异常ip
i=1 while :
do
	tmp=netstat-anplt|grep $ip|awk -F'[/]' '{print $1}'|awk'{print $7}' 
#echo $tmp
if test -z "$tmp" ;then
((i=i+1))
else
  for pid in $tmp; 
   do echo "PID: "${pid}
   result=ls -lh /proc/$pid|grep exe 
   echo "Process: "${result}
   kill -9 $pid
   done
break 
fi 
done
echo "Total number of times: "${i}

Guess you like

Origin blog.csdn.net/ximenjianxue/article/details/132256607