├── NewVerson └── SecurityTest │ ├── README.txt │ ├── Config │ ├── config.xlsx │ └── README.txt │ ├── Log │ └── README.txt │ ├── Report │ └── README.txt │ ├── TestCase │ ├── Authorization_Renzhen │ │ ├── APIlist.xlsx │ │ ├── readme.txt │ │ ├── TestCase_API_Authentication_Console.py │ │ └── _get_registeredPORT.py │ ├── systemSafe │ │ ├── systemSafePolicy.xlsx │ │ ├── systemSafePolicy │ │ │ ├── config.md │ │ │ ├── VM_fileaccess.md │ │ │ ├── VM_RootProcess.md │ │ │ ├── VM_unSavePross.md │ │ │ ├── VM_SensitiveInPross.md │ │ │ └── policy.md │ │ ├── readme.txt │ │ ├── TestCase_systemSafe_VM.py │ │ └── TestCase_systemSafe_Docker.py │ ├── SensitiveInfo │ │ ├── scanSensitivePolicy.xlsx │ │ ├── scanSensitivePolicy │ │ │ ├── FIND_DebugModel.md │ │ │ ├── readme.txt │ │ │ ├── config.md │ │ │ ├── FIND_EmployID.md │ │ │ ├── FIND_Password.md │ │ │ ├── FIND_Annotation_js.md │ │ │ ├── FIND_EncryptTool.md │ │ │ ├── FIND_UnsafeEncrypt.md │ │ │ ├── FIND_Annotation_html.md │ │ │ ├── FIND_Annotation_sh.md │ │ │ ├── FIND_Annotation_python.md │ │ │ ├── FIND_Sensitive.md │ │ │ └── policy.md │ │ ├── readme.txt │ │ ├── TestCase_SensitiveInfo_Document.py │ │ └── TestCase_SensitiveInfo_Code.py │ ├── CommunicationMatrix │ │ ├── CommunicationMatrix_Docker.xlsx │ │ ├── CommunicationMatrix_VM.xlsx │ │ ├── readme.txt │ │ └── TestCase_CommunicationMatrix_Docker.py │ ├── DatabaseConfig │ │ └── readme.txt │ ├── UnauthorizedAccess_Hengxiangyuequan │ │ ├── accessConfig.xlsx │ │ ├── readme.txt │ │ └── TestCase_UnauthorizedAccess.py │ ├── PasswdComplexity │ │ └── README.txt │ ├── SudoersSafe │ │ └── README.txt │ └── Authorization_Jianquan │ │ ├── README.txt │ │ └── TestCase_API_Authorization.py │ └── PublicLib │ ├── GlobalValue.py │ ├── LocalOperate.py │ ├── WordOperate.py │ ├── Log.py │ ├── ExcelOperate.py │ ├── ContainerOperate.py │ └── LinuxOperate.py ├── FirstVersion ├── vmSecureScan │ ├── config │ │ ├── vmInfo.csv │ │ ├── history │ │ │ ├── 单列结果格式举例.xlsx │ │ │ └── 多列结果格式举例.xlsx │ │ ├── script │ │ │ ├── VM_userPasswd.sh │ │ │ ├── VM_Process.sh │ │ │ ├── VM_sudoers.sh │ │ │ ├── VM_netstat_0000.sh │ │ │ ├── VM_unsafePross.sh │ │ │ ├── VM_SensitiveInPross.sh │ │ │ ├── VM_JSX_Language_html.sh │ │ │ ├── VM_JSX_Language_js.sh │ │ │ ├── Container_sudoers.sh │ │ │ ├── VM_JSX_Language_sh.sh │ │ │ ├── VM_JSX_Language_py.sh │ │ │ ├── VM_debugModel.sh │ │ │ ├── VM_unsafePort.sh │ │ │ ├── VM_DockerPS.sh │ │ │ ├── VM_unsafe_encrypt.sh │ │ │ ├── VM_Password.sh │ │ │ ├── VM_CertificateInLog.sh │ │ │ ├── VM_UserNameInLog.sh │ │ │ ├── VM_fileaccess.sh │ │ │ └── VM_Sensitive.sh │ │ └── script-description.txt │ ├── run.py │ ├── README.txt │ ├── libs │ │ └── scanFunctionDef.py │ └── fileTool │ │ └── fileToolDef.py └── Test │ ├── Readme.txt │ ├── test1.py │ └── test2.py ├── Building a software-testing environment.txt └── README.txt /NewVerson/SecurityTest/README.txt: -------------------------------------------------------------------------------- 1 | 进阶版本 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/vmInfo.csv: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/Config/config.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/Log/README.txt: -------------------------------------------------------------------------------- 1 | 执行过程中日志记录 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/Report/README.txt: -------------------------------------------------------------------------------- 1 | 扫描结果输出到该文件夹 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/history/单列结果格式举例.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/history/多列结果格式举例.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Renzhen/APIlist.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/CommunicationMatrix/CommunicationMatrix_Docker.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/CommunicationMatrix/CommunicationMatrix_VM.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/DatabaseConfig/readme.txt: -------------------------------------------------------------------------------- 1 | 检查已安装MySQL数据库节点的数据库安全配置 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/UnauthorizedAccess_Hengxiangyuequan/accessConfig.xlsx: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_userPasswd.sh: -------------------------------------------------------------------------------- 1 | cat /etc/passwd |egrep "[0-9]{4}" 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_Process.sh: -------------------------------------------------------------------------------- 1 | ps -ef | egrep -v '[[0-9]*]| pts/' |grep 'root ' 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_sudoers.sh: -------------------------------------------------------------------------------- 1 | cat /etc/sudoers |egrep -v -i "^#|^Defaults|^$" 2 | -------------------------------------------------------------------------------- /FirstVersion/Test/Readme.txt: -------------------------------------------------------------------------------- 1 | 脚本进行调试 2 | 将原来的脚本分成了小的组成部分 3 | 4 | 脚本test1.py 5 | #该脚本用于验证环境是否搭建成功 6 | #虚机节点是否可以进行连接 7 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_netstat_0000.sh: -------------------------------------------------------------------------------- 1 | netstat -tunlp |egrep "0.0.0.0:[0-9]+|:::[0-9]+" 2 | 3 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_unsafePross.sh: -------------------------------------------------------------------------------- 1 | ps -ef | egrep -i "bootps|pure-ftpd|pppoe|sendmail|isdn|zebra|cupsd|cups-config-daemon|hplip|hpiod|hpssd|bluetooth|hcid|hidd|sdpd|dund|pand|rsh|telnet" 2 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_DebugModel.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/lib(64|)/python2\.7/.* shell 3 | .*/usr/lib/dracut/ shell 4 | \.(log|txt|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 5 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/config.md: -------------------------------------------------------------------------------- 1 | key value 说明 2 | codeDir D:/code1 【必填项】源码所在路径(只支持扫描目录,如果是源码包,请手动解压。如果解压后的目录中含有压缩包,脚本会自动解压)。注意:该目录下放的是源码第一层目录,如 D:/code/cfe-clustermgr-master,脚本会根据红色部分的名称来分类扫描结果 3 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_SensitiveInPross.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | key_words='pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|X-Auth-Token|Authorization|sessionID|token|email' 4 | ps -ef | egrep -i "$key_words" |grep -v grep 5 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/PasswdComplexity/README.txt: -------------------------------------------------------------------------------- 1 | ''' 2 | """ 相关安全要求说明 """ 3 | 系统自身操作维护类口令满足“口令安全要求”。 4 | ''' 5 | ''' 6 | """ 脚本功能 """ 7 | 检查操作系统的账号密码安全 8 | ''' 9 | ''' 10 | """ 脚本配置执行说明 """ 11 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 12 | ''' 13 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/readme.txt: -------------------------------------------------------------------------------- 1 | 2 | 由于systemSafePolicy.xlsx文件比较大 3 | 现将其中的Sheet页单独分成多个文件,在使用的时候将其组合成systemSafePolicy.xlsx文件 4 | Sheet1:policy (需在虚机中执行的Shell命令) 5 | Sheet2:config (指定源码或资料所在路径,只有使用源码或资料敏感信息的时候才会使用到) 6 | Sheet3-:Shell命令结果中需排除的关键字正则表达式 7 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/readme.txt: -------------------------------------------------------------------------------- 1 | 由于scanSensitivePolicy.xlsx文件比较大 2 | 现将其中的Sheet页单独分成多个文件,在使用的时候将其组合成scanSensitivePolicy.xlsx文件 3 | Sheet1:policy (需在虚机中执行的Shell命令) 4 | Sheet2:config (指定源码或资料所在路径,只有使用源码或资料敏感信息的时候才会使用到) 5 | Sheet3-:Shell命令结果中需排除的关键字正则表达式 6 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/CommunicationMatrix/readme.txt: -------------------------------------------------------------------------------- 1 | 检查通信矩阵 2 | 3 | CommunicationMatrix_VM.xlsx与CommunicationMatrix_Docker.xlsx为已经给出的通信矩阵 4 | 按照下列格式进行配置: 5 | Sheet:VM 6 | 目的IP(Destination IP Address) 目的端口(Destination Port) 协议(Protocol) 所属域(Plane) 所属微服务(Involved Microservice) 7 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/readme.txt: -------------------------------------------------------------------------------- 1 | 由于scanSensitivePolicy.xlsx文件比较大 2 | 现将其中的Sheet页单独分成多个文件,在使用的时候将其组合成scanSensitivePolicy.xlsx文件 3 | Sheet1:policy (需在虚机中执行的Shell命令) 4 | Sheet2:config (指定源码或资料所在路径,只有使用源码或资料敏感信息的时候才会使用到) 5 | Sheet3-:Shell命令结果中需排除的关键字正则表达式 6 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SudoersSafe/README.txt: -------------------------------------------------------------------------------- 1 | ''' 2 | """ 相关安全要求说明 """ 3 | 操作系统的普通用户不能提权至root权限,如sudo开得权限太大,使得非root组的用户通过sudo可以提权获取root所有权限。 4 | ''' 5 | 6 | """ 脚本功能 """ 7 | 检查/etc/sudoers中的配置安全 8 | ''' 9 | ''' 10 | """ 脚本配置执行说明 """ 11 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 12 | ''' 13 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/VM_fileaccess.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 说明 2 | lrwxrwxrwx 3 | /home/\w+/\.bash_logout$ 4 | /home/\w+/\.bash_profile$ 5 | /home/\w+/\.bashrc$ 6 | /var/spool/mail/\w+$ 7 | /\w+$ 8 | /home/\w+/.ssh/known_hosts$ 9 | tempScanDocker|tempScan 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_JSX_Language_html.sh: -------------------------------------------------------------------------------- 1 | find / \ 2 | -path /proc -prune -o \ 3 | -path /boot -prune -o \ 4 | -path /tmp -prune -o \ 5 | -type f -name "*.html" -user paas | xargs egrep -n -i '^[[:blank:]]*<\!--|^[[:blank:]]*//|^[[:blank:]]*/\*' | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 6 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_JSX_Language_js.sh: -------------------------------------------------------------------------------- 1 | find / \ 2 | -path /proc -prune -o \ 3 | -path /boot -prune -o \ 4 | -path /tmp -prune -o \ 5 | -type f -name "*.js" -user paas | xargs egrep -n -i '^[[:blank:]]*<\!--|^[[:blank:]]*//|^[[:blank:]]*/\*|^[[:blank:]]*\*' | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 6 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/config.md: -------------------------------------------------------------------------------- 1 | key value 说明 2 | codeDir D:/code1 "【源码扫描必填项】指定源码所在路径(只支持扫描目录,如果是源码包,请手动解压。如果解压后的目录中含有压缩包,脚本会自动解压)。 3 | 注意:该目录下放的是源码第一层目录,如 D:/code1/cfe-clustermgr-master,脚本会根据红色部分的名称来分类扫描结果" 4 | documentDir D:/document "【资料扫描必填项】指定资料所在路径(目前只支持扫描word和excel)。 5 | 注意:该目录下放的是资料文档,如 D:/document/api.docx,脚本会根据红色部分的名称来分类扫描结果" 6 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/VM_RootProcess.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 说明 2 | \sgrep 3 | :[0-9][0-9] sh 4 | :[0-9][0-9] bash 5 | :[0-9][0-9] /(s|)bin/sh 6 | :[0-9][0-9] /(s|)bin/bash 7 | :[0-9][0-9] /sbin/ 8 | :[0-9][0-9] /usr/(s|)bin/ 9 | :[0-9][0-9] (find|curl|grep|egrep|ps -ef|file) 10 | \s\s00:00:0[0-5] 11 | :[0-9][0-9] \[ 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/VM_unSavePross.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 说明 2 | \sgrep 3 | :[0-9][0-9] sh 4 | :[0-9][0-9] bash 5 | :[0-9][0-9] /(s|)bin/sh 6 | :[0-9][0-9] /(s|)bin/bash 7 | :[0-9][0-9] /sbin/ 8 | :[0-9][0-9] /usr/(s|)bin/ 9 | :[0-9][0-9] (find|curl|grep|egrep|ps -ef|file) 10 | \s\s00:00:0[0-5] 11 | :[0-9][0-9] \[ 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/VM_SensitiveInPross.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 说明 2 | \sgrep 3 | :[0-9][0-9] sh 4 | :[0-9][0-9] bash 5 | :[0-9][0-9] /(s|)bin/sh 6 | :[0-9][0-9] /(s|)bin/bash 7 | :[0-9][0-9] /sbin/ 8 | :[0-9][0-9] /usr/(s|)bin/ 9 | :[0-9][0-9] (find|curl|grep|egrep|ps -ef|file) 10 | \s\s00:00:0[0-5] 11 | :[0-9][0-9] \[ 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/Container_sudoers.sh: -------------------------------------------------------------------------------- 1 | images=(`docker ps |egrep -v "pause|CONTAINER" |awk '{print $2}'`) 2 | docker=(`docker ps |egrep -v "pause|CONTAINER" |awk '{print $1}'`) 3 | i=0 4 | len=${#docker[@]} 5 | while(($i<$len)) 6 | do 7 | echo "############### ${docker[$i]} ${images[$i]}" 8 | docker exec -u 0 ${docker[$i]} cat /etc/sudoers |egrep -v "^#|^Defaults|^$" 9 | echo "" 10 | i=$(($i+1)) 11 | done 12 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/Config/README.txt: -------------------------------------------------------------------------------- 1 | config.xlsx中包含两个sheet页:“vmInfo”和“otherConfig” 2 | “vmInfo”页配置如下: 3 | 第1列:服务器IP 4 | 第2列:服务器主机名(选填,无实际用途) 5 | 第3列:服务器登陆账号 6 | 第4列:服务器登陆密码 7 | 第5列:切换服务器管理员账号(如su – root、sudo su) 8 | 第6列:服务器管理员密码 9 | 第7列:是否容器环境OM-Core节点(能够下发kubectl命令的节点) 10 | 第8列:prinvate_key,如果需要密钥登陆,则填写密钥本地完整路径,如D:/code/dis_rsa_2048(如此处不为空,脚本会判断为仅支持密钥登陆) 11 | 第9列:密钥的密码(选填,密钥没有密码的话可以不填) 12 | 注:管理面和数据面节点都请录入 13 | “otherConfig”页的每一项配置,在config.xlsx中自有说明 14 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_JSX_Language_sh.sh: -------------------------------------------------------------------------------- 1 | find / \ 2 | -path /proc -prune -o \ 3 | -path /boot -prune -o \ 4 | -path /tmp -prune -o \ 5 | -type f -name "*.sh" -user paas | xargs egrep -n -i '^#|^[[:blank:]]*#|^#|^[[:blank:]]*//' | egrep -v -i -n '#![[:blank:]]*/bin/bash|# source env|#!/usr/bin/env[[:blank:]]*bash|[[:blank:]]*#--*|#[[:blank:]]*create|#for euler os|#for ubuntu os|#[[:blank:]]*\/' | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 6 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_EmployID.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | /usr/share/i18n shell 3 | /usr/lib/udev/hwdb.d shell 4 | .*/lib(64|)/python2\.7/.* shell 5 | \.log:[0-9]+:.*\"un\":\"([a-z]00[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]wx[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]9[0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]kf[0-9][0-9][0-9][0-9][0-9])\" shell 6 | \.log:[0-9]+:.*\"dn\":\"([a-z]00[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]wx[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]9[0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]kf[0-9][0-9][0-9][0-9][0-9])\" shell 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_JSX_Language_py.sh: -------------------------------------------------------------------------------- 1 | find / \ 2 | -path /proc -prune -o \ 3 | -path /boot -prune -o \ 4 | -path /tmp -prune -o \ 5 | -type f -name "*.py" -user paas | xargs egrep -n -i '^#|^[[:blank:]]*#' | egrep -v -i -n '#![[:blank:]]*/usr/bin/env[[:blank:]]*python|#![[:blank:]]*/usr/bin/python | #![[:blank:]]*/use/bin/python|#[[:blank:]]*Load[[:blank:]]*Modules|#[[:blank:]]*-\*- coding:[[:blank:]]*utf-8 -\*-|[[:blank:]]*#end[[:blank:]]*|[[:blank:]]*#[[:blank:]]*e\.g\.|[[:blank:]]*# for CSR|#stp|#mkdir' | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 6 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_debugModel.sh: -------------------------------------------------------------------------------- 1 | find / \ 2 | -path /proc -prune -o \ 3 | -path /tmp -prune -o \ 4 | -path /boot -prune -o \ 5 | -type f -name "*.sh" | xargs egrep -i -n 'bash[[:blank:]]*-[a-zA-Z]*x|set[[:blank:]]*-[a-zA-Z]*x' | egrep -v "bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt" 2>/dev/null 6 | 7 | find / \ 8 | -path /proc -prune -o \ 9 | -path /tmp -prune -o \ 10 | -path /boot -prune -o \ 11 | -type f -name "*.py" | xargs egrep -i -n 'bash[[:blank:]]*-[a-zA-Z]*x|set[[:blank:]]*-[a-zA-Z]*x' | egrep -v "bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt" 2>/dev/null 12 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_unsafePort.sh: -------------------------------------------------------------------------------- 1 | netstat -tunlp |egrep " 23/| 20/| 21/| 53/| 123/| 22/| 69/| 135/| 445/| 139/| 8888/| 513/| 3389/| 4899/| 1433/| 1434/| 3306/| 5432/| 177/| 6000/| 6001/| 6002/| 6003/| 6004/| 6005/| 6006/| 6007/| 6008/| 6009/| 6010/| 6011/| 6012/| 6013/| 6014/| 6015/| 6016/| 6017/| 6018/| 6019/| 6020/| 6021/| 6022/| 6023/| 6024/| 6025/| 6026/| 6027/| 6028/| 6029/| 6030/| 6031/| 6032/| 6033/| 6034/| 6035/| 6036/| 6037/| 6038/| 6039/| 6040/| 6041/| 6042/| 6043/| 6044/| 6045/| 6046/| 6047/| 6048/| 6049/| 6050/| 6051/| 6052/| 6053/| 6054/| 6055/| 6056/| 6057/| 6058/| 6059/| 6060/| 6061/| 1521/| 1522/| 1523/| 1524/| 1525/" 2 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_DockerPS.sh: -------------------------------------------------------------------------------- 1 | images=(`docker ps |egrep -v "pause|CONTAINER" |awk '{print $2}'`) 2 | docker=(`docker ps |egrep -v "pause|CONTAINER" |awk '{print $1}'`) 3 | mounts=(`find / -name "mount-id"`) 4 | 5 | i=0 6 | len=${#docker[@]} 7 | len_mount=${#mounts[@]} 8 | while(($i<$len)) 9 | do 10 | echo "############### containerID: ${docker[$i]}; image: ${images[$i]}" 11 | j=0 12 | while(($j<$len_mount)) 13 | do 14 | x=`echo "${mounts[$j]}" |grep ${docker[$i]}` 15 | if [ -n "$x" ];then 16 | mntID=`cat ${mounts[$j]}` 17 | echo mntID: $mntID 18 | fi 19 | j=$(($j+1)) 20 | done 21 | echo "" 22 | i=$(($i+1)) 23 | done 24 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_unsafe_encrypt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | 3 | 4 | key_words='\|\<3DES\>|\|\|\|\|\|\|\|\' 5 | find / \ 6 | -path /proc -prune -o \ 7 | -path /tmp -prune -o \ 8 | -path /boot -prune -o \ 9 | -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | \ 10 | egrep -i -v '\s(DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1|BASE64)\s|(DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1|BASE64)[-0-9]|\-(DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1|BASE64)|\s(DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1|BASE64)$' | \ 11 | egrep -v "bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt" 2>/dev/null 12 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_Password.sh: -------------------------------------------------------------------------------- 1 | key_words='C1oudc0w|z9a3Pa55|PaaS#|a123456|FusionSphere123|(root|admin|abc|abcd|Password|Changeme|Test|Administrator)(_12|@[^\]]|#|12|\![^\"])[^(\=|block|live|virtfs|foobar|localhost)]|([^(\^| )]@|[^(\^| |\")]#|123|[^(\^| )]\!|1234)(root|admin|abc|abcd|\.com|_com|@com)[^\.com]|(root|admin|abc|abcd)(root|admin|abc|abcd)' 2 | 3 | dir=$(ls -l / |awk '/^d/ {print $NF}') 4 | for i in $dir 5 | do 6 | if [ $i == 'temp' ]||[ $i == 'runScan' ]||[ $i == 'proc' ]||[ $i == 'boot' ]||[ $i == 'tmp' ];then 7 | continue 8 | fi 9 | find /$i -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -a -n -E -H "$key_words" | egrep -v 'oss3ca@huawei\.com|bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 10 | done 11 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/run.py: -------------------------------------------------------------------------------- 1 | #-*- coding: GBK -*- 2 | import sys 3 | import os 4 | import shutil 5 | 6 | from libs import scanFunctionDef as scanFunction 7 | from fileTool import fileToolDef as fileToolUse 8 | 9 | # 虚机配置 10 | toolPath = sys.path[0] 11 | csvfile = toolPath+"/config/vmInfo.csv" 12 | 13 | 14 | #执行扫描 15 | scanFunction.set_runPath(toolPath) 16 | scanFunction.set_localTime() 17 | scanFunction.set_csvFilename(csvfile) 18 | 19 | scanFunction.runAll() 20 | 21 | #txt格式的报告转化为csv格式(选作,可注释) 22 | txtPath = scanFunction.get_resultPath() 23 | fileToolUse.set_txtPath(txtPath) 24 | fileToolUse.txt_to_csv() 25 | 26 | resultPath = fileToolUse.get_resultPath() 27 | shutil.copy(toolPath+"/config/script-description.txt",resultPath+"/结果排查说明(必读).txt") 28 | #shutil.rmtree(txtPath) #删除原始扫描结果 29 | print "请按任意键结束执行....." 30 | os.system("pause") 31 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/GlobalValue.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import datetime 5 | reload(sys) 6 | sys.setdefaultencoding('utf-8') 7 | 8 | 9 | def init(): 10 | global _global_dict 11 | _global_dict = {} 12 | 13 | def setValue(name,value): 14 | if name == "logDir": 15 | if getValue("startTime") is None: 16 | setValue("startTime",str(datetime.datetime.now())) 17 | _global_dict["logFile"] = value+"/Log"+getValue("startTime").replace(" ","").replace(":","").replace(".","").replace("-","")+".log" 18 | if name == "startTime": 19 | if getValue("startTime") is not None: 20 | value = getValue("startTime") 21 | _global_dict[name] = value 22 | 23 | def getValue(name,value=None): 24 | try: 25 | return _global_dict[name] 26 | except: 27 | return value 28 | 29 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Jianquan/README.txt: -------------------------------------------------------------------------------- 1 | """ 相关安全要求说明 """ 2 | 所有能对系统进行管理的人机接口以及跨信任网络的机机接口必须有接入认证机制,标准协议没有认证机制的除外。 3 | ''' 4 | ''' 5 | """ 脚本功能 """ 6 | 先由开发提供角色权限信息,通过该脚本,可以对这些接口进行鉴权测试。 7 | ''' 8 | ''' 9 | """ 脚本配置执行说明 """ 10 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页,只需要配置一台kubectl节点虚机即可,确保该虚机能连通环境中所有其它虚机 11 | 配置2:本脚本所在目录下的RoleAuthority.xlsx,“RoleAuthority”页。每一列配置表头都有批注说明,请仔细阅读。 12 | 配置3:本脚本所在目录下的RoleAuthority.xlsx,“parameter”页。每一行配置都有说明,请仔细阅读。 13 | ''' 14 | 15 | 该脚本是通过在虚机中执行curl命令来检查接口是否满足鉴权要求 16 | 17 | Authorization_Role.xlsx 18 | Sheet1:RoleAuthority 19 | 界面功能 方法 接口(填写的时候请尽量填入正确参数,通用参数请填入第二页) 端口信息(格式为IP:Port) te_admin readonly 20 | Sheet2:parameter 21 | 参数名 参数值 备注 22 | te_admin_token token值 必填项,对应前一页te_admin角色的权限(命名规则:角色名+"_token") 23 | readonly_token token值 必填项,对应前一页readonly角色的权限(命名规则:角色名+"_token") 24 | project_id a41bf8df857c426b97865b2cc7ed8ce4 选填项,为前一页的参数project_id赋值 25 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/UnauthorizedAccess_Hengxiangyuequan/readme.txt: -------------------------------------------------------------------------------- 1 | """ 相关安全要求说明 """ 2 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 3.1.2 所有能对系统进行管理的人机接口以及跨信任网络的机机接口必须有接入认证机制,标准协议没有认证机制的除外。 3 | ''' 4 | ''' 5 | """ 脚本功能 """ 6 | 先由开发提供角色权限信息,通过该脚本,可以对这些接口进行鉴权测试。 7 | ''' 8 | ''' 9 | """ 脚本配置执行说明 """ 10 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页,只需要配置一台虚机信息即可,确保该虚机能连通环境中所有其它虚机,“是否kubectl节点”要置为TRUE 11 | 配置2:本脚本所在目录下的accessConfig.xlsx,“api”页。每一列配置表头都有批注说明,请仔细阅读。 12 | 配置3:本脚本所在目录下的accessConfig.xlsx,“parameter”页。每一行配置都有说明,请仔细阅读。 13 | ''' 14 | 15 | accessConfig.xlsx 16 | 需配置两个Sheet页: 17 | Sheet1:api 18 | 界面功能 操作说明 方法 接口 端口信息 head user1_body 19 | 20 | Sheet2:parameter 21 | 参数名 参数值 备注 22 | user1_name bcs01_hk 必填项,对应user1的用户名,测试账号,所有API必须在该账号下curl通 23 | user2_name bcs02_hk 必填项,对应user2的用户名,越权账号,在user1调通的curl命令,更换成user2的认证后,进行越权测试 24 | user1_token token1 必填项,对应user1用户的token 25 | user2_token token2 必填项,对应user2用户的token 26 | project_id 具体的project_id 选填项,为前一页的参数project_id赋值,能替换的参数形式有三种:{project_id}、:project_id、[project_id] 27 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/README.txt: -------------------------------------------------------------------------------- 1 | ======================== 功能说明 ======================== 2 | 作用:登陆linux服务器,扫描服务器敏感信息 3 | 4 | windows执行说明: 5 | 1、安装执行环境 6 | 1.1 安装python2.7与配置环境变量(此处不再赘述) 7 | 1.2 安装pycrypto、ecdsa、setuptools、paramiko包(自行百度) 8 | 9 | 2、配置vmSecureScan\config\containerInfo.csv(服务器信息配置) 10 | 第1列:服务器IP 11 | 第2列:服务器名 12 | 第3列:服务器登陆账号 13 | 第4列:服务器登陆密码 14 | 第5列:服务器管理员账号(只能root) 15 | 第6列:服务器管理员密码 16 | 一个服务器配置一行哦 17 | 18 | 3、配置vmSecureScan\config\script目录下的脚本 19 | 这些脚本将被拷贝到linux上执行,并把执行结果保存在windows本地 20 | 可以自行删除、添加和修改脚本 21 | 默认的脚本说明,请参看\config\script-description.txt 22 | 23 | 4、配置vmSecureScan\config\history目录下的文件 24 | 这些文件记录了被定位为非问题的扫描结果,用来和当前扫描结果对比,使扫描结果中筛选掉非问题。 25 | 注意:文件名称,必须与vmSecureScan\result-****目录下的扫描结果名称一模一样。文件格式见history目录下的示例。 26 | PS:history目录下的配置,也可以用来筛选掉已知问题,排查出新问题。如果不想筛选,清空history目录即可。 27 | 28 | 5、执行 29 | 双击run.py 或 cmd打开运行窗口,执行命令python run.py 30 | 31 | 6、结果 32 | 结果存放在vmSecureScan/result/compareResult-**** 33 | 如果配置了第4步,筛选掉(认为不是问题的)存在在vmSecureScan/result/abandonResult-**** 34 | 35 | 36 | 注意点说明: 37 | 脚本使用编码格式为win7 64位默认的GBK(GB2312),如果使用其他系统,可能需要修改编码格式。 38 | 可能要修改的地方(没试过哦,仅供参考): 39 | 1、run.py和scanFunctionDef.py的第一行 40 | 2、run.py和scanFunctionDef.py用Notepad++打开,工具栏点击“格式”,选择与系统相同的编码格式。 41 | -------------------------------------------------------------------------------- /FirstVersion/Test/test1.py: -------------------------------------------------------------------------------- 1 | #该脚本用于验证环境是否搭建成功 2 | #虚机节点是否可以进行连接 3 | 4 | import paramiko 5 | 6 | def getSystemInfo(): 7 | systemInfo = [] 8 | 9 | ip = '192.145.40.52' 10 | systemname = 'ip1' 11 | user = 'funcgraph' 12 | password = 'FunctionGraph@#123' 13 | root = 'root' 14 | rootpassword = 'Huawei12#$' 15 | 16 | systemInfo.append([ip, systemname, user, password, root, rootpassword]) 17 | return systemInfo 18 | 19 | def run_in_vm(): 20 | vmInfo = getSystemInfo() 21 | print vmInfo 22 | i = 0 23 | while i <= len(vmInfo) - 1: 24 | x = vmInfo[i] 25 | ip = x[0] 26 | user = x[2] 27 | passwd = x[3] 28 | rootPasswd = x[5] 29 | print(ip, user, passwd, rootPasswd) 30 | i += 1 31 | ssh = paramiko.SSHClient() 32 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 33 | try: 34 | ssh.connect(ip, username=user, password=passwd) 35 | except: 36 | print(" " * 4 + "// Cannot login {ip} by \"{user}/{passwd}\". ".format(ip=ip, user=user, passwd=passwd)) 37 | stdin, stdout, stderr = ssh.exec_command("whoami") 38 | curUser = stdout.read() 39 | ssh.close() 40 | return curUser 41 | 42 | 43 | if __name__ == '__main__': 44 | print run_in_vm() 45 | -------------------------------------------------------------------------------- /Building a software-testing environment.txt: -------------------------------------------------------------------------------- 1 | 脚本默认运行环境是windows环境 2 | python版本2.7 3 | #本人测试使用python3.6,无奈安装pycrypto库超级复杂,一直错误不断,希望某日碰到合适的pycrypto-2.6.1.win32-py3.6.exe 4 | 5 | 安装过程 6 | 1.安装python和配置Python2.7的环境变量 7 | Windows下双击安装python-2.7.9.amd64.msi即可 8 | 9 | 2.安装setuptools 10 | 安装包下载地址: 11 | 解压setuptools-20.9.0.tar.gz 12 | 安装命令如下 13 | python setup.py build 14 | python setup.py install 15 | 16 | 3.安装pycrypto 17 | 双击安装pycrypto-2.6.win-amd64-py2.7.exe即可 18 | 19 | 4.安装ecdsa包 20 | 安装包下载地址: 21 | 解压ecdsa-0.11.tar.gz 22 | 安装命令如下 23 | python setup.py build 24 | python setup.py install 25 | 26 | 5.安装paramiko包 27 | 28 | 6.安装xlrd、xlwt 29 | 这两个包用于excel操作 30 | 31 | 32 | 33 | 34 | ############################## 35 | 使用pip源安装替代分别下载安装包(用于替代4到6步过程。) 36 | 4.1 安装pip 37 | 我安装的版本是pip-9.0.1 38 | DOS窗口进入pip所在目录,输入命令python setup.py instatll 39 | 40 | 4.2 添加pip环境变量 41 | pip默认安装在C:\Python27\Scripts,参考步骤1.2,将该目录添加到环境变量 42 | 43 | 4.3 设置pip源 44 | 进入你的文件目录 C:\Users\%USERNAME%,创建pip文件夹(默认应该已经有这个目录了),进入pip文件夹内创建pip.ini文件,输入以下内容 45 | [global] 46 | index-url = http://rnd-mirrors.huawei.com/pypi/simple/ 47 | [install] 48 | trusted-host=rnd-mirrors.huawei.com 49 | 50 | 其它支撑包: 51 | pip install ecdsa 52 | pip install paramiko 53 | pip install xlrd 54 | pip install xlwt 55 | pip install xlutils 56 | pip install pymysql 57 | pip install pyyaml 58 | pip install openpyxl 59 | pip install docx 60 | 61 | 使用pip卸载已安装的包 62 | pip uninstall 库名,然后使用pip list 可以查看是否已卸载成功 63 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Renzhen/readme.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 3.1.2 所有能对系统进行管理的人机接口以及跨信任网络的机机接口必须有接入认证机制,标准协议没有认证机制的除外。 4 | ''' 5 | ''' 6 | """ 脚本功能 """ 7 | 先由开发或工具获取到代码中的接口信息,通过该脚本,可以对这些接口进行认证测试。 8 | ''' 9 | ''' 10 | """ 脚本配置执行说明 """ 11 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 12 | 1\ 13 | 配置2:本脚本所在目录下的APIs.xlsx,“API”页。每一列配置表头都有批注说明,请仔细阅读。 14 | 配置3:本脚本所在目录下的APIs.xlsx,“parameter”页。每一行配置都有说明,请仔细阅读。 15 | 16 | APIs.xlsx,“API”页 17 | URI Method PORT Protocol Microservice Parameter Header Class Function OperationId Description 18 | APIs.xlsx,“parameter”页 19 | key value 说明 20 | certMethod 【需要做证书认证时填写,否则留空】证书认证使用的证书(注意横杠“-”开头要有空格,否则会变成运算);使用方式见\SecurityTest\Doc目录下的《接口认证测试方法(简化版).docx》 21 | tokenMethod 【需要做TOKEN认证时填写,否则留空】TOKEN认证使用的token值;使用方式见\SecurityTest\Doc目录下的《接口认证测试方法(简化版).docx》 22 | akskMethod 【需要做AKSK认证时填写,否则留空】AKSK认证使用的AKSK值;使用方式见\SecurityTest\Doc目录下的《接口认证测试方法(简化版).docx》 23 | KUBERNETES_MASTER 【需要查询业务实例信息时填写,否则留空】用于设置kubectl命令环境变量KUBERNETES_MASTER的值;非容器化环境可以不用填写 24 | sessionMethod 【需要做session认证时填写,否则留空】session认证使用的session值(注意横杠“-”开头要有空格,否则会变成运算);使用方式见\SecurityTest\Doc目录下的《接口认证测试方法(简化版).docx》 25 | sessionPort 【需要做session认证时填写,否则留空】cookie认证所在IP和端口,格式为IP:PORT 26 | project_id 【"API页签"具体的API参数】"API页签"具体的API 业务变参,可根据业务实际动态往下增加 27 | 28 | 29 | 30 | 测试结果说明: 31 | 认证 32 | Pass:接口做了认证,测试结果通过 33 | Fail:接口未作认证,测试结果失败 34 | ERROR:含有认证的curl命令下发失败,可能不支持该认证方式或接口不存在,请检查 35 | MSG_ERROR:含有认证的curl命令下发失败,直接用无认证的curl命令进行测试,测试结果需要人工判断 36 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_CertificateInLog.sh: -------------------------------------------------------------------------------- 1 | key_words="(certificate|auth|session|token|key|ak|sk)(\s*:|\s*=|\"\s*(:|=)|\'\s*(:|=)).*[0-9a-zA-Z]{20,}" 2 | find /var -name '*.log' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 3 | find /var -name '*.dat' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 4 | find /var -name '*.trace' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 5 | find /opt -name '*.log' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 6 | find /opt -name '*.dat' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 7 | find /opt -name '*.trace' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" | egrep -v 'bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt' 2>/dev/null 8 | -------------------------------------------------------------------------------- /FirstVersion/Test/test2.py: -------------------------------------------------------------------------------- 1 | #该脚本用于验证多线程可以获取到执行结果 2 | #从Excel中获取节点信息的方法先跳过 3 | 4 | #!/usr/bin/python 5 | # -*- coding: UTF-8 -*- 6 | 7 | import paramiko 8 | import threading 9 | import Queue 10 | 11 | #获取节点信息,从excel文件中获取,涉及I/O操作 12 | def getSystemInfo(): 13 | vmInfo = [['192.145.40.52', 'ip1', 'funcgraph', 'FunctionGraph@#123', 'root', 'Huawei12#$'], 14 | ['192.145.40.52', 'ip1', 'funcgraph', 'FunctionGraph@#123', 'root', 'Huawei12#$'], 15 | ['192.145.40.52', 'ip1', 'funcgraph', 'FunctionGraph@#123', 'root', 'Huawei12#$'], 16 | ['192.145.40.52', 'ip1', 'funcgraph', 'FunctionGraph@#123', 'root', 'Huawei12#$']] 17 | return vmInfo 18 | 19 | #将验证过的节点队列与要执行的命令放入到程序中进行执行 20 | def run_in_vm(L,q): 21 | ip = L[0] 22 | user = L[2] 23 | passwd = L[3] 24 | rootPasswd = L[5] 25 | ssh = paramiko.SSHClient() 26 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 27 | try: 28 | ssh.connect(ip, username=user, password=passwd) 29 | except: 30 | print(" " * 4 + "// Cannot login {ip} by \"{user}/{passwd}\". ".format(ip=ip, user=user, passwd=passwd)) 31 | stdin, stdout, stderr = ssh.exec_command("netstat -tunlp") 32 | curUser = stdout.read() 33 | ssh.close() 34 | q.put(curUser) 35 | 36 | def main(): 37 | q = Queue.Queue() 38 | threads = [] 39 | vmInfo = getSystemInfo() 40 | for i in range(len(vmInfo)): 41 | t = threading.Thread(target=run_in_vm,args=(vmInfo[i],q)) 42 | t.start() 43 | threads.append(t) 44 | for thread in threads: 45 | thread.join() 46 | results = [] 47 | for _ in range(len(vmInfo)): 48 | results.append([q.get(),_]) 49 | print results 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | # LinuxTest 2 | 3 | 脚本基础结构: 4 | 1.传入节点信息(使用python操作excel文件) 5 | 2.传入shell命令(使用python操作excel文件) 6 | 3.在vm中执行shell命令 7 | 4.保存shell执行结果到本地(使用python操作excel文件) 8 | 9 | 10 | 共分为两个版本架构 11 | 第一个版本架构是通过直接传人shell脚本命令来获得执行结果 12 | 第二个版本增加了Excel文件控制模块,将shell命令保存到Excel文件中,达到了数据驱动框架的效果。 13 | 仅通过维护Excel文件即可。 14 | 15 | 版本二已实现功能: 16 | 接口认证、鉴权、资产发现(端口扫描)、MySQL安全配置检查、敏感信息排查、密码复杂度、sudo提权检查 17 | 每个功能有独立的 18 | 19 | 20 | 版本一使用说明: 21 | ======================== 功能说明 ======================== 22 | 作用:登陆linux服务器,扫描服务器敏感信息 23 | 24 | windows执行说明: 25 | 1、安装执行环境 26 | 1.1 安装python2.7与配置环境变量(此处不再赘述) 27 | 1.2 安装pycrypto、ecdsa、setuptools、paramiko包(自行百度) 28 | 2、配置vmSecureScan\config\containerInfo.csv(服务器信息配置) 29 | 第1列:服务器IP 30 | 第2列:服务器名 31 | 第3列:服务器登陆账号 32 | 第4列:服务器登陆密码 33 | 第5列:服务器管理员账号(只能root) 34 | 第6列:服务器管理员密码 35 | 一个服务器配置一行哦 36 | 3、配置vmSecureScan\config\script目录下的脚本 37 | 这些脚本将被拷贝到linux上执行,并把执行结果保存在windows本地 38 | 可以自行删除、添加和修改脚本 39 | 默认的脚本说明,请参看\config\script-description.txt 40 | 4、配置vmSecureScan\config\history目录下的文件 41 | 这些文件记录了被定位为非问题的扫描结果,用来和当前扫描结果对比,使扫描结果中筛选掉非问题。 42 | 注意:文件名称,必须与vmSecureScan\result-****目录下的扫描结果名称一模一样。文件格式见history目录下的示例。 43 | PS:history目录下的配置,也可以用来筛选掉已知问题,排查出新问题。如果不想筛选,清空history目录即可。 44 | 5、执行 45 | 双击run.py 或 cmd打开运行窗口,执行命令python run.py 46 | 6、结果 47 | 结果存放在vmSecureScan/result/compareResult-**** 48 | 如果配置了第4步,筛选掉(认为不是问题的)存在在vmSecureScan/result/abandonResult-**** 49 | 注意点说明: 50 | 脚本使用编码格式为win7 64位默认的GBK(GB2312),如果使用其他系统,可能需要修改编码格式。 51 | 可能要修改的地方(没试过哦,仅供参考): 52 | 1、run.py和scanFunctionDef.py的第一行 53 | 2、run.py和scanFunctionDef.py用Notepad++打开,工具栏点击“格式”,选择与系统相同的编码格式。 54 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_UserNameInLog.sh: -------------------------------------------------------------------------------- 1 | key_words="\"un\":\"\w+@\"" 2 | find / -name '*.log' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 3 | find / -name '*.dat' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 4 | find / -name '*.trace' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 5 | key_words="\"dn\":\"\w*1[0-9]{10}\"" 6 | find / -name '*.log' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 7 | find / -name '*.dat' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 8 | find / -name '*.trace' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 9 | key_words="op_svc_sc_customer_hws" 10 | find / -name '*.log' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 11 | find / -name '*.dat' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 12 | find / -name '*.trace' -type f | xargs file|grep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -n -E -H "$key_words" |egrep -v "/devicemapper/mnt" | head -5 2>/dev/null 13 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/LocalOperate.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import datetime 5 | import os 6 | reload(sys) 7 | sys.setdefaultencoding('utf-8') 8 | 9 | class Local: 10 | def __init__(self): 11 | self.beginTime = None 12 | 13 | 14 | def timenow(self): 15 | return datetime.datetime.now() 16 | 17 | 18 | def unicode(self,string): 19 | tmpString = string 20 | try: 21 | result = tmpString.decode('utf-8').encode('GBK') 22 | except: 23 | try: 24 | result = tmpString.decode('GBK') 25 | except: 26 | try: 27 | result = u"{log}".format(log=tmpString) 28 | except: 29 | result = str(tmpString) 30 | return result 31 | ''' 32 | ##解压zip源码包 33 | def unzipFiles(self,dir): 34 | #dir = os.path.dirname(file) 35 | unzipPath = tempDir 36 | if ".zip" in file: 37 | try: 38 | if not os.path.isdir(unzipPath): 39 | os.makedirs(unzipPath) 40 | f = zipfile.ZipFile(file) 41 | f.extractall(unzipPath) 42 | f.close() 43 | except: 44 | g_Log.writeLog("traceback") 45 | if os.path.isdir(unzipPath): 46 | shutil.rmtree(unzipPath) 47 | return False 48 | 49 | for dirpath,dirnames,filenames in os.walk(unzipPath): 50 | for zip in filenames: 51 | if ".zip" not in zip: 52 | continue 53 | tmpfile = os.path.join(dirpath,zip).replace("\\","/") 54 | try: 55 | os.mkdir(tmpfile+"-bak") 56 | f = zipfile.ZipFile(tmpfile) 57 | f.extractall(tmpfile+"-bak") 58 | f.close() 59 | os.remove(tmpfile) 60 | shutil.copytree(tmpfile+"-bak",tmpfile) 61 | shutil.rmtree(tmpfile+"-bak") 62 | except: 63 | writeLog("traceback") 64 | if os.path.isdir(tmpfile+"-bak"): 65 | shutil.rmtree(tmpfile+"-bak") 66 | return unzipPath 67 | ''' 68 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/WordOperate.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import os 4 | import sys 5 | import docx 6 | import traceback 7 | from win32com.client import Dispatch,constants 8 | 9 | reload(sys) 10 | sys.setdefaultencoding('utf-8') 11 | 12 | import GlobalValue as g_Global 13 | import Log 14 | g_Log = None 15 | import LocalOperate 16 | g_Local = None 17 | 18 | class Word: 19 | def __init__(self,docName=None): 20 | global g_Log,g_Local 21 | g_Log = Log.Log() 22 | g_Local = LocalOperate.Local() 23 | self.docName = docName 24 | 25 | def new(self):#新建一个word 26 | try: 27 | g_Log.writeLog("该功能暂未实现") 28 | return 1 29 | # 检查excel所在路径是否存在,如不存在则新建完整目录 30 | excelPath = os.path.split(self.excelName)[0] 31 | pathExist = os.path.exists(excelPath) 32 | if not pathExist: 33 | os.makedirs(excelPath) 34 | except: 35 | g_Log.writeLog("traceback") 36 | return 0 37 | 38 | def write(self,result,redLine=0):# 向word写入 39 | try: 40 | g_Log.writeLog("该功能暂未实现") 41 | return 1 42 | # 读取word 43 | except: 44 | g_Log.writeLog("traceback") 45 | return 0 46 | 47 | def readlines(self): #读取word内容 48 | output = [] 49 | try: 50 | docName = self.docName 51 | if docName.endswith('.doc'): 52 | g_Log.writeLog(u"暂不支持.doc格式,请另存为.docx格式后重新执行") 53 | return 0 54 | file = self.Document() 55 | for i in range(len(file.paragraphs)): 56 | output.append(file.paragraphs[i].text) 57 | return output 58 | except: 59 | g_Log.writeLog("traceback") 60 | return 0 61 | 62 | 63 | def Document(self): 64 | try: 65 | file = docx.Document(self.docName) 66 | except: 67 | errmsg1 = ''.join(traceback.format_exception(*sys.exc_info())) 68 | try: 69 | file = docx.Document(r'{wordPath}'.format(wordPath=self.docName)) 70 | except: 71 | errmsg2 = ''.join(traceback.format_exception(*sys.exc_info())) 72 | g_Log.writeLog(errmsg1) 73 | g_Log.writeLog(errmsg2) 74 | return file 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Password.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/tiny/tiny\-.*\.js shell 3 | .*/lib(64|)/python2\.7/.* shell 4 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 5 | /etc/dhcp/dhclient.d shell 6 | /etc/euleros_security/ shell 7 | /etc/lvm/ shell 8 | /etc/openvswitch/ shell 9 | /etc/pki/ca-trust shell 10 | /etc/pki/tls shell 11 | /etc/ppp/ shell 12 | /etc/selinux shell 13 | /etc/smartmontools/ shell 14 | /etc/ssh/ shell 15 | /etc/sysconfig/ shell 16 | /etc/yum/ shell 17 | /jdk/jdk[0-9_\.]+/ shell 18 | /jruby/[0-9_\.]+/gems/ shell 19 | /LinuxHicloud/ shell 20 | /logstash/logstash[0-9\.\-]+/ shell 21 | /root/.kube/ shell 22 | /run/udev/data shell 23 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 24 | /usr/bin/yum shell 25 | /usr/include/expat\.h shell 26 | /usr/include/openflow shell 27 | /usr/include/openvswitch shell 28 | /usr/include/python2.7 shell 29 | /usr/lib/crda shell 30 | /usr/lib/dracut shell 31 | /usr/lib/dracut/ shell 32 | /usr/lib/firewalld shell 33 | /usr/lib/firewalld/ shell 34 | /usr/lib/firmware shell 35 | /usr/lib/grub shell 36 | /usr/lib/kbd shell 37 | /usr/lib/kdump shell 38 | /usr/lib/modules shell 39 | /usr/lib/rpm shell 40 | /usr/lib/rpm/ shell 41 | /usr/lib/systemd/ shell 42 | /usr/lib/udev/ shell 43 | /usr/lib/x86_64 shell 44 | /usr/lib64/gconv shell 45 | /usr/lib64/gettext shell 46 | /usr/lib64/perl5 shell 47 | /usr/lib64/pm-utils shell 48 | /usr/local/jre shell 49 | /usr/share/alsa shell 50 | /usr/share/authconfig shell 51 | /usr/share/awk shell 52 | /usr/share/bash-completion shell 53 | /usr/share/dict shell 54 | /usr/share/doc shell 55 | /usr/share/doc/ shell 56 | /usr/share/emacs shell 57 | /usr/share/euleros shell 58 | /usr/share/gcc shell 59 | /usr/share/Gconf shell 60 | /usr/share/gdb shell 61 | /usr/share/gettext shell 62 | /usr/share/glib shell 63 | /usr/share/gnupg shell 64 | /usr/share/groff shell 65 | /usr/share/hwdata shell 66 | /usr/share/i18n shell 67 | /usr/share/licenses shell 68 | /usr/share/man shell 69 | /usr/share/mime shell 70 | /usr/share/misc shell 71 | /usr/share/openvswitch shell 72 | /usr/share/os-prober shell 73 | /usr/share/perl5 shell 74 | /usr/share/pki shell 75 | /usr/share/polkit shell 76 | /usr/share/smartmontools shell 77 | /usr/share/systemd shell 78 | /usr/share/tcl shell 79 | /usr/share/tcl8 shell 80 | /usr/share/vim shell 81 | /usr/share/yum shell 82 | /usr/share/zoneinfo shell 83 | /usr/share/zsh shell 84 | /var/lib/yum/ shell 85 | /var/log/anaconda/ shell 86 | /var/log/dmesg shell 87 | /var/log/messages shell 88 | /var/log/openvswitch shell 89 | /var/log/secure shell 90 | /usr/share/X11/locale shell 91 | /usr/share/cups shell 92 | /usr/share/ghostscript shell 93 | /usr/share/locale/ca shell 94 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 95 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Annotation_js.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/tiny/tiny\-.*\.js shell 3 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 4 | .*/lib(64|)/python2\.7/.* shell 5 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 6 | /etc/dhcp/dhclient.d shell 7 | /etc/euleros_security/ shell 8 | /etc/lvm/ shell 9 | /etc/openvswitch/ shell 10 | /etc/pki/ca-trust shell 11 | /etc/pki/tls shell 12 | /etc/ppp/ shell 13 | /etc/selinux shell 14 | /etc/smartmontools/ shell 15 | /etc/ssh/ shell 16 | /etc/sysconfig/ shell 17 | /etc/yum/ shell 18 | /jdk/jdk[0-9_\.]+ shell 19 | /jdk/jdk[0-9_\.]+/ shell 20 | /jruby/[0-9_\.]+/gems/ shell 21 | /LinuxHicloud/ shell 22 | /logstash/logstash[0-9\.\-]+/ shell 23 | /root/.kube/ shell 24 | /run/udev/data shell 25 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 26 | /usr/bin/yum shell 27 | /usr/include/expat\.h shell 28 | /usr/include/openflow shell 29 | /usr/include/openvswitch shell 30 | /usr/include/python2.7 shell 31 | /usr/lib/crda shell 32 | /usr/lib/dracut shell 33 | /usr/lib/dracut/ shell 34 | /usr/lib/firewalld shell 35 | /usr/lib/firewalld/ shell 36 | /usr/lib/firmware shell 37 | /usr/lib/grub shell 38 | /usr/lib/kbd shell 39 | /usr/lib/kdump shell 40 | /usr/lib/modules shell 41 | /usr/lib/rpm shell 42 | /usr/lib/rpm/ shell 43 | /usr/lib/systemd/ shell 44 | /usr/lib/udev/ shell 45 | /usr/lib/x86_64 shell 46 | /usr/lib64/gconv shell 47 | /usr/lib64/gettext shell 48 | /usr/lib64/perl5 shell 49 | /usr/lib64/pm-utils shell 50 | /usr/local/jre shell 51 | /usr/share/alsa shell 52 | /usr/share/authconfig shell 53 | /usr/share/awk shell 54 | /usr/share/bash-completion shell 55 | /usr/share/dict shell 56 | /usr/share/doc shell 57 | /usr/share/doc/ shell 58 | /usr/share/emacs shell 59 | /usr/share/euleros shell 60 | /usr/share/gcc shell 61 | /usr/share/Gconf shell 62 | /usr/share/gdb shell 63 | /usr/share/gettext shell 64 | /usr/share/glib shell 65 | /usr/share/gnupg shell 66 | /usr/share/groff shell 67 | /usr/share/hwdata shell 68 | /usr/share/i18n shell 69 | /usr/share/licenses shell 70 | /usr/share/man shell 71 | /usr/share/mime shell 72 | /usr/share/misc shell 73 | /usr/share/openvswitch shell 74 | /usr/share/os-prober shell 75 | /usr/share/perl5 shell 76 | /usr/share/pki shell 77 | /usr/share/polkit shell 78 | /usr/share/smartmontools shell 79 | /usr/share/systemd shell 80 | /usr/share/tcl shell 81 | /usr/share/tcl8 shell 82 | /usr/share/vim shell 83 | /usr/share/yum shell 84 | /usr/share/zoneinfo shell 85 | /usr/share/zsh shell 86 | /var/lib/yum/ shell 87 | /var/log/anaconda/ shell 88 | /var/log/dmesg shell 89 | /var/log/messages shell 90 | /var/log/openvswitch shell 91 | /var/log/secure shell 92 | /usr/share/X11/locale shell 93 | /usr/share/cups shell 94 | /usr/share/ghostscript shell 95 | /usr/share/locale/ca shell 96 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 97 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_EncryptTool.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/tiny/tiny\-.*\.js shell 3 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 4 | .*/lib(64|)/python2\.7/.* shell 5 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 6 | /etc/dhcp/dhclient.d shell 7 | /etc/euleros_security/ shell 8 | /etc/lvm/ shell 9 | /etc/openvswitch/ shell 10 | /etc/pki/ca-trust shell 11 | /etc/pki/tls shell 12 | /etc/ppp/ shell 13 | /etc/selinux shell 14 | /etc/smartmontools/ shell 15 | /etc/ssh/ shell 16 | /etc/sysconfig/ shell 17 | /etc/yum/ shell 18 | /jdk/jdk[0-9_\.]+ shell 19 | /jdk/jdk[0-9_\.]+/ shell 20 | /jruby/[0-9_\.]+/gems/ shell 21 | /LinuxHicloud/ shell 22 | /logstash/logstash[0-9\.\-]+/ shell 23 | /root/.kube/ shell 24 | /run/udev/data shell 25 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 26 | /usr/bin/yum shell 27 | /usr/include/expat\.h shell 28 | /usr/include/openflow shell 29 | /usr/include/openvswitch shell 30 | /usr/include/python2.7 shell 31 | /usr/lib/crda shell 32 | /usr/lib/dracut shell 33 | /usr/lib/dracut/ shell 34 | /usr/lib/firewalld shell 35 | /usr/lib/firewalld/ shell 36 | /usr/lib/firmware shell 37 | /usr/lib/grub shell 38 | /usr/lib/kbd shell 39 | /usr/lib/kdump shell 40 | /usr/lib/modules shell 41 | /usr/lib/rpm shell 42 | /usr/lib/rpm/ shell 43 | /usr/lib/systemd/ shell 44 | /usr/lib/udev/ shell 45 | /usr/lib/x86_64 shell 46 | /usr/lib64/gconv shell 47 | /usr/lib64/gettext shell 48 | /usr/lib64/perl5 shell 49 | /usr/lib64/pm-utils shell 50 | /usr/local/jre shell 51 | /usr/share/alsa shell 52 | /usr/share/authconfig shell 53 | /usr/share/awk shell 54 | /usr/share/bash-completion shell 55 | /usr/share/dict shell 56 | /usr/share/doc shell 57 | /usr/share/doc/ shell 58 | /usr/share/emacs shell 59 | /usr/share/euleros shell 60 | /usr/share/gcc shell 61 | /usr/share/Gconf shell 62 | /usr/share/gdb shell 63 | /usr/share/gettext shell 64 | /usr/share/glib shell 65 | /usr/share/gnupg shell 66 | /usr/share/groff shell 67 | /usr/share/hwdata shell 68 | /usr/share/i18n shell 69 | /usr/share/licenses shell 70 | /usr/share/man shell 71 | /usr/share/mime shell 72 | /usr/share/misc shell 73 | /usr/share/openvswitch shell 74 | /usr/share/os-prober shell 75 | /usr/share/perl5 shell 76 | /usr/share/pki shell 77 | /usr/share/polkit shell 78 | /usr/share/smartmontools shell 79 | /usr/share/systemd shell 80 | /usr/share/tcl shell 81 | /usr/share/tcl8 shell 82 | /usr/share/vim shell 83 | /usr/share/yum shell 84 | /usr/share/zoneinfo shell 85 | /usr/share/zsh shell 86 | /var/lib/yum/ shell 87 | /var/log/anaconda/ shell 88 | /var/log/dmesg shell 89 | /var/log/messages shell 90 | /var/log/openvswitch shell 91 | /var/log/secure shell 92 | /usr/share/X11/locale shell 93 | /usr/share/cups shell 94 | /usr/share/ghostscript shell 95 | /usr/share/locale/ca shell 96 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 97 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_UnsafeEncrypt.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/tiny/tiny\-.*\.js shell 3 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 4 | .*/lib(64|)/python2\.7/.* shell 5 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 6 | /etc/dhcp/dhclient.d shell 7 | /etc/euleros_security/ shell 8 | /etc/lvm/ shell 9 | /etc/openvswitch/ shell 10 | /etc/pki/ca-trust shell 11 | /etc/pki/tls shell 12 | /etc/ppp/ shell 13 | /etc/selinux shell 14 | /etc/smartmontools/ shell 15 | /etc/ssh/ shell 16 | /etc/sysconfig/ shell 17 | /etc/yum/ shell 18 | /jdk/jdk[0-9_\.]+ shell 19 | /jdk/jdk[0-9_\.]+/ shell 20 | /jruby/[0-9_\.]+/gems/ shell 21 | /LinuxHicloud/ shell 22 | /logstash/logstash[0-9\.\-]+/ shell 23 | /root/.kube/ shell 24 | /run/udev/data shell 25 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 26 | /usr/bin/yum shell 27 | /usr/include/expat\.h shell 28 | /usr/include/openflow shell 29 | /usr/include/openvswitch shell 30 | /usr/include/python2.7 shell 31 | /usr/lib/crda shell 32 | /usr/lib/dracut shell 33 | /usr/lib/dracut/ shell 34 | /usr/lib/firewalld shell 35 | /usr/lib/firewalld/ shell 36 | /usr/lib/firmware shell 37 | /usr/lib/grub shell 38 | /usr/lib/kbd shell 39 | /usr/lib/kdump shell 40 | /usr/lib/modules shell 41 | /usr/lib/rpm shell 42 | /usr/lib/rpm/ shell 43 | /usr/lib/systemd/ shell 44 | /usr/lib/udev/ shell 45 | /usr/lib/x86_64 shell 46 | /usr/lib64/gconv shell 47 | /usr/lib64/gettext shell 48 | /usr/lib64/perl5 shell 49 | /usr/lib64/pm-utils shell 50 | /usr/local/jre shell 51 | /usr/share/alsa shell 52 | /usr/share/authconfig shell 53 | /usr/share/awk shell 54 | /usr/share/bash-completion shell 55 | /usr/share/dict shell 56 | /usr/share/doc shell 57 | /usr/share/doc/ shell 58 | /usr/share/emacs shell 59 | /usr/share/euleros shell 60 | /usr/share/gcc shell 61 | /usr/share/Gconf shell 62 | /usr/share/gdb shell 63 | /usr/share/gettext shell 64 | /usr/share/glib shell 65 | /usr/share/gnupg shell 66 | /usr/share/groff shell 67 | /usr/share/hwdata shell 68 | /usr/share/i18n shell 69 | /usr/share/licenses shell 70 | /usr/share/man shell 71 | /usr/share/mime shell 72 | /usr/share/misc shell 73 | /usr/share/openvswitch shell 74 | /usr/share/os-prober shell 75 | /usr/share/perl5 shell 76 | /usr/share/pki shell 77 | /usr/share/polkit shell 78 | /usr/share/smartmontools shell 79 | /usr/share/systemd shell 80 | /usr/share/tcl shell 81 | /usr/share/tcl8 shell 82 | /usr/share/vim shell 83 | /usr/share/yum shell 84 | /usr/share/zoneinfo shell 85 | /usr/share/zsh shell 86 | /var/lib/yum/ shell 87 | /var/log/anaconda/ shell 88 | /var/log/dmesg shell 89 | /var/log/messages shell 90 | /var/log/openvswitch shell 91 | /var/log/secure shell 92 | /usr/share/X11/locale shell 93 | /usr/share/cups shell 94 | /usr/share/ghostscript shell 95 | /usr/share/locale/ca shell 96 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 97 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Annotation_html.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | .*/tiny/tiny\-.*\.js shell 3 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 4 | .*/lib(64|)/python2\.7/.* shell 5 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 6 | /etc/dhcp/dhclient.d shell 7 | /etc/euleros_security/ shell 8 | /etc/lvm/ shell 9 | /etc/openvswitch/ shell 10 | /etc/pki/ca-trust shell 11 | /etc/pki/tls shell 12 | /etc/ppp/ shell 13 | /etc/selinux shell 14 | /etc/smartmontools/ shell 15 | /etc/ssh/ shell 16 | /etc/sysconfig/ shell 17 | /etc/yum/ shell 18 | /jdk/jdk[0-9_\.]+ shell 19 | /jdk/jdk[0-9_\.]+/ shell 20 | /jruby/[0-9_\.]+/gems/ shell 21 | /LinuxHicloud/ shell 22 | /logstash/logstash[0-9\.\-]+/ shell 23 | /root/.kube/ shell 24 | /run/udev/data shell 25 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 26 | /usr/bin/yum shell 27 | /usr/include/expat\.h shell 28 | /usr/include/openflow shell 29 | /usr/include/openvswitch shell 30 | /usr/include/python2.7 shell 31 | /usr/lib/crda shell 32 | /usr/lib/dracut shell 33 | /usr/lib/dracut/ shell 34 | /usr/lib/firewalld shell 35 | /usr/lib/firewalld/ shell 36 | /usr/lib/firmware shell 37 | /usr/lib/grub shell 38 | /usr/lib/kbd shell 39 | /usr/lib/kdump shell 40 | /usr/lib/modules shell 41 | /usr/lib/rpm shell 42 | /usr/lib/rpm/ shell 43 | /usr/lib/systemd/ shell 44 | /usr/lib/udev/ shell 45 | /usr/lib/x86_64 shell 46 | /usr/lib64/gconv shell 47 | /usr/lib64/gettext shell 48 | /usr/lib64/perl5 shell 49 | /usr/lib64/pm-utils shell 50 | /usr/local/jre shell 51 | /usr/share/alsa shell 52 | /usr/share/authconfig shell 53 | /usr/share/awk shell 54 | /usr/share/bash-completion shell 55 | /usr/share/dict shell 56 | /usr/share/doc shell 57 | /usr/share/doc/ shell 58 | /usr/share/emacs shell 59 | /usr/share/euleros shell 60 | /usr/share/gcc shell 61 | /usr/share/Gconf shell 62 | /usr/share/gdb shell 63 | /usr/share/gettext shell 64 | /usr/share/glib shell 65 | /usr/share/gnupg shell 66 | /usr/share/groff shell 67 | /usr/share/hwdata shell 68 | /usr/share/i18n shell 69 | /usr/share/licenses shell 70 | /usr/share/man shell 71 | /usr/share/mime shell 72 | /usr/share/misc shell 73 | /usr/share/openvswitch shell 74 | /usr/share/os-prober shell 75 | /usr/share/perl5 shell 76 | /usr/share/pki shell 77 | /usr/share/polkit shell 78 | /usr/share/smartmontools shell 79 | /usr/share/systemd shell 80 | /usr/share/tcl shell 81 | /usr/share/tcl8 shell 82 | /usr/share/vim shell 83 | /usr/share/yum shell 84 | /usr/share/zoneinfo shell 85 | /usr/share/zsh shell 86 | /var/lib/yum/ shell 87 | /var/log/anaconda/ shell 88 | /var/log/dmesg shell 89 | /var/log/messages shell 90 | /var/log/openvswitch shell 91 | /var/log/secure shell 92 | /usr/share/X11/locale shell 93 | /usr/share/cups shell 94 | /usr/share/ghostscript shell 95 | /usr/share/locale/ca shell 96 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 97 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/systemSafePolicy/policy.md: -------------------------------------------------------------------------------- 1 | 是否执行 策略名 命令 支持扫描主体 是否安全红线(YES|NO) 说明 2 | true VM_fileaccess "find / ! -perm 600 -name *.key ! -user root -exec ls -l {} \; 2>/dev/null 3 | find / ! -perm 600 -name *.pwd ! -user root -exec ls -l {} \; 2>/dev/null 4 | find / ! -perm 600 -name *.keytab ! -user root -exec ls -l {} \; 2>/dev/null 5 | find / ! -perm 600 -name *.crt ! -user root -exec ls -l {} \; 2>/dev/null 6 | find / ! -perm 600 -name *.pem ! -user root -exec ls -l {} \; 2>/dev/null 7 | find / ! -perm 640 ! -perm 600 -name *.log ! -user root -exec ls -l {} \; 2>/dev/null 8 | find / -type f ! -user root -perm -640 ! -perm -700 ! -perm 640 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 9 | find / -type f ! -user root -perm -750 ! -perm 750 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 10 | find / -type d ! -user root -perm -750 ! -perm 750 -exec ls -ld {} \; 2>/dev/null | egrep -v -i '/proc/' 11 | find / ! -perm 600 -name *.frm -exec ls -l {} \; 2>/dev/null 12 | find / ! -perm 600 -name *.MYI -exec ls -l {} \; 2>/dev/null 13 | find / ! -perm 600 -name *.MYD -exec ls -l {} \; 2>/dev/null 14 | find / ! -perm 600 -name *.ibd -exec ls -l {} \; 2>/dev/null 15 | find / ! -perm 600 -name *ibdata* -exec ls -l {} \; 2>/dev/null" OS,Docker NO "所有非root用户的文件权限: 16 | 1)含有敏感信息的文件不得大于600(rw------)对于多个OS用户都需要访问敏感文件的场景都不得大于640(rw-r-----),如:数据库备份恢复 17 | 2)日志文件不得大于640(rw-r-----) 18 | 3)不可执行文件不得大于640(rw-r-----) 19 | 4)可执行文件不得大于750(rwxr-x---) 20 | 5)目录不得大于750(rwxr-x---),有时候目录要求不能大于700(rwx------)" 21 | true VM_gccTools rpm -qa | egrep -i -E '(^make|^gcc|^gcc-c++|^cpp|^gdb|^binutils|^glibc_devel|^flex|^tcpdump|^mirror|^glibc-devel|^dexdump|^toolbox|^Netcat|^Wireshark|^ethereal|strace)' OS,Docker NO 检查系统中不能安装调试工具:make|gcc|gcc-c++|cpp|gdb|binutils|glibc_devel|flex|tcpdump|mirror|glibc-devel|dexdump|toolbox|Netcat|Wireshark|ethereal 22 | true VM_nouser find / -nouser 2>/dev/null OS,Docker NO 检查系统中的无属主文件 23 | true VM_RootProcess ps -ef | egrep -v '[[0-9]*]| pts/' |grep 'root ' OS,Docker NO 检查进程越权,产品进程是否用root账号启动 24 | true VM_SensitiveInPross ps -ef | egrep -i "pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|X-Auth-Token|Authorization|sessionID|token|email" OS,Docker YES 检查进程中的敏感信息,关键字:"pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|X-Auth-Token|Authorization|sessionID|token|email" 25 | true VM_unSavePross ps -ef | egrep -i "bootps|pure-ftpd|pppoe|sendmail|isdn|zebra|cupsd|cups-config-daemon|hplip|hpiod|hpssd|bluetooth|hcid|hidd|sdpd|dund|pand|rsh|telnet" OS,Docker NO 检查进程中是否不允许使用的服务:"bootps|pure-ftpd|pppoe|sendmail|isdn|zebra|cupsd|cups-config-daemon|hplip|hpiod|hpssd|bluetooth|hcid|hidd|sdpd|dund|pand|rsh|telnet" 26 | true VM_systemUser cat /etc/passwd |egrep "[0-9]{4}" OS,Docker NO 检查系统中是否含有不需要的账号 27 | true VM_systemUserPassword cat /etc/shadow |egrep -v "(.*?:\*|.*?:\!)" OS,Docker YES 检查系统账号的的密码加密安全(比如不能用Base64加密) 28 | true VM_DBProcess ps -ef | egrep -i 'mysql' |egrep -v "grep" OS,Docker YES 运行数据库进程的帐号权限应该遵循最小权限原则,要使用操作系统的非管理员权限帐号来运行数据库 29 | true VM_unSafeService rpm -qa | egrep -i -E "telnet|ftp|nfs|Samba|RPC|TFTP|Netbios|X-Windows|Snmp|portmap|bluetooth" OS,Docker NO 检查是否安装了不安全的服务 30 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script-description.txt: -------------------------------------------------------------------------------- 1 | VM中的扫描结果查看规则如下: 2 | 1、VM_debugModel:查看是否有Bash-x或Set-X存在; 3 | 在《Shell语言安全编程规范_V1_0.docx》中要求禁止使用调试模式执行shell脚本,调试模式执行shell脚本,虽然能比较方便的查看脚本执行过程以及数据信息,但也会暴露相关的数据,包括可能的敏感信息,存在被利用的风险,调试模式有两种: 4 | a)命令行调用shell脚本时使用选项“-x”,如“bash -x test.sh” 5 | b)在shell脚本中使用命令“set -x”打开调试模式。 6 | 7 | 2、VM_fileaccess:文件权限(此处扫描要求是对文件权限最宽泛的要求,有些特殊文件需要更严格的权限限制,应按照基线用例,从严测试) 8 | 某规范要求系统中所有目录文件必须进行访问权限控制,遵从权限最小化原则。以Unix/Linux系统为例: 9 | 1)敏感文件不得大于600(rw------)对于多个OS用户都需要访问敏感文件的场景都不得大于640(rw-r-----),如:数据库备份恢复 10 | 2)日志文件不得大于640(rw-r-----) 11 | 3)不可执行文件不得大于640(rw-r-----) 12 | 4)可执行文件不得大于750(rwxr-x---) 13 | 5)目录不得大于750(rwxr-x---),有时候目录要求不能大于700(rwx------) 14 | 注意:对于.conf、.json、.bat三种文件的扫描结果需要进一步手动判断,如果不包含敏感信息,权限为不大于640,如果含有敏感信息,则权限不能大于600 15 | 16 | 3、JSX_Language:解释性语言 17 | 某规范要求严禁使用注释行等形式仅使功能失效,当代码中被注释掉的语句去除掉注释性符号后不会对原有代码的功能造成影响(即:注释的代码不是功能语句,只能是解释说明) 18 | 19 | 4、VM_nouser:无属主文件 20 | 某规范要求禁止存在缺乏权限控制的无属主文件,搜索出来的所有问题需开发定位。 21 | 22 | 5、VM_Password:明文密码 23 | 脚本默认扫描根目录,扫描相当缓慢(出现过一台虚机扫描了1小时),建议根据产品情况谨慎指定扫面的目录。 24 | 搜索明文密码关键字“C1oudc0w|z9a3Pa55|PaaS#|a123456|FusionSphere123|root|admin|abc|abcd|Password|Changeme|Test|Administrator|123”(见实际扫描脚本VM_Password.sh) 25 | 26 | 6、VM_Sensitive:敏感信息 27 | 搜索敏感信息关键字“pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|crypto|encrypt|decrypt|X-Auth-Token|Authorization|sessionID|token|email|mobile|ak|sk|akey|skey|accesskey|secretkey|access_key|secret_key”(见实际扫描脚本VM_Sensitive.sh) 28 | 脚本默认扫描根目录,扫描相当缓慢(出现过一台虚机扫描了8小时),建议根据产品情况谨慎指定扫面的目录。 29 | 提醒: 30 | a)当搜索出来的关键字的值为变量时(如key=code、password=$code等等),也需要分析变量(code)是否有风险 31 | b)日志文件中既不能有明文,也不能有密文密码密钥信息,日志中写入密文,要做匿名化处理 32 | c)进一步检查含有密码和敏感信息的文件,文件权限是否限制在600以内 33 | 34 | 7、VM_unsafe_encrypt文件:根据搜索关键字DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1,查看是否含有不安全加密算法,原则: 35 | 1、禁止使用业界已知不安全的加密算法,DES/3DES(除密钥K1≠K2≠K3外的场景)/SKIPJACK/RC2/RSA(1024位及以下)/MD2/MD4。 36 | 说明: 37 | 1)禁止MD5应用在参与生成“数字签名口令加密保存”这两种场景(HMAC-MD5例外),禁止SHA1应用在参与生成“数字签名”的场景; 38 | 2)SHA1算法可用于HMAC、PBKDF2、随机数发生器的场景; 39 | 3)标准协议定义且没有替代算法的、或需要与第三方系统对接、或兼容老系统的除外。如需要与第三方系统对接或兼容老系统,产品支持使用不安全密码算法的情况,对于面向运营商和企业客户的产品,应在产品CPI资料或界面中提示风险。 40 | 2、推荐使用的密码算法: 41 | 1)分组密码算法:AES(密钥长度在128位及以上) 42 | 2)流密码算法:AES(密钥长度在128位及以上)(OFB或CTR模式) 43 | 3)非对称加密算法:RSA(密钥长度在2048位及以上) 44 | 4)哈希算法:SHA2(256位及以上) 45 | 5)密钥交换算法:DH(2048位及以上) 46 | 6)HMAC(基于哈希的消息验证码)算法:HMAC-SHA2 47 | 3、缺省使用安全的加密算法,如客户选择不安全的加密算法,应提示安全风险。 48 | 49 | 50 | 8、VM_SensitiveInPross:进程中的敏感信息 51 | 搜索敏感信息关键字“pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|X-Auth-Token|Authorization|sessionID|token”(见实际扫描脚本VM_SensitiveInPross.sh) 52 | 进程中不能含有明文密码和认证信息 53 | 54 | 9、VM_Pross:排查启动权限过大的进程 55 | 56 | 10、VM_CertificateInLog.sh:日志中的认证信息 57 | 搜索敏感信息关键字“certificate|auth|session|token|key|ak|sk”(见实际扫描脚本VM_CertificateInLog.sh) 58 | 59 | 11、VM_UserNameInLog.sh:日志中的租户名 60 | 租户名可能会是手机号或者邮箱,所以日志中的租户名需要隐匿打印。当前搜索关键字是“op_svc_sc_customer_hws|un|dn”,所有打印了该租户名的日志,都需要开发确认是否有隐匿手机号、邮箱等客户信息的机制 61 | 62 | 12、VM_DockerPS:查询虚机上所有容器信息,用于容器相关的扫描结果分类提单,本身不是软件问题,不用排查!!! 63 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Annotation_sh.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | #\![[:blank:]]*/bin/bash shell 3 | #\![[:blank:]]*/bin/sh shell 4 | # source env shell 5 | #\!/usr/bin/env[[:blank:]]*bash shell 6 | [[:blank:]]*#--* shell 7 | #[[:blank:]]*create shell 8 | #for euler os shell 9 | #for ubuntu os shell 10 | #[[:blank:]]*\/ shell 11 | .*/tiny/tiny\-.*\.js shell 12 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 13 | .*/lib(64|)/python2\.7/.* shell 14 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 15 | /etc/dhcp/dhclient.d shell 16 | /etc/euleros_security/ shell 17 | /etc/lvm/ shell 18 | /etc/openvswitch/ shell 19 | /etc/pki/ca-trust shell 20 | /etc/pki/tls shell 21 | /etc/ppp/ shell 22 | /etc/selinux shell 23 | /etc/smartmontools/ shell 24 | /etc/ssh/ shell 25 | /etc/sysconfig/ shell 26 | /etc/yum/ shell 27 | /jdk/jdk[0-9_\.]+ shell 28 | /jdk/jdk[0-9_\.]+/ shell 29 | /jruby/[0-9_\.]+/gems/ shell 30 | /LinuxHicloud/ shell 31 | /logstash/logstash[0-9\.\-]+/ shell 32 | /root/.kube/ shell 33 | /run/udev/data shell 34 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 35 | /usr/bin/yum shell 36 | /usr/include/expat\.h shell 37 | /usr/include/openflow shell 38 | /usr/include/openvswitch shell 39 | /usr/include/python2.7 shell 40 | /usr/lib/crda shell 41 | /usr/lib/dracut shell 42 | /usr/lib/dracut/ shell 43 | /usr/lib/firewalld shell 44 | /usr/lib/firewalld/ shell 45 | /usr/lib/firmware shell 46 | /usr/lib/grub shell 47 | /usr/lib/kbd shell 48 | /usr/lib/kdump shell 49 | /usr/lib/modules shell 50 | /usr/lib/rpm shell 51 | /usr/lib/rpm/ shell 52 | /usr/lib/systemd/ shell 53 | /usr/lib/udev/ shell 54 | /usr/lib/x86_64 shell 55 | /usr/lib64/gconv shell 56 | /usr/lib64/gettext shell 57 | /usr/lib64/perl5 shell 58 | /usr/lib64/pm-utils shell 59 | /usr/local/jre shell 60 | /usr/share/alsa shell 61 | /usr/share/authconfig shell 62 | /usr/share/awk shell 63 | /usr/share/bash-completion shell 64 | /usr/share/dict shell 65 | /usr/share/doc shell 66 | /usr/share/doc/ shell 67 | /usr/share/emacs shell 68 | /usr/share/euleros shell 69 | /usr/share/gcc shell 70 | /usr/share/Gconf shell 71 | /usr/share/gdb shell 72 | /usr/share/gettext shell 73 | /usr/share/glib shell 74 | /usr/share/gnupg shell 75 | /usr/share/groff shell 76 | /usr/share/hwdata shell 77 | /usr/share/i18n shell 78 | /usr/share/licenses shell 79 | /usr/share/man shell 80 | /usr/share/mime shell 81 | /usr/share/misc shell 82 | /usr/share/openvswitch shell 83 | /usr/share/os-prober shell 84 | /usr/share/perl5 shell 85 | /usr/share/pki shell 86 | /usr/share/polkit shell 87 | /usr/share/smartmontools shell 88 | /usr/share/systemd shell 89 | /usr/share/tcl shell 90 | /usr/share/tcl8 shell 91 | /usr/share/vim shell 92 | /usr/share/yum shell 93 | /usr/share/zoneinfo shell 94 | /usr/share/zsh shell 95 | /var/lib/yum/ shell 96 | /var/log/anaconda/ shell 97 | /var/log/dmesg shell 98 | /var/log/messages shell 99 | /var/log/openvswitch shell 100 | /var/log/secure shell 101 | /usr/share/X11/locale shell 102 | /usr/share/cups shell 103 | /usr/share/ghostscript shell 104 | /usr/share/locale/ca shell 105 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 106 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Annotation_python.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | #\!\s*/usr/bin/env[[:blank:]]*python shell 3 | #\!\s*/usr/bin/python shell 4 | #\!\s*/use/bin/python shell 5 | #\s*Load[[:blank:]]*Modules shell 6 | #\s*-\*- coding:[[:blank:]]*utf-8 -\*- shell 7 | \s*#end[[:blank:]]* shell 8 | \s*#[[:blank:]]*e\.g\. shell 9 | \s*# for CSR shell 10 | #stp shell 11 | #mkdir shell 12 | .*/tiny/tiny\-.*\.js shell 13 | \.(log|txt|sql|dat|trace)(\.[0-9]+|):[0-9]+:.* shell 14 | .*/lib(64|)/python2\.7/.* shell 15 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 16 | /etc/dhcp/dhclient.d shell 17 | /etc/euleros_security/ shell 18 | /etc/lvm/ shell 19 | /etc/openvswitch/ shell 20 | /etc/pki/ca-trust shell 21 | /etc/pki/tls shell 22 | /etc/ppp/ shell 23 | /etc/selinux shell 24 | /etc/smartmontools/ shell 25 | /etc/ssh/ shell 26 | /etc/sysconfig/ shell 27 | /etc/yum/ shell 28 | /jdk/jdk[0-9_\.]+ shell 29 | /jdk/jdk[0-9_\.]+/ shell 30 | /jruby/[0-9_\.]+/gems/ shell 31 | /LinuxHicloud/ shell 32 | /logstash/logstash[0-9\.\-]+/ shell 33 | /root/.kube/ shell 34 | /run/udev/data shell 35 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 36 | /usr/bin/yum shell 37 | /usr/include/expat\.h shell 38 | /usr/include/openflow shell 39 | /usr/include/openvswitch shell 40 | /usr/include/python2.7 shell 41 | /usr/lib/crda shell 42 | /usr/lib/dracut shell 43 | /usr/lib/dracut/ shell 44 | /usr/lib/firewalld shell 45 | /usr/lib/firewalld/ shell 46 | /usr/lib/firmware shell 47 | /usr/lib/grub shell 48 | /usr/lib/kbd shell 49 | /usr/lib/kdump shell 50 | /usr/lib/modules shell 51 | /usr/lib/rpm shell 52 | /usr/lib/rpm/ shell 53 | /usr/lib/systemd/ shell 54 | /usr/lib/udev/ shell 55 | /usr/lib/x86_64 shell 56 | /usr/lib64/gconv shell 57 | /usr/lib64/gettext shell 58 | /usr/lib64/perl5 shell 59 | /usr/lib64/pm-utils shell 60 | /usr/local/jre shell 61 | /usr/share/alsa shell 62 | /usr/share/authconfig shell 63 | /usr/share/awk shell 64 | /usr/share/bash-completion shell 65 | /usr/share/dict shell 66 | /usr/share/doc shell 67 | /usr/share/doc/ shell 68 | /usr/share/emacs shell 69 | /usr/share/euleros shell 70 | /usr/share/gcc shell 71 | /usr/share/Gconf shell 72 | /usr/share/gdb shell 73 | /usr/share/gettext shell 74 | /usr/share/glib shell 75 | /usr/share/gnupg shell 76 | /usr/share/groff shell 77 | /usr/share/hwdata shell 78 | /usr/share/i18n shell 79 | /usr/share/licenses shell 80 | /usr/share/man shell 81 | /usr/share/mime shell 82 | /usr/share/misc shell 83 | /usr/share/openvswitch shell 84 | /usr/share/os-prober shell 85 | /usr/share/perl5 shell 86 | /usr/share/pki shell 87 | /usr/share/polkit shell 88 | /usr/share/smartmontools shell 89 | /usr/share/systemd shell 90 | /usr/share/tcl shell 91 | /usr/share/tcl8 shell 92 | /usr/share/vim shell 93 | /usr/share/yum shell 94 | /usr/share/zoneinfo shell 95 | /usr/share/zsh shell 96 | /var/lib/yum/ shell 97 | /var/log/anaconda/ shell 98 | /var/log/dmesg shell 99 | /var/log/messages shell 100 | /var/log/openvswitch shell 101 | /var/log/secure shell 102 | /usr/share/X11/locale shell 103 | /usr/share/cups shell 104 | /usr/share/ghostscript shell 105 | /usr/share/locale/ca shell 106 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 107 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/Log.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import os 4 | import sys 5 | import traceback 6 | import datetime 7 | reload(sys) 8 | sys.setdefaultencoding('utf-8') 9 | 10 | import LocalOperate 11 | import GlobalValue as g_Global 12 | g_Local = None 13 | class Log: 14 | def __init__(self,logPath=None): 15 | global g_Local 16 | g_Local = LocalOperate.Local() 17 | self.file = self.logFile() 18 | 19 | if not self.tryOpen(): 20 | print "打开日志文件失败:{file}".format(file=self.file) 21 | g_Global.setValue("logFile",self.file) 22 | 23 | def logFile(self): 24 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 25 | logPath = curFile.split("PublicLib")[0]+"Log" 26 | if g_Global.getValue("startTime") is None: 27 | g_Global.setValue("startTime",str(datetime.datetime.now())) 28 | file = "{logPath}/Log-{time}.log".format(logPath=logPath,time=g_Global.getValue("startTime").replace(":","")) 29 | file = file.replace("\\","/") 30 | return file 31 | 32 | def writeLog(self,log,post=None,printlog=True): 33 | log = str(log) 34 | f = open(self.file,"a") 35 | time = str(datetime.datetime.now()) 36 | try: 37 | raise 38 | except: 39 | f1 = sys.exc_info()[2].tb_frame.f_back 40 | post1 = f1.f_code.co_filename +":" + str(f1.f_lineno) +":" 41 | post1 = post1.replace("\\","/") 42 | if post==None: 43 | post = post1 44 | 45 | #post = sys._getframe(0).f_code.co_filename +":" + str(sys._getframe(0).f_lineno) +":" 46 | f.write("["+time+"] "+ post) 47 | if log=="traceback": 48 | f.write("\n") 49 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 50 | f.write(errmsg) 51 | else: 52 | if log[-1:]=="\n": 53 | log = log[:-1] 54 | if "\n" in log: 55 | f.write("\n") 56 | 57 | try: 58 | f.write(log.decode('utf-8').encode('GBK')+"\n") 59 | f.write("\n") 60 | f.close() 61 | except: 62 | doNothing = True 63 | try: 64 | f.write(log.decode('GBK').encode('utf-8')+"\n") 65 | f.write("\n") 66 | f.close() 67 | except: 68 | doNothing = True 69 | try: 70 | f.write(u"{log}".format(log=log)+"\n") 71 | f.write("\n") 72 | f.close() 73 | except: 74 | doNothing = True 75 | 76 | if printlog != True: 77 | return 1 78 | 79 | if log=="traceback": #系统报错 80 | #traceback.print_exc(file=f) 81 | g_last_errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 82 | print g_last_errmsg 83 | else: 84 | print "["+time+"] ",post 85 | try: 86 | print log.decode('utf-8').encode('GBK') 87 | except: 88 | try: 89 | print log.decode('GBK').encode('utf-8') 90 | except: 91 | print log 92 | 93 | return 1 94 | 95 | def printLog(self,log): 96 | time = datetime.datetime.now() 97 | print "["+time+"] " 98 | if log=="traceback": #系统报错 99 | print "["+time+"] ",''.join(traceback.format_exception(*sys.exc_info())) 100 | else: 101 | print "["+time+"] ",log 102 | 103 | def tryOpen(self): 104 | try: 105 | f = open(self.file,"a") 106 | f.close() 107 | except: 108 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 109 | print errmsg 110 | return 0 111 | return 1 112 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_fileaccess.sh: -------------------------------------------------------------------------------- 1 | ######## paas ######## 2 | find / ! -perm 600 -name *.key -user paas -exec ls -l {} \; 2>/dev/null 3 | 4 | find / ! -perm 600 -name *.crt -user paas -exec ls -l {} \; 2>/dev/null 5 | 6 | find / ! -perm 600 -name *.pem -user paas -exec ls -l {} \; 2>/dev/null 7 | 8 | #find / ! -perm 600 -name *.conf -user paas -exec ls -l {} \; 2>/dev/null 9 | 10 | #find / ! -perm 600 -name *.json -user paas -exec ls -l {} \; 2>/dev/null 11 | 12 | #find / ! -perm 600 -name *.bat -user paas -exec ls -l {} \; 2>/dev/null 13 | 14 | find / ! -perm 640 ! -perm 600 -name *.log -user paas -exec ls -l {} \; 2>/dev/null 15 | 16 | find / -type f -user paas -perm -640 ! -perm -700 ! -perm 640 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 17 | 18 | find / -type f -user paas -perm -750 ! -perm 750 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 19 | 20 | find / -type d -user paas -perm -750 ! -perm 750 -exec ls -ld {} \; 2>/dev/null | egrep -v -i '/proc/' 21 | 22 | ######## dbuser ######## 23 | find / ! -perm 600 -name *.key -user dbuser -exec ls -l {} \; 2>/dev/null 24 | 25 | find / ! -perm 600 -name *.crt -user dbuser -exec ls -l {} \; 2>/dev/null 26 | 27 | find / ! -perm 600 -name *.pem -user dbuser -exec ls -l {} \; 2>/dev/null 28 | 29 | #find / ! -perm 600 -name *.conf -user dbuser -exec ls -l {} \; 2>/dev/null 30 | 31 | #find / ! -perm 600 -name *.json -user dbuser -exec ls -l {} \; 2>/dev/null 32 | 33 | #find / ! -perm 600 -name *.bat -user dbuser -exec ls -l {} \; 2>/dev/null 34 | 35 | find / ! -perm 640 ! -perm 600 -name *.log -user dbuser -exec ls -l {} \; 2>/dev/null 36 | 37 | find / -type f -user dbuser -perm -640 ! -perm -700 ! -perm 640 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 38 | 39 | find / -type f -user dbuser -perm -750 ! -perm 750 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 40 | 41 | find / -type d -user dbuser -perm -750 ! -perm 750 -exec ls -ld {} \; 2>/dev/null | egrep -v -i '/proc/' 42 | 43 | ######## elb ######## 44 | find / ! -perm 600 -name *.key -user elb -exec ls -l {} \; 2>/dev/null 45 | 46 | find / ! -perm 600 -name *.crt -user elb -exec ls -l {} \; 2>/dev/null 47 | 48 | find / ! -perm 600 -name *.pem -user elb -exec ls -l {} \; 2>/dev/null 49 | 50 | #find / ! -perm 600 -name *.conf -user elb -exec ls -l {} \; 2>/dev/null 51 | 52 | #find / ! -perm 600 -name *.json -user elb -exec ls -l {} \; 2>/dev/null 53 | 54 | #find / ! -perm 600 -name *.bat -user elb -exec ls -l {} \; 2>/dev/null 55 | 56 | find / ! -perm 640 ! -perm 600 -name *.log -user elb -exec ls -l {} \; 2>/dev/null 57 | 58 | find / -type f -user elb -perm -640 ! -perm -700 ! -perm 640 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 59 | 60 | find / -type f -user elb -perm -750 ! -perm 750 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 61 | 62 | find / -type d -user elb -perm -750 ! -perm 750 -exec ls -ld {} \; 2>/dev/null | egrep -v -i '/proc/' 63 | 64 | ######## cspexpert ######## 65 | find / ! -perm 600 -name *.key -user cspexpert -exec ls -l {} \; 2>/dev/null 66 | 67 | find / ! -perm 600 -name *.crt -user cspexpert -exec ls -l {} \; 2>/dev/null 68 | 69 | find / ! -perm 600 -name *.pem -user cspexpert -exec ls -l {} \; 2>/dev/null 70 | 71 | #find / ! -perm 600 -name *.conf -user cspexpert -exec ls -l {} \; 2>/dev/null 72 | 73 | #find / ! -perm 600 -name *.json -user cspexpert -exec ls -l {} \; 2>/dev/null 74 | 75 | #find / ! -perm 600 -name *.bat -user cspexpert -exec ls -l {} \; 2>/dev/null 76 | 77 | find / ! -perm 640 ! -perm 600 -name *.log -user cspexpert -exec ls -l {} \; 2>/dev/null 78 | 79 | find / -type f -user cspexpert -perm -640 ! -perm -700 ! -perm 640 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 80 | 81 | find / -type f -user cspexpert -perm -750 ! -perm 750 -exec ls -l {} \; 2>/dev/null | egrep -v -i '/proc/|*.log$|*.key$|*.crt$|*.pem$' 82 | 83 | find / -type d -user cspexpert -perm -750 ! -perm 750 -exec ls -ld {} \; 2>/dev/null | egrep -v -i '/proc/' 84 | 85 | ######## alluser ######## 86 | find / ! -perm 600 -name *.frm -exec ls -l {} \; 2>/dev/null 87 | 88 | find / ! -perm 600 -name *.MYI -exec ls -l {} \; 2>/dev/null 89 | 90 | find / ! -perm 600 -name *.MYD -exec ls -l {} \; 2>/dev/null 91 | 92 | find / ! -perm 600 -name *.ibd -exec ls -l {} \; 2>/dev/null 93 | 94 | find / ! -perm 600 -name *ibdata* -exec ls -l {} \; 2>/dev/null 95 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/config/script/VM_Sensitive.sh: -------------------------------------------------------------------------------- 1 | str1="^.*:[0-9]+:\s*(\-|\w+|)(\.|)\s*(\"|\'|)[0-9a-zA-Z_\s\-]+(\"|\'|)(\s*:|\s*=|\"\s*(:|=)|\'\s*(:|=))\s*(\{|\"|\'){0,3}(|[a-z_\.\/\-]+|0x[0-9a-zA-Z]+){0,1}(\{|\"|\'){0,3}(,|\.|)\s*(\/\/[a-zA-Z0-9\. ]+|)\W*$" 2 | str2="^.*:[0-9]+:\s*[a-z_\/\-]+:\s*\{([a-z_\/\-]+:\s*[a-z_\/\-]+\s*,\s*|[a-z_\/\-]+:\s*[0-9_\/\-]+\s*,\s*){0,}[a-z_\/\-]+:\s*[a-z_\/\-]+\s*(\}|,)\s*\W*$" 3 | str3="^.*:[0-9]+:\s*(\"){0,1}[a-z_\/\s\-]+(\"){0,1}\s*(=|:)\s*((\"){0,1}[a-z_\/\.\-]+(\"){0,1}(\"){0,1}|(\"){0,1}[a-z_\/\.\-]+(\"){0,1}|(\"){0,1}[A-Z_\/\.\-]+(\"){0,1})\W*$" 4 | str4="^.*:[0-9]+:\s*(\"){0,}[a-z_\/\-]+(\"){0,}:\s*(\"){0,}\{(\\\"[a-z_\/\-]+\\\":\s*\\\"[a-z_\/\-]+\\\"\s*,\s*|\\\"[a-z_\/\-]+\\\":\s*\\\"\/[a-z0-9_\/\-]+\\\"\s*,\s*){0,}\\\"id\\\":\\\"[0-9a-zA-Z\-]+\\\"\}\"(,|)\W*$" 5 | str5="^/opt/paas/dockyard/tarsum/[0-9a-z]+/layer:[0-9]+:\s*\{.*\}\W*$" 6 | str6="^.*:[0-9]+:\{\"traceId\":[0-9]+,\"name\":\"([A-Za-z0-9_\/\.\-]+:){0,5}[a-z0-9_\/\.\{\}\?\=\-]+\",\"id\":[0-9\-]+,\"parentId\":[0-9\-]+,\"annotations\":\[((|\[)\{\"timestamp\":[0-9]+,\"value\":\"\w+\",\"host\":\{\"ip\":(null|\"[a-z0-9\.\-]+\"),\"port\":\"[0-9]+\"\}\}(,|\])){1,3},\"append\":(|\[)(\{\"key\":\"[a-zA-Z]+\",\"value\":\"([0-9]+|[A-Z]+|[A-Za-z\/]+|)\",\"annotationType\":\"([a-z0-9]+|[A-Z]+)\"\}(,|\])){1,10},\"extinfo\":((\"|)[a-z0-9A-Z\._\-]+(\"|)|\[\{\"key\":\"[a-zA-Z]+\",\"value\":\".*\",\"annotationType\":\"([a-z0-9]+|[A-Z]+)\"\}\])\}\W*$" 7 | str7="^.*:[0-9]+:\{\"annotations\":((|\[)\{\"host\":\{(\"ip\":\"[a-z0-9\.\-]+\",){0,1}\"port\":\"[0-9]+\"\},\"timestamp\":[0-9]+,\"value\":\"\w+\"\}(,|\])){1,3},\"append\":((|\[)\{\"annotationType\":\"([a-z0-9]+|[A-Z]+)\",\"key\":\"[a-zA-Z]+\",\"value\":\"([0-9\-]+|[A-Z]+|[A-Za-z ]+(@[A-Za-z ]+|)|[A-Za-z ]+(\/[A-Za-z ]+|)|)\"\}(,|\]|)){1,10},(\"extinfo\":\[\{\"annotationType\":\"([a-z0-9]+|[A-Z]+)\",\"key\":\"[a-zA-Z]+\",\"value\":\".*\"\}\],){0,1}\"id\":[0-9\-]+,\"name\":\".*\",\"parentId\":[0-9\-]+,\"traceId\":[0-9\-]+\}\W*$" 8 | str8="^.*:[0-9]+:\{\"uid\":\"([0-9a-z]+|)\",\"un\":\"([a-zA-Z0-9_]+|)\",\"ter\":\"([0-9\.:]+|)\",\"op\":\"([a-zA-Z ]+|)\",\"opl\":\"([a-zA-Z]+|)\",\"did\":\"([0-9a-z]+|)\",\"dn\":\"([a-zA-Z0-9_]+|)\",\"pid\":\"([0-9a-z]+|)\",\"pn\":\"([a-zA-Z0-9_]+|)\",\"evnt\":\"([a-zA-Z]+|)\",\"tobj\":\"([a-zA-Z0-9_]+|)\",\"res\":\"([a-zA-Z0-9_]+|)\",\"dtl\":\".*\(using password: YES\).*\",\"src\":\"([a-zA-Z0-9_\-]+|)\",\"ts\":[0-9]+(,\"indexts\":[0-9]+){0,1}\}\W*$" 9 | str9="^.*:[0-9]+:type\=[A-Z]+\s+msg\=audit\([0-9:\.]+\)\:\s+arch\=[a-z0-9\-]+\s+syscall\=[a-z0-9\-]+\s+success\=[a-z0-9\-]+\s+exit=[a-z0-9\-]+\s+(a[0-9]+\=[a-z0-9]+\s+){1,5}items\=[a-z0-9\-]+\s+ppid\=[0-9]+\s+pid\=[0-9]+\s+auid\=[0-9]+\s+uid\=[0-9]+\s+gid\=[0-9]+\s+euid\=[0-9]+\s+suid\=[0-9]+\s+fsuid\=[0-9]+\s+egid\=[0-9]+\s+sgid\=[0-9]+\s+fsgid\=[0-9]+\s+tty\=\(none\)\s+ses\=[0-9]+\s+comm\=(\"|)[a-zA-Z0-9_\.\-]+(\"|)\s+exe\=\"[a-z0-9_\/\-]+\"\s+subj\=([a-z0-9_:\.\-]+){1,5}\s+key\=\(null\)\W*$" 10 | str10="^.*:[0-9]+:type\=[A-Z]+\s+msg\=audit\([0-9:\.]+\)\:\s+avc:\s+denied\s+\{[a-z ]+\}\s+for\s+pid\=[0-9]+\s+comm\=\"[a-z0-9_\.\-]+\"\s+name\=\"[a-zA-Z0-9_\-]+\"\s+dev\=\"[a-zA-Z0-9_\-]+\"\s+ino\=[0-9]+\s+scontext\=([a-z0-9_:\.\-]+){1,5}\s+tcontext\=([a-z0-9_:\.\-]+){1,5}\s+tclass\=[a-z0-9_:\.\-]+\W*$" 11 | str11="^.*oss\.zookeeper\.log:[0-9]+:[0-9:\s\-]+,[0-9]+\s+INFO\s+\(ProcessThread\([a-z0-9:\s\-]+\):\)\s+[a-zA-Z\s\-]+\s+sessionid:\s*0x(\*){6,}[a-z0-9]+\s+(type:[a-zA-Z]+\s+cxid:(0x|)[0-9a-z]+\s+zxid:(0x|)[0-9a-z]+\s+txntype:(\-|)[0-9]+\s+reqpath:[a-z\/]+\s+Error Path:[a-zA-Z0-9_\/\-]+\s+Error:KeeperErrorCode = BadVersion for [a-zA-Z0-9_\/\-]+\s+|)\(PrepRequestProcessor:[0-9]+\)\s*\W*$" 12 | str12="^.*:[0-9]+:\s*Public\-Key:\s+\([0-9]+ bit\)\s*\W*$" 13 | str13="^.*kubelet\.log.*:[0-9]+:[A-Z0-9]+\s+[0-9]+:[0-9]+:[0-9]+\.[0-9]+\s+[0-9]+\s+[a-zA-Z0-9]+\.go:[0-9]+\]\s+[a-zA-Z0-9_\/\.]+:[0-9]+:\s+[A-Za-z\*\. ]+:\s+[a-zA-Z0-9_\/\.\?\= :]+\W*$" 14 | str14="^.*:[0-9]+:[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}\s+[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\s+[0-9]+\s+\[[a-zA-Z]+\]\s+Access denied for user '[a-z]+'@'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'\s+\(using password:\s+(YES|NO)\)$" 15 | str15="^.*/var/log/[a-zA-Z0-9\-]+:[0-9]+:.*$" 16 | 17 | big_str1="^.*\.yaml:[0-9]+:\s*(tls.key:|tls.key.pwd:|kubeconfig:)\s*[0-9a-zA-Z]{64,}\W*$" 18 | big_str2="^.*febsdb.*\.aof:[0-9]+:.*\"ResetPlatformAdminPwd\":\{.*$" 19 | big_str3="^[a-zA-Z0-9_\/\-]+oss\.dbacl_tool\.trace:[0-9]+:.*\"entity\":\[(\{.*,\"total_keys\":\"[0-9]+\"\}(,|\])){1,100}.*,\"detail\":null\}\W*$" 20 | 21 | sys_str1="^.*\/\.bash_history:[0-9]+:.*$" 22 | sys_str2="^.*\/usr/lib(64|)\/python2\.7.*$" 23 | sys_str3="^.*\/usr\/lib\/udev\/hwdb\.d\/[0-9]+\-keyboard\.hwdb.*$" 24 | 25 | key_words="(pass|password|passwd|pswd|mima|key|pwd|PINNUMBER|secret|crypto|encrypt|decrypt|Authorization|sessionID|token|email|mobile)[0-9a-zA-Z_-]*(\s*:|\s*=|\"\s*(:|=)|\'\s*(:|=))|X-Auth-Token|(ak|sk|akey|skey|accesskey|secretkey|access_key|secret_key)[0-9a-zA-Z_\\\"\-]{0,}(:|=)(\s|)(\"|\'|)[0-9a-zA-Z]{40,}" 26 | find / \ 27 | -path /proc -prune -o \ 28 | -path /boot -prune -o \ 29 | -path /tmp -prune -o \ 30 | -type f ! -name "*.bin" | xargs file|egrep -E 'text|XML|PC bitmap data'|awk '{print $1}'|sed 's/:$//g'|xargs grep -i -a -n -E -H "$key_words" \ 31 | |egrep -i -v "bash_history|Binary file|containerScan|vmSecureScan|/devicemapper/mnt|$str1|$str2|$str3|$str4|$str5|$str6|$str7|$str8|$str9|$str10|$str11|$str12|$str13|$str14|$str15|$big_str1|$big_str2|$big_str3|$sys_str1|$sys_str2|$sys_str3" 2>/dev/null 32 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/ExcelOperate.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import os 4 | import sys 5 | import xlwt 6 | import xlrd 7 | from xlutils.copy import copy 8 | reload(sys) 9 | sys.setdefaultencoding('utf8') 10 | 11 | import Log 12 | g_Log = None 13 | import LocalOperate 14 | g_Local = None 15 | 16 | class Excel: 17 | def __init__(self,excelName=None,sheetName=None,sheetID=None,lineNum=None,columnNum=None): 18 | global g_Log,g_Local 19 | g_Log = Log.Log() 20 | g_Local = LocalOperate.Local() 21 | self.excelName = excelName 22 | self.sheetName = sheetName 23 | self.sheetID = sheetID 24 | self.lineNum = lineNum 25 | self.columnNum = columnNum 26 | 27 | def new(self):#新建一个excel 28 | try: 29 | g_Log.writeLog(u"尝试新建{excelPath}".format(excelPath=g_Local.unicode(self.excelName))) 30 | # 检查excel所在路径是否存在,如不存在则新建完整目录 31 | excelPath = os.path.split(self.excelName)[0] 32 | pathExist = os.path.exists(excelPath) 33 | if not pathExist: 34 | os.makedirs(excelPath) 35 | 36 | file = xlwt.Workbook() #新建excel 37 | if self.sheetName is not None: 38 | table = file.add_sheet(self.sheetName) #按sheetName新建sheet 39 | else: 40 | table = file.add_sheet('sheet1') #新建sheet,取名默认sheet1 41 | file.save(self.excelName) #保存excel 42 | g_Log.writeLog(u"新建成功") 43 | except: 44 | g_Log.writeLog("traceback") 45 | return 0 46 | 47 | def write(self,result,redLine=0):# 向excel写入 48 | try: 49 | g_Log.writeLog(u"打开并尝试写入{excelPath}".format(excelPath=g_Local.unicode(self.excelName))) 50 | # 读取excel 51 | workbook = xlrd.open_workbook(r'{excelPath}'.format(excelPath=self.excelName),formatting_info=True) 52 | if self.sheetID is not None: 53 | oldSheet=workbook.sheet_by_index(self.sheetID) 54 | g_Log.writeLog(u"写入第{id}页".format(id=self.sheetID)) 55 | elif self.sheetName is not None: 56 | oldSheet=workbook.sheet_by_name(self.sheetName) 57 | g_Log.writeLog(u"写入\"{sheet}\"页".format(sheet=self.sheetName)) 58 | 59 | n_workbook = copy(workbook) 60 | table = n_workbook.get_sheet(0) 61 | 62 | # 设定excel标题的颜色和字体 63 | # 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray 64 | pattern1 = xlwt.Pattern() 65 | pattern1.pattern = xlwt.Pattern.SOLID_PATTERN 66 | pattern1.pattern_fore_colour = 3 67 | style1 = xlwt.XFStyle() 68 | style1.pattern = pattern1 69 | pattern2 = xlwt.Pattern() 70 | pattern2.pattern = xlwt.Pattern.SOLID_PATTERN 71 | pattern2.pattern_fore_colour = 2 72 | style2 = xlwt.XFStyle() 73 | style2.pattern = pattern2 74 | 75 | # 向excel写入内容 76 | firstrow = oldSheet.nrows 77 | firstcol = oldSheet.ncols 78 | for row in range(0,len(result)): 79 | t = result[row] 80 | for col in range(0,len(t)): 81 | text = t[col][0:32000] 82 | if row+firstrow == 0: 83 | if col < len(t)-redLine: 84 | table.write(row+firstrow,col,text,style1) 85 | else: 86 | table.write(row+firstrow,col,text,style2) 87 | else: 88 | table.write(row+firstrow,col,text) 89 | n_workbook.save(self.excelName) #保存 90 | g_Log.writeLog(u"写入成功") 91 | except: 92 | g_Log.writeLog("traceback") 93 | return 0 94 | 95 | def read(self): #读取excel内容 96 | result = [] 97 | g_Log.writeLog(u"打开并尝试读取{excelPath}".format(excelPath=g_Local.unicode(self.excelName))) 98 | try: 99 | print self.excelName 100 | workbook = xlrd.open_workbook(r'{excelPath}'.format(excelPath=self.excelName)) 101 | if self.sheetID is not None: 102 | sheetInfo = workbook.sheet_by_index(self.sheetID) 103 | g_Log.writeLog(u"读取第{id}页".format(id=self.sheetID)) 104 | elif self.sheetName is not None: 105 | sheetInfo = workbook.sheet_by_name(self.sheetName) 106 | g_Log.writeLog(u"读取\"{sheet}\"页".format(sheet=g_Local.unicode(self.sheetName))) 107 | for i in range(0,sheetInfo.nrows): 108 | rowInfo = [] 109 | for j in range(0,sheetInfo.ncols): 110 | value = sheetInfo.row_values(i) 111 | tvalue = value[j] 112 | if tvalue == None: 113 | tvalue = "" 114 | rowInfo.append(tvalue) 115 | result.append(rowInfo) 116 | g_Log.writeLog(u"读取成功") 117 | return result 118 | except: 119 | g_Log.writeLog("traceback") 120 | return 0 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/libs/scanFunctionDef.py: -------------------------------------------------------------------------------- 1 | #-*- coding: GBK -*- 2 | import time 3 | import commands 4 | import sys 5 | import os 6 | import re 7 | import csv 8 | import paramiko 9 | 10 | class scanFunctionDef: 11 | filename = None 12 | localTime = None 13 | runPath = "" 14 | resultPath = "" 15 | 16 | def set_csvFilename(filename): 17 | scanFunctionDef.filename = filename 18 | def get_csvFilename(): 19 | return scanFunctionDef.filename 20 | 21 | def set_localTime(): 22 | scanFunctionDef.localTime = time.strftime('%Y-%m-%d_%H%M%S') 23 | def get_localTime(): 24 | return scanFunctionDef.localTime 25 | 26 | def set_runPath(path): 27 | scanFunctionDef.runPath = path 28 | def get_runPath(): 29 | return scanFunctionDef.runPath 30 | 31 | def get_resultPath(): 32 | return scanFunctionDef.resultPath 33 | 34 | #从csv中获取配置信息 35 | def getSystemInfo(): 36 | systemInfo = [] 37 | filename = get_csvFilename() 38 | csvReader = csv.reader( open(filename,'rb') ) 39 | try: 40 | for ip,systemname,user,password,root,rootpassword in csvReader: 41 | systemInfo.append( [ip,systemname,user,password,root,rootpassword] ) 42 | except: 43 | print "No information in csv or the information in csv is not correct." 44 | return False 45 | return systemInfo 46 | 47 | #输出结果文件的路径及格式 48 | def resultFile(ip,sysName,shName): 49 | path = get_runPath() 50 | time = get_localTime() 51 | sign1 = sysName+"-"+ip 52 | sign2 = shName[0:-3] 53 | 54 | resultPath = path+"/result-"+time 55 | pathExist1 = os.path.exists(resultPath) 56 | if not pathExist1: 57 | t1 = os.mkdir(resultPath) 58 | 59 | scanFunctionDef.resultPath = resultPath 60 | resultPath = resultPath + "/" + sign1 61 | pathExist1 = os.path.exists(resultPath) 62 | if not pathExist1: 63 | t1 = os.mkdir(resultPath) 64 | 65 | fileName = resultPath + "/" + sign2 + ".txt" 66 | fileExists = os.path.exists(fileName) 67 | #print fileName 68 | if not fileExists: 69 | fileName = unicode(fileName,"GB2312") 70 | #fileName = fileName.encode(encoding='utf-8').decode(encoding='GB2312') 71 | file = open( fileName, 'w') 72 | file.write("") 73 | file.close() 74 | return fileName 75 | 76 | #从script文件夹中获取要执行的Linux脚本 77 | def getScript(): 78 | workPath = get_runPath() 79 | path = workPath+'/config/script' 80 | shlist = os.listdir(path) 81 | length = len(shlist) 82 | i = 0 83 | while i < length: 84 | if ".sh" not in shlist[i]: 85 | del shlist[i] 86 | continue 87 | shlist[i] = path + "/" + shlist[i] 88 | i = i+1 89 | return shlist 90 | 91 | def runAll(): 92 | #先获取配置信息 93 | vmInfo = getSystemInfo() 94 | #检测配置信息是否正确 95 | i = 0 96 | while i < len(vmInfo)-1: 97 | x = vmInfo[i] 98 | ip = x[0] 99 | user = x[2] 100 | passwd = x[3] 101 | rootPasswd = x[5] 102 | ssh=paramiko.SSHClient() 103 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 104 | try: 105 | ssh.connect(ip,username=user,password=passwd) 106 | except: 107 | print " "*4+"// Cannot login {ip} by \"{user}/{passwd}\". ".format(ip=ip,user=user,passwd=passwd) 108 | del vmInfo[i] 109 | continue 110 | stdin,stdout,stderr = ssh.exec_command( "echo -e {passwd}|su root -c 'whoami'".format(passwd=rootPasswd) ) 111 | curUser = stdout.read() 112 | if "root" not in curUser: 113 | print " "*4+"// su root in {ip} with password '{passwd}' failed!".format(ip=ip,passwd=rootPasswd) 114 | del vmInfo[i] 115 | continue 116 | i = i+1 117 | 118 | #获取要执行的Linux脚本 119 | shScripts = getScript() 120 | for sct in shScripts: 121 | shName = sct.split("/")[-1] 122 | if ".sh" not in sct: 123 | continue 124 | print " "*4+"Run {shName}".format(shName=shName) 125 | #对脚本中特殊字符进行python格式转义 126 | file = open(sct) 127 | info = file.read() 128 | #if '\n' in info: 129 | #info = info.replace('\n', '') 130 | if '\\' in info: 131 | info = info.replace('\\', '\\\\') 132 | if '$' in info: 133 | info = info.replace('$', '\$') 134 | if '"' in info: 135 | info = info.replace('"', '\\"') 136 | if '`' in info: 137 | info = info.replace('`', '\\`') 138 | #执行脚本部分,先拿出一条脚本到不同虚机节点执行,再切换下一条脚本 139 | for x in vmInfo: 140 | ip = x[0] 141 | sysName = x[1] 142 | user = x[2] 143 | passwd = x[3] 144 | rootPasswd = x[5] 145 | print " "*8+"Run scan script for {ip}".format(user=user,ip=ip) 146 | ssh=paramiko.SSHClient() 147 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 148 | ssh.connect(ip,username=user,password=passwd) 149 | 150 | stdin,stdout,stderr = ssh.exec_command( "rm -rf /tmp/{shName}".format(shName=shName) ) 151 | stdout.read() 152 | stdin,stdout,stderr = ssh.exec_command( "touch /tmp/{shName}".format(shName=shName) ) 153 | stdout.read() 154 | 155 | stdin,stdout,stderr = ssh.exec_command( "echo -e {passwd}|su root -c 'chmod 700 /tmp/{shName}'".format(passwd=rootPasswd,shName=shName) ) 156 | stdout.read() 157 | stdin,stdout,stderr = ssh.exec_command( "echo \"{cmd}\">>/tmp/{shName}".format(cmd=info,shName=shName) ) 158 | stdout.read() 159 | 160 | stdin,stdout,stderr = ssh.exec_command( "echo -e {passwd}|su root -c '/usr/bin/sh /tmp/{shName}'".format(passwd=rootPasswd,shName=shName) ) 161 | shResult = stdout.read() 162 | shError = stderr.read() 163 | if "terminated by" in shError: 164 | stdin,stdout,stderr = ssh.exec_command( "echo -e {passwd}|su root -c '/usr/bin/sh /tmp/{shName}'".format(passwd=rootPasswd,shName=shName) ) 165 | shResult = stdout.read() 166 | shError = stderr.read() 167 | if "terminated by" in shError: 168 | stdin,stdout,stderr = ssh.exec_command( "echo -e {passwd}|su root -c '/usr/bin/sh /tmp/{shName}'".format(passwd=rootPasswd,shName=shName) ) 169 | shResult = stdout.read() 170 | shError = stderr.read() 171 | shResult = shResult.split("\n") 172 | ssh.close() 173 | 174 | ssh=paramiko.SSHClient() 175 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 176 | ssh.connect(ip,username=user,password=passwd) 177 | stdin,stdout,stderr = ssh.exec_command( "rm -rf /tmp/{shName}".format(shName=shName) ) 178 | 179 | result = resultFile(ip,sysName,shName) 180 | file = open( result,'w' ) 181 | for line in shResult: 182 | if "fileaccess" in shName and "lrwxrwxrwx" in line: 183 | continue 184 | if shName in line: 185 | continue 186 | if len(line)>180000: 187 | continue 188 | file.write(line+"\n") 189 | ssh.close() 190 | 191 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/FIND_Sensitive.md: -------------------------------------------------------------------------------- 1 | 排除关键字(支持正则表达式) 筛选方式 说明 2 | ^.*:[0-9]+:\s*(\-|\w+|)(\.|)\s*(\"|\'|)[0-9a-zA-Z_\s\-]+(\"|\'|)(\s*:|\s*=|\"\s*(:|=)|\'\s*(:|=))\s*(\{|\"|\'){0,3}(|[a-z_\.\/\-]+|0x[0-9a-zA-Z]+){0,1}(\{|\"|\'){0,3}(,|\.|)\s*(\/\/[a-zA-Z0-9\. ]+|)\W*$ shell 3 | ^.*:[0-9]+:\s*[a-z_\/\-]+:\s*\{([a-z_\/\-]+:\s*[a-z_\/\-]+\s*,\s*|[a-z_\/\-]+:\s*[0-9_\/\-]+\s*,\s*){0,}[a-z_\/\-]+:\s*[a-z_\/\-]+\s*(\}|,)\s*\W*$ shell 4 | ^.*:[0-9]+:\s*(\"){0,1}[a-z_\/\s\-]+(\"){0,1}\s*(=|:)\s*((\"){0,1}[a-z_\/\.\-]+(\"){0,1}(\"){0,1}|(\"){0,1}[a-z_\/\.\-]+(\"){0,1}|(\"){0,1}[A-Z_\/\.\-]+(\"){0,1})\W*$ shell 5 | ^.*:[0-9]+:\s*(\"){0,}[a-z_\/\-]+(\"){0,}:\s*(\"){0,}\{(\\\"[a-z_\/\-]+\\\":\s*\\\"[a-z_\/\-]+\\\"\s*,\s*|\\\"[a-z_\/\-]+\\\":\s*\\\"\/[a-z0-9_\/\-]+\\\"\s*,\s*){0,}\\\"id\\\":\\\"[0-9a-zA-Z\-]+\\\"\}\"(,|)\W*$ shell 6 | ^/opt/paas/dockyard/tarsum/[0-9a-z]+/layer:[0-9]+:\s*\{.*\}\W*$ shell 7 | ^.*:[0-9]+:\{\"traceId\":[0-9]+,\"name\":\"([A-Za-z0-9_\/\.\-]+:){0,5}[a-z0-9_\/\.\{\}\?\=\-]+\",\"id\":[0-9\-]+,\"parentId\":[0-9\-]+,\"annotations\":\[((|\[)\{\"timestamp\":[0-9]+,\"value\":\"\w+\",\"host\":\{\"ip\":(null|\"[a-z0-9\.\-]+\"),\"port\":\"[0-9]+\"\}\}(,|\])){1,3},\"append\":(|\[)(\{\"key\":\"[a-zA-Z]+\",\"value\":\"([0-9]+|[A-Z]+|[A-Za-z0-9_\/\-]+|)\",\"annotationType\":\"([a-z0-9]+|[A-Z]+)\"\}(,|\])){1,10},\"extinfo\":((\"|)[a-z0-9A-Z\._\-]+(\"|)|\[\{\"key\":\"[a-zA-Z]+\",\"value\":\".*\",\"annotationType\":\"([a-z0-9]+|[A-Z]+)\"\}\])\}\W*$ shell 8 | ^.*:[0-9]+:\{\"annotations\":((|\[)\{\"host\":\{(\"ip\":\"[a-z0-9\.\-]+\",){0,1}\"port\":\"[0-9]+\"\},\"timestamp\":[0-9]+,\"value\":\"\w+\"\}(,|\])){1,3},\"append\":((|\[)\{\"annotationType\":\"([a-z0-9]+|[A-Z]+)\",\"key\":\"[a-zA-Z]+\",\"value\":\"([0-9\-]+|[A-Z]+|[A-Za-z ]+(@[A-Za-z ]+|)|[A-Za-z ]+(\/[A-Za-z ]+|)|)\"\}(,|\]|)){1,10},(\"extinfo\":\[\{\"annotationType\":\"([a-z0-9]+|[A-Z]+)\",\"key\":\"[a-zA-Z]+\",\"value\":\".*\"\}\],){0,1}\"id\":[0-9\-]+,\"name\":\".*\",\"parentId\":[0-9\-]+,\"traceId\":[0-9\-]+\}\W*$ shell 9 | ^.*:[0-9]+:\{\"uid\":\"([0-9a-z]+|)\",\"un\":\"([a-zA-Z0-9_]+|)\",\"ter\":\"([0-9\.:]+|)\",\"op\":\"([a-zA-Z ]+|)\",\"opl\":\"([a-zA-Z]+|)\",\"did\":\"([0-9a-z]+|)\",\"dn\":\"([a-zA-Z0-9_]+|)\",\"pid\":\"([0-9a-z]+|)\",\"pn\":\"([a-zA-Z0-9_]+|)\",\"evnt\":\"([a-zA-Z]+|)\",\"tobj\":\"([a-zA-Z0-9_]+|)\",\"res\":\"([a-zA-Z0-9_]+|)\",\"dtl\":\".*\(using password: YES\).*\",\"src\":\"([a-zA-Z0-9_\-]+|)\",\"ts\":[0-9]+(,\"indexts\":[0-9]+){0,1}\}\W*$ shell 10 | ^.*:[0-9]+:type\=[A-Z_]+\s+msg\=audit\([0-9:\.]+\)\:\s+(arch\=[a-z0-9\-]+\s+|)(syscall\=[a-z0-9\-]+\s+|)(success\=[a-z0-9\-]+\s+|)(exit=[a-z0-9\-]+\s+|)(a[0-9]+\=[a-z0-9]+\s+){0,5}(items\=[a-z0-9\-]+\s+|)(ppid\=[0-9]+\s+|)pid\=[0-9]+\s+(auid\=[0-9]+\s+uid\=[0-9]+\s+|uid\=[0-9]+\s+auid\=[0-9]+\s+)(gid\=[0-9]+\s+|)(euid\=[0-9]+\s+|)(suid\=[0-9]+\s+|)(fsuid\=[0-9]+\s+|)(egid\=[0-9]+\s+|)(sgid\=[0-9]+\s+|)(fsgid\=[0-9]+\s+|)(tty\=\(none\)\s+|)ses\=[0-9]+\s+(comm\=(\"|)[a-zA-Z0-9_\.\-]+(\"|)\s+|)(exe\=\"[a-z0-9_\/\-]+\"\s+|)subj\=([a-z0-9_:\.\-]+){1,5}\s+(msg='\w+=[a-zA-Z0-9\:_,=\"\/\?\s]+'|)(key\=(\(null\)|\"[a-zA-Z]+\")|)\W*$ shell 11 | ^.*:[0-9]+:type\=[A-Z]+\s+msg\=audit\([0-9:\.]+\)\:\s+avc:\s+denied\s+\{[a-z ]+\}\s+for\s+pid\=[0-9]+\s+comm\=\"[a-z0-9_\.\-]+\"\s+name\=\"[a-zA-Z0-9_\-]+\"\s+dev\=\"[a-zA-Z0-9_\-]+\"\s+ino\=[0-9]+\s+scontext\=([a-z0-9_:\.\-]+){1,5}\s+tcontext\=([a-z0-9_:\.\-]+){1,5}\s+tclass\=[a-z0-9_:\.\-]+\W*$ shell 12 | ^.*oss\.zookeeper\.log:[0-9]+:[0-9:\s\-]+,[0-9]+\s+INFO\s+\(ProcessThread\([a-z0-9:\s\-]+\):\)\s+[a-zA-Z\s\-]+\s+sessionid:\s*0x(\*){6,}[a-z0-9]+\s+(type:[a-zA-Z]+\s+cxid:(0x|)[0-9a-z]+\s+zxid:(0x|)[0-9a-z]+\s+txntype:(\-|)[0-9]+\s+reqpath:[a-z\/]+\s+Error Path:[a-zA-Z0-9_\/\-]+\s+Error:KeeperErrorCode = BadVersion for [a-zA-Z0-9_\/\-]+\s+|)\(PrepRequestProcessor:[0-9]+\)\s*\W*$ shell 13 | ^.*:[0-9]+:\s*Public\-Key:\s+\([0-9]+ bit\)\s*\W*$ shell 14 | ^.*kubelet\.log.*:[0-9]+:[A-Z0-9]+\s+[0-9]+:[0-9]+:[0-9]+\.[0-9]+\s+[0-9]+\s+[a-zA-Z0-9]+\.go:[0-9]+\]\s+[a-zA-Z0-9_\/\.]+:[0-9]+:\s+[A-Za-z\*\. ]+:\s+[a-zA-Z0-9_\/\.\?\= :]+\W*$ shell 15 | ^.*:[0-9]+:[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}\s+[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\s+[0-9]+\s+\[[a-zA-Z]+\]\s+Access denied for user '[a-z]+'@'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'\s+\(using password:\s+(YES|NO)\)$ shell 16 | ^.*/var/log/[a-zA-Z0-9\-]+:[0-9]+:.*$ shell 17 | ^.*\.yaml:[0-9]+:\s*(tls.key:|tls.key.pwd:|kubeconfig:)\s*[0-9a-zA-Z]{64,}\W*$ shell 18 | ^.*febsdb.*\.aof:[0-9]+:.*\"ResetPlatformAdminPwd\":\{.*$ shell 19 | ^[a-zA-Z0-9_\/\-]+oss\.dbacl_tool\.trace:[0-9]+:.*\"entity\":\[(\{.*,\"total_keys\":\"[0-9]+\"\}(,|\])){1,100}.*,\"detail\":null\}\W*$ shell 20 | ^.*logstash\.log.*:[0-9]+:\{:timestamp\=>\"[0-9\-]+T[0-9:\.\+]+\",\s*:message\=>\"[a-zA-Z0-9\s\-]+\",\s*:level=>:[a-z]+\} shell 21 | .*/tiny/tiny\-.*\.js shell 22 | .*/lib(64|)/python2\.7/.* shell 23 | /etc/[a-zA-Z0-9_\.\-]+:[0-9]+:.* shell 24 | /etc/dhcp/dhclient.d shell 25 | /etc/euleros_security/ shell 26 | /etc/lvm/ shell 27 | /etc/openvswitch/ shell 28 | /etc/pki/ca-trust shell 29 | /etc/pki/tls shell 30 | /etc/ppp/ shell 31 | /etc/selinux shell 32 | /etc/smartmontools/ shell 33 | /etc/ssh/ shell 34 | /etc/sysconfig/ shell 35 | /etc/yum/ shell 36 | /jdk/jdk[0-9_\.]+ shell 37 | /jdk/jdk[0-9_\.]+/ shell 38 | /jruby/[0-9_\.]+/gems/ shell 39 | /LinuxHicloud/ shell 40 | /logstash/logstash[0-9\.\-]+/ shell 41 | /root/.kube/ shell 42 | /run/udev/data shell 43 | /usr/(s|)bin/[a-zA-Z0-9_\-]+:[0-9]+:.* shell 44 | /usr/bin/yum shell 45 | /usr/include/expat\.h shell 46 | /usr/include/openflow shell 47 | /usr/include/openvswitch shell 48 | /usr/include/python2.7 shell 49 | /usr/lib/crda shell 50 | /usr/lib/dracut shell 51 | /usr/lib/dracut/ shell 52 | /usr/lib/firewalld shell 53 | /usr/lib/firewalld/ shell 54 | /usr/lib/firmware shell 55 | /usr/lib/grub shell 56 | /usr/lib/kbd shell 57 | /usr/lib/kdump shell 58 | /usr/lib/modules shell 59 | /usr/lib/rpm shell 60 | /usr/lib/rpm/ shell 61 | /usr/lib/systemd/ shell 62 | /usr/lib/udev/ shell 63 | /usr/lib/x86_64 shell 64 | /usr/lib64/gconv shell 65 | /usr/lib64/gettext shell 66 | /usr/lib64/perl5 shell 67 | /usr/lib64/pm-utils shell 68 | /usr/local/jre shell 69 | /usr/share/alsa shell 70 | /usr/share/authconfig shell 71 | /usr/share/awk shell 72 | /usr/share/bash-completion shell 73 | /usr/share/dict shell 74 | /usr/share/doc shell 75 | /usr/share/doc/ shell 76 | /usr/share/emacs shell 77 | /usr/share/euleros shell 78 | /usr/share/gcc shell 79 | /usr/share/Gconf shell 80 | /usr/share/gdb shell 81 | /usr/share/gettext shell 82 | /usr/share/glib shell 83 | /usr/share/gnupg shell 84 | /usr/share/groff shell 85 | /usr/share/hwdata shell 86 | /usr/share/i18n shell 87 | /usr/share/licenses shell 88 | /usr/share/man shell 89 | /usr/share/mime shell 90 | /usr/share/misc shell 91 | /usr/share/openvswitch shell 92 | /usr/share/os-prober shell 93 | /usr/share/perl5 shell 94 | /usr/share/pki shell 95 | /usr/share/polkit shell 96 | /usr/share/smartmontools shell 97 | /usr/share/systemd shell 98 | /usr/share/tcl shell 99 | /usr/share/tcl8 shell 100 | /usr/share/vim shell 101 | /usr/share/yum shell 102 | /usr/share/zoneinfo shell 103 | /usr/share/zsh shell 104 | /var/lib/yum/ shell 105 | /var/log/anaconda/ shell 106 | /var/log/dmesg shell 107 | /var/log/messages shell 108 | /var/log/openvswitch shell 109 | /var/log/secure shell 110 | /usr/share/X11/locale shell 111 | /usr/share/cups shell 112 | /usr/share/ghostscript shell 113 | /usr/share/locale/ca shell 114 | /jre[0-9]+\.[0-9]+\.[0-9]+_[0-9]+/ shell 115 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/TestCase_SensitiveInfo_Document.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | import time 9 | import shutil 10 | import docx 11 | 12 | from sys import path 13 | # 系统默认Unicode解码,需要换成utf-8形式 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | ''' 18 | """ 相关安全要求说明 """ 19 | 《01 产品网络安全红线落地解读及指导V2_1.xls》: 20 | 8.1.1 系统自身操作维护类口令满足“口令安全要求” 21 | 《中央软件院网络安全测试基线V2.0.xlsx》 中关于弱口令词典等要求 22 | ''' 23 | ''' 24 | """ 脚本功能 """ 25 | 扫描资料中的弱口令等问题点(目前只支持扫描word和excel),扫描策略见本脚本所在目录下的scanSensitivePolicy.xlsx 26 | 注意:不支持.doc文件,请打开后另存为.docx格式 27 | ''' 28 | ''' 29 | """ 脚本配置执行说明 """ 30 | 配置1:本脚本所在目录下的scanSensitivePolicy.xlsx,“policy”页。 31 | 配置2:本脚本所在目录下的scanSensitivePolicy.xlsx,“config”页。每一行配置都有说明,请仔细阅读。 32 | ''' 33 | 34 | ''' 35 | """ 可以在此处下方添加自己的代码(函数) """ 36 | ''' 37 | try: 38 | g_Log = None 39 | g_Global = None 40 | g_caseName = None 41 | 42 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 43 | g_caseName = curFile.replace("\\","/") 44 | g_curDir = os.path.split(g_caseName)[0] 45 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 46 | 47 | import GlobalValue as g_Global 48 | g_Global.init() 49 | g_Global.setValue("startTime",str(datetime.datetime.now())) 50 | 51 | import Log 52 | import ExcelOperate 53 | import WordOperate 54 | import ContainerOperate 55 | import LinuxOperate 56 | import LocalOperate 57 | g_Log = Log.Log() 58 | g_Local = LocalOperate.Local() 59 | 60 | ##### 获取环境配置信息 61 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 62 | excel0 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 63 | g_vmInfo = excel0.read() 64 | del g_vmInfo[0] 65 | scanPolicyExcel = g_curDir + "/scanSensitivePolicy.xlsx" 66 | excel1 = ExcelOperate.Excel(excelName=scanPolicyExcel,sheetName="policy") 67 | g_scanPolicy = excel1.read() 68 | del g_scanPolicy[0] 69 | excel2 = ExcelOperate.Excel(excelName=scanPolicyExcel,sheetName="config") 70 | g_config = excel2.read() 71 | del g_config[0] 72 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 73 | except: 74 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 75 | print errmsg 76 | exit(0) 77 | 78 | def getScanPolicy(): #获取所有支持系统扫描的策略信息 79 | global g_scanPolicy 80 | policy = [] 81 | for p in g_scanPolicy: 82 | supportSys = p[6].lower() 83 | if p[0].lower() == "true" and "document" in supportSys.lower(): 84 | policy.append(p) 85 | g_scanPolicy = policy 86 | return 1 87 | 88 | def scanWord(matchKey,wordFile): 89 | result = [] 90 | try: 91 | word = WordOperate.Word(docName=wordFile) 92 | wordRead = word.readlines() 93 | lineNum = len(wordRead) 94 | for row in range(1,lineNum): 95 | lineNum = str(row+1) 96 | lineInfo = wordRead[row] 97 | 98 | x1 = re.findall(matchKey,lineInfo,re.I) 99 | if x1 == []: 100 | continue 101 | result.append([wordFile,lineNum,lineInfo]) 102 | except: 103 | g_Log.writeLog("traceback") 104 | return result 105 | 106 | def scanExcel(matchKey,excelFile): 107 | result = [] 108 | try: 109 | excel0 = ExcelOperate.Excel(excelName=excelFile) 110 | sheetNumber = excel0.sheetNumber() 111 | for i in range(0,sheetNumber): 112 | excel = ExcelOperate.Excel(excelName=excelFile,sheetID=i) 113 | excelInfo = excel.read() 114 | rowNum = len(excelInfo) 115 | for row in range(0,rowNum): 116 | colNum = len(excelInfo[row]) 117 | for col in range(0,colNum): 118 | position = excel.position(col,row) 119 | position = " ["+"sheetID="+str(i)+";"+position+"] " 120 | lineInfo = excelInfo[row][col] 121 | if type(lineInfo) != type("str"): 122 | lineInfo=str(lineInfo) 123 | x1 = re.findall(matchKey,lineInfo,re.I) 124 | if x1 == []: 125 | continue 126 | result.append([excelFile,position,lineInfo]) 127 | except: 128 | g_Log.writeLog("traceback") 129 | return result 130 | 131 | def scanDocument(reportPath,file): 132 | for policy in g_scanPolicy: 133 | matchKey = policy[2] 134 | ifRed = policy[7] 135 | result = [] 136 | if ifRed == "YES": 137 | resultFile = reportPath + "/(RedLine)" + str(policy[1]) + ".txt" 138 | else: 139 | resultFile = reportPath + "/" + str(policy[1]) + ".txt" 140 | if file[-5:]==".docx" or file[-4:]==".doc": 141 | result1 = scanWord(matchKey,file) 142 | if result1 != False: 143 | result = result + result1 144 | if file[-5:]==".xlsx" or file[-4:]==".xls": 145 | result2 = scanExcel(matchKey,file) 146 | if result2 != False: 147 | result = result + result2 148 | 149 | if not os.path.exists(reportPath): 150 | os.makedirs(reportPath) 151 | if result == []: 152 | continue 153 | f_result = open(resultFile,'a') 154 | for res in result: 155 | file = res[0] 156 | line = res[1] 157 | info = res[2] 158 | info = info.replace("\n","\\n") 159 | f_result.write(file+":"+line+":"+info+"\n") 160 | f_result.close() 161 | return 1 162 | 163 | def scan_in_Document(): 164 | global g_documentDir 165 | getScanPolicy() 166 | for conf in g_config: 167 | if conf[0]=="documentDir": 168 | g_documentDir = conf[1] 169 | if g_documentDir=="": 170 | g_Log.writeLog(u"错误信息:没有配置源码路径") 171 | return 0 172 | if g_scanPolicy==[]: 173 | g_Log.writeLog(u"错误信息:没有配置扫描策略") 174 | return 0 175 | reportPath = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 176 | if not os.path.exists(reportPath): 177 | os.makedirs(reportPath) 178 | shutil.copy(g_curDir+"/scanSensitivePolicy.xlsx",reportPath+"/scanSensitivePolicy.xlsx") 179 | 180 | for docFile in os.listdir(g_documentDir): 181 | tmpfile = os.path.join(g_documentDir,docFile).replace("\\","/") 182 | if tmpfile.split("/")[-1][0:2]=="~$": 183 | continue 184 | g_Log.writeLog("Begin to scan \"{file}\"".format(file=tmpfile)) 185 | scanDocument(reportPath,tmpfile) 186 | 187 | 188 | 189 | ''' 190 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 191 | ''' 192 | # 执行前的准备操作 193 | def prepare(): 194 | try: 195 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 196 | except: 197 | g_Log.writeLog("traceback") 198 | return 0 199 | return 1 200 | 201 | # 执行用例 202 | def run(): 203 | try: 204 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 205 | getScanPolicy() 206 | scan_in_Document() 207 | except: 208 | g_Log.writeLog("traceback") 209 | return 0 210 | return 1 211 | 212 | # 执行后清理环境 213 | def clearup(): 214 | try: 215 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 216 | except: 217 | g_Log.writeLog("traceback") 218 | return 0 219 | return 1 220 | 221 | if __name__ == '__main__': 222 | res = prepare() 223 | if not res: 224 | print "执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 225 | else: 226 | run() 227 | clearup() 228 | 229 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/TestCase_systemSafe_VM.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | import zipfile 9 | import shutil 10 | 11 | 12 | from sys import path 13 | # 系统默认Unicode解码,需要换成utf-8形式 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | 18 | ''' 19 | """ 相关安全要求说明 """ 20 | 《01 产品网络安全红线落地解读及指导V2_1.xls》: 21 | 6.1.2 使用操作系统的非管理员权限帐号来运行数据库 22 | 关于系统中中无用账号及不安全密码、文件权限、调试工具、无属主文件、进程安全等要求 23 | ''' 24 | ''' 25 | """ 脚本功能 """ 26 | 扫描系统中的无用账号及不安全密码、文件权限、调试工具、无属主文件、进程安全等问题点,扫描策略见本脚本所在目录下的systemSafePolicy.xlsx 27 | ''' 28 | ''' 29 | """ 脚本配置执行说明 """ 30 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 31 | 配置2:本脚本所在目录下的systemSafePolicy.xlsx,“policy”页。 32 | 配置3:本脚本所在目录下的systemSafePolicy.xlsx,“config”页。每一行配置都有说明,请仔细阅读。 33 | ''' 34 | 35 | ''' 36 | """ 可以在此处下方添加自己的代码(函数) """ 37 | ''' 38 | try: 39 | g_Log = None 40 | g_Global = None 41 | g_caseName = None 42 | 43 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 44 | g_caseName = curFile.replace("\\","/") 45 | g_curDir = os.path.split(g_caseName)[0] 46 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 47 | 48 | import GlobalValue as g_Global 49 | g_Global.init() 50 | g_Global.setValue("startTime",str(datetime.datetime.now())) 51 | 52 | import Log 53 | import ExcelOperate 54 | import ContainerOperate 55 | import LinuxOperate 56 | import LocalOperate 57 | g_Log = Log.Log() 58 | g_Local = LocalOperate.Local() 59 | 60 | ##### 获取环境配置信息 61 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 62 | excel0 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 63 | g_vmInfo = excel0.read() 64 | del g_vmInfo[0] 65 | systemSafePolicyExcel = g_curDir + "/systemSafePolicy.xlsx" 66 | excel1 = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName="policy") 67 | g_systemSafePolicy = excel1.read() 68 | del g_systemSafePolicy[0] 69 | excel2 = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName="config") 70 | g_config = excel2.read() 71 | del g_config[0] 72 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 73 | except: 74 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 75 | print errmsg 76 | exit(0) 77 | 78 | def getsystemSafePolicy(): #获取所有支持系统扫描的策略信息 79 | global g_systemSafePolicy 80 | policy = [] 81 | for p in g_systemSafePolicy: 82 | supportSys = p[3].lower() 83 | if p[0].lower() == "true" and "os" in supportSys.lower(): 84 | policy.append(p) 85 | g_systemSafePolicy = policy 86 | return 1 87 | 88 | def scan_in_MV(): 89 | reportPath = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 90 | if not os.path.exists(reportPath): 91 | os.makedirs(reportPath) 92 | shutil.copy(g_curDir+"/systemSafePolicy.xlsx",reportPath+"/systemSafePolicy.xlsx") 93 | for vm in g_vmInfo: 94 | try: 95 | vmIP = vm[0] 96 | vmName = vm[1] 97 | vmUser = vm[2] 98 | vmUserPasswd = vm[3] 99 | vmSuRoot = vm[4] 100 | vmRootPasswd = vm[5] 101 | for scan in g_systemSafePolicy: 102 | name = scan[1] 103 | info = scan[2] 104 | ifRed = scan[4] 105 | 106 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 107 | 108 | if '\\' in info: 109 | info = info.replace('\\', '\\\\') 110 | if '$' in info: 111 | info = info.replace('$', '\$') 112 | if '"' in info: 113 | info = info.replace('"', '\\"') 114 | if '`' in info: 115 | info = info.replace('`', '\\`') 116 | 117 | tLinux.sendRootCommand("rm -rf /tmp/tempScan.sh") 118 | tLinux.sendCommand('echo \"{cmd}\">/tmp/tempScan.sh'.format(cmd=info)) 119 | tLinux.sendRootCommand("chmod 777 /tmp/tempScan.sh") 120 | output = tLinux.sendRootCommand("/usr/bin/sh /tmp/tempScan.sh") 121 | result = output[0] 122 | tLinux.logout() 123 | 124 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 125 | tLinux.sendRootCommand("rm -rf /tmp/tempScan.sh") 126 | tLinux.logout() 127 | 128 | # 检查是否有需要进行结果筛选 129 | if ifRed.upper() == "YES": 130 | resultPath = reportPath + "/(RedLine)" + str(vmIP) 131 | else: 132 | resultPath = reportPath + "/" + str(vmIP) 133 | if not os.path.exists(resultPath): 134 | os.makedirs(resultPath) 135 | resultFile = resultPath + "/" + str(name) + ".txt" 136 | f1 = open(resultFile,'a') 137 | lines = result.split("\n") 138 | try: 139 | excel = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName=name) 140 | ignoreKeys = excel.read() 141 | if ignoreKeys == False: 142 | ignoreKeys = [] 143 | else: 144 | del ignoreKeys[0] 145 | pythonRegular = "" 146 | for x in ignoreKeys: 147 | pythonRegular = pythonRegular + x[0] + "|" 148 | if pythonRegular == "": # 没有配置python形式的结果排查,扫描结果直接写入结果文件 149 | raise "no python values" 150 | pythonRegular = pythonRegular[:-1] 151 | 152 | for line in lines: # 配置了python形式的结果排查,扫描结果筛选后写入结果文件 153 | if "/devicemapper/mnt/" in line: 154 | continue 155 | x0 = re.findall(pythonRegular,line) 156 | if x0==[]: 157 | f1.write(line+"\n") 158 | except: 159 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 160 | if "no python values" in errmsg: 161 | g_Log.writeLog(u"没有为{name}配置python形式的结果排查,扫描结果直接写入结果文件".format(name=name)) 162 | else: 163 | g_Log.writeLog("traceback") 164 | lines = result.split("\n") 165 | for line in lines: 166 | if "/devicemapper/mnt/" in line: 167 | continue 168 | f1.write(line+"\n") 169 | 170 | f1.close() 171 | except: 172 | g_Log.writeLog("traceback") 173 | 174 | 175 | ''' 176 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 177 | ''' 178 | # 执行前的准备操作 179 | def prepare(): 180 | try: 181 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 182 | except: 183 | g_Log.writeLog("traceback") 184 | return 0 185 | return 1 186 | 187 | # 执行用例 188 | def run(): 189 | try: 190 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 191 | getsystemSafePolicy() 192 | scan_in_MV() 193 | except: 194 | g_Log.writeLog("traceback") 195 | return 0 196 | return 1 197 | 198 | # 执行后清理环境 199 | def clearup(): 200 | try: 201 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 202 | except: 203 | g_Log.writeLog("traceback") 204 | return 0 205 | return 1 206 | 207 | if __name__ == '__main__': 208 | res = prepare() 209 | if not res: 210 | print "执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 211 | else: 212 | run() 213 | clearup() 214 | 215 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Jianquan/TestCase_API_Authorization.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | 9 | 10 | from sys import path 11 | reload(sys) 12 | sys.setdefaultencoding('utf-8') 13 | 14 | 15 | try: 16 | g_Log = None 17 | g_Global = None 18 | g_caseName = None 19 | 20 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 21 | g_caseName = curFile.replace("\\","/") 22 | g_curDir = os.path.split(g_caseName)[0] 23 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 24 | 25 | import GlobalValue as g_Global 26 | g_Global.init() 27 | g_Global.setValue("startTime",str(datetime.datetime.now())) 28 | 29 | import Log 30 | import ExcelOperate 31 | import ContainerOperate 32 | import LinuxOperate 33 | import LocalOperate 34 | g_Log = Log.Log() 35 | g_Local = LocalOperate.Local() 36 | 37 | ##### 获取环境配置信息 38 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 39 | excel1 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 40 | g_vmInfo = excel1.read() 41 | del g_vmInfo[0] 42 | g_omCoreInfo = [] 43 | for vm in g_vmInfo: 44 | g_omCoreInfo = [vm[0], vm[1], vm[2], vm[3], vm[4], vm[5]] 45 | g_errInfo = [] 46 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 47 | except: 48 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 49 | print errmsg 50 | exit(0) 51 | 52 | def get_roleInfo(): 53 | global g_errInfo #格式为[[roleName,url,method,tokenLink,support,response,errInfo,result]] 54 | roleInfo = [] 55 | roleExcel = g_curDir + "/Authorization_Role.xlsx" 56 | excel1 = ExcelOperate.Excel(excelName=roleExcel,sheetName="RoleAuthority") 57 | roleSet = excel1.read() 58 | excel2 = ExcelOperate.Excel(excelName=roleExcel,sheetName="parameter") 59 | parameters = excel2.read() 60 | del parameters[0] 61 | apiNum = len(roleSet) 62 | roleNames = [] 63 | tempInfo = [] 64 | for i in range(0,apiNum): 65 | tmprole = roleSet[i] 66 | sup = [] 67 | if i == 0: 68 | roleNum = len(tmprole)-4 69 | for i in range(0,roleNum): 70 | roleNames.append(tmprole[i+4]) 71 | continue 72 | else: 73 | roleNum = len(tmprole)-4 74 | for i in range(0,roleNum): 75 | sup.append(tmprole[i+4]) 76 | method = tmprole[1] 77 | url = tmprole[2] 78 | port = tmprole[3] 79 | 80 | roleNum = len(roleNames) 81 | for i in range(0,roleNum): 82 | tempInfo.append([roleNames[i],url,method,port,sup[i]]) 83 | 84 | for info in tempInfo: 85 | roleName = info[0] 86 | url = info[1] 87 | method = info[2] 88 | port = info[3] 89 | support = info[4] 90 | tmpToken = "" 91 | for para in parameters: 92 | if para[0] == roleName+"_token": 93 | tmpToken = para[1] 94 | x = re.findall("\{"+para[0]+"\}|:"+para[0],url) 95 | if x != []: 96 | url = re.subn("\{"+para[0]+"\}", para[1],url)[0] 97 | url = re.subn(":"+para[0], para[1],url)[0] 98 | if tmpToken == "": 99 | g_errInfo.append([roleNames[i],u"",u"",u"",u"",u"",u"没有配置token值,无法测试",u"Error"]) 100 | continue 101 | tokenLink = "token=\"{token}\";curl -k -X {method} https://{ip_port}{url} -H \"X-Auth-Token:$token\"".format(method=method.upper(),ip_port=port,url=url,token=tmpToken) 102 | roleInfo.append([roleName,url,method,support,tokenLink]) 103 | return roleInfo 104 | 105 | def check_role(roleInfo): 106 | global g_errInfo #格式为[[roleName,url,method,tokenLink,support,response,errInfo,result]] 107 | omCoreIP = g_omCoreInfo[0] 108 | omCoreUser = g_omCoreInfo[2] 109 | omCoreUserPasswd = g_omCoreInfo[3] 110 | omCoreSuRoot = g_omCoreInfo[4] 111 | omCoreRootPasswd = g_omCoreInfo[5] 112 | ssh = LinuxOperate.Linux(ip=omCoreIP,user=omCoreUser,password=omCoreUserPasswd,suRoot=omCoreSuRoot,rootPassword=omCoreRootPasswd) 113 | for role in roleInfo: #[roleName,url,method,support,tokenLink] 114 | tokenLink = role[4] 115 | support = role[3] 116 | output = ssh.sendCommand(tokenLink,timeout=30) 117 | if output[0]!="": 118 | response = output[0] 119 | else: 120 | response = output[1] 121 | res = checkResponse(response) 122 | if res[1]=="Error": 123 | g_errInfo.append([u"{x}".format(x=role[0]),u"{x}".format(x=role[1]),u"{x}".format(x=role[2]),u"{x}".format(x=role[4]),u"",u"{x}".format(x=role[3]),u"命令返回失败,可能是参数错误或接口错误,请检查",u"Error"]) 124 | elif (res[1]=="Pass" and support=="Y") or (res[1]=="Fail" and support=="N"): 125 | g_errInfo.append([u"{x}".format(x=role[0]),u"{x}".format(x=role[1]),u"{x}".format(x=role[2]),u"{x}".format(x=role[4]),u"{x}".format(x=res[0]),u"{x}".format(x=role[3]),u"角色权限与命令结果不符,需定位",u"Fail"]) 126 | else: 127 | g_errInfo.append([u"{x}".format(x=role[0]),u"{x}".format(x=role[1]),u"{x}".format(x=role[2]),u"{x}".format(x=role[4]),u"{x}".format(x=res[0]),u"{x}".format(x=role[3]),u"角色权限与命令结果相符",u"Pass"]) 128 | 129 | def checkResponse(response): 130 | res = "" 131 | lines = response.split("\n") 132 | for line in lines: 133 | x = re.findall("(curl:\s*\(.*)",line) 134 | if x!=[]: 135 | res = x[0] 136 | break 137 | elif "" in line: 138 | res = line 139 | break 140 | elif "Connection refused" in line: 141 | res = line 142 | break 143 | elif "You like 404 pages" in line: 144 | res = "404 page not found" 145 | break 146 | else: 147 | res = "" 148 | continue 149 | if res=="": 150 | res = response 151 | 152 | result = "Fail" 153 | errCase1 = "curl:.*certificate|curl:.*identifier|curl:.*unrecognized|curl:.*Connection refused|curl:.*SSL received a record|curl:.*clientcert|curl:.*authenticate" 154 | errCase2 = "^Unauthorized| no token |404 page not found|404 Not Found| must authenticate before making a request|Please login firstly|Authorization failed|validation does not pass|Authorized failed|Auth failedl" 155 | x = re.findall(errCase1+"|"+errCase2,res,re.IGNORECASE) 156 | if x != []: 157 | result = "Error" 158 | if "Operation timed out" in res: 159 | result = "Error" 160 | if "Permission denied" in res: 161 | result = "Pass" 162 | return [res,result] 163 | 164 | ''' 165 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 166 | ''' 167 | # 执行前的准备操作 168 | def prepare(): 169 | try: 170 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 171 | if g_omCoreInfo == []: 172 | g_Log.writeLog(u"错误信息:没有配置kubectl节点,请配置在/SecurityTest/Config/config.xlsx") 173 | return 0 174 | except: 175 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 176 | g_Log.writeLog(errmsg) 177 | return 0 178 | return 1 179 | 180 | # 执行用例 181 | def run(): 182 | try: 183 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 184 | global g_ResultFile 185 | roleInfo = get_roleInfo() 186 | check_role(roleInfo) 187 | 188 | ## 创建excel用于保存扫描结果 ,格式为[[roleName,url,method,tokenLink,support,response,errInfo,result]] 189 | excelResult = ExcelOperate.Excel(excelName=g_ResultFile,sheetID=0) 190 | excelResult.new() 191 | excelResult.write([[u"角色名称",u"接口",u"方法",u"认证命令",u"命令返回信息",u"角色权限",u"执行结果",u"测试结果"]],redLine=4) 192 | excelResult.write(g_errInfo) 193 | except: 194 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 195 | g_Log.writeLog(errmsg) 196 | return 0 197 | return 1 198 | 199 | # 执行后清理环境 200 | def clearup(): 201 | try: 202 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 203 | 204 | except: 205 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 206 | g_Log.writeLog(errmsg) 207 | return 0 208 | return 1 209 | 210 | 211 | if __name__ == '__main__': 212 | res = prepare() 213 | if not res: 214 | print "错误信息:执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 215 | else: 216 | run() 217 | clearup() 218 | 219 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/TestCase_SensitiveInfo_Code.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | import zipfile 9 | import shutil 10 | 11 | 12 | from sys import path 13 | # 系统默认Unicode解码,需要换成utf-8形式 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | 18 | ''' 19 | """ 相关安全要求说明 """ 20 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 7.1.4 用于敏感数据传输加密的密钥,不能硬编码在代码中。 21 | 《中央软件院网络安全测试基线V2.0.xlsx》 中关于代码中无用账号、敏感信息、明文密码、加密算法、解释性语言、命令注入、危险函数等要求 22 | ''' 23 | ''' 24 | """ 脚本功能 """ 25 | 扫描源码中的无用账号、敏感信息、明文密码、加密算法、解释性语言、命令注入、危险函数等问题点,扫描策略见本脚本所在目录下的scanSensitivePolicy.xlsx 26 | ''' 27 | ''' 28 | """ 脚本配置执行说明 """ 29 | 配置1:本脚本所在目录下的scanSensitivePolicy.xlsx,“policy”页。 30 | 配置2:本脚本所在目录下的scanSensitivePolicy.xlsx,“config”页。每一行配置都有说明,请仔细阅读。 31 | ''' 32 | 33 | ''' 34 | """ 可以在此处下方添加自己的代码(函数) """ 35 | ''' 36 | try: 37 | g_Log = None 38 | g_Global = None 39 | g_caseName = None 40 | 41 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 42 | g_caseName = curFile.replace("\\","/") 43 | g_curDir = os.path.split(g_caseName)[0] 44 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 45 | 46 | import GlobalValue as g_Global 47 | g_Global.init() 48 | g_Global.setValue("startTime",str(datetime.datetime.now())) 49 | 50 | import Log 51 | import ExcelOperate 52 | import ContainerOperate 53 | import LinuxOperate 54 | import LocalOperate 55 | g_Log = Log.Log() 56 | g_Local = LocalOperate.Local() 57 | 58 | ##### 获取环境配置信息 59 | scanSensitivePolicyExcel = g_curDir + "/scanSensitivePolicy.xlsx" 60 | excel1 = ExcelOperate.Excel(excelName=scanSensitivePolicyExcel,sheetName="policy") 61 | g_scanPolicy = excel1.read() 62 | del g_scanPolicy[0] 63 | excel2 = ExcelOperate.Excel(excelName=scanSensitivePolicyExcel,sheetName="config") 64 | g_config = excel2.read() 65 | del g_config[0] 66 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 67 | except: 68 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 69 | print errmsg 70 | exit(0) 71 | 72 | def getScanPolicy(): #获取所有支持系统扫描的策略信息 73 | global g_scanPolicy 74 | policy = [] 75 | for p in g_scanPolicy: 76 | supportSys = p[6].lower() 77 | if p[0].lower() == "true" and "code" in supportSys.lower(): 78 | policy.append(p) 79 | g_scanPolicy = policy 80 | return 1 81 | 82 | def unzipFiles(scanDir): ##解压目录下可能含有的zip源码包 83 | for dirpath,dirnames,filenames in os.walk(scanDir): 84 | for zip in filenames: 85 | try: 86 | if ".zip" not in zip: 87 | continue 88 | tmpfile = os.path.join(dirpath,zip).replace("\\","/") 89 | os.mkdir(tmpfile+"-bak") 90 | f = zipfile.ZipFile(tmpfile) 91 | f.extractall(tmpfile+"-bak") 92 | f.close() 93 | os.remove(tmpfile) 94 | shutil.copytree(tmpfile+"-bak",tmpfile) 95 | shutil.rmtree(tmpfile+"-bak") 96 | except: 97 | g_Log.writeLog("traceback") 98 | if os.path.isdir(tmpfile+"-bak"): 99 | shutil.rmtree(tmpfile+"-bak") 100 | return 1 101 | 102 | def scanFile(resultPath,filename,subDir): ## 按扫描策略在文件中扫描关键字 103 | reportPath = resultPath 104 | try: 105 | f = open(filename,'r') 106 | except: 107 | g_Log.writeLog("traceback") 108 | return 0 109 | 110 | shutil.copy(g_curDir+"/scanSensitivePolicy.xlsx",reportPath+"/scanSensitivePolicy.xlsx") 111 | for (num,line) in enumerate(f): 112 | #resultPath = runPath+"/result-"+beginTime+"/"+codeZip 113 | attrDir = os.path.split(subDir)[1] 114 | x0 = re.findall("/tiny/tiny|\.css|/webapp/.*\.js$|\.min\.js",filename,re.I) 115 | if len(line)>5000 and x0!=[]: 116 | continue 117 | 118 | try: 119 | for conf in g_scanPolicy: 120 | suffix = conf[3].replace(";","|").replace(".","\.").replace(" ","").strip() 121 | ifRed = conf[7] 122 | while True: 123 | if suffix[0:1]=="|": 124 | suffix = suffix[1:] 125 | elif suffix[-1:]=="|": 126 | suffix = suffix[:-1] 127 | elif "||" in suffix: 128 | suffix = suffix.replace("||","|") 129 | else: 130 | break 131 | suffix = suffix.replace("|","$|")+"$" 132 | 133 | fName = filename.split("/")[-1] 134 | x1 = re.findall(suffix,fName,re.I) 135 | if suffix!="": 136 | if x1==[]: 137 | continue 138 | if ifRed.upper() == "YES": 139 | resultPath = reportPath+"/(RedLine)"+str(attrDir) 140 | else: 141 | resultPath = reportPath+"/"+str(attrDir) 142 | resultFile = resultPath + "/" + str(conf[1]) + ".txt" 143 | line = line.replace("\r","").replace("\n","") 144 | x2 = re.findall(conf[2],line,re.I) 145 | if x2 == []: 146 | continue 147 | if not os.path.exists(resultPath): 148 | os.makedirs(resultPath) 149 | f_result = open(resultFile,'a') 150 | if conf[1] == "FIND_TLS_CONFIG": 151 | f_result.write("###############################################################################"+"\n") 152 | f1 = open(filename,'r') 153 | for (num1,line1) in enumerate(f1): 154 | if num1>=num and num1<num+6: 155 | line1 = line1.strip() 156 | f_result.write(str(filename.replace(g_codeDir,""))+":"+str(num1)+":"+str(line1)+"\n") 157 | f1.close() 158 | f_result.write("\n") 159 | else: 160 | f_result.write(str(filename.replace(g_codeDir,""))+":"+str(num)+":"+str(line)+"\n") 161 | f_result.close() 162 | except: 163 | g_Log.writeLog("traceback") 164 | f.close() 165 | 166 | return True 167 | 168 | def scanCodeSafe(): ##扫描主函数 169 | reportPath = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 170 | if not os.path.exists(reportPath): 171 | os.makedirs(reportPath) 172 | global g_codeDir 173 | getScanPolicy() 174 | for conf in g_config: 175 | if conf[0]=="codeDir": 176 | g_codeDir = conf[1] 177 | codeDir = g_codeDir 178 | if g_codeDir=="": 179 | g_Log.writeLog(u"错误信息:没有配置源码路径") 180 | return 0 181 | if g_scanPolicy==[]: 182 | g_Log.writeLog(u"错误信息:没有配置扫描策略") 183 | return 0 184 | 185 | unzipFiles(codeDir) 186 | for dir in os.listdir(codeDir): 187 | subDir = os.path.join(codeDir,dir).replace("\\","/") 188 | if not os.path.isdir(subDir): 189 | g_Log.writeLog(u"错误信息:{file}不是一个目录,不支持扫描".format(file=subDir)) 190 | continue 191 | g_Log.writeLog(u"开始扫描 {dir}".format(dir=subDir)) 192 | for dirpath,dirnames,filenames in os.walk(subDir): 193 | for filename in filenames: 194 | tmpfile = os.path.join(dirpath,filename).replace("\\","/") 195 | scanFile(reportPath,tmpfile,subDir) 196 | 197 | ''' 198 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 199 | ''' 200 | # 执行前的准备操作 201 | def prepare(): 202 | try: 203 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 204 | except: 205 | g_Log.writeLog("traceback") 206 | return 0 207 | return 1 208 | 209 | # 执行用例 210 | def run(): 211 | try: 212 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 213 | scanCodeSafe() 214 | except: 215 | g_Log.writeLog("traceback") 216 | return 0 217 | return 1 218 | 219 | # 执行后清理环境 220 | def clearup(): 221 | try: 222 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 223 | except: 224 | g_Log.writeLog("traceback") 225 | return 0 226 | return 1 227 | 228 | if __name__ == '__main__': 229 | res = prepare() 230 | if not res: 231 | print "执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 232 | else: 233 | run() 234 | clearup() 235 | 236 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/ContainerOperate.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import re 6 | reload(sys) 7 | sys.setdefaultencoding('utf-8') 8 | 9 | import LocalOperate 10 | import LinuxOperate 11 | import Log 12 | g_Local = None 13 | g_linux = None 14 | g_Log = None 15 | class Container: 16 | def __init__(self,ip=None,user=None,password=None,suRoot=None,rootPassword=None,image="ALL"): 17 | global g_linux,g_Local,g_Log 18 | g_linux = LinuxOperate.Linux(ip=ip,user=user,password=password,suRoot=suRoot,rootPassword=rootPassword) 19 | g_Local = LocalOperate.Local() 20 | g_Log = Log.Log() 21 | self.ip = ip 22 | self.user = user 23 | self.password = password 24 | self.suRoot = suRoot 25 | self.rootPassword = rootPassword 26 | self.image = image 27 | self.dockerInfo = self.getDockerInfo() 28 | self.containerInfo = None 29 | 30 | def Container_Mount_link(self): 31 | try: 32 | g_Log.writeLog(u"在{ip}上查询容器的docker信息和mount信息:".format(ip=self.ip)) 33 | containerInfo = [] 34 | 35 | mountInfo = [] 36 | output = g_linux.sendRootCommand("find / -name mount-id") 37 | mounts = output[0].split("\n") 38 | for mount in mounts: 39 | x0 = g_linux.sendRootCommand("cat {file}".format(file=mount)) 40 | mountID = x0[0].split("\n")[0] 41 | if mountID == "": 42 | continue 43 | mountInfo.append([mount,mountID]) 44 | 45 | dockerInfo = self.dockerInfo 46 | 47 | for docker in dockerInfo: 48 | for mount in mountInfo: 49 | if docker[1] in mount[0]: 50 | x1 = g_linux.sendRootCommand("find / -name {mountID}".format(mountID=mount[1])) 51 | dirs = x1[0].split("\n") 52 | for dir in dirs: 53 | if "/devicemapper/mnt/" not in dir: 54 | continue 55 | mountLink = dir+"/rootfs" 56 | containerInfo.append([docker[0],docker[1],mountLink]) 57 | self.containerInfo = containerInfo 58 | except: 59 | g_Log.writeLog("traceback") 60 | return 0 61 | return containerInfo 62 | 63 | def getDockerInfo(self): 64 | try: 65 | g_Log.writeLog(u"在{ip}上查询容器的docker信息:".format(ip=self.ip)) 66 | dockerInfo = [] 67 | output = g_linux.sendRootCommand("docker ps |egrep -v 'CONTAINER ID|pause'") 68 | dockers = output[0].split("\n") 69 | for docker in dockers: 70 | if docker == "": 71 | continue 72 | dockerID = docker.split()[0] 73 | dockerImage = docker.split()[1] 74 | dockerNames = docker.split()[-1] 75 | x0 = re.findall("^[a-z0-9]+$",dockerImage) 76 | x1 = re.findall("k8s_([a-zA-Z0-9_\.]+\-[a-zA-Z0-9\.\-]+)_",dockerNames) 77 | if x0!=[] and x1!=[]: 78 | dockerImage = x1[0] 79 | dockerInfo.append([dockerImage,dockerID]) 80 | if dockerInfo == []: 81 | g_Log.writeLog(u"在虚机{ip}上没有找到需要的容器:\n{docker}".format(ip=self.ip,docker=output[0])) 82 | return 0 83 | except: 84 | g_Log.writeLog("traceback") 85 | return 0 86 | return dockerInfo 87 | 88 | def getContainerID(self,image): 89 | try: 90 | g_Log.writeLog(u"在{ip}上查询容器的docker信息:".format(ip=self.ip)) 91 | id = [] 92 | dockerInfo = self.dockerInfo 93 | for docker in dockerInfo: 94 | if image in docker[0]: 95 | id.append(docker[1]) 96 | if id == []: 97 | g_Log.writeLog(u"在虚机{ip}上没有找到名为{image}的容器".format(ip=self.ip,image=image)) 98 | return 0 99 | except: 100 | g_Log.writeLog("traceback") 101 | return 0 102 | return id 103 | 104 | def sendCommand(self,cmd): 105 | try: 106 | result = [] 107 | cmd = cmd.replace("\'","\"").replace("'","\"") 108 | dockerInfo = self.dockerInfo 109 | for docker in dockerInfo: 110 | try: 111 | g_Log.writeLog(u"[IP={ip},DockerImage={image},DockerID={id}]上正在执行命令:{cmd}".format(ip=self.ip,image=docker[0],id=docker[1],cmd=cmd)) 112 | output = g_linux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=docker[1],cmd=cmd)) 113 | result.append(["[IP={ip},DockerImage={image},DockerID={id}]".format(ip=self.ip,image=docker[0],id=docker[1]),output[0]]) 114 | except: 115 | g_Log.writeLog("traceback") 116 | except: 117 | g_Log.writeLog("traceback") 118 | return 0 119 | return result 120 | 121 | def uploadFileFromLocal(self,localFile,destFile): 122 | try: 123 | localFile=localFile.replace("\\","/") 124 | destFile=destFile.replace("\\","/") 125 | fileName = localFile.split("/")[-1] 126 | tempFile = "/tmp/"+fileName 127 | g_linux.uploadFileByRead(localFile=localFile,destFile=tempFile) 128 | containerInfo = self.containerInfo 129 | if containerInfo is None: 130 | containerInfo = self.Container_Mount_link() 131 | for container in containerInfo:#[docker[0],docker[1],mountLink] 132 | try: 133 | g_Log.writeLog(u"正在向[IP={ip},DockerImage={image},DockerID={id}]拷贝文件{file}".format(ip=self.ip,image=container[0],id=container[1],file=localFile)) 134 | destFile = container[2]+destFile 135 | destDir = os.path.dirname(destFile) 136 | output = self.sendRootCommand( "if [ -d \"{file}\" ]; then echo \"true\"; else echo \"false\"; fi".format(file=destDir) ) 137 | if "true" not in output[0]: 138 | g_Log.writeLog(u"目的目录不存在:{file}".format(file=destDir)) 139 | continue 140 | output = self.sendRootCommand( "ls -l {file}".format(file=destFile) ) 141 | if "No such file or directory" not in output[1] or "total" in output[0]: 142 | g_Log.writeLog(u"目的文件已经存在:{file}".format(file=destFile)) 143 | continue 144 | output = g_linux.sendRootCommand("cp {localFile} {destFile}".format(localFile=tempFile,destFile=destFile)) 145 | if output[1] != "" and len(output[1])>9: 146 | continue 147 | output = g_linux.sendRootCommand("ls -l {destFile}".format(destFile=destFile)) 148 | if output[1] != "" and len(output[1])>9: 149 | continue 150 | except: 151 | g_Log.writeLog("traceback") 152 | output = g_linux.sendRootCommand("rm -rf {localFile}".format(localFile=tempFile)) 153 | output = g_linux.sendRootCommand("rm -rf {localFile}".format(localFile=tempFile)) 154 | except: 155 | g_Log.writeLog("traceback") 156 | return 0 157 | return 1 158 | 159 | def deleteFile(self,file=None): 160 | try: 161 | containerInfo = self.containerInfo 162 | if containerInfo is None: 163 | containerInfo = self.Container_Mount_link() 164 | self.containerInfo = containerInfo 165 | for container in containerInfo:#[docker[0],docker[1],mountLink] 166 | try: 167 | g_Log.writeLog(u"正在向[IP={ip},DockerImage={image},DockerID={id}]删除文件{file}".format(ip=self.ip,image=container[0],id=container[1],file=file)) 168 | output = g_linux.sendRootCommand("rm -rf {file}".format(file=file)) 169 | if output[1] != "" and len(output[1])>9: 170 | continue 171 | output = g_linux.sendRootCommand("ls -l {file}".format(file=file)) 172 | if output[1] != "" and len(output[1])>9: 173 | continue 174 | except: 175 | g_Log.writeLog("traceback") 176 | except: 177 | g_Log.writeLog("traceback") 178 | return 0 179 | return 1 180 | 181 | 182 | 183 | def logout(self): 184 | try: 185 | g_Log.writeLog(u"用户{user}/{password}注销登陆{ip}".format(user=self.user,password=self.password,ip=self.ip)) 186 | g_linux.logout() 187 | except: 188 | g_Log.writeLog("traceback") 189 | return 0 190 | return 1 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | -------------------------------------------------------------------------------- /FirstVersion/vmSecureScan/fileTool/fileToolDef.py: -------------------------------------------------------------------------------- 1 | #-*- coding: GBK -*- 2 | import sys 3 | import os 4 | import re 5 | import csv 6 | import string 7 | import time 8 | 9 | 10 | class fileToolDef: 11 | resultPath = "" 12 | txtPath = "" 13 | 14 | def set_txtPath(path): 15 | fileToolDef.txtPath = path 16 | def get_txtPath(): 17 | return fileToolDef.txtPath 18 | def set_resultPath(path): 19 | fileToolDef.resultPath = path 20 | def get_resultPath(): 21 | return fileToolDef.resultPath 22 | 23 | def getAllTxt(): 24 | txtPath = get_txtPath() 25 | all_txtFile = [] 26 | for parent, dirnames, filenames in os.walk(txtPath): 27 | for name in filenames: 28 | if name[-4:] == ".txt" : # and name[:3]=="VM_" 29 | parent = parent.replace("\\","/") 30 | if dirnames == []: 31 | all_txtFile.append(parent + "/" + name) 32 | if dirnames != []: 33 | dirname = dirnames[0].replace("\\","/") 34 | all_txtFile.append(parent + "/" +dirname + "/" +name) 35 | return all_txtFile 36 | 37 | 38 | def resultFile(txtFile): 39 | txtPath = get_txtPath() 40 | csvPath = txtPath.replace("/result", "/csvResult") 41 | return csvPath 42 | 43 | def readBigFile(txtFile): 44 | size = os.path.getsize(txtFile) 45 | allfile = "" 46 | if size < 30000000: 47 | oldFile = open(txtFile,'rb') 48 | data = oldFile.read() 49 | allfile = allfile + data 50 | oldFile.close() 51 | return allfile 52 | 53 | i = 0 54 | with open(txtFile,'rb') as oldFile: 55 | while True: 56 | data = oldFile.read(30000000) 57 | allfile = allfile + data 58 | i = i+1 59 | if data == "": 60 | break 61 | if i > size/30000000 +1: 62 | break 63 | oldFile.close() 64 | return allfile 65 | 66 | def txtFormat(txtFile): 67 | result = [] 68 | reader = readBigFile(txtFile) 69 | reader = reader.split('\n') 70 | ''' 71 | isFileRead = True 72 | for r in reader: 73 | r = r.replace("\r","").replace("\n","").strip() 74 | if r=='': 75 | continue 76 | if not re.match('.*(:\d+:).*',r): 77 | isFileRead = False 78 | ''' 79 | x0 = re.findall('VM_Bash-X|VM_JSX_Language|VM_Password|VM_Sensitive|VM_unsafe_encrypt',txtFile) 80 | x1 = re.findall('VM_SensitiveInPross',txtFile) 81 | if x0!=[] and x1==[]: # or isFileRead==True 82 | result.append(["文件名称","行号","内容"]) 83 | for r in reader: 84 | r = r.replace("\r","").replace("\n","").strip() 85 | temp = re.findall('^\d+:/',r) 86 | if temp != []: 87 | r = r[len(temp[0])-1:] 88 | 89 | if r=='': 90 | continue 91 | #r = r.replace("\r","") 92 | r1 = r 93 | x = re.findall(':\d+:',r1) 94 | if x==[]: 95 | continue 96 | i1 = r1.index(x[0]) 97 | rec1 = r1[:i1] 98 | r2 = r1[i1+1:] 99 | i2 = r2.index(":") 100 | rec2 = r2[:i2] 101 | rec3 = r2[i2+1:] 102 | 103 | temp = re.findall('^-|^\+',rec3) 104 | if temp != []: 105 | rec3 = ' '+rec3 106 | 107 | #if len(rec3) >90000: 108 | # continue 109 | #elif rec3 >60000: 110 | # rec3 = [rec3[0:30000],rec3[30000:60000],rec3[60000:90000]] 111 | #elif rec3 >30000: 112 | # rec3 = [rec3[0:30000],rec3[30000:60000]] 113 | #else: 114 | # rec3 = [rec3] 115 | 116 | result.append([rec1,rec2,rec3]) 117 | else: 118 | result.append(["扫描结果"]) 119 | for r in reader: 120 | if r=='\n': 121 | continue 122 | r = r.replace("\r","") 123 | r = r.replace("\n","") 124 | 125 | temp = re.findall('^-|^\+',r) 126 | if temp != []: 127 | r = ' '+r 128 | 129 | result.append([r]) 130 | 131 | return result 132 | 133 | def compareHistory(fileName,readResult): 134 | compareResult = [] 135 | abandonResult = [] 136 | fileName = fileName.split("/")[-1] 137 | fileName = fileName.replace(".txt",".csv") 138 | historyPath = get_resultPath()+"/../config/history/"+fileName 139 | #historyFileName = os.listdir(historyPath) 140 | pathExist = os.path.exists(historyPath) 141 | 142 | if not pathExist: 143 | compareResult = readResult 144 | return [compareResult,abandonResult] 145 | 146 | historyResult = [] 147 | historyRead = csv.reader(file(historyPath, 'rb')) 148 | for line in historyRead: 149 | #if not re.match('^\w|^-|^/|\[|^\s',line[0]): 150 | # continue 151 | 152 | tmp = re.findall('VM_Set-X|VM_Bash-X|VM_JSX_Language|VM_Password|VM_Sensitive|VM_unsafe_encrypt',historyPath) 153 | #if ("VM_Set-X" or "VM_Bash-X" or "VM_JSX_Language" or "VM_Password" or "VM_Sensitive" or "VM_unsafe_encrypt") in historyPath: 154 | if tmp != []: 155 | type = line[3] 156 | historyResult.append([":".join([line[0],line[1],line[2]]),type]) 157 | else: 158 | type = line[1] 159 | historyResult.append([line[0],type]) 160 | 161 | 162 | history_rs = "" 163 | for hs in historyResult: 164 | temp = hs[0].replace(' -', '').replace(' +', '') 165 | #temp = temp.replace('\\', '\\\\').replace('*', '\*').replace('$', '\$').replace('(', '\(').replace(')', '\)').replace('^', '\^').replace("\"","\\\"").replace(".","\.").replace("|","\|").replace("[isBlock]",".*") 166 | temp = "^"+temp+"$" 167 | history_rs = history_rs + temp + "|" 168 | history_rs = history_rs[:len(history_rs)-1] 169 | 170 | for tmpR in readResult: 171 | isMatch = False 172 | rs = ":".join(tmpR) 173 | rs = rs.replace("\n","") 174 | rs = rs.replace(' -', '').replace(' +', '') 175 | if len(rs) > 70000: 176 | abandonResult.append(tmpR) 177 | continue 178 | if len(rs) > 3000: 179 | compareResult.append(tmpR) 180 | continue 181 | x0 = re.findall(history_rs,rs) 182 | if x0!=[]: 183 | isMatch = True 184 | 185 | if isMatch == False: 186 | compareResult.append(tmpR) 187 | else: 188 | abandonResult.append(tmpR) 189 | 190 | 191 | return [compareResult,abandonResult] 192 | 193 | 194 | def txt_to_csv(): 195 | print 'Compare with history:' 196 | all_txtFile = getAllTxt() 197 | for f in all_txtFile: 198 | print ' '*4+time.strftime('%Y-%m-%d %H:%M:%S') 199 | print ' '*4+f 200 | newTxt_c = f.replace("/result","/result/compareResult") 201 | newCsv_c = newTxt_c.replace(".txt",".csv") 202 | dir_c = os.path.dirname(newCsv_c) 203 | pathExist_c = os.path.exists(dir_c) 204 | if not pathExist_c: 205 | os.makedirs(dir_c) 206 | 207 | newTxt_a = f.replace("/result","/result/abandonResult") 208 | newCsv_a = newTxt_a.replace(".txt",".csv") 209 | dir_a = os.path.dirname(newCsv_a) 210 | pathExist_a = os.path.exists(dir_a) 211 | if not pathExist_a: 212 | os.makedirs(dir_a) 213 | 214 | resultPath = f.split('/result')[0]+'/result' 215 | set_resultPath(resultPath) 216 | 217 | newResult = txtFormat(f) 218 | rs = compareHistory(f,newResult) 219 | compareResult = rs[0] 220 | abandonResult = rs[1] 221 | 222 | if len(compareResult)>1: #or (compareResult!=[] and re.match('^\w|^-|^/|\[|^\s',compareResult[0][0]) ): 223 | csvFile = open(newCsv_c,"wb") 224 | txtFile = open(newTxt_c,"wb") 225 | writer = csv.writer(csvFile) 226 | for rs in compareResult: 227 | writer.writerow(rs) 228 | if rs == compareResult[0] or ""==":".join(rs): 229 | continue 230 | txtFile.write(":".join(rs)+"\n") 231 | csvFile.close() 232 | txtFile.close() 233 | 234 | if len(abandonResult)>1 or (abandonResult!=[] and re.match('^\w|^-|^/|\[|^\s',abandonResult[0][0]) ): 235 | csvFile = open(newCsv_a,"wb") 236 | txtFile = open(newTxt_a,"wb") 237 | writer = csv.writer(csvFile) 238 | for rs in abandonResult: 239 | writer.writerow(rs) 240 | if rs == abandonResult[0] or ""==":".join(rs): 241 | continue 242 | txtFile.write(":".join(rs)+"\n") 243 | csvFile.close() 244 | txtFile.close() 245 | 246 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/SensitiveInfo/scanSensitivePolicy/policy.md: -------------------------------------------------------------------------------- 1 | 是否执行 策略名 关键字(正则表达式) 文件名 OS扫描路径 OS排除路径 支持扫描主体 是否安全红线(YES|NO) 说明 2 | true FIND_Password C1oudc0w|z9a3Pa55|PaaS#|a123456|iewauH|Cloud\.123|Wasd|Om68fo|Am12|89Ijn|SsMini1 / /proc;/boot code,OS,Docker YES 检查系统或源码中是否含有明文密码 3 | true FIND_Weak_Password (Huawei|root|admin|abc|abcd|123|1234|QAZ|xsw|cnp200|SX3000|FusionSphere|operator|Changeme|Password|\.com|_com|com|wsx|HW)(@|#|\!|_|2|)(Huawei|root|admin|abc|abcd|12|QAZ|xsw|cnp200|SX3000|operator|\.com|_com|com|wsx|HW|@|#|_|\!)|(\"1234\"|\"1234567\"|\"guest\"|\"P@ssw0rd\"|\"root\"|\"tomcat\"|\"anonymous\"|\"admin\"|\"123456\"|\"12345\"|\"HUAWEI\"|\"Hua123wei\"|\"hua123wei\"|\"huawei\"|\"password\"|\"sa\"|\"root\"|\"toor\"|\"password\"|\"change_on_install\"|\"manager\"|\"oem_temp\"|\"tiger\"|\"aqadm\"|\"dbsnmp\"|\"a123456\"|\"Administrator\"|\"Password\") / /proc;/boot code,OS,Docker,Document YES 检查系统或源码中是否含有明文的弱口令 4 | true FIND_Sensitive (pass|password|passwd|pswd|mima|key|PINNUMBER|secret|Authorization|sessionID|token|email|mobile|X-Auth-Token|akey|skey|accesskey|secretkey|access_key|secret_key)|(ak|sk)[0-9a-zA-Z_\\\"\-]{0,}(:|=)(\s|)(\"|\'|)[0-9a-zA-Z]{40,} / /proc;/boot code,OS,Docker YES "检查系统或源码中是否含有敏感信息 5 | 提醒: 6 | a)当搜索出来的关键字的值为变量时(如key=code、password=$code等等),也需要分析变量(code)是否有风险 7 | b)日志文件中既不能有明文,也不能有密文密码密钥信息,日志中写入密文,要做匿名化处理 8 | c)进一步检查含有密码和敏感信息的文件,文件权限是否限制在600以内(非安全红线检查点)" 9 | true FIND_UnsafeEncrypt DES|3DES|SKIPJACK|RC2|RSA|MD2|MD4|MD5|SHA1|base64|Blowfish|2TDEA|TEA|SEAL|CipherFactory|cipherName|Cipher|getInstance|SecretKeySpec|SecretKeyFactory|generateSecret|KeyFactory|IvParameterSpec|MessageDigest|PBKDF2WithHmacMD5|signature|PBKDF|PBEKeySpec|[a-zA-Z0-9]{10,}==|mac.*hash / /proc;/boot code,OS,Docker YES "检查系统或源码中是否使用了不安全加密算法 10 | 参考:http://3ms.huawei.com/km/blogs/details/5491857 11 | 可以学习下http://3ms.huawei.com/km/blogs/details/1739153" 12 | true FIND_Annotation_python ^#|^\s*#|[\"]{3}|[\']{3} .py / /proc;/boot code,OS,Docker NO python脚本解释性语言(严禁使用注释行等形式仅使功能失效) 13 | true FIND_Annotation_sh ^#|^\s*#|^\s*//' .sh / /proc;/boot code,OS,Docker NO shell脚本解释性语言(严禁使用注释行等形式仅使功能失效) 14 | true FIND_Annotation_html ^\s*<\!--|^\s*//|^\s*/\*|^\s*\* .html / /proc;/boot code,OS,Docker NO html语言的解释性语言(严禁使用注释行等形式仅使功能失效) 15 | true FIND_Annotation_js ^\s*<\!--|^\s*//|^\s*/\*|^\s*\* .js / /proc;/boot code,OS,Docker NO js语言的解释性语言(严禁使用注释行等形式仅使功能失效) 16 | true FIND_DebugModel bash\s+\-[a-zA-Z]*x|set\s+\-[a-zA-Z]*x|^#\s+set\s+\+[a-zA-Z]*x|^#\s+bash\s+\+[a-zA-Z]*x / /proc;/boot code,OS,Docker NO "禁止使用调试模式执行shell脚本,调试模式执行shell脚本,虽然能比较方便的查看脚本执行过程以及数据信息,但也会暴露相关的数据,包括可能的敏感信息,存在被利用的风险,调试模式有两种: 17 | a)命令行调用shell脚本时使用选项“-x”,如“bash -x test.sh” 18 | b)在shell脚本中使用命令“set -x”打开调试模式。" 19 | true FIND_EncryptTool encrypt|enc|dec|decrypt code NO 禁止提供独立的解密敏感数据的工具和脚本 20 | true FIND_EmployID \W([a-z]00[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]wx[0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]9[0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[a-z]kf[0-9][0-9][0-9][0-9][0-9])\W code NO 排查源码中可能暴露的员工工号(重点排查shell脚本,以及其他可执行脚本,如python) 21 | true FIND_UserName userid|username|user|username|usrid|user|uid|ftp|ftpuser|super|superuser|root|name|loginname|login|ftpid|101|fixation|system|sys|super|support|master|imapuser|verfiycode|authenticationcode|sharekey|sharecode|key|ftppasswd|ftppass|ftppassword|passcode|manager|privilege|sysadmin|administrator|admin code YES 禁止不可管理的认证/访问方式1:用户不可管理的帐号 22 | true FIND_Keyboard (ctrl|alt|shift|F1)((?![0-9A-Za-z]|\s*=|\[|\.|\s*:|\||\?|\{|\(|\\).) code NO 禁止存在绕过正常认证机制直接进入到系统的隐秘通道1:组合键、鼠标特殊敲击 23 | true FIND_Injection_C&C++ system|_wsystem|popen|ShellExecute|ShellExecuteA|ShellExecuteW|WinExec|spawnve|spawnvpe|spawn|spawnlpe|spawnlp|spawnl|spawnle|spawnvp|spawnv|_spawn|_spawnlpe|_spawnlp|_spawnl|_spawnle|_wspawn|_wspawnlpe|_wspawnlp|_wspawnl|_wspawnle|_tspawn|_tspawnlpe|_tspawnlp|_tspawnl|_tspawnle|_spawnve|_spawnvpe|_wspawnve|_wspawnvpe|_tspawnve|_tspawnvpe|_spawnvp|_spawnv|_wspawnvp|_wspawnv|_tspawnvp|_tspawnv|g_spawn_command_line_async|g_spawn_command_line_sync|g_spawn_async_with_pipes|g_spawn_async|g_spawn_sync|exec|execlp|execl|execlpe|execle|execv|execvp|_exec|_execv|_execvp|_texec|_texecv|_texecvp|_wexec|_wexecv|_wexecvp|_execve|_execvpe|_texecve|_texecvpe|_wexecve|_texecvpe|_execlp|_execl|_execlpe|_execle|_texec|_texeclp|_texecl|_texeclpe|_texecle|_wexec|_wexeclp|_wexecl|_wexeclpe|_wexecle|CreateProcess|CreateProcessA|CreateProcessW|CreateProcessWithTokenW|CreateProcessAsUser|CreateProcessAsUserA|CreateProcessAsUserW|CreateProcessWithLoginW|CreateProcessWithLogonW .c;.cpp;.h code NO "C语言命令注入(Command Injection)风险: 24 | 1、(system,_wsystem)操作系统的命令解释器,如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 25 | 2、(popen)管道启动进程相关函数。 26 | 3、(ShellExecute,ShellExecuteA,ShellExecuteW)windows下shell相关API类似system函数,容易导致操作系统命令注入漏洞。 27 | 4、(spawn系列函数)如果将用户的输入作为spawn函数的应用程序名称参数(file),命令行参数(argv[])或环境变量参数(envp[]),可能会导致用户随意输入程序路径执行恶意命令。 28 | 5、(exec系列函数)如果将用户的输入作为exec函数的应用程序名称参数(file或path),命令行参数(argv[])或环境变量参数(envp[]),可能会导致用户随意输入程序路径执行恶意命令。 29 | 6、(CreateProcess系列函数)如果将用户的输入作为Windows下创建进程相关API的应用程序名称参数(lpApplicationName)或命令行参数(lpCommandLine),可能会导致用户随意输入程序路径执行恶意命令。" 30 | true FIND_Injection_JAVA \w\.exec\(|\w\.command\(|flex\.management\.jmx\.MBeanServerGateway\.invoke|flex\.messaging\.io\.amf\.client\.AMFConnection\.call|org\.apache\.axis\.client\.AdminClient\.main|org\.apache\.axis\.client\.AdminClient\.process|org\.apache\.axis\.client\.Call\.invoke|org\.apache\.axis\.client\.Call\.setOperation|org\.apache\.axis\.client\.Call\.setOperationName|org\.apache\.axis\.client\.Call\.SOAActionURI|org\.apache\.axis\.client\.Call\.setTargetEndpointAddress|org\.owasp\.esapi\.Executor\.executeSystemCommand|org\.apache\.hadoop\.util\.ProgramDriver\.driver|org\.apache\.hadoop\.util\.Tool\.run|org\.apache\.hadoop\.util\.RunJar\.main|org\.apache\.hadoop\.util\.Shell\.execCommand|org\.apache\.hadoop\.streaming\.StreamJob\.run|org\.apache\.hadoop\.mapred\.tools\.MRAdmin\.run .java;.jsp;.js;.class code NO "JAVA语言命令注入(Command Injection)风险: 31 | 1、(Runtime.exec函数)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 32 | 2、(ProcessBuilder.command函数)如果将用户的输入作为ProcessBuilder.command函数的应用程序名称参数或命令行参数,可能会导致用户随意输入程序路径执行恶意命令。 33 | 3、JSP相关函数" 34 | true FIND_Injection_PHP exec|shell_exec|passthru|proc_open|popen|system|ssh1_exec|ssh2_exec .php code NO "PHP语言命令注入(Command Injection)风险: 35 | 1、(exec,shell_exec,passthru,proc_open,popen,system)如果php的操作系统shell命令函数接收用户输入的命令参数,则用户可以通过命令连接符进行命令注入。 36 | 2、(ssh1_exec,ssh2_exec)远程shell命令函数,如果命令参数来自于用户的输入,则用户可以通过命令连接符,进行命令拼接,在远程主机上实施操作系统命令注入。" 37 | true FIND_Injection_PYTHON subprocess\.Popen|subprocess\.call|subprocess\.check_call|subprocess\.check_output|utils\.execute|utils\.execute_with_timeout|os\.system|os\.popen|os\.popen2|os\.popen3|os\.popen4|popen2\.popen2|popen2\.popen3|popen2\.popen4|popen2\.Popen3|popen2\.Popen4|commands\.getoutput|commands\.getstatusoutput .py;.pyc code NO "PYTHON语言命令注入(Command Injection)风险: 38 | 1、(os系列命令)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 39 | 2、(subprocess系列命令)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 40 | 3、(utils系列命令)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 41 | 4、(popen2系列命令)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。 42 | 5、(commands系列命令)如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。" 43 | true FIND_Injection_GO exec\.Command\( .go code NO "GO语言命令注入(Command Injection)风险: 44 | 1、(exec.Command(path,arg))path参数启动shell执行命令时,如果允许用户输入命令参数,则用户可以通过命令连接符进行命令注入。" 45 | true FIND_SQL ((?![a-zA-Z0-9_\s\-]).)\s*select\s code NO 禁止直接使用不可信数据拼接SQL语句 46 | true FIND_REQUEST_URL href\s*\=.*\$\{\w+\}|\Waction\s*\=.*\$\{\w+\}|[^-]url\s*\=.*\$\{\w+\}|\.getRequestURL\(|\.getRequestURI\(|\.startsWith\(|\.endsWith\(|\.contains\( .java;.js;.css;.html;.jsp;.tag;.usl;.xml code NO "url注入,参考: 47 | http://3ms.huawei.com/hi/group/1503621/wiki_4439281.html 48 | http://3ms.huawei.com/hi/group/1503621/wiki_3141499.html" 49 | true FIND_HTTP http(?!(:|s|\s)) code NO 检查源码中是否有采用http方式进行数据传输 50 | true FIND_Create_File os\.Create\(|os\.MkdirAll\( .go code NO 源码中创建了文件和目录,要检查是否限制了文件和目录权限 51 | true FIND_HAZARD_FUNCTION_C&C++ memcpy\(|wmemcpy\(|memmove\(|wmemmove\(|memset\(|strcpy\(|wcscpy\(|strncpy\(|wcsncpy\(|strcat\(|wcscat\(|strncat\(|wcsncat\(|sprintf\(|swprintf\(|vsprintf\(|vswprintf\(|snprintf\(|vsnprintf\( |scanf\(|wscanf\(|vscanf\(|vwscanf\(|fscanf\(|fwscanf\(|vfscanf\(|vfwscanf\(|sscanf\(|swscanf\(|vsscanf\(|vswscanf\(|gets\( .c;.cpp;.h C语言中的危险函数 52 | true FIND_Random_C&C++ rand\(\)|random\(\) .c;.cpp;.h code NO C标准库函数rand()和random()产生的随机数随机性很不好,其产生的随机数序列存在一个较短的循环周期,因此它的随机数是可预测的,禁止用于安全用途。 53 | true FIND_Random_JAVA java\.util\.Random .java;.jsp;.js;.class code NO "java.util.Random类不能用于安全敏感应用或者敏感数据保护。应使用更加安全的随机数生成器,例如java.security.SecureRandom类。 54 | 但是java.security.SecureRandom类本身有可能会产生阻塞的情况,所以建议在非敏感应用或者非敏感数据保护时使用伪随机数生成器PRNG。" 55 | true FIND_Random_PHP rnd\( .php code NO 禁止使用rnd()函数生成安全随机数,安全随机数长度至少8个byte。 56 | true FIND_Random_PYTHON random\. .py;.pyc code NO Python产生随机数的功能在random模块中实现,实现了各种分布的伪随机数生成器,不能应用于安全加密目的的应用中。如果你需要一个真正的密码安全随机数,在Linux和类Unix下用,请使用/dev/random生成安全随机数,在windows下,使用random模块中的SystemRandom类来实现。 57 | true FIND_Random_GO rand\(|random\( .go code NO cryto/rand包中提供了密码学安全伪随机数生成器,它提供了Reader变量,在Unix系统中Reader读取/dev/urandom生成随机数、在Linux系统中Reader使用getrandom生成随机数、在Windows系统中Reader使用CryptGenRandom API生成随机数。 58 | true FIND_TLS_CONFIG tls\.Config\{ code NO 检查源码中的TLS配置(脚本中特殊处理,会打印源码中含有关键字的那一行及后面5行,方便分析) 59 | true FIND_PublicIP \d+\.\d+\.\d+\.\d+ code NO "不需要与公网进行交互的产品/组件,IP地址使用“私网地址”,禁止使用公网地址。 60 | 说明: 61 | 默认私有地址范围: 62 | IPv4: 63 | A类 10.0.0.0-10.255.255.255; 64 | B类 172.16.0.0-172.31.255.255; 65 | C类 192.168.0.0-192.168.255.255 66 | IPv6: 67 | fc00::/7 (Site-Local IPv6 Unicast Addresses,站点本地单播地址,相当于IPv4的私有地址) 68 | fe80::/10 (Link-Local IPv6 Unicast Addresses,链路本地单播地址,IPv6特有地址)" 69 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/PublicLib/LinuxOperate.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import paramiko 5 | import os 6 | import traceback 7 | import re 8 | reload(sys) 9 | sys.setdefaultencoding('utf8') 10 | 11 | import LocalOperate 12 | import Log 13 | import GlobalValue as g_Global 14 | g_Local = None 15 | g_Log = None 16 | 17 | class Linux: 18 | def __init__(self,ip="",name="",user="",password="",suRoot="",rootPassword="",pkey="",pkey_password=""): 19 | global g_Local,g_Log 20 | g_Local = LocalOperate.Local() 21 | g_Log = Log.Log() 22 | if rootPassword != "": 23 | rootPassword = rootPassword.replace("\$","$").replace("\#","#").replace("\!","!").replace("\*","*").replace("\?","?") 24 | rootPassword = rootPassword.replace("$","\$").replace("#","\#").replace("!","\!").replace("*","\*").replace("?","\?") 25 | self.ip = ip 26 | self.name = name 27 | self.user = user 28 | self.password = password 29 | self.suRoot = suRoot 30 | self.rootPassword = rootPassword 31 | self.pkey = pkey.replace("\\","/") 32 | self.pkey_password = pkey_password 33 | self.ssh = self.login() 34 | 35 | 36 | def login(self): 37 | try: 38 | password = self.password 39 | if self.pkey != "": 40 | password = "私钥:\"{keyFile}\"".format(keyFile=self.pkey) 41 | g_Log.writeLog(u"用户 {user}/{password} 登陆{ip}".format(user=self.user,password=password,ip=self.ip)) 42 | 43 | ssh=paramiko.SSHClient() 44 | ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() ) 45 | if self.pkey != "": 46 | if self.pkey_password != "": 47 | private_key = paramiko.RSAKey.from_private_key_file(self.pkey,password=self.pkey_password) 48 | else: 49 | private_key = paramiko.RSAKey.from_private_key_file(self.pkey) 50 | ssh.connect(self.ip,username=self.user,pkey=private_key) 51 | else: 52 | ssh.connect(self.ip,username=self.user,password=self.password) 53 | g_Log.writeLog(u"用户登陆成功") 54 | except: 55 | g_Log.writeLog("traceback") 56 | return 0 57 | return ssh 58 | 59 | def sendCommand(self,cmd,timeout=None): 60 | try: 61 | g_Log.writeLog(u"在{ip}上执行{user}用户命令:".format(ip=self.ip,user=self.user)+cmd) 62 | stdin,stdout,stderr = self.ssh.exec_command( cmd,timeout=timeout ) 63 | output = (stdout.read().strip(),stderr.read().replace("Password: ","")) 64 | except: 65 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 66 | g_Log.writeLog("traceback") 67 | if "timeout" in errmsg and timeout is not None: 68 | output = ("","Operation timed out after {time} seconds.".format(time=timeout)) 69 | return output 70 | return 0 71 | return output 72 | 73 | def logout(self): 74 | try: 75 | g_Log.writeLog(u"用户{user}/{password}注销登陆{ip}".format(user=self.user,password=self.password,ip=self.ip)) 76 | self.ssh.close() 77 | g_Log.writeLog(u"用户注销成功") 78 | except: 79 | g_Log.writeLog("traceback") 80 | return 0 81 | 82 | def checkSuRoot(self): 83 | try: 84 | if self.suRoot == "": 85 | g_Log.writeLog(u"没有定义切换root的命令!") 86 | return 0 87 | g_Log.writeLog(u"在{ip}上从用户{user}切换到用户root".format(ip=self.ip,user=self.user)) 88 | if self.rootPassword == "": 89 | stdin,stdout,stderr = self.ssh.exec_command( "{type} -c '{cmd}'".format(type=self.suRoot,cmd="whoami") ,timeout=30) 90 | else: 91 | stdin,stdout,stderr = self.ssh.exec_command( "echo -e {passwd}|{type} -c '{cmd}'".format(passwd=self.rootPassword,type=self.suRoot,cmd="whoami") ,timeout=30) 92 | except: 93 | g_Log.writeLog("traceback") 94 | return 0 95 | 96 | output = (stdout.read(),stderr.read().replace("Password: ","")) 97 | if "root" not in output[0]: 98 | g_Log.writeLog(u"用户{user}切换root失败,请检查账号密码{root}/{rootPassword}".format(user=self.user,root=self.suRoot,rootPassword=self.rootPassword)) 99 | g_Log.writeLog(output[1]) 100 | return 0 101 | return 1 102 | 103 | def sendRootCommand(self,cmd,timeout=None): 104 | try: 105 | cmd = cmd.replace("\'","\"").replace("'","\"") 106 | g_Log.writeLog(u"在{ip}上执行root用户命令:".format(ip=self.ip)+cmd) 107 | if self.suRoot == "": 108 | stdin,stdout,stderr = self.ssh.exec_command( cmd,timeout=timeout ) 109 | elif self.rootPassword == "": 110 | stdin,stdout,stderr = self.ssh.exec_command( "{type} -c '{cmd}'".format(type=self.suRoot,cmd=cmd),timeout=timeout ) 111 | else: 112 | stdin,stdout,stderr = self.ssh.exec_command( "echo -e {passwd}|{type} -c '{cmd}'".format(passwd=self.rootPassword,type=self.suRoot,cmd=cmd),timeout=timeout ) 113 | output = (stdout.read().strip(),stderr.read().strip().replace("Password: ","")) 114 | if output[1] != "" and len(output[1])>9: 115 | g_Log.writeLog(u"执行命令异常:"+output[1]) 116 | except: 117 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 118 | g_Log.writeLog("traceback") 119 | if "timeout" in errmsg and timeout is not None: 120 | output = ("","Operation timed out after {time} seconds.".format(time=timeout)) 121 | return output 122 | return 0 123 | return output 124 | 125 | def uploadFileByRead(self,localFile=None,destFile=None): 126 | try: 127 | g_Log.writeLog(u"向{ip}上传文件{file}:".format(ip=self.ip,file=localFile)) 128 | localFile=localFile.replace("\\","/") 129 | destFile=destFile.replace("\\","/") 130 | if not os.path.exists(localFile): 131 | g_Log.writeLog(u"源文件不存在:{file}".format(file=localFile)) 132 | return 0 133 | destDir = os.path.dirname(destFile) 134 | output = self.sendRootCommand( "if [ -d \"{file}\" ]; then echo \"true\"; else echo \"false\"; fi".format(file=destDir) ) 135 | if "true" not in output[0]: 136 | g_Log.writeLog(u"目的目录不存在:{file}".format(file=destDir)) 137 | return 0 138 | output = self.sendRootCommand( "ls -l {file}".format(file=destFile) ) 139 | if "No such file or directory" not in output[1] or "total" in output[0]: 140 | g_Log.writeLog(u"目的文件已经存在:{file}".format(file=destFile)) 141 | return 0 142 | 143 | file = open(localFile) 144 | info = file.read() 145 | if '\\' in info: 146 | info = info.replace('\\', '\\\\') 147 | if '$' in info: 148 | info = info.replace('$', '\$') 149 | if '"' in info: 150 | info = info.replace('"', '\\"') 151 | if '`' in info: 152 | info = info.replace('`', '\\`') 153 | 154 | output = self.sendCommand( "echo \"{cmd}\">{shName}".format(cmd=info,shName=destFile) ) 155 | if output[1] != "" and len(output[1])>9 : 156 | g_Log.writeLog(u"上传文件异常:"+output[1]) 157 | return 0 158 | output = self.sendRootCommand("ls -l {shName}".format(shName=destFile)) 159 | if output[1] != "" and len(output[1])>9 : 160 | g_Log.writeLog(u"上传文件异常:"+output[1]) 161 | return 0 162 | except: 163 | g_Log.writeLog("traceback") 164 | return 0 165 | 166 | return output 167 | 168 | def findFile(self,type=None,dir=None): 169 | type = "list" 170 | 171 | def deleteFile(self,file): 172 | try: 173 | g_Log.writeLog(u"在{ip}上删除文件{file}".format(ip=self.ip,file=file)) 174 | output1 = self.sendRootCommand( "rm -rf {file}".format(file=file) ) 175 | output2 = self.sendRootCommand( "ls -l {file}".format(file=file) ) 176 | if output2[0] != "": 177 | g_Log.writeLog(u"文件删除失败:"+output1[1]) 178 | return 0 179 | except: 180 | g_Log.writeLog("traceback") 181 | return 0 182 | return 1 183 | 184 | def getIdleDisc(self): 185 | try: 186 | output = self.sendRootCommand( "df -h" ) 187 | if output==False or output[0] == "": 188 | g_Log.writeLog(u"磁盘信息获取失败") 189 | return 0 190 | discInfo = output[0].split("\n") 191 | idleDisc = "" 192 | discSize = 0 #单位为M 193 | for d in discInfo: 194 | x1 = re.findall(" ([0-9\.]+)G\s+[0-9]+% (/\w+)\s*$",d) 195 | x2 = re.findall(" ([0-9\.]+)M\s+[0-9]+% (/\w+)\s*$",d) 196 | if x1==[] and x2==[]: 197 | continue 198 | if x1==[]: #查找到的单位为M 199 | dInfo = x2[0] 200 | tempSize = float(dInfo[0]) 201 | if x2==[]: #查找到的单位为G,要转换为M 202 | dInfo = x1[0] 203 | tempSize = float(dInfo[0])*1000 204 | if tempSize > discSize: 205 | discSize = tempSize 206 | idleDisc = dInfo[1] 207 | 208 | if discSize == 0 or idleDisc == "": 209 | g_Log.writeLog(u"没有获取到空闲的磁盘信息") 210 | return 0 211 | else: 212 | g_Log.writeLog(u"获取到空闲的磁盘为{disc},大小为{size}".format(disc=idleDisc,size=idleDisc)) 213 | return [idleDisc,discSize] 214 | except: 215 | g_Log.writeLog("traceback") 216 | return 0 217 | return 1 218 | 219 | 220 | 221 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/UnauthorizedAccess_Hengxiangyuequan/TestCase_UnauthorizedAccess.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | 9 | 10 | from sys import path 11 | reload(sys) 12 | sys.setdefaultencoding('utf-8') 13 | 14 | 15 | ''' 16 | """ 相关安全要求说明 """ 17 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 3.1.2 所有能对系统进行管理的人机接口以及跨信任网络的机机接口必须有接入认证机制,标准协议没有认证机制的除外。 18 | ''' 19 | ''' 20 | """ 脚本功能 """ 21 | 先由开发提供角色权限信息,通过该脚本,可以对这些接口进行鉴权测试。 22 | ''' 23 | ''' 24 | """ 脚本配置执行说明 """ 25 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页,只需要配置一台虚机信息即可,确保该虚机能连通环境中所有其它虚机,“是否kubectl节点”要置为TRUE 26 | 配置2:本脚本所在目录下的accessConfig.xlsx,“api”页。每一列配置表头都有批注说明,请仔细阅读。 27 | 配置3:本脚本所在目录下的accessConfig.xlsx,“parameter”页。每一行配置都有说明,请仔细阅读。 28 | ''' 29 | 30 | ''' 31 | """ 可以在此处下方添加自己的代码(函数) """ 32 | ''' 33 | try: 34 | g_Log = None 35 | g_Global = None 36 | g_caseName = None 37 | 38 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 39 | g_caseName = curFile.replace("\\","/") 40 | g_curDir = os.path.split(g_caseName)[0] 41 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 42 | 43 | import GlobalValue as g_Global 44 | g_Global.init() 45 | g_Global.setValue("startTime",str(datetime.datetime.now())) 46 | 47 | import Log 48 | import ExcelOperate 49 | import ContainerOperate 50 | import LinuxOperate 51 | import LocalOperate 52 | g_Log = Log.Log() 53 | g_Local = LocalOperate.Local() 54 | 55 | ##### 获取环境配置信息 56 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 57 | excel1 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 58 | g_vmInfo = excel1.read() 59 | del g_vmInfo[0] 60 | g_omCoreInfo = [] 61 | for vm in g_vmInfo: 62 | if vm[6]==1 or str(vm[6]).upper() == "TRUE": 63 | g_omCoreInfo = [vm[0], vm[1], vm[2], vm[3], vm[4], vm[5]] 64 | g_apiInfo = [] 65 | g_errInfo = [] 66 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 67 | except: 68 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 69 | print errmsg 70 | exit(0) 71 | 72 | def get_apiInfo(): 73 | global g_apiInfo #格式为[[webMark,method,url,port,head,user1_body,user2_body]] 74 | roleExcel = g_curDir + "/accessConfig.xlsx" 75 | excel1 = ExcelOperate.Excel(excelName=roleExcel,sheetName="api") 76 | configs = excel1.read() 77 | del configs[0] 78 | mark = 0 79 | webMark = "" 80 | tempInfo = [] 81 | for conf in configs: 82 | try: 83 | if conf[4].strip()=="": 84 | continue 85 | env = conf[0].strip() 86 | if env!="": 87 | mark = mark + 1 88 | webMark = str(mark) 89 | if conf != configs[0]: 90 | g_apiInfo.append(tempInfo) 91 | tempInfo = [] 92 | #tempInfo.append(webMark) 93 | tempInfo.append([conf[2],conf[3],conf[4],conf[5],conf[6]]) 94 | if conf == configs[-1]: 95 | g_apiInfo.append(tempInfo) 96 | except: 97 | g_Log.writeLog("traceback") 98 | 99 | return 1 100 | 101 | def runScene(): #执行一种场景(功能)下的api(遍历创建、查询、修改、删除) 102 | omCoreIP = g_omCoreInfo[0] 103 | omCoreUser = g_omCoreInfo[2] 104 | omCoreUserPasswd = g_omCoreInfo[3] 105 | omCoreSuRoot = g_omCoreInfo[4] 106 | omCoreRootPasswd = g_omCoreInfo[5] 107 | ssh = LinuxOperate.Linux(ip=omCoreIP,user=omCoreUser,password=omCoreUserPasswd,suRoot=omCoreSuRoot,rootPassword=omCoreRootPasswd) 108 | roleExcel = g_curDir + "/accessConfig.xlsx" 109 | excel1 = ExcelOperate.Excel(excelName=roleExcel,sheetName="parameter") 110 | configs = excel1.read() 111 | del configs[0] 112 | for conf in configs: 113 | if conf[0] == "user1_name": 114 | user1_name = conf[1] 115 | if conf[0] == "user2_name": 116 | user2_name = conf[1] 117 | if conf[0] == "user1_token": 118 | user1_token = conf[1] 119 | if conf[0] == "user2_token": 120 | user2_token = conf[1] 121 | for apis in g_apiInfo: 122 | for api in apis: 123 | method = api[0] 124 | url = api[1] 125 | ip_port = api[2] 126 | head = api[3] 127 | user1_body = api[4] 128 | check_apiAccess(ssh,user1_name,user2_name,user1_token,user2_token,method,url,ip_port,head,user1_body) 129 | 130 | return 1 131 | 132 | # 对比结果:[[url,method,correctLink,response,errorLink,response,errInfo,result]] 133 | def check_apiAccess(ssh,user1_name,user2_name,user1_token,user2_token,method,url,ip_port,head,user1_body): 134 | global g_errInfo 135 | if head == "": 136 | head = " -H \"Content-Type:application/json;charset=utf8\"" 137 | if user1_body.strip() != "" and user1_body.strip().split()[0] != "-d": 138 | user1_body = " -d\'"+user1_body+"\'" 139 | correctLink = "token=\"{token}\";curl -k -X {method} https://{ip_port}{url} -H \"X-Auth-Token:$token\" {head} {body}".format(method=method.upper(),ip_port=ip_port,url=url,token=user1_token,head=head,body=user1_body) 140 | errorLink = "token=\"{token}\";curl -k -X {method} https://{ip_port}{url} -H \"X-Auth-Token:$token\" {head} {body}".format(method=method.upper(),ip_port=ip_port,url=url,token=user2_token,head=head,body=user1_body) 141 | correctLink = correctLink.replace("&","\&") 142 | errorLink = errorLink.replace("&","\&") 143 | 144 | errorOutput = ssh.sendCommand(errorLink,timeout=120) 145 | if errorOutput==False: 146 | errorOutput = ssh.sendCommand(errorLink,timeout=120) 147 | if errorOutput==False: 148 | return 0 149 | 150 | correctOutput = ssh.sendCommand(correctLink,timeout=120) 151 | if correctOutput==False: 152 | return 0 153 | response = correctOutput[0] 154 | if response=="": 155 | response = correctOutput[1] 156 | res = checkResponse(response) 157 | if "Operation timed out" in correctOutput[1]: 158 | g_errInfo.append([url,method,correctLink,"","","",u"用账号{user1}执行curl命令超时,请手动进一步验证".format(user1=user1_name),u"Check"]) 159 | return 0 160 | if res[1] == "Fail": 161 | g_errInfo.append([url,method,correctLink,u"{x}".format(x=res[0]),"","",u"用账号{user1}执行curl命令失败,可能是接口或参数有问题,请手动进一步验证".format(user1=user1_name),u"Check"]) 162 | return 0 163 | if correctOutput[0] == "": 164 | g_errInfo.append([url,method,correctLink,"","",u"用账号{user1}执行该接口,没有返回任何信息,请手动进一步验证".format(user1=user1_name),u"Check"]) 165 | return 0 166 | if errorOutput[0] == correctOutput[0]: 167 | g_errInfo.append([url,method,correctLink,u"{x}".format(x=correctOutput[0]),errorLink,u"{x}".format(x=errorOutput[0]),u"该接口,账号{user1}执行结果与{user2}执行结果一致,可能存在横向越权风险,请确认执行结果".format(user1=user1_name,user2=user2_name),u"Fail"]) 168 | return 0 169 | g_errInfo.append([url,method,correctLink,u"{x}".format(x=correctOutput[0]),errorLink,u"{x}".format(x=errorOutput[0]),u"该接口,账号{user1}执行结果与{user2}执行结果不一致,脚本认为没有越权风险,但请人工再确认一下返回结果".format(user1=user1_name,user2=user2_name),u"Pass"]) 170 | 171 | return 1 172 | 173 | 174 | def checkResponse(response): 175 | res = "" 176 | lines = response.split("\n") 177 | for line in lines: 178 | x = re.findall("(curl:\s*\(.*)",line) 179 | if x!=[]: 180 | res = x[0] 181 | break 182 | elif "<head><title>" in line: 183 | res = line 184 | break 185 | elif "Connection refused" in line: 186 | res = line 187 | break 188 | elif "You like 404 pages" in line: 189 | res = "404 page not found" 190 | break 191 | else: 192 | res = "" 193 | continue 194 | if res=="": 195 | res = response 196 | 197 | result = "Fail" 198 | errCase1 = "curl:.*certificate|curl:.*identifier|curl:.*unrecognized|curl:.*Connection refused|curl:.*SSL received a record|curl:.*clientcert|curl:.*authenticate" 199 | errCase2 = "^Unauthorized| no token |404 page not found|404 Not Found| must authenticate before making a request|Please login firstly|Authorization failed|validation does not pass|Authorized failed|Auth failedl" 200 | x = re.findall(errCase1+"|"+errCase2,res,re.IGNORECASE) 201 | if x == []: 202 | result = "Pass" 203 | return [res,result] 204 | 205 | ''' 206 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 207 | ''' 208 | # 执行前的准备操作 209 | def prepare(): 210 | try: 211 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 212 | except: 213 | g_Log.writeLog("traceback") 214 | return 0 215 | return 1 216 | 217 | # 执行用例 218 | def run(): 219 | try: 220 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 221 | get_apiInfo() 222 | runScene() 223 | 224 | global g_ResultFile 225 | 226 | ## 创建excel用于保存扫描结果 ,格式为[[url,method,correctLink,response,errorLink,response,errInfo,result]] 227 | roleExcel = g_curDir + "/accessConfig.xlsx" 228 | excel1 = ExcelOperate.Excel(excelName=roleExcel,sheetName="parameter") 229 | configs = excel1.read() 230 | del configs[0] 231 | for conf in configs: 232 | if conf[0] == "user1_name": 233 | user1_name = conf[1] 234 | if conf[0] == "user2_name": 235 | user2_name = conf[1] 236 | excelResult = ExcelOperate.Excel(excelName=g_ResultFile,sheetID=0) 237 | excelResult.new() 238 | excelResult.write([[u"URL",u"Method",u"账号{user1}测试接口命令".format(user1=user1_name),u"账号{user1}测试接口返回结果".format(user1=user1_name),u"账号{user2}测试接口命令".format(user2=user2_name),u"账号{user2}测试接口返回结果".format(user2=user2_name),u"错误信息",u"测试结果"]],redLine=2) 239 | excelResult.write(g_errInfo) 240 | 241 | except: 242 | g_Log.writeLog("traceback") 243 | return 0 244 | return 1 245 | 246 | # 执行后清理环境 247 | def clearup(): 248 | try: 249 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 250 | 251 | except: 252 | g_Log.writeLog("traceback") 253 | return 0 254 | return 1 255 | 256 | 257 | if __name__ == '__main__': 258 | res = prepare() 259 | if not res: 260 | print "错误信息:执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 261 | else: 262 | run() 263 | clearup() 264 | 265 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Renzhen/TestCase_API_Authentication_Console.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import yaml 8 | import json 9 | import re 10 | 11 | 12 | from sys import path 13 | reload(sys) 14 | sys.setdefaultencoding('utf-8') 15 | 16 | 17 | ''' 18 | """ 相关安全要求说明 """ 19 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 3.1.2 所有能对系统进行管理的人机接口以及跨信任网络的机机接口必须有接入认证机制,标准协议没有认证机制的除外。 20 | ''' 21 | ''' 22 | """ 脚本功能 """ 23 | 遍历环境中的所有节点,查询tomcat下的directrouters中配置的接口,用session认证进行认证测试 24 | ''' 25 | ''' 26 | """ 脚本配置执行说明 """ 27 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 28 | 配置2:本脚本所在目录下的APIlist.xlsx,“parameter”页。需配置sessionMethod和sessionPort 29 | ''' 30 | 31 | ''' 32 | """ 可以在此处下方添加自己的代码(函数) """ 33 | ''' 34 | try: 35 | g_Log = None 36 | g_Global = None 37 | g_caseName = None 38 | 39 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 40 | g_caseName = curFile.replace("\\","/") 41 | g_curDir = os.path.split(g_caseName)[0] 42 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 43 | 44 | import GlobalValue as g_Global 45 | g_Global.init() 46 | g_Global.setValue("startTime",str(datetime.datetime.now())) 47 | 48 | import Log 49 | import ExcelOperate 50 | import ContainerOperate 51 | import LinuxOperate 52 | import LocalOperate 53 | g_Log = Log.Log() 54 | g_Local = LocalOperate.Local() 55 | 56 | ##### 获取环境配置信息 57 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 58 | excel1 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 59 | g_vmInfo = excel1.read() 60 | del g_vmInfo[0] 61 | g_omCoreInfo = [] 62 | for vm in g_vmInfo: 63 | if vm[6]==1 or str(vm[6]).upper() == "TRUE": 64 | g_omCoreInfo = [ vm[0], vm[1], vm[2], vm[3], vm[4], vm[5]] 65 | excel2 = ExcelOperate.Excel(excelName=excelName,sheetName="otherConfig") 66 | g_config = excel2.read() 67 | del g_config[0] 68 | g_apiInfo = [] 69 | except: 70 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 71 | print errmsg 72 | exit(0) 73 | 74 | def getAPI_by_Tomcat(): 75 | apis = [] 76 | global g_apiInfo 77 | for vm in g_vmInfo: 78 | try: 79 | vmIP = vm[0] 80 | vmName = vm[1] 81 | vmUser = vm[2] 82 | vmUserPasswd = vm[3] 83 | vmSuRoot = vm[4] 84 | vmRootPasswd = vm[5] 85 | tLinux = LinuxOperate.Linux(ip=vmIP,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 86 | output = tLinux.sendRootCommand("find / -name directrouters") 87 | if output[0] == "": 88 | continue 89 | dirs = output[0].split("\n") 90 | for dir in dirs: 91 | output = tLinux.sendRootCommand("ls {dir}".format(dir=dir)) 92 | if output[0] == "": 93 | continue 94 | files = output[0].split() 95 | for f in files: 96 | if f[-4:] != ".xml": 97 | continue 98 | fileName = dir + "/" + f 99 | output = tLinux.sendRootCommand("cat {f1}".format(f1=fileName) + " |egrep \"^\s{8}<uri>|^\s{8}<protocol>|\s{16}<method>\"") 100 | if output[0] == "": 101 | continue 102 | x1 = output[0].replace(" ","").replace("\n","").replace("<uri>","\n<uri>") 103 | fileInfo = x1.split("\n") 104 | for info in fileInfo: 105 | info = info.strip() 106 | if info == "": 107 | continue 108 | a = re.findall("<uri>(.*?)</uri>",info) 109 | uri = a[0] 110 | a = re.findall("<protocol>(.*?)</protocol>",info) 111 | protocol = a[0] 112 | a = re.findall("<method>(.*?)</method>",info) 113 | methods = a 114 | for method in methods: 115 | apis.append([vmIP,fileName,method,protocol,uri]) 116 | if [method,protocol,uri] in g_apiInfo: 117 | continue 118 | g_apiInfo.append([method,protocol,uri]) 119 | 120 | except: 121 | g_Log.writeLog("traceback") 122 | return apis 123 | 124 | 125 | def check_httpAPI_bySession(): #主要函数3:校验url的cookie认证,输出结果:[[method,protocol,uri,certLink,simpleLink,errorLog]] 126 | global g_apiInfo 127 | for conf in g_config: 128 | if conf[0]=="sessionMethod": 129 | sessionMethod = conf[1] 130 | if conf[0]=="sessionPort": 131 | sessionPort = conf[1] 132 | messages = [] #格式为[[method,protocol,uri,certLink,simpleLink,errorLog]] 133 | for info in g_apiInfo: #[method,protocol,uri] 134 | url = info[2] 135 | protocol = info[1] 136 | method = info[0] 137 | simpleLink = "curl -k -X {method} {protocol}://{ip_port}{url}".format(method=method.upper(),ip_port=sessionPort,url=url,protocol=protocol) 138 | sessionLink = "curl -k -X {method} {protocol}://{ip_port}{url} {sessionMethod}".format(method=method.upper(),ip_port=sessionPort,url=url,sessionMethod=sessionMethod,protocol=protocol) 139 | sessionLink = re.subn("\{.*?\}", "parameter123",sessionLink)[0] 140 | simpleLink = re.subn("\{.*?\}", "parameter123",simpleLink)[0] 141 | messages.append([info[0],info[1],info[2],sessionLink,simpleLink,""]) 142 | 143 | result = [] #格式为[[microService,url,serverName,link,errorLog]] 144 | omCoreIP = g_omCoreInfo[0] 145 | omCoreUser = g_omCoreInfo[2] 146 | omCoreUserPasswd = g_omCoreInfo[3] 147 | omCoreSuRoot = g_omCoreInfo[4] 148 | omCoreRootPasswd = g_omCoreInfo[5] 149 | for msg in messages: 150 | ssh = LinuxOperate.Linux(ip=omCoreIP,user=omCoreUser,password=omCoreUserPasswd,suRoot=omCoreSuRoot,rootPassword=omCoreRootPasswd) 151 | sessionLink = msg[3] 152 | simpleLink = msg[4] 153 | #certLink = revisePara(certLink) 154 | output = ssh.sendCommand(sessionLink,timeout=30) 155 | if output[0]=="": 156 | result.append([u"{x}".format(x=msg[0]),u"{x}".format(x=msg[1]),u"{x}".format(x=msg[2]),u"{x}".format(x=msg[3]),u"{x}".format(x=msg[4]),u"",u"命令下发失败,可能支持session认证或参数错误",u"请手动测试"]) 157 | continue 158 | output = ssh.sendCommand(simpleLink,timeout=30) 159 | if output[0]!="": 160 | response = output[0] 161 | else: 162 | response = output[1] 163 | res = checkResponse(response) 164 | result.append([u"{x}".format(x=msg[0]),u"{x}".format(x=msg[1]),u"{x}".format(x=msg[2]),u"{x}".format(x=msg[3]),u"{x}".format(x=msg[4]),u"{x}".format(x=res[0]),u"{x}".format(x=res[1])]) 165 | ssh.logout() 166 | return result 167 | 168 | def checkResponse(response): 169 | res = "" 170 | lines = response.split("\n") 171 | for line in lines: 172 | x = re.findall("(curl:\s*\(.*)",line) 173 | if x!=[]: 174 | res = x[0] 175 | break 176 | elif "<head><title>" in line: 177 | res = line 178 | break 179 | elif "Connection refused" in line: 180 | res = line 181 | break 182 | elif "You like 404 pages" in line: 183 | res = "404 page not found" 184 | break 185 | else: 186 | res = "" 187 | continue 188 | if res=="": 189 | res = response 190 | 191 | result = "Fail" 192 | errCase1 = "curl:.*certificate|curl:.*identifier|curl:.*unrecognized|curl:.*Connection refused|curl:.*SSL received a record|curl:.*clientcert|curl:.*authenticate" 193 | errCase2 = "^Unauthorized| no token |404 page not found|404 Not Found| must authenticate before making a request|Please login firstly|Authorization failed|validation does not pass|Authorized failed|Auth failed|token error" 194 | x = re.findall(errCase1+"|"+errCase2,res,re.IGNORECASE) 195 | if x != []: 196 | result = "Pass" 197 | if "Operation timed out" in res: 198 | result = "Pass" 199 | 200 | return [res,result] 201 | 202 | #def get_unAuthAPI(authAPI): 203 | 204 | 205 | ''' 206 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 207 | ''' 208 | # 执行前的准备操作 209 | def prepare(): 210 | try: 211 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 212 | if g_omCoreInfo == []: 213 | g_Log.writeLog(u"错误信息:没有配置kubectl节点,请配置在/SecurityTest/Config/config.xlsx") 214 | return 0 215 | 216 | except: 217 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 218 | g_Log.writeLog(errmsg) 219 | return 0 220 | return 1 221 | 222 | # 执行用例 223 | def run(): 224 | try: 225 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 226 | global g_ResultFile 227 | 228 | curDir = os.path.split(g_caseName)[0] 229 | resultDir = curDir.replace("TestCase","Report") 230 | startTimeSign = g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 231 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+startTimeSign+".xls" 232 | #g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 233 | 234 | ## 查找所有注册在tomcat的API接口,格式:[method,protocol,uri] 235 | errAPI = getAPI_by_Tomcat() 236 | sessionAPIExcel = resultDir + "/sessionAPI-"+startTimeSign+".xls" 237 | sessionAPI = ExcelOperate.Excel(excelName=sessionAPIExcel,sheetID=0) 238 | sessionAPI.new() 239 | sessionAPI.write([[u"主机IP",u"来源文件",u"Method",u"Protocol",u"URL"]]) 240 | sessionAPI.write(errAPI) 241 | 242 | ## 创建excel用于保存扫描结果 243 | excelResult = ExcelOperate.Excel(excelName=g_ResultFile,sheetID=0) 244 | excelResult.new() 245 | excelResult.write([[u"Method",u"Protocol",u"URL",u"URL正常认证命令",u"URL无认证命令",u"执行结果",u"测试结果"]],redLine=1) 246 | ## Session认证测试结果(该功能比较独立,本脚本目录下有另外单独脚本) 247 | checkResult = check_httpAPI_bySession() #[[method,protocol,uri,certLink,simpleLink,errorLog,result]] 248 | excelResult.write(checkResult) 249 | 250 | except: 251 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 252 | g_Log.writeLog(errmsg) 253 | return 0 254 | return 1 255 | 256 | # 执行后清理环境 257 | def clearup(): 258 | try: 259 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 260 | 261 | except: 262 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 263 | g_Log.writeLog(errmsg) 264 | return 0 265 | return 1 266 | 267 | 268 | if __name__ == '__main__': 269 | res = prepare() 270 | if not res: 271 | print "错误信息:执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 272 | else: 273 | run() 274 | clearup() 275 | 276 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/systemSafe/TestCase_systemSafe_Docker.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | import zipfile 9 | import shutil 10 | 11 | 12 | from sys import path 13 | # 系统默认Unicode解码,需要换成utf-8形式 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | 18 | ''' 19 | """ 相关安全要求说明 """ 20 | 《01 产品网络安全红线落地解读及指导V2_1.xls》: 21 | 6.1.2 使用操作系统的非管理员权限帐号来运行数据库 22 | 《中央软件院网络安全测试基线V2.0.xlsx》 中关于系统中中无用账号及不安全密码、文件权限、调试工具、无属主文件、进程安全等要求 23 | ''' 24 | ''' 25 | """ 脚本功能 """ 26 | 扫描系统中的无用账号及不安全密码、文件权限、调试工具、无属主文件、进程安全等问题点,扫描策略见本脚本所在目录下的systemSafePolicy.xlsx 27 | ''' 28 | ''' 29 | """ 脚本配置执行说明 """ 30 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 31 | 配置2:本脚本所在目录下的systemSafePolicy.xlsx,“policy”页。 32 | 配置3:本脚本所在目录下的systemSafePolicy.xlsx,“config”页。每一行配置都有说明,请仔细阅读。 33 | ''' 34 | 35 | ''' 36 | """ 可以在此处下方添加自己的代码(函数) """ 37 | ''' 38 | try: 39 | g_Log = None 40 | g_Global = None 41 | g_caseName = None 42 | 43 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 44 | g_caseName = curFile.replace("\\","/") 45 | g_curDir = os.path.split(g_caseName)[0] 46 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 47 | 48 | import GlobalValue as g_Global 49 | g_Global.init() 50 | g_Global.setValue("startTime",str(datetime.datetime.now())) 51 | 52 | import Log 53 | import ExcelOperate 54 | import ContainerOperate 55 | import LinuxOperate 56 | import LocalOperate 57 | g_Log = Log.Log() 58 | g_Local = LocalOperate.Local() 59 | 60 | ##### 获取环境配置信息 61 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 62 | excel0 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 63 | g_vmInfo = excel0.read() 64 | del g_vmInfo[0] 65 | systemSafePolicyExcel = g_curDir + "/systemSafePolicy.xlsx" 66 | excel1 = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName="policy") 67 | g_systemSafePolicy = excel1.read() 68 | del g_systemSafePolicy[0] 69 | excel2 = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName="config") 70 | g_config = excel2.read() 71 | del g_config[0] 72 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 73 | except: 74 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 75 | print errmsg 76 | exit(0) 77 | 78 | def getsystemSafePolicy(): #获取所有支持系统扫描的策略信息 79 | global g_systemSafePolicy 80 | policy = [] 81 | for p in g_systemSafePolicy: 82 | supportSys = p[3].lower() 83 | if p[0].lower() == "true" and "os" in supportSys.lower(): 84 | policy.append(p) 85 | g_systemSafePolicy = policy 86 | return 1 87 | 88 | def scan_in_MV(): 89 | reportPath = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 90 | if not os.path.exists(reportPath): 91 | os.makedirs(reportPath) 92 | shutil.copy(g_curDir+"/systemSafePolicy.xlsx",reportPath+"/systemSafePolicy.xlsx") 93 | for vm in g_vmInfo: 94 | try: 95 | vmIP = vm[0] 96 | vmName = vm[1] 97 | vmUser = vm[2] 98 | vmUserPasswd = vm[3] 99 | vmSuRoot = vm[4] 100 | vmRootPasswd = vm[5] 101 | tDocker = ContainerOperate.Container(ip=vmIP,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 102 | containerInfo = tDocker.Container_Mount_link() 103 | for scan in g_systemSafePolicy: 104 | name = scan[1] 105 | info = scan[2] 106 | ifRed = scan[4] 107 | 108 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 109 | 110 | if '\\' in info: 111 | info = info.replace('\\', '\\\\') 112 | if '$' in info: 113 | info = info.replace('$', '\$') 114 | if '"' in info: 115 | info = info.replace('"', '\\"') 116 | if '`' in info: 117 | info = info.replace('`', '\\`') 118 | 119 | tLinux.sendRootCommand("rm -rf /tmp/tempScan.sh") 120 | tLinux.sendCommand('echo \"{cmd}\">/tmp/tempScan.sh'.format(cmd=info)) 121 | tLinux.sendRootCommand("chmod 777 /tmp/tempScan.sh") 122 | for container in containerInfo: 123 | try: 124 | image = container[0].split("/")[-1].split(":")[0] 125 | id = container[1] 126 | mntDir = container[2] 127 | output = tLinux.sendRootCommand("docker ps |grep {id}".format(id=id)) 128 | if output==False or output[0]=="": 129 | continue 130 | tLinux.sendRootCommand("cp /tmp/tempScan.sh {dir}/tmp/tempScan.sh".format(dir=mntDir)) 131 | cmd = "chmod 777 /tmp/tempScan.sh" 132 | output = tLinux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=id,cmd=cmd)) 133 | cmd = "/usr/bin/sh /tmp/tempScan.sh" 134 | output = tLinux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=id,cmd=cmd)) 135 | result = output[0] 136 | cmd = "rm -rf /tmp/tempScan.sh" 137 | tLinux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=id,cmd=cmd)) 138 | 139 | # 检查是否有需要进行结果筛选 140 | if ifRed.upper() == "YES": 141 | resultPath = reportPath + "/(RedLine)" + str(vmIP) + "/" + str(image) 142 | else: 143 | resultPath = reportPath + "/" + str(vmIP) + "/" + str(image) 144 | if not os.path.exists(resultPath): 145 | os.makedirs(resultPath) 146 | resultFile = resultPath + "/" + str(name) + ".txt" 147 | f1 = open(resultFile,'a') 148 | try: 149 | excel = ExcelOperate.Excel(excelName=systemSafePolicyExcel,sheetName=name) 150 | ignoreKeys = excel.read() 151 | if ignoreKeys == False: 152 | ignoreKeys = [] 153 | else: 154 | del ignoreKeys[0] 155 | pythonRegular = "" 156 | for x in ignoreKeys: 157 | pythonRegular = pythonRegular + x[0] + "|" 158 | if pythonRegular == "": # 没有配置python形式的结果排查,扫描结果直接写入结果文件 159 | raise "no python values" 160 | pythonRegular = pythonRegular[:-1] 161 | 162 | lines = result.split("\n") 163 | for line in lines: # 配置了python形式的结果排查,扫描结果筛选后写入结果文件 164 | if "/devicemapper/mnt/" in line: 165 | continue 166 | x0 = re.findall(pythonRegular,line) 167 | if x0==[]: 168 | f1.write(line+"\n") 169 | except: 170 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 171 | if "no python values" in errmsg: 172 | g_Log.writeLog(u"没有为{name}配置python形式的结果排查,扫描结果直接写入结果文件".format(name=name)) 173 | else: 174 | g_Log.writeLog("traceback") 175 | lines = result.split("\n") 176 | for line in lines: # 配置了python形式的结果排查,扫描结果筛选后写入结果文件 177 | if "/devicemapper/mnt/" in line: 178 | continue 179 | f1.write(line+"\n") 180 | except: 181 | g_Log.writeLog("traceback") 182 | 183 | f1.close() 184 | tLinux.logout() 185 | tDocker.logout() 186 | except: 187 | g_Log.writeLog("traceback") 188 | #### 清除环境中的残留脚本 189 | try: 190 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 191 | output = tLinux.sendRootCommand("find / -name tempScan.sh") 192 | if output!=False and output[0]!="": 193 | files = output[0].split("\n") 194 | for f in files: 195 | cmd = "rm -rf {file}".format(file=f) 196 | tLinux.sendRootCommand("rm -rf {cmd}".format(cmd=cmd)) 197 | tLinux.logout() 198 | except: 199 | g_Log.writeLog("traceback") 200 | 201 | def cleanAll(): 202 | for vm in g_vmInfo: 203 | try: 204 | vmIP = vm[0] 205 | vmName = vm[1] 206 | vmUser = vm[2] 207 | vmUserPasswd = vm[3] 208 | vmSuRoot = vm[4] 209 | vmRootPasswd = vm[5] 210 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 211 | output = tLinux.sendRootCommand("find / -name tempScan.sh") 212 | if output!=False and output[0]!="": 213 | files = output[0].split("\n") 214 | for f in files: 215 | cmd = "rm -rf {file}".format(file=f) 216 | tLinux.sendRootCommand("rm -rf {cmd}".format(cmd=cmd)) 217 | tLinux.logout() 218 | except: 219 | g_Log.writeLog("traceback") 220 | 221 | 222 | ''' 223 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 224 | ''' 225 | # 执行前的准备操作 226 | def prepare(): 227 | try: 228 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 229 | cleanAll() 230 | except: 231 | g_Log.writeLog("traceback") 232 | return 0 233 | return 1 234 | 235 | # 执行用例 236 | def run(): 237 | try: 238 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 239 | getsystemSafePolicy() 240 | scan_in_MV() 241 | except: 242 | g_Log.writeLog("traceback") 243 | return 0 244 | return 1 245 | 246 | # 执行后清理环境 247 | def clearup(): 248 | try: 249 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 250 | cleanAll() 251 | except: 252 | g_Log.writeLog("traceback") 253 | return 0 254 | return 1 255 | 256 | if __name__ == '__main__': 257 | res = prepare() 258 | if not res: 259 | print "执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 260 | else: 261 | run() 262 | clearup() 263 | 264 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/CommunicationMatrix/TestCase_CommunicationMatrix_Docker.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | 9 | 10 | from sys import path 11 | # 系统默认Unicode解码,需要换成utf-8形式 12 | reload(sys) 13 | sys.setdefaultencoding('utf-8') 14 | 15 | 16 | ''' 17 | """ 相关安全要求说明 """ 18 | 《01 产品网络安全红线落地解读及指导V2_1.xls》 3.1.1 系统所有的对外通信连接必须是系统运行和维护必需的,对使用到的通信端口在产品通信矩阵文档中说明,动态侦听端口必须限定确定的合理的范围。通过端口扫描工具验证,未在通信矩阵中列出的端口必须关闭。 19 | ''' 20 | ''' 21 | """ 脚本功能 """ 22 | 扫描Docker容器中的端口信息(netstat -tunlp查询结果),与通信矩阵的内容对比,查看是否有多余或缺失的端口。 23 | ''' 24 | ''' 25 | """ 脚本配置执行说明 """ 26 | 配置1:/SecurityTest/Config/config.xlsx,“vmInfo”页 27 | 配置2:本脚本所在目录下的CommunicationMatrix_Docker.xlsx,“Docker”页。每一列配置表头都有批注说明,请仔细阅读。 28 | ''' 29 | 30 | ''' 31 | """ 可以在此处下方添加自己的代码(函数) """ 32 | ''' 33 | try: 34 | g_Log = None 35 | g_Global = None 36 | g_caseName = None 37 | 38 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 39 | g_caseName = curFile.replace("\\","/") 40 | g_curDir = os.path.split(g_caseName)[0] 41 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 42 | 43 | import GlobalValue as g_Global 44 | g_Global.init() 45 | g_Global.setValue("startTime",str(datetime.datetime.now())) 46 | 47 | import Log 48 | import ExcelOperate 49 | import ContainerOperate 50 | import LinuxOperate 51 | import LocalOperate 52 | g_Log = Log.Log() 53 | g_Local = LocalOperate.Local() 54 | 55 | ##### 获取环境配置信息 56 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 57 | excel1 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 58 | g_vmInfo = excel1.read() 59 | del g_vmInfo[0] 60 | g_omCoreInfo = [] 61 | for vm in g_vmInfo: 62 | if vm[6]==1 or str(vm[6]).upper() == "TRUE": 63 | g_omCoreInfo = [ vm[0], vm[1], vm[2], vm[3], vm[4], vm[5]] 64 | 65 | communicationMatrixExcel = g_curDir + "/CommunicationMatrix_Docker.xlsx" 66 | excel1 = ExcelOperate.Excel(excelName=communicationMatrixExcel,sheetName="VM") 67 | g_matrixInfo = excel1.read() 68 | del g_matrixInfo[0] 69 | 70 | g_ResultFile = g_caseName.replace("TestCase","Report").replace(".py","")+"-"+g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","")+".xls" 71 | except: 72 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 73 | print errmsg 74 | exit(0) 75 | 76 | def getNetstatInfo(): ## 遍历每一台虚机,netstat -tunlp命令查询所有监听端口及其对应的进程 77 | #netstatInfo格式:[[vmIP,cmd,port,portIP,protocol,proc]] 78 | netstatInfo = [] 79 | for vm in g_vmInfo: 80 | try: 81 | vmIP = vm[0] 82 | vmName = vm[1] 83 | vmUser = vm[2] 84 | vmUserPasswd = vm[3] 85 | vmSuRoot = vm[4] 86 | vmRootPasswd = vm[5] 87 | 88 | tLinux = LinuxOperate.Linux(ip=vmIP,name=vmName,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 89 | output1 = tLinux.sendCommand("/usr/sbin/ifconfig eth0") 90 | ip1 = re.findall("inet\s+(\d+\.\d+\.\d+\.\d+)",output1[0]) 91 | ip_linux = ip1[0] 92 | 93 | tDocker = ContainerOperate.Container(ip=vmIP,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 94 | containerInfo = tDocker.Container_Mount_link() 95 | for container in containerInfo: 96 | image = container[0].split("/")[-1].split(":")[0] 97 | id = container[1] 98 | cmd = "/usr/sbin/ifconfig eth0" 99 | output2 = tLinux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=id,cmd=cmd),timeout=10) 100 | ip2 = re.findall("inet\s+(\d+\.\d+\.\d+\.\d+)",output2[0]) 101 | if ip2!=False and ip2[0]!="": 102 | ip_container = ip2[0] 103 | if ip_container == ip_linux: 104 | continue 105 | 106 | cmd = "netstat -tunlp" 107 | output3 = tLinux.sendRootCommand("docker exec -u 0 {id} {cmd}".format(id=id,cmd=cmd),timeout=10) 108 | netInfo = output3[0].split("\n") 109 | for net in netInfo: 110 | if net[:3]!="tcp" and net[:3]!="udp": 111 | continue 112 | temp = net.split() 113 | 114 | ip_port = temp[3] 115 | x = re.findall("\d+",ip_port) 116 | port = x[-1] 117 | ptip = ip_port[:len(ip_port)-len(port)-1] 118 | 119 | protocol = temp[0] 120 | 121 | netstatInfo.append([vmIP,"netstat -tunlp",port,ptip,protocol,image]) 122 | tDocker.logout() 123 | tLinux.logout() 124 | except: 125 | g_Log.writeLog("traceback") 126 | 127 | return netstatInfo 128 | 129 | def getPortInfo(): ## 查询环境中的各种监听端口,格式:[[vmIP,cmd,port,portIP,protocol,proc]] 130 | portInfo = [] 131 | portInfo = portInfo + getNetstatInfo() 132 | #portInfo = list(set(portInfo)) 133 | return portInfo 134 | 135 | def checkMonitorPort(monitorPort,matrixPort,vmPorts,monitorProc,description): 136 | result = False 137 | matrixPort = str(matrixPort).split(".")[0] #防止在通信矩阵中获取到的是float型 138 | 139 | pts1 = matrixPort.split(",") 140 | if monitorPort in pts1: 141 | result = True 142 | 143 | pts2 = matrixPort.split("/") 144 | if monitorPort in pts2: 145 | result = True 146 | 147 | pts3 = re.findall('\d+-\d+',matrixPort) 148 | for p in pts3: 149 | tmp = p.split("-") 150 | netPort_int = int(monitorPort) 151 | pf_int = int(tmp[0]) 152 | pe_int = int(tmp[1]) 153 | if "/bin/kube-proxy" in monitorProc: 154 | if "kube-proxy" in description: #对"kube-proxy"监听端口的特殊处理(该端口在通信矩阵中1024~65535,描述太广) 155 | if netPort_int > pf_int and netPort_int < pe_int and netPort_int not in vmPorts: 156 | result = True 157 | else: 158 | if "kube-proxy" not in description: 159 | if netPort_int > pf_int and netPort_int < pe_int and netPort_int not in vmPorts: 160 | result = True 161 | 162 | pts4 = re.findall('\d+~\d+',matrixPort) 163 | for p in pts4: 164 | tmp = p.split("~") 165 | netPort_int = int(monitorPort) 166 | pf_int = int(tmp[0]) 167 | pe_int = int(tmp[1]) 168 | if "/bin/kube-proxy" in monitorProc: 169 | if "kube-proxy" in description: #对"kube-proxy"监听端口的特殊处理(该端口在通信矩阵中1024~65535,描述太广) 170 | if netPort_int > pf_int and netPort_int < pe_int and netPort_int not in vmPorts: 171 | result = True 172 | else: 173 | if "kube-proxy" not in description: 174 | if netPort_int > pf_int and netPort_int < pe_int and netPort_int not in vmPorts: 175 | result = True 176 | 177 | return result 178 | 179 | def check_Ports_in_CommunicationMatrix(vmPorts): 180 | errInfo = [] 181 | for vmPt in vmPorts: ## 查询环境中的各种监听端口,格式:[[vmIP,cmd,port,portIP,protocol,proc]] 182 | vmIP = vmPt[0] 183 | command = vmPt[1] 184 | monitorPort = vmPt[2] 185 | monitorIP = vmPt[3] 186 | monitorProtocol = vmPt[4] 187 | monitorProc = vmPt[5] 188 | #x = re.findall("/usr/sbin/ntpd|/usr/sbin/sshd",monitorProc) 189 | #if x != []: 190 | # continue 191 | 192 | checkPortResult = False 193 | checkIpResult = False 194 | checkProtocolResult = False 195 | checkServiceResult = False 196 | for matrix in g_matrixInfo: 197 | destPort = str(matrix[1]) 198 | destIP = str(matrix[0]) 199 | protocol = str(matrix[2]) 200 | service = str(matrix[4]) 201 | destPort = destPort.replace("、","/").replace(" ","/").replace("~","~") 202 | 203 | checkPort = checkMonitorPort(monitorPort,destPort,vmPorts,monitorProc,destIP+service) 204 | if checkPort == False: 205 | continue 206 | else: 207 | checkPortResult = True 208 | 209 | if "127.0.0.1" in destIP and "127.0.0.1" == monitorIP: 210 | checkIpResult = True 211 | elif "0.0.0.0" in destIP and "0.0.0.0" == monitorIP: 212 | checkIpResult = True 213 | elif "ipv6" in destIP.lower() and "::" == monitorIP: 214 | checkIpResult = True 215 | 216 | if "tcp" in monitorProtocol.lower() and "tcp" in protocol.lower(): 217 | checkProtocolResult = True 218 | elif "udp" in monitorProtocol.lower() and "udp" in protocol.lower(): 219 | checkProtocolResult = True 220 | elif monitorProtocol.lower() == protocol.lower(): 221 | checkProtocolResult = True 222 | 223 | if service.lower() in monitorProc.lower(): 224 | checkServiceResult = True 225 | 226 | err = "" 227 | errLevel = "Pass" 228 | if checkPortResult == False: 229 | errLevel = "Fail" 230 | err = u"通信矩阵中没有找到该端口" 231 | else: 232 | if checkIpResult == False: 233 | err = err + u"通信矩阵中\"目的IP\"的描述与环境实际端口监听的IP可能不匹配,请人工观察对比\n" 234 | if checkProtocolResult == False: 235 | err = err + u"通信矩阵中\"协议\"的描述与环境实际端口协议可能不匹配,请人工观察对比\n" 236 | if checkServiceResult == False: 237 | err = err + u"通信矩阵中\"所属微服务\"的描述与环境实际端口所在服务可能不匹配,请人工观察对比\n" 238 | err = err.strip() 239 | if err != "": 240 | errLevel = "Warn" 241 | 242 | errInfo.append([vmIP,command,monitorPort,monitorIP,monitorProtocol,monitorProc,errLevel,err]) 243 | return errInfo 244 | 245 | ''' 246 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 247 | ''' 248 | # 执行前的准备操作 249 | def prepare(): 250 | try: 251 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 252 | except: 253 | g_Log.writeLog("traceback") 254 | return 0 255 | return 1 256 | 257 | # 执行用例 258 | def run(): 259 | try: 260 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 261 | 262 | portInfo = getPortInfo() 263 | result = check_Ports_in_CommunicationMatrix(portInfo) #[vmIP,command,monitorPort,monitorIP,monitorProtocol,monitorProc,errLevel,err] 264 | excelResult = ExcelOperate.Excel(excelName=g_ResultFile,sheetID=0) 265 | excelResult.new() 266 | excelResult.write([[u"端口所在节点",u"查询命令",u"端口",u"监听IP",u"协议",u"进程或实例信息",u"问题级别",u"问题描述"]],redLine=2) 267 | excelResult.write(result) 268 | except: 269 | g_Log.writeLog("traceback") 270 | return 0 271 | return 1 272 | 273 | # 执行后清理环境 274 | def clearup(): 275 | try: 276 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 277 | except: 278 | g_Log.writeLog("traceback") 279 | return 0 280 | return 1 281 | 282 | if __name__ == '__main__': 283 | res = prepare() 284 | if not res: 285 | print "错误信息:执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 286 | else: 287 | run() 288 | clearup() 289 | 290 | -------------------------------------------------------------------------------- /NewVerson/SecurityTest/TestCase/Authorization_Renzhen/_get_registeredPORT.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import datetime 7 | import re 8 | 9 | 10 | from sys import path 11 | reload(sys) 12 | sys.setdefaultencoding('utf-8') 13 | 14 | 15 | ''' 16 | """ 脚本配置执行说明 """ 17 | 该脚本不是单独的用例,仅用于获取环境中注册到nginx的API接口。 18 | ''' 19 | 20 | ''' 21 | """ 可以在此处下方添加自己的代码(函数) """ 22 | ''' 23 | try: 24 | g_Log = None 25 | g_Global = None 26 | g_caseName = None 27 | g_registeredAPIExcel = None 28 | 29 | curFile = os.path.abspath(sys._getframe(0).f_code.co_filename) 30 | g_caseName = curFile.replace("\\","/") 31 | g_curDir = os.path.split(g_caseName)[0] 32 | path.append( g_caseName.split("TestCase")[0]+"PublicLib" ) 33 | 34 | startTime = None 35 | tempConfig = g_curDir+"/_tempConfig.ini" 36 | pathExist = os.path.exists(tempConfig) 37 | if pathExist: 38 | file = open(tempConfig) 39 | info = file.readlines() 40 | for line in info: 41 | if "startTime" in line: 42 | startTime = line.split("startTime:")[1].strip() 43 | if startTime == None: 44 | startTime = str(datetime.datetime.now()) 45 | import GlobalValue as g_Global 46 | g_Global.init() 47 | g_Global.setValue("startTime",startTime) 48 | 49 | import Log 50 | import ExcelOperate 51 | import ContainerOperate 52 | import LinuxOperate 53 | import LocalOperate 54 | g_Log = Log.Log() 55 | g_Local = LocalOperate.Local() 56 | 57 | ##### 获取环境配置信息 58 | excelName = g_caseName.split("TestCase")[0]+"Config/config.xlsx" 59 | excel1 = ExcelOperate.Excel(excelName=excelName,sheetName="vmInfo") 60 | g_vmInfo = excel1.read() 61 | del g_vmInfo[0] 62 | g_omCoreInfo = [] 63 | for vm in g_vmInfo: 64 | if vm[6]==1 or str(vm[6]).upper() == "TRUE": 65 | g_omCoreInfo = [ vm[0], vm[1], vm[2], vm[3], vm[4], vm[5]] 66 | 67 | codeAPIExcel = g_curDir + "/APIlist.xlsx" 68 | excel1 = ExcelOperate.Excel(excelName=codeAPIExcel,sheetName="API") 69 | g_codeAPI = excel1.read() 70 | del g_codeAPI[0] 71 | excel2 = ExcelOperate.Excel(excelName=codeAPIExcel,sheetName="parameter") 72 | g_config = excel2.read() 73 | del g_config[0] 74 | 75 | g_allPorts = [] 76 | for api in g_codeAPI: 77 | port = str(api[2]).strip().split(".")[0] 78 | ports = port.split(";") 79 | for p in ports: 80 | if p not in g_allPorts: 81 | g_allPorts.append(p) 82 | except: 83 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 84 | print errmsg 85 | exit(0) 86 | 87 | def get_vmRealIP(linux): # 根据虚机挂载的大网IP获取实际eth0信息 88 | try: 89 | output = linux.sendRootCommand("/usr/sbin/ifconfig eth0") 90 | readIP = re.findall("inet\s+(\d+\.\d+\.\d+\.\d+)",output[0]) 91 | return readIP[0] 92 | except: 93 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 94 | g_Log.writeLog(errmsg) 95 | return "" 96 | 97 | def get_externalPortBySVC(): # 通过kubectl get svc --all-namespaces命令获取虚机上启动的external端口及容器端口,格式:[[serviceName,port]] 98 | externalPorts = [] 99 | if g_omCoreInfo == []: 100 | return externalPorts 101 | for conf in g_config: 102 | if conf[0]=="KUBERNETES_MASTER": 103 | kubernetes_master = conf[1] 104 | if kubernetes_master == None: 105 | return externalPorts 106 | omCoreIP = g_omCoreInfo[0] 107 | omCoreUser = g_omCoreInfo[2] 108 | omCoreUserPasswd = g_omCoreInfo[3] 109 | omCoreSuRoot = g_omCoreInfo[4] 110 | omCoreRootPasswd = g_omCoreInfo[5] 111 | ssh = LinuxOperate.Linux(ip=omCoreIP,user=omCoreUser,password=omCoreUserPasswd,suRoot=omCoreSuRoot,rootPassword=omCoreRootPasswd) 112 | command = "ps -ef | grep /usr/local/bin/kubelet | grep -v grep | awk -F \"api-servers=\" '{print $2}' | awk '{print $1}'" 113 | output = ssh.sendCommand(command) 114 | kubernetes_master = output[0].strip() 115 | command = "export KUBERNETES_MASTER={kubernetes_master};export PAAS_CRYPTO_PATH=/var/paas/srv/kubernetes;/var/paas/kubernetes/kubectl --client-certificate=${key1}/server.cer --client-key=${key1}/server_key.pem --certificate-authority=${key1}/ca.cer -s ${key2} get svc --all-namespaces".format(kubernetes_master=kubernetes_master,key1="{PAAS_CRYPTO_PATH}",key2="{KUBERNETES_MASTER}") 116 | output = ssh.sendRootCommand(command) 117 | svcInfo = output[0].split("\n") 118 | for svc in svcInfo: 119 | try: 120 | if svc.strip() == "" or "NAMESPACE" in svc: 121 | continue 122 | res = svc.split() 123 | namespace = res[0] 124 | serName = res[1] 125 | command = "export KUBERNETES_MASTER={kubernetes_master};export PAAS_CRYPTO_PATH=/var/paas/srv/kubernetes;/var/paas/kubernetes/kubectl --client-certificate=${key1}/server.cer --client-key=${key1}/server_key.pem --certificate-authority=${key1}/ca.cer -s ${key2} describe svc {serice} -n {namespace} |egrep \"IP:|Name:|Namespace:|Type:|External IPs:|LoadBalancer Ingress:|Port:|NodePort:|Endpoints:\"".format(kubernetes_master=kubernetes_master,key1="{PAAS_CRYPTO_PATH}",key2="{KUBERNETES_MASTER}",namespace=namespace,serice=serName) 126 | output = ssh.sendRootCommand(command) 127 | x = re.findall("Name:\s*(.*?)\s*\n",output[0]) 128 | name = x[0] 129 | t1_port1 = re.findall("\W+Port:\s+[a-zA-Z0-9\<\>\s\-]+\s+(\d+)/\w+\s*\n\s*Endpoints:\s*([0-9:,\.]+)",output[0]) 130 | t1_port2 = re.findall("\W+Port:\s+[a-zA-Z0-9\<\>\s\-]+\s+(\d+)/\w+\s*\n\s*NodePort:\s+[a-zA-Z0-9\s\-]+\s+\d+/\w+\s*\n\s*Endpoints:\s+([0-9:,\.]+)",output[0]) 131 | t1_ports = t1_port1+t1_port2 132 | t1_ip = re.findall("IP:\s*(\d+\.\d+\.\d+\.\d+)",output[0]) 133 | t1_externalip = re.findall("External IPs:\s*(\d+\.\d+\.\d+\.\d+)",output[0]) 134 | t1_ingress = re.findall("LoadBalancer Ingress:\s*(\d+\.\d+\.\d+\.\d+)",output[0]) 135 | #t1_nodeport = re.findall("NodePort:.*\s+(\d+)/\w+",output[0]) 136 | t1_nodeport = re.findall("\W*NodePort:\s+[a-zA-Z0-9\s\-]+\s+(\d+)/\w+\s*\n\s*Endpoints:\s*([0-9:,\.]+)",output[0]) 137 | 138 | ifFind = False 139 | if t1_ports != [] and t1_ip != []: 140 | for p in t1_ports: 141 | endPoints = p[1] 142 | externalPort = t1_ip[0]+":"+p[0] 143 | externalPorts.append([name,externalPort,endPoints]) 144 | ifFind = True 145 | if t1_ports != [] and t1_externalip != []: 146 | for p in t1_ports: 147 | endPoints = p[1] 148 | externalPort = t1_externalip[0]+":"+p[0] 149 | externalPorts.append([name,externalPort,endPoints]) 150 | ifFind = True 151 | if t1_ports != [] and t1_ingress != []: 152 | for p in t1_ports: 153 | endPoints = p[1] 154 | externalPort = t1_ingress[0]+":"+p[0] 155 | externalPorts.append([name,externalPort,endPoints]) 156 | ifFind = True 157 | if t1_nodeport != []: 158 | tmpcmd = "export KUBERNETES_MASTER={kubernetes_master};export PAAS_CRYPTO_PATH=/var/paas/srv/kubernetes;/var/paas/kubernetes/kubectl --client-certificate=${key1}/server.cer --client-key=${key1}/server_key.pem --certificate-authority=${key1}/ca.cer -s ${key2} get pods -n {namespace} |grep {serice}".format(kubernetes_master=kubernetes_master,key1="{PAAS_CRYPTO_PATH}",key2="{KUBERNETES_MASTER}",namespace=namespace,serice=serName) 159 | tmpout = ssh.sendRootCommand(tmpcmd) 160 | pods = re.findall("({serice}.*?)\s".format(serice=serName),tmpout[0]) 161 | for pod in pods: 162 | try: 163 | tmpcmd1 = "export KUBERNETES_MASTER={kubernetes_master};export PAAS_CRYPTO_PATH=/var/paas/srv/kubernetes;/var/paas/kubernetes/kubectl --client-certificate=${key1}/server.cer --client-key=${key1}/server_key.pem --certificate-authority=${key1}/ca.cer -s ${key2} get pods {pod} -n {namespace} -o yaml |grep hostIP".format(kubernetes_master=kubernetes_master,key1="{PAAS_CRYPTO_PATH}",key2="{KUBERNETES_MASTER}",namespace=namespace,pod=pod) 164 | tmpout1 = ssh.sendRootCommand(tmpcmd1) 165 | tempx = re.findall("hostIP:\s*(\d+\.\d+\.\d+\.\d+)",tmpout1[0]) 166 | hostIP = tempx[0] 167 | for p in t1_nodeport: 168 | endPoints = p[1] 169 | externalPort = hostIP+":"+p[0] 170 | externalPorts.append([name,externalPort,endPoints]) 171 | except: 172 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 173 | g_Log.writeLog(errmsg) 174 | ifFind = True 175 | if ifFind == False: 176 | g_Log.writeLog("以下服务的端口自动化判断为不涉及认证(api注册信息中不包含这些端口),无需测试:\n"+output[0]) 177 | continue 178 | except: 179 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 180 | g_Log.writeLog(errmsg) 181 | return externalPorts 182 | 183 | def get_netstatPort(): # 通过netstat -tunlp命令获取虚机上监听的相关端口,格式:[[ip,port]] 184 | netstatPorts = [] 185 | for vm in g_vmInfo: 186 | try: 187 | vmIP = vm[0] 188 | vmUser = vm[2] 189 | vmUserPasswd = vm[3] 190 | vmSuRoot = vm[4] 191 | vmRootPasswd = vm[5] 192 | tLinux = LinuxOperate.Linux(ip=vmIP,user=vmUser,password=vmUserPasswd,suRoot=vmSuRoot,rootPassword=vmRootPasswd) 193 | realIP = get_vmRealIP(tLinux) 194 | 195 | scanPort = "|".join(g_allPorts) 196 | scanPort = scanPort.replace("|"," |:") 197 | scanPort = ":"+scanPort+" " 198 | output = tLinux.sendRootCommand("/usr/bin/netstat -tunlp |egrep \"{port}\"".format(port=scanPort)) 199 | vmPorts = re.findall("\d+\.\d+\.\d+\.\d+:\d+|:::\d+",output[0]) 200 | rvmPorts = [] 201 | for p in vmPorts: 202 | if "127.0.0.1" in p: 203 | continue 204 | if "0.0.0.0:" in p: 205 | rvmPorts.append([vmIP,realIP+":"+p.split(":")[1]]) 206 | elif ":::" in p: 207 | rvmPorts.append([vmIP,realIP+":"+p.split(":")[1]]) 208 | else: 209 | rvmPorts.append([vmIP,p]) 210 | netstatPorts = netstatPorts+rvmPorts 211 | except: 212 | g_Log.writeLog("traceback") 213 | return netstatPorts 214 | 215 | def get_allExternalPort(): #获取虚机上所有启动的external IP和端口,格式:[[ip,port]] 216 | allExternalPort = [] 217 | #externalPortBySVC = get_externalPortBySVC() 218 | #allExternalPort = allExternalPort + externalPortBySVC 219 | netstatPort = get_netstatPort() 220 | allExternalPort = allExternalPort + netstatPort 221 | 222 | return allExternalPort 223 | 224 | ''' 225 | """ 以下定义的函数,请在特定位置添加自己的代码 """ 226 | ''' 227 | # 执行前的准备操作 228 | def prepare(): 229 | try: 230 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 231 | except: 232 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 233 | g_Log.writeLog(errmsg) 234 | return 0 235 | return 1 236 | 237 | # 执行用例 238 | def run(): 239 | try: 240 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 241 | curDir = os.path.split(g_caseName)[0] 242 | resultDir = curDir.replace("TestCase","Report") 243 | startTimeSign = g_Global.getValue("startTime").replace(":","").replace(" ","").replace("-","") 244 | #startTimeSign = "20180228145712.735000" 245 | externalPortExcelName=resultDir+"/externalPorts-{startTime}.xls".format(startTime=startTimeSign) 246 | 247 | externalPort = get_allExternalPort() # 输出格式:[LinuxIP,dir,urlNo,location_url,serverName,"ip_port,ip_port"] 248 | print externalPort 249 | externalPortExcel = ExcelOperate.Excel(excelName=externalPortExcelName,sheetID=0) 250 | externalPortExcel.new() 251 | externalPortExcel.write([[u"端口所在服务或虚机",u"端口"]]) 252 | externalPortExcel.write(externalPort) 253 | 254 | global g_externalPortExcel 255 | g_externalPortExcel = externalPortExcelName 256 | except: 257 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 258 | g_Log.writeLog(errmsg) 259 | return 0 260 | return 1 261 | 262 | # 执行后清理环境 263 | def clearup(): 264 | try: 265 | ''''''''' 可以在此处下方添加自己的代码 ''''''''' 266 | curDir = os.path.split(g_caseName)[0] 267 | tempConfig=curDir+"/_tempConfig.ini" 268 | file = open( tempConfig,'a' ) 269 | file.write("externalPortExcel:"+g_externalPortExcel+"\n") 270 | file.close() 271 | except: 272 | errmsg = ''.join(traceback.format_exception(*sys.exc_info())) 273 | g_Log.writeLog(errmsg) 274 | return 0 275 | return 1 276 | 277 | 278 | res = prepare() 279 | if not res: 280 | print "执行用例prepare模块失败,结束用例{name}的执行".format(name=g_caseName) 281 | else: 282 | run() 283 | clearup() 284 | 285 | --------------------------------------------------------------------------------